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 |
|---|---|---|---|---|---|---|
simonpercic/AirCycle | example/src/main/java/com/github/simonpercic/example/aircycle/activity/a08/BindConfigActivity.java | // Path: aircycle-api/src/main/java/com/github/simonpercic/aircycle/ActivityLifecycle.java
// public final class ActivityLifecycle {
//
// @IntDef({CREATE, START, RESUME, PAUSE, STOP, SAVE_INSTANCE_STATE, DESTROY})
// @Retention(RetentionPolicy.SOURCE)
// public @interface ActivityLifecycleEvent {
// }
//
// public static final int CREATE = 1;
// public static final int START = 2;
// public static final int RESUME = 3;
// public static final int PAUSE = 4;
// public static final int STOP = 5;
// public static final int SAVE_INSTANCE_STATE = 6;
// public static final int DESTROY = 7;
//
// private ActivityLifecycle() {
// // no instance
// }
// }
//
// Path: aircycle-api/src/main/java/com/github/simonpercic/aircycle/AirCycleConfig.java
// public final class AirCycleConfig {
//
// private final boolean passIntentBundleOnCreate;
// @Nullable private final Set<Integer> ignoredLifecycleCallbacks;
//
// private AirCycleConfig(boolean passIntentBundleOnCreate, @Nullable Set<Integer> ignoredLifecycleCallbacks) {
// this.passIntentBundleOnCreate = passIntentBundleOnCreate;
// this.ignoredLifecycleCallbacks = ignoredLifecycleCallbacks;
// }
//
// boolean passIntentBundleOnCreate() {
// return passIntentBundleOnCreate;
// }
//
// boolean ignoreLifecycleCallback(int lifecycle) {
// return ignoredLifecycleCallbacks != null
// && ignoredLifecycleCallbacks.size() > 0
// && ignoredLifecycleCallbacks.contains(lifecycle);
// }
//
// /**
// * Get a builder for the AirCycleConfig.
// *
// * @return AirCycleConfig builder
// */
// public static Builder builder() {
// return new Builder();
// }
//
// /**
// * AirCycleConfig's builder class.
// */
// public static final class Builder {
//
// private boolean passIntentBundleOnCreate;
// @Nullable private Set<Integer> ignoredLifecycleCallbacks;
//
// private Builder() {
//
// }
//
// /**
// * Whether to pass the Activity's starting Intent Extras Bundle if its savedInstanceState is null in onCreate().
// *
// * @param passIntentBundleOnCreate if true, it passes the Activity's starting Intent Extras Bundle only if its
// * savedInstanceState is null in onCreate()
// * @return this Builder, for chaining calls
// */
// public Builder passIntentBundleOnCreate(boolean passIntentBundleOnCreate) {
// this.passIntentBundleOnCreate = passIntentBundleOnCreate;
// return this;
// }
//
// /**
// * Disable passing of an Activity lifecycle callback from {@link ActivityLifecycle}'s constants.
// *
// * @param lifecycleCallback lifecycle callback to ignore
// * @return this Builder, for chaining calls
// */
// public Builder ignoreLifecycleCallback(@ActivityLifecycle.ActivityLifecycleEvent int lifecycleCallback) {
// switch (lifecycleCallback) {
// case ActivityLifecycle.CREATE:
// case ActivityLifecycle.START:
// case ActivityLifecycle.RESUME:
// case ActivityLifecycle.PAUSE:
// case ActivityLifecycle.STOP:
// case ActivityLifecycle.SAVE_INSTANCE_STATE:
// case ActivityLifecycle.DESTROY:
// if (ignoredLifecycleCallbacks == null) {
// ignoredLifecycleCallbacks = new HashSet<>();
// }
//
// ignoredLifecycleCallbacks.add(lifecycleCallback);
// return this;
// default:
// throw new IllegalArgumentException("unknown lifecycle type");
// }
// }
//
// /**
// * Build the AirCycleConfig.
// *
// * @return built AirCycleConfig
// */
// public AirCycleConfig build() {
// return new AirCycleConfig(passIntentBundleOnCreate, ignoredLifecycleCallbacks);
// }
// }
// }
//
// Path: example/src/main/java/com/github/simonpercic/example/aircycle/listener/BundleListener.java
// public class BundleListener extends ActivityBundleAirCycleLogger {
//
// public static final String EXTRA_INT = BundleListener.class.getCanonicalName() + ".extraInt";
//
// private int extra;
//
// @Override
// public void onCreate(Bundle bundle) {
// extra = bundle.getInt(EXTRA_INT);
// }
//
// @Override
// public void onSaveInstanceState(Bundle outState) {
// outState.putInt(EXTRA_INT, extra);
// }
// }
| import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import com.github.simonpercic.aircycle.ActivityLifecycle;
import com.github.simonpercic.aircycle.AirCycle;
import com.github.simonpercic.aircycle.AirCycleConfig;
import com.github.simonpercic.example.aircycle.R;
import com.github.simonpercic.example.aircycle.listener.BundleListener; | package com.github.simonpercic.example.aircycle.activity.a08;
/**
* Example Activity showing usage of a custom AirCycleConfig passed while binding.
*
* @author Simon Percic <a href="https://github.com/simonpercic">https://github.com/simonpercic</a>
*/
public class BindConfigActivity extends AppCompatActivity {
@AirCycle final BundleListener bundleListener = new BundleListener();
@Override
protected void onCreate(Bundle savedInstanceState) { | // Path: aircycle-api/src/main/java/com/github/simonpercic/aircycle/ActivityLifecycle.java
// public final class ActivityLifecycle {
//
// @IntDef({CREATE, START, RESUME, PAUSE, STOP, SAVE_INSTANCE_STATE, DESTROY})
// @Retention(RetentionPolicy.SOURCE)
// public @interface ActivityLifecycleEvent {
// }
//
// public static final int CREATE = 1;
// public static final int START = 2;
// public static final int RESUME = 3;
// public static final int PAUSE = 4;
// public static final int STOP = 5;
// public static final int SAVE_INSTANCE_STATE = 6;
// public static final int DESTROY = 7;
//
// private ActivityLifecycle() {
// // no instance
// }
// }
//
// Path: aircycle-api/src/main/java/com/github/simonpercic/aircycle/AirCycleConfig.java
// public final class AirCycleConfig {
//
// private final boolean passIntentBundleOnCreate;
// @Nullable private final Set<Integer> ignoredLifecycleCallbacks;
//
// private AirCycleConfig(boolean passIntentBundleOnCreate, @Nullable Set<Integer> ignoredLifecycleCallbacks) {
// this.passIntentBundleOnCreate = passIntentBundleOnCreate;
// this.ignoredLifecycleCallbacks = ignoredLifecycleCallbacks;
// }
//
// boolean passIntentBundleOnCreate() {
// return passIntentBundleOnCreate;
// }
//
// boolean ignoreLifecycleCallback(int lifecycle) {
// return ignoredLifecycleCallbacks != null
// && ignoredLifecycleCallbacks.size() > 0
// && ignoredLifecycleCallbacks.contains(lifecycle);
// }
//
// /**
// * Get a builder for the AirCycleConfig.
// *
// * @return AirCycleConfig builder
// */
// public static Builder builder() {
// return new Builder();
// }
//
// /**
// * AirCycleConfig's builder class.
// */
// public static final class Builder {
//
// private boolean passIntentBundleOnCreate;
// @Nullable private Set<Integer> ignoredLifecycleCallbacks;
//
// private Builder() {
//
// }
//
// /**
// * Whether to pass the Activity's starting Intent Extras Bundle if its savedInstanceState is null in onCreate().
// *
// * @param passIntentBundleOnCreate if true, it passes the Activity's starting Intent Extras Bundle only if its
// * savedInstanceState is null in onCreate()
// * @return this Builder, for chaining calls
// */
// public Builder passIntentBundleOnCreate(boolean passIntentBundleOnCreate) {
// this.passIntentBundleOnCreate = passIntentBundleOnCreate;
// return this;
// }
//
// /**
// * Disable passing of an Activity lifecycle callback from {@link ActivityLifecycle}'s constants.
// *
// * @param lifecycleCallback lifecycle callback to ignore
// * @return this Builder, for chaining calls
// */
// public Builder ignoreLifecycleCallback(@ActivityLifecycle.ActivityLifecycleEvent int lifecycleCallback) {
// switch (lifecycleCallback) {
// case ActivityLifecycle.CREATE:
// case ActivityLifecycle.START:
// case ActivityLifecycle.RESUME:
// case ActivityLifecycle.PAUSE:
// case ActivityLifecycle.STOP:
// case ActivityLifecycle.SAVE_INSTANCE_STATE:
// case ActivityLifecycle.DESTROY:
// if (ignoredLifecycleCallbacks == null) {
// ignoredLifecycleCallbacks = new HashSet<>();
// }
//
// ignoredLifecycleCallbacks.add(lifecycleCallback);
// return this;
// default:
// throw new IllegalArgumentException("unknown lifecycle type");
// }
// }
//
// /**
// * Build the AirCycleConfig.
// *
// * @return built AirCycleConfig
// */
// public AirCycleConfig build() {
// return new AirCycleConfig(passIntentBundleOnCreate, ignoredLifecycleCallbacks);
// }
// }
// }
//
// Path: example/src/main/java/com/github/simonpercic/example/aircycle/listener/BundleListener.java
// public class BundleListener extends ActivityBundleAirCycleLogger {
//
// public static final String EXTRA_INT = BundleListener.class.getCanonicalName() + ".extraInt";
//
// private int extra;
//
// @Override
// public void onCreate(Bundle bundle) {
// extra = bundle.getInt(EXTRA_INT);
// }
//
// @Override
// public void onSaveInstanceState(Bundle outState) {
// outState.putInt(EXTRA_INT, extra);
// }
// }
// Path: example/src/main/java/com/github/simonpercic/example/aircycle/activity/a08/BindConfigActivity.java
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import com.github.simonpercic.aircycle.ActivityLifecycle;
import com.github.simonpercic.aircycle.AirCycle;
import com.github.simonpercic.aircycle.AirCycleConfig;
import com.github.simonpercic.example.aircycle.R;
import com.github.simonpercic.example.aircycle.listener.BundleListener;
package com.github.simonpercic.example.aircycle.activity.a08;
/**
* Example Activity showing usage of a custom AirCycleConfig passed while binding.
*
* @author Simon Percic <a href="https://github.com/simonpercic">https://github.com/simonpercic</a>
*/
public class BindConfigActivity extends AppCompatActivity {
@AirCycle final BundleListener bundleListener = new BundleListener();
@Override
protected void onCreate(Bundle savedInstanceState) { | AirCycleConfig airCycleConfig = AirCycleConfig.builder() |
simonpercic/AirCycle | example/src/main/java/com/github/simonpercic/example/aircycle/activity/a08/BindConfigActivity.java | // Path: aircycle-api/src/main/java/com/github/simonpercic/aircycle/ActivityLifecycle.java
// public final class ActivityLifecycle {
//
// @IntDef({CREATE, START, RESUME, PAUSE, STOP, SAVE_INSTANCE_STATE, DESTROY})
// @Retention(RetentionPolicy.SOURCE)
// public @interface ActivityLifecycleEvent {
// }
//
// public static final int CREATE = 1;
// public static final int START = 2;
// public static final int RESUME = 3;
// public static final int PAUSE = 4;
// public static final int STOP = 5;
// public static final int SAVE_INSTANCE_STATE = 6;
// public static final int DESTROY = 7;
//
// private ActivityLifecycle() {
// // no instance
// }
// }
//
// Path: aircycle-api/src/main/java/com/github/simonpercic/aircycle/AirCycleConfig.java
// public final class AirCycleConfig {
//
// private final boolean passIntentBundleOnCreate;
// @Nullable private final Set<Integer> ignoredLifecycleCallbacks;
//
// private AirCycleConfig(boolean passIntentBundleOnCreate, @Nullable Set<Integer> ignoredLifecycleCallbacks) {
// this.passIntentBundleOnCreate = passIntentBundleOnCreate;
// this.ignoredLifecycleCallbacks = ignoredLifecycleCallbacks;
// }
//
// boolean passIntentBundleOnCreate() {
// return passIntentBundleOnCreate;
// }
//
// boolean ignoreLifecycleCallback(int lifecycle) {
// return ignoredLifecycleCallbacks != null
// && ignoredLifecycleCallbacks.size() > 0
// && ignoredLifecycleCallbacks.contains(lifecycle);
// }
//
// /**
// * Get a builder for the AirCycleConfig.
// *
// * @return AirCycleConfig builder
// */
// public static Builder builder() {
// return new Builder();
// }
//
// /**
// * AirCycleConfig's builder class.
// */
// public static final class Builder {
//
// private boolean passIntentBundleOnCreate;
// @Nullable private Set<Integer> ignoredLifecycleCallbacks;
//
// private Builder() {
//
// }
//
// /**
// * Whether to pass the Activity's starting Intent Extras Bundle if its savedInstanceState is null in onCreate().
// *
// * @param passIntentBundleOnCreate if true, it passes the Activity's starting Intent Extras Bundle only if its
// * savedInstanceState is null in onCreate()
// * @return this Builder, for chaining calls
// */
// public Builder passIntentBundleOnCreate(boolean passIntentBundleOnCreate) {
// this.passIntentBundleOnCreate = passIntentBundleOnCreate;
// return this;
// }
//
// /**
// * Disable passing of an Activity lifecycle callback from {@link ActivityLifecycle}'s constants.
// *
// * @param lifecycleCallback lifecycle callback to ignore
// * @return this Builder, for chaining calls
// */
// public Builder ignoreLifecycleCallback(@ActivityLifecycle.ActivityLifecycleEvent int lifecycleCallback) {
// switch (lifecycleCallback) {
// case ActivityLifecycle.CREATE:
// case ActivityLifecycle.START:
// case ActivityLifecycle.RESUME:
// case ActivityLifecycle.PAUSE:
// case ActivityLifecycle.STOP:
// case ActivityLifecycle.SAVE_INSTANCE_STATE:
// case ActivityLifecycle.DESTROY:
// if (ignoredLifecycleCallbacks == null) {
// ignoredLifecycleCallbacks = new HashSet<>();
// }
//
// ignoredLifecycleCallbacks.add(lifecycleCallback);
// return this;
// default:
// throw new IllegalArgumentException("unknown lifecycle type");
// }
// }
//
// /**
// * Build the AirCycleConfig.
// *
// * @return built AirCycleConfig
// */
// public AirCycleConfig build() {
// return new AirCycleConfig(passIntentBundleOnCreate, ignoredLifecycleCallbacks);
// }
// }
// }
//
// Path: example/src/main/java/com/github/simonpercic/example/aircycle/listener/BundleListener.java
// public class BundleListener extends ActivityBundleAirCycleLogger {
//
// public static final String EXTRA_INT = BundleListener.class.getCanonicalName() + ".extraInt";
//
// private int extra;
//
// @Override
// public void onCreate(Bundle bundle) {
// extra = bundle.getInt(EXTRA_INT);
// }
//
// @Override
// public void onSaveInstanceState(Bundle outState) {
// outState.putInt(EXTRA_INT, extra);
// }
// }
| import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import com.github.simonpercic.aircycle.ActivityLifecycle;
import com.github.simonpercic.aircycle.AirCycle;
import com.github.simonpercic.aircycle.AirCycleConfig;
import com.github.simonpercic.example.aircycle.R;
import com.github.simonpercic.example.aircycle.listener.BundleListener; | package com.github.simonpercic.example.aircycle.activity.a08;
/**
* Example Activity showing usage of a custom AirCycleConfig passed while binding.
*
* @author Simon Percic <a href="https://github.com/simonpercic">https://github.com/simonpercic</a>
*/
public class BindConfigActivity extends AppCompatActivity {
@AirCycle final BundleListener bundleListener = new BundleListener();
@Override
protected void onCreate(Bundle savedInstanceState) {
AirCycleConfig airCycleConfig = AirCycleConfig.builder()
.passIntentBundleOnCreate(true) | // Path: aircycle-api/src/main/java/com/github/simonpercic/aircycle/ActivityLifecycle.java
// public final class ActivityLifecycle {
//
// @IntDef({CREATE, START, RESUME, PAUSE, STOP, SAVE_INSTANCE_STATE, DESTROY})
// @Retention(RetentionPolicy.SOURCE)
// public @interface ActivityLifecycleEvent {
// }
//
// public static final int CREATE = 1;
// public static final int START = 2;
// public static final int RESUME = 3;
// public static final int PAUSE = 4;
// public static final int STOP = 5;
// public static final int SAVE_INSTANCE_STATE = 6;
// public static final int DESTROY = 7;
//
// private ActivityLifecycle() {
// // no instance
// }
// }
//
// Path: aircycle-api/src/main/java/com/github/simonpercic/aircycle/AirCycleConfig.java
// public final class AirCycleConfig {
//
// private final boolean passIntentBundleOnCreate;
// @Nullable private final Set<Integer> ignoredLifecycleCallbacks;
//
// private AirCycleConfig(boolean passIntentBundleOnCreate, @Nullable Set<Integer> ignoredLifecycleCallbacks) {
// this.passIntentBundleOnCreate = passIntentBundleOnCreate;
// this.ignoredLifecycleCallbacks = ignoredLifecycleCallbacks;
// }
//
// boolean passIntentBundleOnCreate() {
// return passIntentBundleOnCreate;
// }
//
// boolean ignoreLifecycleCallback(int lifecycle) {
// return ignoredLifecycleCallbacks != null
// && ignoredLifecycleCallbacks.size() > 0
// && ignoredLifecycleCallbacks.contains(lifecycle);
// }
//
// /**
// * Get a builder for the AirCycleConfig.
// *
// * @return AirCycleConfig builder
// */
// public static Builder builder() {
// return new Builder();
// }
//
// /**
// * AirCycleConfig's builder class.
// */
// public static final class Builder {
//
// private boolean passIntentBundleOnCreate;
// @Nullable private Set<Integer> ignoredLifecycleCallbacks;
//
// private Builder() {
//
// }
//
// /**
// * Whether to pass the Activity's starting Intent Extras Bundle if its savedInstanceState is null in onCreate().
// *
// * @param passIntentBundleOnCreate if true, it passes the Activity's starting Intent Extras Bundle only if its
// * savedInstanceState is null in onCreate()
// * @return this Builder, for chaining calls
// */
// public Builder passIntentBundleOnCreate(boolean passIntentBundleOnCreate) {
// this.passIntentBundleOnCreate = passIntentBundleOnCreate;
// return this;
// }
//
// /**
// * Disable passing of an Activity lifecycle callback from {@link ActivityLifecycle}'s constants.
// *
// * @param lifecycleCallback lifecycle callback to ignore
// * @return this Builder, for chaining calls
// */
// public Builder ignoreLifecycleCallback(@ActivityLifecycle.ActivityLifecycleEvent int lifecycleCallback) {
// switch (lifecycleCallback) {
// case ActivityLifecycle.CREATE:
// case ActivityLifecycle.START:
// case ActivityLifecycle.RESUME:
// case ActivityLifecycle.PAUSE:
// case ActivityLifecycle.STOP:
// case ActivityLifecycle.SAVE_INSTANCE_STATE:
// case ActivityLifecycle.DESTROY:
// if (ignoredLifecycleCallbacks == null) {
// ignoredLifecycleCallbacks = new HashSet<>();
// }
//
// ignoredLifecycleCallbacks.add(lifecycleCallback);
// return this;
// default:
// throw new IllegalArgumentException("unknown lifecycle type");
// }
// }
//
// /**
// * Build the AirCycleConfig.
// *
// * @return built AirCycleConfig
// */
// public AirCycleConfig build() {
// return new AirCycleConfig(passIntentBundleOnCreate, ignoredLifecycleCallbacks);
// }
// }
// }
//
// Path: example/src/main/java/com/github/simonpercic/example/aircycle/listener/BundleListener.java
// public class BundleListener extends ActivityBundleAirCycleLogger {
//
// public static final String EXTRA_INT = BundleListener.class.getCanonicalName() + ".extraInt";
//
// private int extra;
//
// @Override
// public void onCreate(Bundle bundle) {
// extra = bundle.getInt(EXTRA_INT);
// }
//
// @Override
// public void onSaveInstanceState(Bundle outState) {
// outState.putInt(EXTRA_INT, extra);
// }
// }
// Path: example/src/main/java/com/github/simonpercic/example/aircycle/activity/a08/BindConfigActivity.java
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import com.github.simonpercic.aircycle.ActivityLifecycle;
import com.github.simonpercic.aircycle.AirCycle;
import com.github.simonpercic.aircycle.AirCycleConfig;
import com.github.simonpercic.example.aircycle.R;
import com.github.simonpercic.example.aircycle.listener.BundleListener;
package com.github.simonpercic.example.aircycle.activity.a08;
/**
* Example Activity showing usage of a custom AirCycleConfig passed while binding.
*
* @author Simon Percic <a href="https://github.com/simonpercic">https://github.com/simonpercic</a>
*/
public class BindConfigActivity extends AppCompatActivity {
@AirCycle final BundleListener bundleListener = new BundleListener();
@Override
protected void onCreate(Bundle savedInstanceState) {
AirCycleConfig airCycleConfig = AirCycleConfig.builder()
.passIntentBundleOnCreate(true) | .ignoreLifecycleCallback(ActivityLifecycle.RESUME) |
simonpercic/AirCycle | aircycle-compiler/src/main/java/com/github/simonpercic/aircycle/manager/MethodParser.java | // Path: aircycle-compiler/src/main/java/com/github/simonpercic/aircycle/exception/MethodArgumentsException.java
// public class MethodArgumentsException extends Exception {
//
// public MethodArgumentsException(String message) {
// super(message);
// }
// }
//
// Path: aircycle-compiler/src/main/java/com/github/simonpercic/aircycle/model/ListenerMethod.java
// public class ListenerMethod {
//
// private final String methodName;
// private final List<ListenerArgType> args;
//
// public ListenerMethod(String methodName, List<ListenerArgType> args) {
// this.methodName = methodName;
// this.args = ImmutableList.copyOf(args);
// }
//
// public String getMethodName() {
// return methodName;
// }
//
// public List<ListenerArgType> getArgs() {
// return args;
// }
//
// public static Builder builder(ActivityLifecycleType activityLifecycle, String methodName) {
// if (activityLifecycle == null) {
// throw new IllegalArgumentException("activityLifecycle is null");
// }
//
// if (StringUtils.isEmpty(methodName)) {
// throw new IllegalArgumentException("methodName is empty");
// }
//
// return new Builder(activityLifecycle, methodName);
// }
//
// public static class Builder {
//
// private final ActivityLifecycleType lifecycleType;
// private final String methodName;
// private final List<ListenerArgType> args;
//
// private Builder(ActivityLifecycleType lifecycleType, String methodName) {
// this.lifecycleType = lifecycleType;
// this.methodName = methodName;
// this.args = new ArrayList<>(2);
// }
//
// public Builder addBundleArg() throws MethodArgumentsException {
// if (args.contains(ListenerArgType.BUNDLE)) {
// String message = String.format("`bundle` arg already present in `%s`", methodName);
// throw new MethodArgumentsException(message);
// }
//
// if (lifecycleType != ActivityLifecycleType.CREATE && lifecycleType != ActivityLifecycleType.SAVE_INSTANCE_STATE) {
// String message = String.format(
// "`bundle` arg can only be added for `onCreate` or `onSaveInstanceState` in `%s`",
// methodName);
//
// throw new MethodArgumentsException(message);
// }
//
// args.add(ListenerArgType.BUNDLE);
//
// return this;
// }
//
// public Builder addActivityArg() throws MethodArgumentsException {
// if (args.contains(ListenerArgType.ACTIVITY)) {
// String message = String.format("`activity` arg already present in `%s`", methodName);
// throw new MethodArgumentsException(message);
// }
//
// args.add(ListenerArgType.ACTIVITY);
//
// return this;
// }
//
// public ListenerMethod build() {
// return new ListenerMethod(methodName, args);
// }
// }
// }
//
// Path: aircycle-compiler/src/main/java/com/github/simonpercic/aircycle/model/type/ActivityLifecycleType.java
// public enum ActivityLifecycleType {
// CREATE,
// START,
// RESUME,
// PAUSE,
// STOP,
// SAVE_INSTANCE_STATE,
// DESTROY
// }
//
// Path: aircycle-compiler/src/main/java/com/github/simonpercic/aircycle/utils/ElementValidator.java
// public final class ElementValidator {
//
// private ElementValidator() {
// // no instance
// }
//
// public static boolean isPublic(Element element) {
// return hasModifier(element, Modifier.PUBLIC);
// }
//
// public static boolean isPrivate(Element element) {
// return hasModifier(element, Modifier.PRIVATE);
// }
//
// private static boolean hasModifier(Element element, Modifier modifier) {
// return element.getModifiers().contains(modifier);
// }
// }
| import android.app.Activity;
import android.os.Bundle;
import com.github.simonpercic.aircycle.exception.MethodArgumentsException;
import com.github.simonpercic.aircycle.model.ListenerMethod;
import com.github.simonpercic.aircycle.model.type.ActivityLifecycleType;
import com.github.simonpercic.aircycle.utils.ElementValidator;
import com.github.simonpercic.collectionhelper.CollectionHelper;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import javax.inject.Inject;
import javax.inject.Singleton;
import javax.lang.model.element.Element;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.util.ElementFilter;
import javax.lang.model.util.Elements;
import javax.lang.model.util.Types; | package com.github.simonpercic.aircycle.manager;
/**
* Listener method parser.
*
* @author Simon Percic <a href="https://github.com/simonpercic">https://github.com/simonpercic</a>
*/
@Singleton
public class MethodParser {
private final ProcessorLogger logger;
private final Elements elementUtils;
private final Types typeUtils;
@Inject
public MethodParser(ProcessorLogger logger, Elements elementUtils, Types typeUtils) {
this.logger = logger;
this.elementUtils = elementUtils;
this.typeUtils = typeUtils;
}
| // Path: aircycle-compiler/src/main/java/com/github/simonpercic/aircycle/exception/MethodArgumentsException.java
// public class MethodArgumentsException extends Exception {
//
// public MethodArgumentsException(String message) {
// super(message);
// }
// }
//
// Path: aircycle-compiler/src/main/java/com/github/simonpercic/aircycle/model/ListenerMethod.java
// public class ListenerMethod {
//
// private final String methodName;
// private final List<ListenerArgType> args;
//
// public ListenerMethod(String methodName, List<ListenerArgType> args) {
// this.methodName = methodName;
// this.args = ImmutableList.copyOf(args);
// }
//
// public String getMethodName() {
// return methodName;
// }
//
// public List<ListenerArgType> getArgs() {
// return args;
// }
//
// public static Builder builder(ActivityLifecycleType activityLifecycle, String methodName) {
// if (activityLifecycle == null) {
// throw new IllegalArgumentException("activityLifecycle is null");
// }
//
// if (StringUtils.isEmpty(methodName)) {
// throw new IllegalArgumentException("methodName is empty");
// }
//
// return new Builder(activityLifecycle, methodName);
// }
//
// public static class Builder {
//
// private final ActivityLifecycleType lifecycleType;
// private final String methodName;
// private final List<ListenerArgType> args;
//
// private Builder(ActivityLifecycleType lifecycleType, String methodName) {
// this.lifecycleType = lifecycleType;
// this.methodName = methodName;
// this.args = new ArrayList<>(2);
// }
//
// public Builder addBundleArg() throws MethodArgumentsException {
// if (args.contains(ListenerArgType.BUNDLE)) {
// String message = String.format("`bundle` arg already present in `%s`", methodName);
// throw new MethodArgumentsException(message);
// }
//
// if (lifecycleType != ActivityLifecycleType.CREATE && lifecycleType != ActivityLifecycleType.SAVE_INSTANCE_STATE) {
// String message = String.format(
// "`bundle` arg can only be added for `onCreate` or `onSaveInstanceState` in `%s`",
// methodName);
//
// throw new MethodArgumentsException(message);
// }
//
// args.add(ListenerArgType.BUNDLE);
//
// return this;
// }
//
// public Builder addActivityArg() throws MethodArgumentsException {
// if (args.contains(ListenerArgType.ACTIVITY)) {
// String message = String.format("`activity` arg already present in `%s`", methodName);
// throw new MethodArgumentsException(message);
// }
//
// args.add(ListenerArgType.ACTIVITY);
//
// return this;
// }
//
// public ListenerMethod build() {
// return new ListenerMethod(methodName, args);
// }
// }
// }
//
// Path: aircycle-compiler/src/main/java/com/github/simonpercic/aircycle/model/type/ActivityLifecycleType.java
// public enum ActivityLifecycleType {
// CREATE,
// START,
// RESUME,
// PAUSE,
// STOP,
// SAVE_INSTANCE_STATE,
// DESTROY
// }
//
// Path: aircycle-compiler/src/main/java/com/github/simonpercic/aircycle/utils/ElementValidator.java
// public final class ElementValidator {
//
// private ElementValidator() {
// // no instance
// }
//
// public static boolean isPublic(Element element) {
// return hasModifier(element, Modifier.PUBLIC);
// }
//
// public static boolean isPrivate(Element element) {
// return hasModifier(element, Modifier.PRIVATE);
// }
//
// private static boolean hasModifier(Element element, Modifier modifier) {
// return element.getModifiers().contains(modifier);
// }
// }
// Path: aircycle-compiler/src/main/java/com/github/simonpercic/aircycle/manager/MethodParser.java
import android.app.Activity;
import android.os.Bundle;
import com.github.simonpercic.aircycle.exception.MethodArgumentsException;
import com.github.simonpercic.aircycle.model.ListenerMethod;
import com.github.simonpercic.aircycle.model.type.ActivityLifecycleType;
import com.github.simonpercic.aircycle.utils.ElementValidator;
import com.github.simonpercic.collectionhelper.CollectionHelper;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import javax.inject.Inject;
import javax.inject.Singleton;
import javax.lang.model.element.Element;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.util.ElementFilter;
import javax.lang.model.util.Elements;
import javax.lang.model.util.Types;
package com.github.simonpercic.aircycle.manager;
/**
* Listener method parser.
*
* @author Simon Percic <a href="https://github.com/simonpercic">https://github.com/simonpercic</a>
*/
@Singleton
public class MethodParser {
private final ProcessorLogger logger;
private final Elements elementUtils;
private final Types typeUtils;
@Inject
public MethodParser(ProcessorLogger logger, Elements elementUtils, Types typeUtils) {
this.logger = logger;
this.elementUtils = elementUtils;
this.typeUtils = typeUtils;
}
| public Map<ActivityLifecycleType, List<ListenerMethod>> parseLifecycleMethods(TypeElement element, |
simonpercic/AirCycle | aircycle-compiler/src/main/java/com/github/simonpercic/aircycle/manager/MethodParser.java | // Path: aircycle-compiler/src/main/java/com/github/simonpercic/aircycle/exception/MethodArgumentsException.java
// public class MethodArgumentsException extends Exception {
//
// public MethodArgumentsException(String message) {
// super(message);
// }
// }
//
// Path: aircycle-compiler/src/main/java/com/github/simonpercic/aircycle/model/ListenerMethod.java
// public class ListenerMethod {
//
// private final String methodName;
// private final List<ListenerArgType> args;
//
// public ListenerMethod(String methodName, List<ListenerArgType> args) {
// this.methodName = methodName;
// this.args = ImmutableList.copyOf(args);
// }
//
// public String getMethodName() {
// return methodName;
// }
//
// public List<ListenerArgType> getArgs() {
// return args;
// }
//
// public static Builder builder(ActivityLifecycleType activityLifecycle, String methodName) {
// if (activityLifecycle == null) {
// throw new IllegalArgumentException("activityLifecycle is null");
// }
//
// if (StringUtils.isEmpty(methodName)) {
// throw new IllegalArgumentException("methodName is empty");
// }
//
// return new Builder(activityLifecycle, methodName);
// }
//
// public static class Builder {
//
// private final ActivityLifecycleType lifecycleType;
// private final String methodName;
// private final List<ListenerArgType> args;
//
// private Builder(ActivityLifecycleType lifecycleType, String methodName) {
// this.lifecycleType = lifecycleType;
// this.methodName = methodName;
// this.args = new ArrayList<>(2);
// }
//
// public Builder addBundleArg() throws MethodArgumentsException {
// if (args.contains(ListenerArgType.BUNDLE)) {
// String message = String.format("`bundle` arg already present in `%s`", methodName);
// throw new MethodArgumentsException(message);
// }
//
// if (lifecycleType != ActivityLifecycleType.CREATE && lifecycleType != ActivityLifecycleType.SAVE_INSTANCE_STATE) {
// String message = String.format(
// "`bundle` arg can only be added for `onCreate` or `onSaveInstanceState` in `%s`",
// methodName);
//
// throw new MethodArgumentsException(message);
// }
//
// args.add(ListenerArgType.BUNDLE);
//
// return this;
// }
//
// public Builder addActivityArg() throws MethodArgumentsException {
// if (args.contains(ListenerArgType.ACTIVITY)) {
// String message = String.format("`activity` arg already present in `%s`", methodName);
// throw new MethodArgumentsException(message);
// }
//
// args.add(ListenerArgType.ACTIVITY);
//
// return this;
// }
//
// public ListenerMethod build() {
// return new ListenerMethod(methodName, args);
// }
// }
// }
//
// Path: aircycle-compiler/src/main/java/com/github/simonpercic/aircycle/model/type/ActivityLifecycleType.java
// public enum ActivityLifecycleType {
// CREATE,
// START,
// RESUME,
// PAUSE,
// STOP,
// SAVE_INSTANCE_STATE,
// DESTROY
// }
//
// Path: aircycle-compiler/src/main/java/com/github/simonpercic/aircycle/utils/ElementValidator.java
// public final class ElementValidator {
//
// private ElementValidator() {
// // no instance
// }
//
// public static boolean isPublic(Element element) {
// return hasModifier(element, Modifier.PUBLIC);
// }
//
// public static boolean isPrivate(Element element) {
// return hasModifier(element, Modifier.PRIVATE);
// }
//
// private static boolean hasModifier(Element element, Modifier modifier) {
// return element.getModifiers().contains(modifier);
// }
// }
| import android.app.Activity;
import android.os.Bundle;
import com.github.simonpercic.aircycle.exception.MethodArgumentsException;
import com.github.simonpercic.aircycle.model.ListenerMethod;
import com.github.simonpercic.aircycle.model.type.ActivityLifecycleType;
import com.github.simonpercic.aircycle.utils.ElementValidator;
import com.github.simonpercic.collectionhelper.CollectionHelper;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import javax.inject.Inject;
import javax.inject.Singleton;
import javax.lang.model.element.Element;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.util.ElementFilter;
import javax.lang.model.util.Elements;
import javax.lang.model.util.Types; | package com.github.simonpercic.aircycle.manager;
/**
* Listener method parser.
*
* @author Simon Percic <a href="https://github.com/simonpercic">https://github.com/simonpercic</a>
*/
@Singleton
public class MethodParser {
private final ProcessorLogger logger;
private final Elements elementUtils;
private final Types typeUtils;
@Inject
public MethodParser(ProcessorLogger logger, Elements elementUtils, Types typeUtils) {
this.logger = logger;
this.elementUtils = elementUtils;
this.typeUtils = typeUtils;
}
| // Path: aircycle-compiler/src/main/java/com/github/simonpercic/aircycle/exception/MethodArgumentsException.java
// public class MethodArgumentsException extends Exception {
//
// public MethodArgumentsException(String message) {
// super(message);
// }
// }
//
// Path: aircycle-compiler/src/main/java/com/github/simonpercic/aircycle/model/ListenerMethod.java
// public class ListenerMethod {
//
// private final String methodName;
// private final List<ListenerArgType> args;
//
// public ListenerMethod(String methodName, List<ListenerArgType> args) {
// this.methodName = methodName;
// this.args = ImmutableList.copyOf(args);
// }
//
// public String getMethodName() {
// return methodName;
// }
//
// public List<ListenerArgType> getArgs() {
// return args;
// }
//
// public static Builder builder(ActivityLifecycleType activityLifecycle, String methodName) {
// if (activityLifecycle == null) {
// throw new IllegalArgumentException("activityLifecycle is null");
// }
//
// if (StringUtils.isEmpty(methodName)) {
// throw new IllegalArgumentException("methodName is empty");
// }
//
// return new Builder(activityLifecycle, methodName);
// }
//
// public static class Builder {
//
// private final ActivityLifecycleType lifecycleType;
// private final String methodName;
// private final List<ListenerArgType> args;
//
// private Builder(ActivityLifecycleType lifecycleType, String methodName) {
// this.lifecycleType = lifecycleType;
// this.methodName = methodName;
// this.args = new ArrayList<>(2);
// }
//
// public Builder addBundleArg() throws MethodArgumentsException {
// if (args.contains(ListenerArgType.BUNDLE)) {
// String message = String.format("`bundle` arg already present in `%s`", methodName);
// throw new MethodArgumentsException(message);
// }
//
// if (lifecycleType != ActivityLifecycleType.CREATE && lifecycleType != ActivityLifecycleType.SAVE_INSTANCE_STATE) {
// String message = String.format(
// "`bundle` arg can only be added for `onCreate` or `onSaveInstanceState` in `%s`",
// methodName);
//
// throw new MethodArgumentsException(message);
// }
//
// args.add(ListenerArgType.BUNDLE);
//
// return this;
// }
//
// public Builder addActivityArg() throws MethodArgumentsException {
// if (args.contains(ListenerArgType.ACTIVITY)) {
// String message = String.format("`activity` arg already present in `%s`", methodName);
// throw new MethodArgumentsException(message);
// }
//
// args.add(ListenerArgType.ACTIVITY);
//
// return this;
// }
//
// public ListenerMethod build() {
// return new ListenerMethod(methodName, args);
// }
// }
// }
//
// Path: aircycle-compiler/src/main/java/com/github/simonpercic/aircycle/model/type/ActivityLifecycleType.java
// public enum ActivityLifecycleType {
// CREATE,
// START,
// RESUME,
// PAUSE,
// STOP,
// SAVE_INSTANCE_STATE,
// DESTROY
// }
//
// Path: aircycle-compiler/src/main/java/com/github/simonpercic/aircycle/utils/ElementValidator.java
// public final class ElementValidator {
//
// private ElementValidator() {
// // no instance
// }
//
// public static boolean isPublic(Element element) {
// return hasModifier(element, Modifier.PUBLIC);
// }
//
// public static boolean isPrivate(Element element) {
// return hasModifier(element, Modifier.PRIVATE);
// }
//
// private static boolean hasModifier(Element element, Modifier modifier) {
// return element.getModifiers().contains(modifier);
// }
// }
// Path: aircycle-compiler/src/main/java/com/github/simonpercic/aircycle/manager/MethodParser.java
import android.app.Activity;
import android.os.Bundle;
import com.github.simonpercic.aircycle.exception.MethodArgumentsException;
import com.github.simonpercic.aircycle.model.ListenerMethod;
import com.github.simonpercic.aircycle.model.type.ActivityLifecycleType;
import com.github.simonpercic.aircycle.utils.ElementValidator;
import com.github.simonpercic.collectionhelper.CollectionHelper;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import javax.inject.Inject;
import javax.inject.Singleton;
import javax.lang.model.element.Element;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.util.ElementFilter;
import javax.lang.model.util.Elements;
import javax.lang.model.util.Types;
package com.github.simonpercic.aircycle.manager;
/**
* Listener method parser.
*
* @author Simon Percic <a href="https://github.com/simonpercic">https://github.com/simonpercic</a>
*/
@Singleton
public class MethodParser {
private final ProcessorLogger logger;
private final Elements elementUtils;
private final Types typeUtils;
@Inject
public MethodParser(ProcessorLogger logger, Elements elementUtils, Types typeUtils) {
this.logger = logger;
this.elementUtils = elementUtils;
this.typeUtils = typeUtils;
}
| public Map<ActivityLifecycleType, List<ListenerMethod>> parseLifecycleMethods(TypeElement element, |
simonpercic/AirCycle | aircycle-compiler/src/main/java/com/github/simonpercic/aircycle/manager/MethodParser.java | // Path: aircycle-compiler/src/main/java/com/github/simonpercic/aircycle/exception/MethodArgumentsException.java
// public class MethodArgumentsException extends Exception {
//
// public MethodArgumentsException(String message) {
// super(message);
// }
// }
//
// Path: aircycle-compiler/src/main/java/com/github/simonpercic/aircycle/model/ListenerMethod.java
// public class ListenerMethod {
//
// private final String methodName;
// private final List<ListenerArgType> args;
//
// public ListenerMethod(String methodName, List<ListenerArgType> args) {
// this.methodName = methodName;
// this.args = ImmutableList.copyOf(args);
// }
//
// public String getMethodName() {
// return methodName;
// }
//
// public List<ListenerArgType> getArgs() {
// return args;
// }
//
// public static Builder builder(ActivityLifecycleType activityLifecycle, String methodName) {
// if (activityLifecycle == null) {
// throw new IllegalArgumentException("activityLifecycle is null");
// }
//
// if (StringUtils.isEmpty(methodName)) {
// throw new IllegalArgumentException("methodName is empty");
// }
//
// return new Builder(activityLifecycle, methodName);
// }
//
// public static class Builder {
//
// private final ActivityLifecycleType lifecycleType;
// private final String methodName;
// private final List<ListenerArgType> args;
//
// private Builder(ActivityLifecycleType lifecycleType, String methodName) {
// this.lifecycleType = lifecycleType;
// this.methodName = methodName;
// this.args = new ArrayList<>(2);
// }
//
// public Builder addBundleArg() throws MethodArgumentsException {
// if (args.contains(ListenerArgType.BUNDLE)) {
// String message = String.format("`bundle` arg already present in `%s`", methodName);
// throw new MethodArgumentsException(message);
// }
//
// if (lifecycleType != ActivityLifecycleType.CREATE && lifecycleType != ActivityLifecycleType.SAVE_INSTANCE_STATE) {
// String message = String.format(
// "`bundle` arg can only be added for `onCreate` or `onSaveInstanceState` in `%s`",
// methodName);
//
// throw new MethodArgumentsException(message);
// }
//
// args.add(ListenerArgType.BUNDLE);
//
// return this;
// }
//
// public Builder addActivityArg() throws MethodArgumentsException {
// if (args.contains(ListenerArgType.ACTIVITY)) {
// String message = String.format("`activity` arg already present in `%s`", methodName);
// throw new MethodArgumentsException(message);
// }
//
// args.add(ListenerArgType.ACTIVITY);
//
// return this;
// }
//
// public ListenerMethod build() {
// return new ListenerMethod(methodName, args);
// }
// }
// }
//
// Path: aircycle-compiler/src/main/java/com/github/simonpercic/aircycle/model/type/ActivityLifecycleType.java
// public enum ActivityLifecycleType {
// CREATE,
// START,
// RESUME,
// PAUSE,
// STOP,
// SAVE_INSTANCE_STATE,
// DESTROY
// }
//
// Path: aircycle-compiler/src/main/java/com/github/simonpercic/aircycle/utils/ElementValidator.java
// public final class ElementValidator {
//
// private ElementValidator() {
// // no instance
// }
//
// public static boolean isPublic(Element element) {
// return hasModifier(element, Modifier.PUBLIC);
// }
//
// public static boolean isPrivate(Element element) {
// return hasModifier(element, Modifier.PRIVATE);
// }
//
// private static boolean hasModifier(Element element, Modifier modifier) {
// return element.getModifiers().contains(modifier);
// }
// }
| import android.app.Activity;
import android.os.Bundle;
import com.github.simonpercic.aircycle.exception.MethodArgumentsException;
import com.github.simonpercic.aircycle.model.ListenerMethod;
import com.github.simonpercic.aircycle.model.type.ActivityLifecycleType;
import com.github.simonpercic.aircycle.utils.ElementValidator;
import com.github.simonpercic.collectionhelper.CollectionHelper;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import javax.inject.Inject;
import javax.inject.Singleton;
import javax.lang.model.element.Element;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.util.ElementFilter;
import javax.lang.model.util.Elements;
import javax.lang.model.util.Types; | String validMethods = "Valid lifecycle methods are: \n"
+ "onCreate() / onActivityCreated(), \n"
+ "onStart() / onActivityStarted(), \n"
+ "onResume() / onActivityResumed(), \n"
+ "onPause() / onActivityPaused(), \n"
+ "onStop() / onActivityStopped(), \n"
+ "onSaveInstanceState() / onActivitySaveInstanceState(), \n"
+ "onDestroy() / onActivityDestroyed()";
String message = String.format("`%s` does not contain any Activity lifecycle methods. %s",
element.getQualifiedName(), validMethods);
logger.w(message, element);
}
return lifecycleMethods;
}
private LifecycleMethod parseLifecycleMethod(ExecutableElement method, TypeElement enclosingElement) {
if (method == null) {
throw new IllegalArgumentException("method is null");
}
String methodName = method.getSimpleName().toString();
ActivityLifecycleType activityLifecycle = parseLifecycle(methodName);
if (activityLifecycle == null) {
return null;
}
| // Path: aircycle-compiler/src/main/java/com/github/simonpercic/aircycle/exception/MethodArgumentsException.java
// public class MethodArgumentsException extends Exception {
//
// public MethodArgumentsException(String message) {
// super(message);
// }
// }
//
// Path: aircycle-compiler/src/main/java/com/github/simonpercic/aircycle/model/ListenerMethod.java
// public class ListenerMethod {
//
// private final String methodName;
// private final List<ListenerArgType> args;
//
// public ListenerMethod(String methodName, List<ListenerArgType> args) {
// this.methodName = methodName;
// this.args = ImmutableList.copyOf(args);
// }
//
// public String getMethodName() {
// return methodName;
// }
//
// public List<ListenerArgType> getArgs() {
// return args;
// }
//
// public static Builder builder(ActivityLifecycleType activityLifecycle, String methodName) {
// if (activityLifecycle == null) {
// throw new IllegalArgumentException("activityLifecycle is null");
// }
//
// if (StringUtils.isEmpty(methodName)) {
// throw new IllegalArgumentException("methodName is empty");
// }
//
// return new Builder(activityLifecycle, methodName);
// }
//
// public static class Builder {
//
// private final ActivityLifecycleType lifecycleType;
// private final String methodName;
// private final List<ListenerArgType> args;
//
// private Builder(ActivityLifecycleType lifecycleType, String methodName) {
// this.lifecycleType = lifecycleType;
// this.methodName = methodName;
// this.args = new ArrayList<>(2);
// }
//
// public Builder addBundleArg() throws MethodArgumentsException {
// if (args.contains(ListenerArgType.BUNDLE)) {
// String message = String.format("`bundle` arg already present in `%s`", methodName);
// throw new MethodArgumentsException(message);
// }
//
// if (lifecycleType != ActivityLifecycleType.CREATE && lifecycleType != ActivityLifecycleType.SAVE_INSTANCE_STATE) {
// String message = String.format(
// "`bundle` arg can only be added for `onCreate` or `onSaveInstanceState` in `%s`",
// methodName);
//
// throw new MethodArgumentsException(message);
// }
//
// args.add(ListenerArgType.BUNDLE);
//
// return this;
// }
//
// public Builder addActivityArg() throws MethodArgumentsException {
// if (args.contains(ListenerArgType.ACTIVITY)) {
// String message = String.format("`activity` arg already present in `%s`", methodName);
// throw new MethodArgumentsException(message);
// }
//
// args.add(ListenerArgType.ACTIVITY);
//
// return this;
// }
//
// public ListenerMethod build() {
// return new ListenerMethod(methodName, args);
// }
// }
// }
//
// Path: aircycle-compiler/src/main/java/com/github/simonpercic/aircycle/model/type/ActivityLifecycleType.java
// public enum ActivityLifecycleType {
// CREATE,
// START,
// RESUME,
// PAUSE,
// STOP,
// SAVE_INSTANCE_STATE,
// DESTROY
// }
//
// Path: aircycle-compiler/src/main/java/com/github/simonpercic/aircycle/utils/ElementValidator.java
// public final class ElementValidator {
//
// private ElementValidator() {
// // no instance
// }
//
// public static boolean isPublic(Element element) {
// return hasModifier(element, Modifier.PUBLIC);
// }
//
// public static boolean isPrivate(Element element) {
// return hasModifier(element, Modifier.PRIVATE);
// }
//
// private static boolean hasModifier(Element element, Modifier modifier) {
// return element.getModifiers().contains(modifier);
// }
// }
// Path: aircycle-compiler/src/main/java/com/github/simonpercic/aircycle/manager/MethodParser.java
import android.app.Activity;
import android.os.Bundle;
import com.github.simonpercic.aircycle.exception.MethodArgumentsException;
import com.github.simonpercic.aircycle.model.ListenerMethod;
import com.github.simonpercic.aircycle.model.type.ActivityLifecycleType;
import com.github.simonpercic.aircycle.utils.ElementValidator;
import com.github.simonpercic.collectionhelper.CollectionHelper;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import javax.inject.Inject;
import javax.inject.Singleton;
import javax.lang.model.element.Element;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.util.ElementFilter;
import javax.lang.model.util.Elements;
import javax.lang.model.util.Types;
String validMethods = "Valid lifecycle methods are: \n"
+ "onCreate() / onActivityCreated(), \n"
+ "onStart() / onActivityStarted(), \n"
+ "onResume() / onActivityResumed(), \n"
+ "onPause() / onActivityPaused(), \n"
+ "onStop() / onActivityStopped(), \n"
+ "onSaveInstanceState() / onActivitySaveInstanceState(), \n"
+ "onDestroy() / onActivityDestroyed()";
String message = String.format("`%s` does not contain any Activity lifecycle methods. %s",
element.getQualifiedName(), validMethods);
logger.w(message, element);
}
return lifecycleMethods;
}
private LifecycleMethod parseLifecycleMethod(ExecutableElement method, TypeElement enclosingElement) {
if (method == null) {
throw new IllegalArgumentException("method is null");
}
String methodName = method.getSimpleName().toString();
ActivityLifecycleType activityLifecycle = parseLifecycle(methodName);
if (activityLifecycle == null) {
return null;
}
| if (!ElementValidator.isPublic(method)) { |
simonpercic/AirCycle | aircycle-compiler/src/main/java/com/github/simonpercic/aircycle/manager/MethodParser.java | // Path: aircycle-compiler/src/main/java/com/github/simonpercic/aircycle/exception/MethodArgumentsException.java
// public class MethodArgumentsException extends Exception {
//
// public MethodArgumentsException(String message) {
// super(message);
// }
// }
//
// Path: aircycle-compiler/src/main/java/com/github/simonpercic/aircycle/model/ListenerMethod.java
// public class ListenerMethod {
//
// private final String methodName;
// private final List<ListenerArgType> args;
//
// public ListenerMethod(String methodName, List<ListenerArgType> args) {
// this.methodName = methodName;
// this.args = ImmutableList.copyOf(args);
// }
//
// public String getMethodName() {
// return methodName;
// }
//
// public List<ListenerArgType> getArgs() {
// return args;
// }
//
// public static Builder builder(ActivityLifecycleType activityLifecycle, String methodName) {
// if (activityLifecycle == null) {
// throw new IllegalArgumentException("activityLifecycle is null");
// }
//
// if (StringUtils.isEmpty(methodName)) {
// throw new IllegalArgumentException("methodName is empty");
// }
//
// return new Builder(activityLifecycle, methodName);
// }
//
// public static class Builder {
//
// private final ActivityLifecycleType lifecycleType;
// private final String methodName;
// private final List<ListenerArgType> args;
//
// private Builder(ActivityLifecycleType lifecycleType, String methodName) {
// this.lifecycleType = lifecycleType;
// this.methodName = methodName;
// this.args = new ArrayList<>(2);
// }
//
// public Builder addBundleArg() throws MethodArgumentsException {
// if (args.contains(ListenerArgType.BUNDLE)) {
// String message = String.format("`bundle` arg already present in `%s`", methodName);
// throw new MethodArgumentsException(message);
// }
//
// if (lifecycleType != ActivityLifecycleType.CREATE && lifecycleType != ActivityLifecycleType.SAVE_INSTANCE_STATE) {
// String message = String.format(
// "`bundle` arg can only be added for `onCreate` or `onSaveInstanceState` in `%s`",
// methodName);
//
// throw new MethodArgumentsException(message);
// }
//
// args.add(ListenerArgType.BUNDLE);
//
// return this;
// }
//
// public Builder addActivityArg() throws MethodArgumentsException {
// if (args.contains(ListenerArgType.ACTIVITY)) {
// String message = String.format("`activity` arg already present in `%s`", methodName);
// throw new MethodArgumentsException(message);
// }
//
// args.add(ListenerArgType.ACTIVITY);
//
// return this;
// }
//
// public ListenerMethod build() {
// return new ListenerMethod(methodName, args);
// }
// }
// }
//
// Path: aircycle-compiler/src/main/java/com/github/simonpercic/aircycle/model/type/ActivityLifecycleType.java
// public enum ActivityLifecycleType {
// CREATE,
// START,
// RESUME,
// PAUSE,
// STOP,
// SAVE_INSTANCE_STATE,
// DESTROY
// }
//
// Path: aircycle-compiler/src/main/java/com/github/simonpercic/aircycle/utils/ElementValidator.java
// public final class ElementValidator {
//
// private ElementValidator() {
// // no instance
// }
//
// public static boolean isPublic(Element element) {
// return hasModifier(element, Modifier.PUBLIC);
// }
//
// public static boolean isPrivate(Element element) {
// return hasModifier(element, Modifier.PRIVATE);
// }
//
// private static boolean hasModifier(Element element, Modifier modifier) {
// return element.getModifiers().contains(modifier);
// }
// }
| import android.app.Activity;
import android.os.Bundle;
import com.github.simonpercic.aircycle.exception.MethodArgumentsException;
import com.github.simonpercic.aircycle.model.ListenerMethod;
import com.github.simonpercic.aircycle.model.type.ActivityLifecycleType;
import com.github.simonpercic.aircycle.utils.ElementValidator;
import com.github.simonpercic.collectionhelper.CollectionHelper;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import javax.inject.Inject;
import javax.inject.Singleton;
import javax.lang.model.element.Element;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.util.ElementFilter;
import javax.lang.model.util.Elements;
import javax.lang.model.util.Types; | enclosingElement.getQualifiedName());
logger.e(message, enclosingElement);
return null;
}
ListenerMethod.Builder builder = ListenerMethod.builder(activityLifecycle, methodName);
List<? extends VariableElement> parameters = method.getParameters();
if (!CollectionHelper.isEmpty(parameters)) {
TypeMirror bundleType = elementUtils.getTypeElement(Bundle.class.getCanonicalName()).asType();
TypeMirror activityType = elementUtils.getTypeElement(Activity.class.getCanonicalName()).asType();
for (int i = 0; i < parameters.size(); i++) {
VariableElement parameter = parameters.get(i);
TypeMirror paramType = parameter.asType();
try {
if (typeUtils.isSubtype(paramType, activityType)) {
builder.addActivityArg();
} else if (typeUtils.isSameType(paramType, bundleType)) {
builder.addBundleArg();
} else {
String message = String.format(
"Invalid method argument of type `%s` at index `%s` in `%s",
paramType.toString(), i, methodName);
logger.e(message, method);
} | // Path: aircycle-compiler/src/main/java/com/github/simonpercic/aircycle/exception/MethodArgumentsException.java
// public class MethodArgumentsException extends Exception {
//
// public MethodArgumentsException(String message) {
// super(message);
// }
// }
//
// Path: aircycle-compiler/src/main/java/com/github/simonpercic/aircycle/model/ListenerMethod.java
// public class ListenerMethod {
//
// private final String methodName;
// private final List<ListenerArgType> args;
//
// public ListenerMethod(String methodName, List<ListenerArgType> args) {
// this.methodName = methodName;
// this.args = ImmutableList.copyOf(args);
// }
//
// public String getMethodName() {
// return methodName;
// }
//
// public List<ListenerArgType> getArgs() {
// return args;
// }
//
// public static Builder builder(ActivityLifecycleType activityLifecycle, String methodName) {
// if (activityLifecycle == null) {
// throw new IllegalArgumentException("activityLifecycle is null");
// }
//
// if (StringUtils.isEmpty(methodName)) {
// throw new IllegalArgumentException("methodName is empty");
// }
//
// return new Builder(activityLifecycle, methodName);
// }
//
// public static class Builder {
//
// private final ActivityLifecycleType lifecycleType;
// private final String methodName;
// private final List<ListenerArgType> args;
//
// private Builder(ActivityLifecycleType lifecycleType, String methodName) {
// this.lifecycleType = lifecycleType;
// this.methodName = methodName;
// this.args = new ArrayList<>(2);
// }
//
// public Builder addBundleArg() throws MethodArgumentsException {
// if (args.contains(ListenerArgType.BUNDLE)) {
// String message = String.format("`bundle` arg already present in `%s`", methodName);
// throw new MethodArgumentsException(message);
// }
//
// if (lifecycleType != ActivityLifecycleType.CREATE && lifecycleType != ActivityLifecycleType.SAVE_INSTANCE_STATE) {
// String message = String.format(
// "`bundle` arg can only be added for `onCreate` or `onSaveInstanceState` in `%s`",
// methodName);
//
// throw new MethodArgumentsException(message);
// }
//
// args.add(ListenerArgType.BUNDLE);
//
// return this;
// }
//
// public Builder addActivityArg() throws MethodArgumentsException {
// if (args.contains(ListenerArgType.ACTIVITY)) {
// String message = String.format("`activity` arg already present in `%s`", methodName);
// throw new MethodArgumentsException(message);
// }
//
// args.add(ListenerArgType.ACTIVITY);
//
// return this;
// }
//
// public ListenerMethod build() {
// return new ListenerMethod(methodName, args);
// }
// }
// }
//
// Path: aircycle-compiler/src/main/java/com/github/simonpercic/aircycle/model/type/ActivityLifecycleType.java
// public enum ActivityLifecycleType {
// CREATE,
// START,
// RESUME,
// PAUSE,
// STOP,
// SAVE_INSTANCE_STATE,
// DESTROY
// }
//
// Path: aircycle-compiler/src/main/java/com/github/simonpercic/aircycle/utils/ElementValidator.java
// public final class ElementValidator {
//
// private ElementValidator() {
// // no instance
// }
//
// public static boolean isPublic(Element element) {
// return hasModifier(element, Modifier.PUBLIC);
// }
//
// public static boolean isPrivate(Element element) {
// return hasModifier(element, Modifier.PRIVATE);
// }
//
// private static boolean hasModifier(Element element, Modifier modifier) {
// return element.getModifiers().contains(modifier);
// }
// }
// Path: aircycle-compiler/src/main/java/com/github/simonpercic/aircycle/manager/MethodParser.java
import android.app.Activity;
import android.os.Bundle;
import com.github.simonpercic.aircycle.exception.MethodArgumentsException;
import com.github.simonpercic.aircycle.model.ListenerMethod;
import com.github.simonpercic.aircycle.model.type.ActivityLifecycleType;
import com.github.simonpercic.aircycle.utils.ElementValidator;
import com.github.simonpercic.collectionhelper.CollectionHelper;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import javax.inject.Inject;
import javax.inject.Singleton;
import javax.lang.model.element.Element;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.util.ElementFilter;
import javax.lang.model.util.Elements;
import javax.lang.model.util.Types;
enclosingElement.getQualifiedName());
logger.e(message, enclosingElement);
return null;
}
ListenerMethod.Builder builder = ListenerMethod.builder(activityLifecycle, methodName);
List<? extends VariableElement> parameters = method.getParameters();
if (!CollectionHelper.isEmpty(parameters)) {
TypeMirror bundleType = elementUtils.getTypeElement(Bundle.class.getCanonicalName()).asType();
TypeMirror activityType = elementUtils.getTypeElement(Activity.class.getCanonicalName()).asType();
for (int i = 0; i < parameters.size(); i++) {
VariableElement parameter = parameters.get(i);
TypeMirror paramType = parameter.asType();
try {
if (typeUtils.isSubtype(paramType, activityType)) {
builder.addActivityArg();
} else if (typeUtils.isSameType(paramType, bundleType)) {
builder.addBundleArg();
} else {
String message = String.format(
"Invalid method argument of type `%s` at index `%s` in `%s",
paramType.toString(), i, methodName);
logger.e(message, method);
} | } catch (MethodArgumentsException e) { |
simonpercic/AirCycle | example-mvp/src/main/java/com/github/simonpercic/mvp/example/aircycle/ui/main/MainActivity.java | // Path: example-mvp/src/main/java/com/github/simonpercic/mvp/example/aircycle/ui/countdown/CountdownActivity.java
// public class CountdownActivity extends AppCompatActivity implements CountdownMvp.View {
//
// @AirCycle @Inject CountdownMvp.Presenter presenter;
//
// @BindView(R.id.tv_value) TextView tvValue;
// @BindView(R.id.btn_close) View btnClose;
// @BindView(R.id.coordinator_layout) CoordinatorLayout coordinatorLayout;
//
// // region Activity callbacks
//
// @Override protected void onCreate(@Nullable Bundle savedInstanceState) {
// CountdownActivityAirCycle.bind(this);
// super.onCreate(savedInstanceState);
//
// setContentView(R.layout.activity_countdown);
// ButterKnife.bind(this);
//
// DaggerCountdownComponent.builder()
// .countdownModule(new CountdownModule(this))
// .build()
// .inject(this);
// }
//
// // endregion Activity callbacks
//
// // region View impl
//
// @Override public void showStart() {
// tvValue.setText(R.string.countdown_state_start);
// }
//
// @Override public void showValue(String value) {
// tvValue.setText(value);
// }
//
// @Override public void showComplete() {
// tvValue.setText(R.string.countdown_state_complete);
// }
//
// @Override public void showError(String message) {
// Snackbar.make(coordinatorLayout, message, Snackbar.LENGTH_LONG).show();
// }
//
// @Override public void showCloseButton() {
// btnClose.setVisibility(View.VISIBLE);
// }
//
// @Override public void hideCloseButton() {
// btnClose.setVisibility(View.GONE);
// }
//
// // endregion View impl
//
// // region Click listeners
//
// @OnClick(R.id.btn_close) void onBtnCloseClicked() {
// finish();
// }
//
// // endregion Click listeners
//
// @NonNull public static Intent getIntent(@NonNull Context context) {
// return new Intent(context, CountdownActivity.class);
// }
// }
| import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.github.simonpercic.mvp.example.aircycle.R;
import com.github.simonpercic.mvp.example.aircycle.ui.countdown.CountdownActivity;
import butterknife.ButterKnife;
import butterknife.OnClick; | package com.github.simonpercic.mvp.example.aircycle.ui.main;
/**
* Main MVP example app Activity.
*
* @author Simon Percic <a href="https://github.com/simonpercic">https://github.com/simonpercic</a>
*/
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
}
@OnClick(R.id.btn_open_countdown) void onBtnOpenCountdownClicked() { | // Path: example-mvp/src/main/java/com/github/simonpercic/mvp/example/aircycle/ui/countdown/CountdownActivity.java
// public class CountdownActivity extends AppCompatActivity implements CountdownMvp.View {
//
// @AirCycle @Inject CountdownMvp.Presenter presenter;
//
// @BindView(R.id.tv_value) TextView tvValue;
// @BindView(R.id.btn_close) View btnClose;
// @BindView(R.id.coordinator_layout) CoordinatorLayout coordinatorLayout;
//
// // region Activity callbacks
//
// @Override protected void onCreate(@Nullable Bundle savedInstanceState) {
// CountdownActivityAirCycle.bind(this);
// super.onCreate(savedInstanceState);
//
// setContentView(R.layout.activity_countdown);
// ButterKnife.bind(this);
//
// DaggerCountdownComponent.builder()
// .countdownModule(new CountdownModule(this))
// .build()
// .inject(this);
// }
//
// // endregion Activity callbacks
//
// // region View impl
//
// @Override public void showStart() {
// tvValue.setText(R.string.countdown_state_start);
// }
//
// @Override public void showValue(String value) {
// tvValue.setText(value);
// }
//
// @Override public void showComplete() {
// tvValue.setText(R.string.countdown_state_complete);
// }
//
// @Override public void showError(String message) {
// Snackbar.make(coordinatorLayout, message, Snackbar.LENGTH_LONG).show();
// }
//
// @Override public void showCloseButton() {
// btnClose.setVisibility(View.VISIBLE);
// }
//
// @Override public void hideCloseButton() {
// btnClose.setVisibility(View.GONE);
// }
//
// // endregion View impl
//
// // region Click listeners
//
// @OnClick(R.id.btn_close) void onBtnCloseClicked() {
// finish();
// }
//
// // endregion Click listeners
//
// @NonNull public static Intent getIntent(@NonNull Context context) {
// return new Intent(context, CountdownActivity.class);
// }
// }
// Path: example-mvp/src/main/java/com/github/simonpercic/mvp/example/aircycle/ui/main/MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.github.simonpercic.mvp.example.aircycle.R;
import com.github.simonpercic.mvp.example.aircycle.ui.countdown.CountdownActivity;
import butterknife.ButterKnife;
import butterknife.OnClick;
package com.github.simonpercic.mvp.example.aircycle.ui.main;
/**
* Main MVP example app Activity.
*
* @author Simon Percic <a href="https://github.com/simonpercic">https://github.com/simonpercic</a>
*/
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
}
@OnClick(R.id.btn_open_countdown) void onBtnOpenCountdownClicked() { | startActivity(CountdownActivity.getIntent(this)); |
simonpercic/AirCycle | aircycle-compiler/src/main/java/com/github/simonpercic/aircycle/manager/ActivityLifecycleConverter.java | // Path: aircycle-api/src/main/java/com/github/simonpercic/aircycle/ActivityLifecycle.java
// public final class ActivityLifecycle {
//
// @IntDef({CREATE, START, RESUME, PAUSE, STOP, SAVE_INSTANCE_STATE, DESTROY})
// @Retention(RetentionPolicy.SOURCE)
// public @interface ActivityLifecycleEvent {
// }
//
// public static final int CREATE = 1;
// public static final int START = 2;
// public static final int RESUME = 3;
// public static final int PAUSE = 4;
// public static final int STOP = 5;
// public static final int SAVE_INSTANCE_STATE = 6;
// public static final int DESTROY = 7;
//
// private ActivityLifecycle() {
// // no instance
// }
// }
//
// Path: aircycle-compiler/src/main/java/com/github/simonpercic/aircycle/model/type/ActivityLifecycleType.java
// public enum ActivityLifecycleType {
// CREATE,
// START,
// RESUME,
// PAUSE,
// STOP,
// SAVE_INSTANCE_STATE,
// DESTROY
// }
| import com.github.simonpercic.aircycle.ActivityLifecycle;
import com.github.simonpercic.aircycle.model.type.ActivityLifecycleType;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import javax.inject.Inject;
import javax.inject.Singleton;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement; | package com.github.simonpercic.aircycle.manager;
/**
* Activity lifecycle converter manager.
*
* @author Simon Percic <a href="https://github.com/simonpercic">https://github.com/simonpercic</a>
*/
@Singleton
public class ActivityLifecycleConverter {
private final ProcessorLogger logger;
@Inject
public ActivityLifecycleConverter(ProcessorLogger logger) {
this.logger = logger;
}
| // Path: aircycle-api/src/main/java/com/github/simonpercic/aircycle/ActivityLifecycle.java
// public final class ActivityLifecycle {
//
// @IntDef({CREATE, START, RESUME, PAUSE, STOP, SAVE_INSTANCE_STATE, DESTROY})
// @Retention(RetentionPolicy.SOURCE)
// public @interface ActivityLifecycleEvent {
// }
//
// public static final int CREATE = 1;
// public static final int START = 2;
// public static final int RESUME = 3;
// public static final int PAUSE = 4;
// public static final int STOP = 5;
// public static final int SAVE_INSTANCE_STATE = 6;
// public static final int DESTROY = 7;
//
// private ActivityLifecycle() {
// // no instance
// }
// }
//
// Path: aircycle-compiler/src/main/java/com/github/simonpercic/aircycle/model/type/ActivityLifecycleType.java
// public enum ActivityLifecycleType {
// CREATE,
// START,
// RESUME,
// PAUSE,
// STOP,
// SAVE_INSTANCE_STATE,
// DESTROY
// }
// Path: aircycle-compiler/src/main/java/com/github/simonpercic/aircycle/manager/ActivityLifecycleConverter.java
import com.github.simonpercic.aircycle.ActivityLifecycle;
import com.github.simonpercic.aircycle.model.type.ActivityLifecycleType;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import javax.inject.Inject;
import javax.inject.Singleton;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
package com.github.simonpercic.aircycle.manager;
/**
* Activity lifecycle converter manager.
*
* @author Simon Percic <a href="https://github.com/simonpercic">https://github.com/simonpercic</a>
*/
@Singleton
public class ActivityLifecycleConverter {
private final ProcessorLogger logger;
@Inject
public ActivityLifecycleConverter(ProcessorLogger logger) {
this.logger = logger;
}
| public List<ActivityLifecycleType> fromInts(int[] values, VariableElement field, TypeElement enclosingElement) { |
simonpercic/AirCycle | aircycle-compiler/src/main/java/com/github/simonpercic/aircycle/manager/ActivityLifecycleConverter.java | // Path: aircycle-api/src/main/java/com/github/simonpercic/aircycle/ActivityLifecycle.java
// public final class ActivityLifecycle {
//
// @IntDef({CREATE, START, RESUME, PAUSE, STOP, SAVE_INSTANCE_STATE, DESTROY})
// @Retention(RetentionPolicy.SOURCE)
// public @interface ActivityLifecycleEvent {
// }
//
// public static final int CREATE = 1;
// public static final int START = 2;
// public static final int RESUME = 3;
// public static final int PAUSE = 4;
// public static final int STOP = 5;
// public static final int SAVE_INSTANCE_STATE = 6;
// public static final int DESTROY = 7;
//
// private ActivityLifecycle() {
// // no instance
// }
// }
//
// Path: aircycle-compiler/src/main/java/com/github/simonpercic/aircycle/model/type/ActivityLifecycleType.java
// public enum ActivityLifecycleType {
// CREATE,
// START,
// RESUME,
// PAUSE,
// STOP,
// SAVE_INSTANCE_STATE,
// DESTROY
// }
| import com.github.simonpercic.aircycle.ActivityLifecycle;
import com.github.simonpercic.aircycle.model.type.ActivityLifecycleType;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import javax.inject.Inject;
import javax.inject.Singleton;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement; | List<ActivityLifecycleType> result = new ArrayList<>();
for (int value : values) {
ActivityLifecycleType activityLifecycle = fromInt(value);
if (activityLifecycle == null) {
String message = String.format(Locale.US, "Field `%s` in `%s` has an invalid lifecycle type `%d`. "
+ "Valid values are: \n"
+ "ActivityLifecycle.CREATE (1), \n"
+ "ActivityLifecycle.START (2), \n"
+ "ActivityLifecycle.RESUME (3), \n"
+ "ActivityLifecycle.PAUSE (4), \n"
+ "ActivityLifecycle.STOP (5), \n"
+ "ActivityLifecycle.SAVE_INSTANCE_STATE (6) or \n"
+ "ActivityLifecycle.DESTROY (7).",
field.getSimpleName(),
enclosingElement.getQualifiedName(),
value);
logger.e(message, enclosingElement);
return null;
}
result.add(activityLifecycle);
}
return result;
}
private static ActivityLifecycleType fromInt(int value) {
switch (value) { | // Path: aircycle-api/src/main/java/com/github/simonpercic/aircycle/ActivityLifecycle.java
// public final class ActivityLifecycle {
//
// @IntDef({CREATE, START, RESUME, PAUSE, STOP, SAVE_INSTANCE_STATE, DESTROY})
// @Retention(RetentionPolicy.SOURCE)
// public @interface ActivityLifecycleEvent {
// }
//
// public static final int CREATE = 1;
// public static final int START = 2;
// public static final int RESUME = 3;
// public static final int PAUSE = 4;
// public static final int STOP = 5;
// public static final int SAVE_INSTANCE_STATE = 6;
// public static final int DESTROY = 7;
//
// private ActivityLifecycle() {
// // no instance
// }
// }
//
// Path: aircycle-compiler/src/main/java/com/github/simonpercic/aircycle/model/type/ActivityLifecycleType.java
// public enum ActivityLifecycleType {
// CREATE,
// START,
// RESUME,
// PAUSE,
// STOP,
// SAVE_INSTANCE_STATE,
// DESTROY
// }
// Path: aircycle-compiler/src/main/java/com/github/simonpercic/aircycle/manager/ActivityLifecycleConverter.java
import com.github.simonpercic.aircycle.ActivityLifecycle;
import com.github.simonpercic.aircycle.model.type.ActivityLifecycleType;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import javax.inject.Inject;
import javax.inject.Singleton;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
List<ActivityLifecycleType> result = new ArrayList<>();
for (int value : values) {
ActivityLifecycleType activityLifecycle = fromInt(value);
if (activityLifecycle == null) {
String message = String.format(Locale.US, "Field `%s` in `%s` has an invalid lifecycle type `%d`. "
+ "Valid values are: \n"
+ "ActivityLifecycle.CREATE (1), \n"
+ "ActivityLifecycle.START (2), \n"
+ "ActivityLifecycle.RESUME (3), \n"
+ "ActivityLifecycle.PAUSE (4), \n"
+ "ActivityLifecycle.STOP (5), \n"
+ "ActivityLifecycle.SAVE_INSTANCE_STATE (6) or \n"
+ "ActivityLifecycle.DESTROY (7).",
field.getSimpleName(),
enclosingElement.getQualifiedName(),
value);
logger.e(message, enclosingElement);
return null;
}
result.add(activityLifecycle);
}
return result;
}
private static ActivityLifecycleType fromInt(int value) {
switch (value) { | case ActivityLifecycle.CREATE: |
simonpercic/AirCycle | example/src/main/java/com/github/simonpercic/example/aircycle/activity/a09/DefaultConfigActivity.java | // Path: aircycle-api/src/main/java/com/github/simonpercic/aircycle/ActivityLifecycle.java
// public final class ActivityLifecycle {
//
// @IntDef({CREATE, START, RESUME, PAUSE, STOP, SAVE_INSTANCE_STATE, DESTROY})
// @Retention(RetentionPolicy.SOURCE)
// public @interface ActivityLifecycleEvent {
// }
//
// public static final int CREATE = 1;
// public static final int START = 2;
// public static final int RESUME = 3;
// public static final int PAUSE = 4;
// public static final int STOP = 5;
// public static final int SAVE_INSTANCE_STATE = 6;
// public static final int DESTROY = 7;
//
// private ActivityLifecycle() {
// // no instance
// }
// }
//
// Path: aircycle-api/src/main/java/com/github/simonpercic/aircycle/AirCycleConfig.java
// public final class AirCycleConfig {
//
// private final boolean passIntentBundleOnCreate;
// @Nullable private final Set<Integer> ignoredLifecycleCallbacks;
//
// private AirCycleConfig(boolean passIntentBundleOnCreate, @Nullable Set<Integer> ignoredLifecycleCallbacks) {
// this.passIntentBundleOnCreate = passIntentBundleOnCreate;
// this.ignoredLifecycleCallbacks = ignoredLifecycleCallbacks;
// }
//
// boolean passIntentBundleOnCreate() {
// return passIntentBundleOnCreate;
// }
//
// boolean ignoreLifecycleCallback(int lifecycle) {
// return ignoredLifecycleCallbacks != null
// && ignoredLifecycleCallbacks.size() > 0
// && ignoredLifecycleCallbacks.contains(lifecycle);
// }
//
// /**
// * Get a builder for the AirCycleConfig.
// *
// * @return AirCycleConfig builder
// */
// public static Builder builder() {
// return new Builder();
// }
//
// /**
// * AirCycleConfig's builder class.
// */
// public static final class Builder {
//
// private boolean passIntentBundleOnCreate;
// @Nullable private Set<Integer> ignoredLifecycleCallbacks;
//
// private Builder() {
//
// }
//
// /**
// * Whether to pass the Activity's starting Intent Extras Bundle if its savedInstanceState is null in onCreate().
// *
// * @param passIntentBundleOnCreate if true, it passes the Activity's starting Intent Extras Bundle only if its
// * savedInstanceState is null in onCreate()
// * @return this Builder, for chaining calls
// */
// public Builder passIntentBundleOnCreate(boolean passIntentBundleOnCreate) {
// this.passIntentBundleOnCreate = passIntentBundleOnCreate;
// return this;
// }
//
// /**
// * Disable passing of an Activity lifecycle callback from {@link ActivityLifecycle}'s constants.
// *
// * @param lifecycleCallback lifecycle callback to ignore
// * @return this Builder, for chaining calls
// */
// public Builder ignoreLifecycleCallback(@ActivityLifecycle.ActivityLifecycleEvent int lifecycleCallback) {
// switch (lifecycleCallback) {
// case ActivityLifecycle.CREATE:
// case ActivityLifecycle.START:
// case ActivityLifecycle.RESUME:
// case ActivityLifecycle.PAUSE:
// case ActivityLifecycle.STOP:
// case ActivityLifecycle.SAVE_INSTANCE_STATE:
// case ActivityLifecycle.DESTROY:
// if (ignoredLifecycleCallbacks == null) {
// ignoredLifecycleCallbacks = new HashSet<>();
// }
//
// ignoredLifecycleCallbacks.add(lifecycleCallback);
// return this;
// default:
// throw new IllegalArgumentException("unknown lifecycle type");
// }
// }
//
// /**
// * Build the AirCycleConfig.
// *
// * @return built AirCycleConfig
// */
// public AirCycleConfig build() {
// return new AirCycleConfig(passIntentBundleOnCreate, ignoredLifecycleCallbacks);
// }
// }
// }
//
// Path: aircycle-api/src/main/java/com/github/simonpercic/aircycle/AirCycleDefaultConfig.java
// public final class AirCycleDefaultConfig {
//
// @Nullable private static AirCycleConfig defaultConfig;
//
// private AirCycleDefaultConfig() {
// // no instance
// }
//
// /**
// * Set the default config.
// *
// * @param defaultConfig AirCycleConfig used as the default
// */
// public static void setConfig(@Nullable AirCycleConfig defaultConfig) {
// AirCycleDefaultConfig.defaultConfig = defaultConfig;
// }
//
// @Nullable static AirCycleConfig getConfig() {
// return defaultConfig;
// }
// }
//
// Path: example/src/main/java/com/github/simonpercic/example/aircycle/listener/BundleListener.java
// public class BundleListener extends ActivityBundleAirCycleLogger {
//
// public static final String EXTRA_INT = BundleListener.class.getCanonicalName() + ".extraInt";
//
// private int extra;
//
// @Override
// public void onCreate(Bundle bundle) {
// extra = bundle.getInt(EXTRA_INT);
// }
//
// @Override
// public void onSaveInstanceState(Bundle outState) {
// outState.putInt(EXTRA_INT, extra);
// }
// }
| import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import com.github.simonpercic.aircycle.ActivityLifecycle;
import com.github.simonpercic.aircycle.AirCycle;
import com.github.simonpercic.aircycle.AirCycleConfig;
import com.github.simonpercic.aircycle.AirCycleDefaultConfig;
import com.github.simonpercic.example.aircycle.R;
import com.github.simonpercic.example.aircycle.listener.BundleListener; | package com.github.simonpercic.example.aircycle.activity.a09;
/**
* Example Activity showing usage of a custom AirCycleConfig set as the app-wide default.
*
* @author Simon Percic <a href="https://github.com/simonpercic">https://github.com/simonpercic</a>
*/
public class DefaultConfigActivity extends AppCompatActivity {
@AirCycle final BundleListener bundleListener = new BundleListener();
@Override
protected void onCreate(Bundle savedInstanceState) { | // Path: aircycle-api/src/main/java/com/github/simonpercic/aircycle/ActivityLifecycle.java
// public final class ActivityLifecycle {
//
// @IntDef({CREATE, START, RESUME, PAUSE, STOP, SAVE_INSTANCE_STATE, DESTROY})
// @Retention(RetentionPolicy.SOURCE)
// public @interface ActivityLifecycleEvent {
// }
//
// public static final int CREATE = 1;
// public static final int START = 2;
// public static final int RESUME = 3;
// public static final int PAUSE = 4;
// public static final int STOP = 5;
// public static final int SAVE_INSTANCE_STATE = 6;
// public static final int DESTROY = 7;
//
// private ActivityLifecycle() {
// // no instance
// }
// }
//
// Path: aircycle-api/src/main/java/com/github/simonpercic/aircycle/AirCycleConfig.java
// public final class AirCycleConfig {
//
// private final boolean passIntentBundleOnCreate;
// @Nullable private final Set<Integer> ignoredLifecycleCallbacks;
//
// private AirCycleConfig(boolean passIntentBundleOnCreate, @Nullable Set<Integer> ignoredLifecycleCallbacks) {
// this.passIntentBundleOnCreate = passIntentBundleOnCreate;
// this.ignoredLifecycleCallbacks = ignoredLifecycleCallbacks;
// }
//
// boolean passIntentBundleOnCreate() {
// return passIntentBundleOnCreate;
// }
//
// boolean ignoreLifecycleCallback(int lifecycle) {
// return ignoredLifecycleCallbacks != null
// && ignoredLifecycleCallbacks.size() > 0
// && ignoredLifecycleCallbacks.contains(lifecycle);
// }
//
// /**
// * Get a builder for the AirCycleConfig.
// *
// * @return AirCycleConfig builder
// */
// public static Builder builder() {
// return new Builder();
// }
//
// /**
// * AirCycleConfig's builder class.
// */
// public static final class Builder {
//
// private boolean passIntentBundleOnCreate;
// @Nullable private Set<Integer> ignoredLifecycleCallbacks;
//
// private Builder() {
//
// }
//
// /**
// * Whether to pass the Activity's starting Intent Extras Bundle if its savedInstanceState is null in onCreate().
// *
// * @param passIntentBundleOnCreate if true, it passes the Activity's starting Intent Extras Bundle only if its
// * savedInstanceState is null in onCreate()
// * @return this Builder, for chaining calls
// */
// public Builder passIntentBundleOnCreate(boolean passIntentBundleOnCreate) {
// this.passIntentBundleOnCreate = passIntentBundleOnCreate;
// return this;
// }
//
// /**
// * Disable passing of an Activity lifecycle callback from {@link ActivityLifecycle}'s constants.
// *
// * @param lifecycleCallback lifecycle callback to ignore
// * @return this Builder, for chaining calls
// */
// public Builder ignoreLifecycleCallback(@ActivityLifecycle.ActivityLifecycleEvent int lifecycleCallback) {
// switch (lifecycleCallback) {
// case ActivityLifecycle.CREATE:
// case ActivityLifecycle.START:
// case ActivityLifecycle.RESUME:
// case ActivityLifecycle.PAUSE:
// case ActivityLifecycle.STOP:
// case ActivityLifecycle.SAVE_INSTANCE_STATE:
// case ActivityLifecycle.DESTROY:
// if (ignoredLifecycleCallbacks == null) {
// ignoredLifecycleCallbacks = new HashSet<>();
// }
//
// ignoredLifecycleCallbacks.add(lifecycleCallback);
// return this;
// default:
// throw new IllegalArgumentException("unknown lifecycle type");
// }
// }
//
// /**
// * Build the AirCycleConfig.
// *
// * @return built AirCycleConfig
// */
// public AirCycleConfig build() {
// return new AirCycleConfig(passIntentBundleOnCreate, ignoredLifecycleCallbacks);
// }
// }
// }
//
// Path: aircycle-api/src/main/java/com/github/simonpercic/aircycle/AirCycleDefaultConfig.java
// public final class AirCycleDefaultConfig {
//
// @Nullable private static AirCycleConfig defaultConfig;
//
// private AirCycleDefaultConfig() {
// // no instance
// }
//
// /**
// * Set the default config.
// *
// * @param defaultConfig AirCycleConfig used as the default
// */
// public static void setConfig(@Nullable AirCycleConfig defaultConfig) {
// AirCycleDefaultConfig.defaultConfig = defaultConfig;
// }
//
// @Nullable static AirCycleConfig getConfig() {
// return defaultConfig;
// }
// }
//
// Path: example/src/main/java/com/github/simonpercic/example/aircycle/listener/BundleListener.java
// public class BundleListener extends ActivityBundleAirCycleLogger {
//
// public static final String EXTRA_INT = BundleListener.class.getCanonicalName() + ".extraInt";
//
// private int extra;
//
// @Override
// public void onCreate(Bundle bundle) {
// extra = bundle.getInt(EXTRA_INT);
// }
//
// @Override
// public void onSaveInstanceState(Bundle outState) {
// outState.putInt(EXTRA_INT, extra);
// }
// }
// Path: example/src/main/java/com/github/simonpercic/example/aircycle/activity/a09/DefaultConfigActivity.java
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import com.github.simonpercic.aircycle.ActivityLifecycle;
import com.github.simonpercic.aircycle.AirCycle;
import com.github.simonpercic.aircycle.AirCycleConfig;
import com.github.simonpercic.aircycle.AirCycleDefaultConfig;
import com.github.simonpercic.example.aircycle.R;
import com.github.simonpercic.example.aircycle.listener.BundleListener;
package com.github.simonpercic.example.aircycle.activity.a09;
/**
* Example Activity showing usage of a custom AirCycleConfig set as the app-wide default.
*
* @author Simon Percic <a href="https://github.com/simonpercic">https://github.com/simonpercic</a>
*/
public class DefaultConfigActivity extends AppCompatActivity {
@AirCycle final BundleListener bundleListener = new BundleListener();
@Override
protected void onCreate(Bundle savedInstanceState) { | AirCycleConfig airCycleConfig = AirCycleConfig.builder() |
simonpercic/AirCycle | example/src/main/java/com/github/simonpercic/example/aircycle/activity/a09/DefaultConfigActivity.java | // Path: aircycle-api/src/main/java/com/github/simonpercic/aircycle/ActivityLifecycle.java
// public final class ActivityLifecycle {
//
// @IntDef({CREATE, START, RESUME, PAUSE, STOP, SAVE_INSTANCE_STATE, DESTROY})
// @Retention(RetentionPolicy.SOURCE)
// public @interface ActivityLifecycleEvent {
// }
//
// public static final int CREATE = 1;
// public static final int START = 2;
// public static final int RESUME = 3;
// public static final int PAUSE = 4;
// public static final int STOP = 5;
// public static final int SAVE_INSTANCE_STATE = 6;
// public static final int DESTROY = 7;
//
// private ActivityLifecycle() {
// // no instance
// }
// }
//
// Path: aircycle-api/src/main/java/com/github/simonpercic/aircycle/AirCycleConfig.java
// public final class AirCycleConfig {
//
// private final boolean passIntentBundleOnCreate;
// @Nullable private final Set<Integer> ignoredLifecycleCallbacks;
//
// private AirCycleConfig(boolean passIntentBundleOnCreate, @Nullable Set<Integer> ignoredLifecycleCallbacks) {
// this.passIntentBundleOnCreate = passIntentBundleOnCreate;
// this.ignoredLifecycleCallbacks = ignoredLifecycleCallbacks;
// }
//
// boolean passIntentBundleOnCreate() {
// return passIntentBundleOnCreate;
// }
//
// boolean ignoreLifecycleCallback(int lifecycle) {
// return ignoredLifecycleCallbacks != null
// && ignoredLifecycleCallbacks.size() > 0
// && ignoredLifecycleCallbacks.contains(lifecycle);
// }
//
// /**
// * Get a builder for the AirCycleConfig.
// *
// * @return AirCycleConfig builder
// */
// public static Builder builder() {
// return new Builder();
// }
//
// /**
// * AirCycleConfig's builder class.
// */
// public static final class Builder {
//
// private boolean passIntentBundleOnCreate;
// @Nullable private Set<Integer> ignoredLifecycleCallbacks;
//
// private Builder() {
//
// }
//
// /**
// * Whether to pass the Activity's starting Intent Extras Bundle if its savedInstanceState is null in onCreate().
// *
// * @param passIntentBundleOnCreate if true, it passes the Activity's starting Intent Extras Bundle only if its
// * savedInstanceState is null in onCreate()
// * @return this Builder, for chaining calls
// */
// public Builder passIntentBundleOnCreate(boolean passIntentBundleOnCreate) {
// this.passIntentBundleOnCreate = passIntentBundleOnCreate;
// return this;
// }
//
// /**
// * Disable passing of an Activity lifecycle callback from {@link ActivityLifecycle}'s constants.
// *
// * @param lifecycleCallback lifecycle callback to ignore
// * @return this Builder, for chaining calls
// */
// public Builder ignoreLifecycleCallback(@ActivityLifecycle.ActivityLifecycleEvent int lifecycleCallback) {
// switch (lifecycleCallback) {
// case ActivityLifecycle.CREATE:
// case ActivityLifecycle.START:
// case ActivityLifecycle.RESUME:
// case ActivityLifecycle.PAUSE:
// case ActivityLifecycle.STOP:
// case ActivityLifecycle.SAVE_INSTANCE_STATE:
// case ActivityLifecycle.DESTROY:
// if (ignoredLifecycleCallbacks == null) {
// ignoredLifecycleCallbacks = new HashSet<>();
// }
//
// ignoredLifecycleCallbacks.add(lifecycleCallback);
// return this;
// default:
// throw new IllegalArgumentException("unknown lifecycle type");
// }
// }
//
// /**
// * Build the AirCycleConfig.
// *
// * @return built AirCycleConfig
// */
// public AirCycleConfig build() {
// return new AirCycleConfig(passIntentBundleOnCreate, ignoredLifecycleCallbacks);
// }
// }
// }
//
// Path: aircycle-api/src/main/java/com/github/simonpercic/aircycle/AirCycleDefaultConfig.java
// public final class AirCycleDefaultConfig {
//
// @Nullable private static AirCycleConfig defaultConfig;
//
// private AirCycleDefaultConfig() {
// // no instance
// }
//
// /**
// * Set the default config.
// *
// * @param defaultConfig AirCycleConfig used as the default
// */
// public static void setConfig(@Nullable AirCycleConfig defaultConfig) {
// AirCycleDefaultConfig.defaultConfig = defaultConfig;
// }
//
// @Nullable static AirCycleConfig getConfig() {
// return defaultConfig;
// }
// }
//
// Path: example/src/main/java/com/github/simonpercic/example/aircycle/listener/BundleListener.java
// public class BundleListener extends ActivityBundleAirCycleLogger {
//
// public static final String EXTRA_INT = BundleListener.class.getCanonicalName() + ".extraInt";
//
// private int extra;
//
// @Override
// public void onCreate(Bundle bundle) {
// extra = bundle.getInt(EXTRA_INT);
// }
//
// @Override
// public void onSaveInstanceState(Bundle outState) {
// outState.putInt(EXTRA_INT, extra);
// }
// }
| import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import com.github.simonpercic.aircycle.ActivityLifecycle;
import com.github.simonpercic.aircycle.AirCycle;
import com.github.simonpercic.aircycle.AirCycleConfig;
import com.github.simonpercic.aircycle.AirCycleDefaultConfig;
import com.github.simonpercic.example.aircycle.R;
import com.github.simonpercic.example.aircycle.listener.BundleListener; | package com.github.simonpercic.example.aircycle.activity.a09;
/**
* Example Activity showing usage of a custom AirCycleConfig set as the app-wide default.
*
* @author Simon Percic <a href="https://github.com/simonpercic">https://github.com/simonpercic</a>
*/
public class DefaultConfigActivity extends AppCompatActivity {
@AirCycle final BundleListener bundleListener = new BundleListener();
@Override
protected void onCreate(Bundle savedInstanceState) {
AirCycleConfig airCycleConfig = AirCycleConfig.builder()
.passIntentBundleOnCreate(true) | // Path: aircycle-api/src/main/java/com/github/simonpercic/aircycle/ActivityLifecycle.java
// public final class ActivityLifecycle {
//
// @IntDef({CREATE, START, RESUME, PAUSE, STOP, SAVE_INSTANCE_STATE, DESTROY})
// @Retention(RetentionPolicy.SOURCE)
// public @interface ActivityLifecycleEvent {
// }
//
// public static final int CREATE = 1;
// public static final int START = 2;
// public static final int RESUME = 3;
// public static final int PAUSE = 4;
// public static final int STOP = 5;
// public static final int SAVE_INSTANCE_STATE = 6;
// public static final int DESTROY = 7;
//
// private ActivityLifecycle() {
// // no instance
// }
// }
//
// Path: aircycle-api/src/main/java/com/github/simonpercic/aircycle/AirCycleConfig.java
// public final class AirCycleConfig {
//
// private final boolean passIntentBundleOnCreate;
// @Nullable private final Set<Integer> ignoredLifecycleCallbacks;
//
// private AirCycleConfig(boolean passIntentBundleOnCreate, @Nullable Set<Integer> ignoredLifecycleCallbacks) {
// this.passIntentBundleOnCreate = passIntentBundleOnCreate;
// this.ignoredLifecycleCallbacks = ignoredLifecycleCallbacks;
// }
//
// boolean passIntentBundleOnCreate() {
// return passIntentBundleOnCreate;
// }
//
// boolean ignoreLifecycleCallback(int lifecycle) {
// return ignoredLifecycleCallbacks != null
// && ignoredLifecycleCallbacks.size() > 0
// && ignoredLifecycleCallbacks.contains(lifecycle);
// }
//
// /**
// * Get a builder for the AirCycleConfig.
// *
// * @return AirCycleConfig builder
// */
// public static Builder builder() {
// return new Builder();
// }
//
// /**
// * AirCycleConfig's builder class.
// */
// public static final class Builder {
//
// private boolean passIntentBundleOnCreate;
// @Nullable private Set<Integer> ignoredLifecycleCallbacks;
//
// private Builder() {
//
// }
//
// /**
// * Whether to pass the Activity's starting Intent Extras Bundle if its savedInstanceState is null in onCreate().
// *
// * @param passIntentBundleOnCreate if true, it passes the Activity's starting Intent Extras Bundle only if its
// * savedInstanceState is null in onCreate()
// * @return this Builder, for chaining calls
// */
// public Builder passIntentBundleOnCreate(boolean passIntentBundleOnCreate) {
// this.passIntentBundleOnCreate = passIntentBundleOnCreate;
// return this;
// }
//
// /**
// * Disable passing of an Activity lifecycle callback from {@link ActivityLifecycle}'s constants.
// *
// * @param lifecycleCallback lifecycle callback to ignore
// * @return this Builder, for chaining calls
// */
// public Builder ignoreLifecycleCallback(@ActivityLifecycle.ActivityLifecycleEvent int lifecycleCallback) {
// switch (lifecycleCallback) {
// case ActivityLifecycle.CREATE:
// case ActivityLifecycle.START:
// case ActivityLifecycle.RESUME:
// case ActivityLifecycle.PAUSE:
// case ActivityLifecycle.STOP:
// case ActivityLifecycle.SAVE_INSTANCE_STATE:
// case ActivityLifecycle.DESTROY:
// if (ignoredLifecycleCallbacks == null) {
// ignoredLifecycleCallbacks = new HashSet<>();
// }
//
// ignoredLifecycleCallbacks.add(lifecycleCallback);
// return this;
// default:
// throw new IllegalArgumentException("unknown lifecycle type");
// }
// }
//
// /**
// * Build the AirCycleConfig.
// *
// * @return built AirCycleConfig
// */
// public AirCycleConfig build() {
// return new AirCycleConfig(passIntentBundleOnCreate, ignoredLifecycleCallbacks);
// }
// }
// }
//
// Path: aircycle-api/src/main/java/com/github/simonpercic/aircycle/AirCycleDefaultConfig.java
// public final class AirCycleDefaultConfig {
//
// @Nullable private static AirCycleConfig defaultConfig;
//
// private AirCycleDefaultConfig() {
// // no instance
// }
//
// /**
// * Set the default config.
// *
// * @param defaultConfig AirCycleConfig used as the default
// */
// public static void setConfig(@Nullable AirCycleConfig defaultConfig) {
// AirCycleDefaultConfig.defaultConfig = defaultConfig;
// }
//
// @Nullable static AirCycleConfig getConfig() {
// return defaultConfig;
// }
// }
//
// Path: example/src/main/java/com/github/simonpercic/example/aircycle/listener/BundleListener.java
// public class BundleListener extends ActivityBundleAirCycleLogger {
//
// public static final String EXTRA_INT = BundleListener.class.getCanonicalName() + ".extraInt";
//
// private int extra;
//
// @Override
// public void onCreate(Bundle bundle) {
// extra = bundle.getInt(EXTRA_INT);
// }
//
// @Override
// public void onSaveInstanceState(Bundle outState) {
// outState.putInt(EXTRA_INT, extra);
// }
// }
// Path: example/src/main/java/com/github/simonpercic/example/aircycle/activity/a09/DefaultConfigActivity.java
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import com.github.simonpercic.aircycle.ActivityLifecycle;
import com.github.simonpercic.aircycle.AirCycle;
import com.github.simonpercic.aircycle.AirCycleConfig;
import com.github.simonpercic.aircycle.AirCycleDefaultConfig;
import com.github.simonpercic.example.aircycle.R;
import com.github.simonpercic.example.aircycle.listener.BundleListener;
package com.github.simonpercic.example.aircycle.activity.a09;
/**
* Example Activity showing usage of a custom AirCycleConfig set as the app-wide default.
*
* @author Simon Percic <a href="https://github.com/simonpercic">https://github.com/simonpercic</a>
*/
public class DefaultConfigActivity extends AppCompatActivity {
@AirCycle final BundleListener bundleListener = new BundleListener();
@Override
protected void onCreate(Bundle savedInstanceState) {
AirCycleConfig airCycleConfig = AirCycleConfig.builder()
.passIntentBundleOnCreate(true) | .ignoreLifecycleCallback(ActivityLifecycle.START) |
simonpercic/AirCycle | aircycle-compiler/src/main/java/com/github/simonpercic/aircycle/manager/FieldValidator.java | // Path: aircycle-compiler/src/main/java/com/github/simonpercic/aircycle/utils/ElementValidator.java
// public final class ElementValidator {
//
// private ElementValidator() {
// // no instance
// }
//
// public static boolean isPublic(Element element) {
// return hasModifier(element, Modifier.PUBLIC);
// }
//
// public static boolean isPrivate(Element element) {
// return hasModifier(element, Modifier.PRIVATE);
// }
//
// private static boolean hasModifier(Element element, Modifier modifier) {
// return element.getModifiers().contains(modifier);
// }
// }
| import android.app.Activity;
import com.github.simonpercic.aircycle.AirCycle;
import com.github.simonpercic.aircycle.utils.ElementValidator;
import javax.inject.Inject;
import javax.inject.Singleton;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.util.Elements;
import javax.lang.model.util.Types; | package com.github.simonpercic.aircycle.manager;
/**
* Listener field validator.
*
* @author Simon Percic <a href="https://github.com/simonpercic">https://github.com/simonpercic</a>
*/
@Singleton
public class FieldValidator {
private final ProcessorLogger logger;
private final Elements elementUtils;
private final Types typeUtils;
@Inject
public FieldValidator(ProcessorLogger logger, Elements elementUtils, Types typeUtils) {
this.logger = logger;
this.elementUtils = elementUtils;
this.typeUtils = typeUtils;
}
public boolean isFieldValid(VariableElement field) { | // Path: aircycle-compiler/src/main/java/com/github/simonpercic/aircycle/utils/ElementValidator.java
// public final class ElementValidator {
//
// private ElementValidator() {
// // no instance
// }
//
// public static boolean isPublic(Element element) {
// return hasModifier(element, Modifier.PUBLIC);
// }
//
// public static boolean isPrivate(Element element) {
// return hasModifier(element, Modifier.PRIVATE);
// }
//
// private static boolean hasModifier(Element element, Modifier modifier) {
// return element.getModifiers().contains(modifier);
// }
// }
// Path: aircycle-compiler/src/main/java/com/github/simonpercic/aircycle/manager/FieldValidator.java
import android.app.Activity;
import com.github.simonpercic.aircycle.AirCycle;
import com.github.simonpercic.aircycle.utils.ElementValidator;
import javax.inject.Inject;
import javax.inject.Singleton;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
import javax.lang.model.util.Elements;
import javax.lang.model.util.Types;
package com.github.simonpercic.aircycle.manager;
/**
* Listener field validator.
*
* @author Simon Percic <a href="https://github.com/simonpercic">https://github.com/simonpercic</a>
*/
@Singleton
public class FieldValidator {
private final ProcessorLogger logger;
private final Elements elementUtils;
private final Types typeUtils;
@Inject
public FieldValidator(ProcessorLogger logger, Elements elementUtils, Types typeUtils) {
this.logger = logger;
this.elementUtils = elementUtils;
this.typeUtils = typeUtils;
}
public boolean isFieldValid(VariableElement field) { | if (ElementValidator.isPrivate(field)) { |
simonpercic/AirCycle | example/src/main/java/com/github/simonpercic/example/aircycle/activity/a06/MultipleListenersActivity.java | // Path: example/src/main/java/com/github/simonpercic/example/aircycle/logger/ActivityAirCycleLogger.java
// public class ActivityAirCycleLogger implements ActivityAirCycle {
//
// @Override public void onCreate() {
// Timber.d("onCreate");
// }
//
// @Override public void onStart() {
// Timber.d("onStart");
// }
//
// @Override public void onResume() {
// Timber.d("onResume");
// }
//
// @Override public void onPause() {
// Timber.d("onPause");
// }
//
// @Override public void onStop() {
// Timber.d("onStop");
// }
//
// @Override public void onSaveInstanceState() {
// Timber.d("onSaveInstanceState");
// }
//
// @Override public void onDestroy() {
// Timber.d("onDestroy");
// }
// }
//
// Path: example/src/main/java/com/github/simonpercic/example/aircycle/logger/ActivityBundleAirCycleLogger.java
// public class ActivityBundleAirCycleLogger implements ActivityBundleAirCycle {
//
// @Override public void onCreate(Bundle savedInstanceState) {
// Timber.d("onCreate savedInstanceState: %s", savedInstanceState);
// }
//
// @Override public void onStart() {
// Timber.d("onStart");
// }
//
// @Override public void onResume() {
// Timber.d("onResume");
// }
//
// @Override public void onPause() {
// Timber.d("onPause");
// }
//
// @Override public void onStop() {
// Timber.d("onStop");
// }
//
// @Override public void onSaveInstanceState(Bundle outState) {
// Timber.d("onSaveInstanceState outState: %s", outState);
// }
//
// @Override public void onDestroy() {
// Timber.d("onDestroy");
// }
// }
| import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import com.github.simonpercic.aircycle.AirCycle;
import com.github.simonpercic.example.aircycle.R;
import com.github.simonpercic.example.aircycle.logger.ActivityAirCycleLogger;
import com.github.simonpercic.example.aircycle.logger.ActivityBundleAirCycleLogger; | package com.github.simonpercic.example.aircycle.activity.a06;
/**
* Example Activity showing usage of multiple listeners annotated with AirCycle in the same Activity.
*
* @author Simon Percic <a href="https://github.com/simonpercic">https://github.com/simonpercic</a>
*/
public class MultipleListenersActivity extends AppCompatActivity {
@AirCycle ActivityAirCycleLogger airCycleLogger; | // Path: example/src/main/java/com/github/simonpercic/example/aircycle/logger/ActivityAirCycleLogger.java
// public class ActivityAirCycleLogger implements ActivityAirCycle {
//
// @Override public void onCreate() {
// Timber.d("onCreate");
// }
//
// @Override public void onStart() {
// Timber.d("onStart");
// }
//
// @Override public void onResume() {
// Timber.d("onResume");
// }
//
// @Override public void onPause() {
// Timber.d("onPause");
// }
//
// @Override public void onStop() {
// Timber.d("onStop");
// }
//
// @Override public void onSaveInstanceState() {
// Timber.d("onSaveInstanceState");
// }
//
// @Override public void onDestroy() {
// Timber.d("onDestroy");
// }
// }
//
// Path: example/src/main/java/com/github/simonpercic/example/aircycle/logger/ActivityBundleAirCycleLogger.java
// public class ActivityBundleAirCycleLogger implements ActivityBundleAirCycle {
//
// @Override public void onCreate(Bundle savedInstanceState) {
// Timber.d("onCreate savedInstanceState: %s", savedInstanceState);
// }
//
// @Override public void onStart() {
// Timber.d("onStart");
// }
//
// @Override public void onResume() {
// Timber.d("onResume");
// }
//
// @Override public void onPause() {
// Timber.d("onPause");
// }
//
// @Override public void onStop() {
// Timber.d("onStop");
// }
//
// @Override public void onSaveInstanceState(Bundle outState) {
// Timber.d("onSaveInstanceState outState: %s", outState);
// }
//
// @Override public void onDestroy() {
// Timber.d("onDestroy");
// }
// }
// Path: example/src/main/java/com/github/simonpercic/example/aircycle/activity/a06/MultipleListenersActivity.java
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import com.github.simonpercic.aircycle.AirCycle;
import com.github.simonpercic.example.aircycle.R;
import com.github.simonpercic.example.aircycle.logger.ActivityAirCycleLogger;
import com.github.simonpercic.example.aircycle.logger.ActivityBundleAirCycleLogger;
package com.github.simonpercic.example.aircycle.activity.a06;
/**
* Example Activity showing usage of multiple listeners annotated with AirCycle in the same Activity.
*
* @author Simon Percic <a href="https://github.com/simonpercic">https://github.com/simonpercic</a>
*/
public class MultipleListenersActivity extends AppCompatActivity {
@AirCycle ActivityAirCycleLogger airCycleLogger; | @AirCycle final ActivityBundleAirCycleLogger bundleAirCycleLogger = new ActivityBundleAirCycleLogger(); |
fintx/fintx-common | src/test/java/org/fintx/util/ObjectsTest.java | // Path: src/main/java/org/fintx/lang/Encoding.java
// public enum Encoding implements Codeable<String> {
// UTF_8("UTF-8"), GBK("GBK"), GB18030("GB18030");
// private String code;
//
// private Encoding(String code) {
// this.code = code;
// }
//
// @Override
// public String getCode() {
// // TODO Auto-generated method stub
// return code;
// }
// }
| import java.util.List;
import java.util.Map;
import javax.xml.bind.JAXBException;
import org.fintx.lang.Encoding;
import net.sf.cglib.beans.BeanCopier;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.sql.Date;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
| Assert.assertTrue(10 == bytes.length);
int[] ints = Objects.deepClone(new int[10]);
Assert.assertTrue(10 == ints.length);
PoJo pojo = new PoJo();
pojo.setIn(0);
ints[0] = 1;
pojo.setIns(ints);
pojo.setObjs(new Object[10]);
pojo.getObjs() [0]="s";
pojo.setStr("aa");
pojo.setStrs(new String[3]);
bytes[9] = 10;
pojo.setBytes(bytes);
pojo.getBytes()[2] = 1;
List<String> list=new ArrayList<String>();
list.add("a");
list.add("b");
pojo.setList(list);
String xml = Objects.Xml.toString(pojo);
System.out.println(xml);
PoJo pojo2 = Objects.Xml.toObject(xml, PoJo.class);
Assert.assertTrue(0 == pojo2.getIn());
Assert.assertTrue(1 == pojo2.getIns()[0]);
Assert.assertTrue("aa".equals(pojo2.getStr()));
Assert.assertTrue(10 == pojo2.getBytes()[9]);
Assert.assertTrue("b".equals(pojo2.getList().get(1)) );
PoJo2 pojo3=new PoJo2();
Objects.copyProperties(pojo, pojo3);
Map<String,String> mapper=new HashMap<String,String>();
mapper.put("www.adtec.com.cn", "adt");
| // Path: src/main/java/org/fintx/lang/Encoding.java
// public enum Encoding implements Codeable<String> {
// UTF_8("UTF-8"), GBK("GBK"), GB18030("GB18030");
// private String code;
//
// private Encoding(String code) {
// this.code = code;
// }
//
// @Override
// public String getCode() {
// // TODO Auto-generated method stub
// return code;
// }
// }
// Path: src/test/java/org/fintx/util/ObjectsTest.java
import java.util.List;
import java.util.Map;
import javax.xml.bind.JAXBException;
import org.fintx.lang.Encoding;
import net.sf.cglib.beans.BeanCopier;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.sql.Date;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
Assert.assertTrue(10 == bytes.length);
int[] ints = Objects.deepClone(new int[10]);
Assert.assertTrue(10 == ints.length);
PoJo pojo = new PoJo();
pojo.setIn(0);
ints[0] = 1;
pojo.setIns(ints);
pojo.setObjs(new Object[10]);
pojo.getObjs() [0]="s";
pojo.setStr("aa");
pojo.setStrs(new String[3]);
bytes[9] = 10;
pojo.setBytes(bytes);
pojo.getBytes()[2] = 1;
List<String> list=new ArrayList<String>();
list.add("a");
list.add("b");
pojo.setList(list);
String xml = Objects.Xml.toString(pojo);
System.out.println(xml);
PoJo pojo2 = Objects.Xml.toObject(xml, PoJo.class);
Assert.assertTrue(0 == pojo2.getIn());
Assert.assertTrue(1 == pojo2.getIns()[0]);
Assert.assertTrue("aa".equals(pojo2.getStr()));
Assert.assertTrue(10 == pojo2.getBytes()[9]);
Assert.assertTrue("b".equals(pojo2.getList().get(1)) );
PoJo2 pojo3=new PoJo2();
Objects.copyProperties(pojo, pojo3);
Map<String,String> mapper=new HashMap<String,String>();
mapper.put("www.adtec.com.cn", "adt");
| ObjectXmls xmlConvertor = Objects.Xml.custom(mapper, false, Encoding.GB18030, false, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
|
fintx/fintx-common | src/main/java/org/fintx/util/ObjectXmls.java | // Path: src/main/java/org/fintx/lang/Encoding.java
// public enum Encoding implements Codeable<String> {
// UTF_8("UTF-8"), GBK("GBK"), GB18030("GB18030");
// private String code;
//
// private Encoding(String code) {
// this.code = code;
// }
//
// @Override
// public String getCode() {
// // TODO Auto-generated method stub
// return code;
// }
// }
//
// Path: src/main/java/org/fintx/util/convertor/ObjectStringConvertor.java
// public interface ObjectStringConvertor {
// public <T> String toString(T obj) throws Exception;
//
// public <T> T toObject(String text, Class<T> clazz) throws Exception;
//
// // public <T> String toString(T obj, Properties prop) throws Exception;
//
// // public <T> T toObject(String text, Class<T> clazz, Properties prop) throws
// // Exception;
// }
| import java.io.StringReader;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;
import javax.xml.XMLConstants;
import javax.xml.bind.*;
import org.fintx.lang.Encoding;
import org.fintx.util.convertor.ObjectStringConvertor;
import com.sun.xml.bind.marshaller.NamespacePrefixMapper;
import com.sun.xml.bind.v2.WellKnownNamespace;
import lombok.AllArgsConstructor;
import lombok.AccessLevel;
| /**
* Copyright 2017 FinTx
*
* 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 org.fintx.util;
/**
* @author bluecreator(qiang.x.wang@gmail.com)
*
*/
@SuppressWarnings("restriction")
@AllArgsConstructor(access = AccessLevel.PACKAGE)
| // Path: src/main/java/org/fintx/lang/Encoding.java
// public enum Encoding implements Codeable<String> {
// UTF_8("UTF-8"), GBK("GBK"), GB18030("GB18030");
// private String code;
//
// private Encoding(String code) {
// this.code = code;
// }
//
// @Override
// public String getCode() {
// // TODO Auto-generated method stub
// return code;
// }
// }
//
// Path: src/main/java/org/fintx/util/convertor/ObjectStringConvertor.java
// public interface ObjectStringConvertor {
// public <T> String toString(T obj) throws Exception;
//
// public <T> T toObject(String text, Class<T> clazz) throws Exception;
//
// // public <T> String toString(T obj, Properties prop) throws Exception;
//
// // public <T> T toObject(String text, Class<T> clazz, Properties prop) throws
// // Exception;
// }
// Path: src/main/java/org/fintx/util/ObjectXmls.java
import java.io.StringReader;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;
import javax.xml.XMLConstants;
import javax.xml.bind.*;
import org.fintx.lang.Encoding;
import org.fintx.util.convertor.ObjectStringConvertor;
import com.sun.xml.bind.marshaller.NamespacePrefixMapper;
import com.sun.xml.bind.v2.WellKnownNamespace;
import lombok.AllArgsConstructor;
import lombok.AccessLevel;
/**
* Copyright 2017 FinTx
*
* 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 org.fintx.util;
/**
* @author bluecreator(qiang.x.wang@gmail.com)
*
*/
@SuppressWarnings("restriction")
@AllArgsConstructor(access = AccessLevel.PACKAGE)
| public final class ObjectXmls implements ObjectStringConvertor {
|
fintx/fintx-common | src/main/java/org/fintx/util/ObjectXmls.java | // Path: src/main/java/org/fintx/lang/Encoding.java
// public enum Encoding implements Codeable<String> {
// UTF_8("UTF-8"), GBK("GBK"), GB18030("GB18030");
// private String code;
//
// private Encoding(String code) {
// this.code = code;
// }
//
// @Override
// public String getCode() {
// // TODO Auto-generated method stub
// return code;
// }
// }
//
// Path: src/main/java/org/fintx/util/convertor/ObjectStringConvertor.java
// public interface ObjectStringConvertor {
// public <T> String toString(T obj) throws Exception;
//
// public <T> T toObject(String text, Class<T> clazz) throws Exception;
//
// // public <T> String toString(T obj, Properties prop) throws Exception;
//
// // public <T> T toObject(String text, Class<T> clazz, Properties prop) throws
// // Exception;
// }
| import java.io.StringReader;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;
import javax.xml.XMLConstants;
import javax.xml.bind.*;
import org.fintx.lang.Encoding;
import org.fintx.util.convertor.ObjectStringConvertor;
import com.sun.xml.bind.marshaller.NamespacePrefixMapper;
import com.sun.xml.bind.v2.WellKnownNamespace;
import lombok.AllArgsConstructor;
import lombok.AccessLevel;
| /**
* Copyright 2017 FinTx
*
* 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 org.fintx.util;
/**
* @author bluecreator(qiang.x.wang@gmail.com)
*
*/
@SuppressWarnings("restriction")
@AllArgsConstructor(access = AccessLevel.PACKAGE)
public final class ObjectXmls implements ObjectStringConvertor {
private Map<String, String> namespacePrefixMapper;
private boolean formatted;
| // Path: src/main/java/org/fintx/lang/Encoding.java
// public enum Encoding implements Codeable<String> {
// UTF_8("UTF-8"), GBK("GBK"), GB18030("GB18030");
// private String code;
//
// private Encoding(String code) {
// this.code = code;
// }
//
// @Override
// public String getCode() {
// // TODO Auto-generated method stub
// return code;
// }
// }
//
// Path: src/main/java/org/fintx/util/convertor/ObjectStringConvertor.java
// public interface ObjectStringConvertor {
// public <T> String toString(T obj) throws Exception;
//
// public <T> T toObject(String text, Class<T> clazz) throws Exception;
//
// // public <T> String toString(T obj, Properties prop) throws Exception;
//
// // public <T> T toObject(String text, Class<T> clazz, Properties prop) throws
// // Exception;
// }
// Path: src/main/java/org/fintx/util/ObjectXmls.java
import java.io.StringReader;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;
import javax.xml.XMLConstants;
import javax.xml.bind.*;
import org.fintx.lang.Encoding;
import org.fintx.util.convertor.ObjectStringConvertor;
import com.sun.xml.bind.marshaller.NamespacePrefixMapper;
import com.sun.xml.bind.v2.WellKnownNamespace;
import lombok.AllArgsConstructor;
import lombok.AccessLevel;
/**
* Copyright 2017 FinTx
*
* 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 org.fintx.util;
/**
* @author bluecreator(qiang.x.wang@gmail.com)
*
*/
@SuppressWarnings("restriction")
@AllArgsConstructor(access = AccessLevel.PACKAGE)
public final class ObjectXmls implements ObjectStringConvertor {
private Map<String, String> namespacePrefixMapper;
private boolean formatted;
| private Encoding encoding;
|
fintx/fintx-common | src/test/java/org/fintx/lang/PairTest.java | // Path: src/main/java/org/fintx/lang/Pair.java
// public class Pair<L, R> implements Serializable {
//
// /** Serialization version */
// private static final long serialVersionUID = 4954918890077093841L;
//
// /** Left object */
// public L left;
// /** Right object */
// public R right;
//
// /**
// * <p>
// * Obtains an immutable pair of from two objects inferring the generic types.
// * </p>
// *
// * <p>
// * This factory allows the pair to be created using inference to obtain the generic types.
// * </p>
// *
// * @param <L> the left element type
// * @param <R> the right element type
// * @param left the left element, may be null
// * @param right the right element, may be null
// * @return a pair formed from the two parameters, not null
// */
// public static <L, R> Pair<L, R> of(final L left, final R right) {
// return new Pair<L, R>(left, right);
// }
//
// /**
// * Create a new pair instance of two nulls.
// */
// public Pair() {
// super();
// }
//
// /**
// * Create a new pair instance.
// *
// * @param left the left value, may be null
// * @param right the right value, may be null
// */
// public Pair(final L left, final R right) {
// super();
// this.left = left;
// this.right = right;
// }
//
// // -----------------------------------------------------------------------
// /**
// * {@inheritDoc}
// */
// public L getLeft() {
// return left;
// }
//
// /**
// * Sets the left element of the pair.
// *
// * @param left the new value of the left element, may be null
// */
// public void setLeft(final L left) {
// this.left = left;
// }
//
// /**
// * {@inheritDoc}
// */
// public R getRight() {
// return right;
// }
//
// /**
// * Sets the right element of the pair.
// *
// * @param right the new value of the right element, may be null
// */
// public void setRight(final R right) {
// this.right = right;
// }
//
// }
| import static org.junit.Assert.*;
import org.fintx.lang.Pair;
import org.junit.Test;
| /**
* Copyright 2017 FinTx
*
* 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 org.fintx.lang;
/**
* @author bluecreator(qiang.x.wang@gmail.com)
*
*/
public class PairTest {
@Test
public void test() {
| // Path: src/main/java/org/fintx/lang/Pair.java
// public class Pair<L, R> implements Serializable {
//
// /** Serialization version */
// private static final long serialVersionUID = 4954918890077093841L;
//
// /** Left object */
// public L left;
// /** Right object */
// public R right;
//
// /**
// * <p>
// * Obtains an immutable pair of from two objects inferring the generic types.
// * </p>
// *
// * <p>
// * This factory allows the pair to be created using inference to obtain the generic types.
// * </p>
// *
// * @param <L> the left element type
// * @param <R> the right element type
// * @param left the left element, may be null
// * @param right the right element, may be null
// * @return a pair formed from the two parameters, not null
// */
// public static <L, R> Pair<L, R> of(final L left, final R right) {
// return new Pair<L, R>(left, right);
// }
//
// /**
// * Create a new pair instance of two nulls.
// */
// public Pair() {
// super();
// }
//
// /**
// * Create a new pair instance.
// *
// * @param left the left value, may be null
// * @param right the right value, may be null
// */
// public Pair(final L left, final R right) {
// super();
// this.left = left;
// this.right = right;
// }
//
// // -----------------------------------------------------------------------
// /**
// * {@inheritDoc}
// */
// public L getLeft() {
// return left;
// }
//
// /**
// * Sets the left element of the pair.
// *
// * @param left the new value of the left element, may be null
// */
// public void setLeft(final L left) {
// this.left = left;
// }
//
// /**
// * {@inheritDoc}
// */
// public R getRight() {
// return right;
// }
//
// /**
// * Sets the right element of the pair.
// *
// * @param right the new value of the right element, may be null
// */
// public void setRight(final R right) {
// this.right = right;
// }
//
// }
// Path: src/test/java/org/fintx/lang/PairTest.java
import static org.junit.Assert.*;
import org.fintx.lang.Pair;
import org.junit.Test;
/**
* Copyright 2017 FinTx
*
* 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 org.fintx.lang;
/**
* @author bluecreator(qiang.x.wang@gmail.com)
*
*/
public class PairTest {
@Test
public void test() {
| Pair<String,String> pair1=new Pair<String,String>();
|
fintx/fintx-common | src/main/java/org/fintx/util/Objects.java | // Path: src/main/java/org/fintx/lang/Encoding.java
// public enum Encoding implements Codeable<String> {
// UTF_8("UTF-8"), GBK("GBK"), GB18030("GB18030");
// private String code;
//
// private Encoding(String code) {
// this.code = code;
// }
//
// @Override
// public String getCode() {
// // TODO Auto-generated method stub
// return code;
// }
// }
| import org.fintx.lang.Encoding;
import net.sf.cglib.beans.BeanCopier;
import net.sf.cglib.core.Converter;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Array;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.function.Supplier;
import javax.xml.bind.JAXBException;
| * @param obj a reference to be checked against {@code null}
* @return {@code true} if the provided reference is non-{@code null} otherwise {@code false}
*
* @see java.util.function.Predicate
* @since 1.8
*/
public static boolean nonNull(Object obj) {
return java.util.Objects.nonNull(obj);
}
/**
* Checks that the specified object reference is not {@code null} and throws a customized {@link NullPointerException} if it is.
*
* <p>
* Unlike the method {@link #requireNonNull(Object, String)}, this method allows creation of the message to be deferred until after the null check is made.
* While this may confer a performance advantage in the non-null case, when deciding to call this method care should be taken that the costs of creating the
* message supplier are less than the cost of just creating the string message directly.
*
* @param obj the object reference to check for nullity
* @param messageSupplier supplier of the detail message to be used in the event that a {@code NullPointerException} is thrown
* @param <T> the type of the reference
* @return {@code obj} if not {@code null}
* @throws NullPointerException if {@code obj} is {@code null}
* @since 1.8
*/
public static <T> T requireNonNull(T obj, Supplier<String> messageSupplier) {
return java.util.Objects.requireNonNull(obj, messageSupplier);
}
public static class Xml {
| // Path: src/main/java/org/fintx/lang/Encoding.java
// public enum Encoding implements Codeable<String> {
// UTF_8("UTF-8"), GBK("GBK"), GB18030("GB18030");
// private String code;
//
// private Encoding(String code) {
// this.code = code;
// }
//
// @Override
// public String getCode() {
// // TODO Auto-generated method stub
// return code;
// }
// }
// Path: src/main/java/org/fintx/util/Objects.java
import org.fintx.lang.Encoding;
import net.sf.cglib.beans.BeanCopier;
import net.sf.cglib.core.Converter;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Array;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.function.Supplier;
import javax.xml.bind.JAXBException;
* @param obj a reference to be checked against {@code null}
* @return {@code true} if the provided reference is non-{@code null} otherwise {@code false}
*
* @see java.util.function.Predicate
* @since 1.8
*/
public static boolean nonNull(Object obj) {
return java.util.Objects.nonNull(obj);
}
/**
* Checks that the specified object reference is not {@code null} and throws a customized {@link NullPointerException} if it is.
*
* <p>
* Unlike the method {@link #requireNonNull(Object, String)}, this method allows creation of the message to be deferred until after the null check is made.
* While this may confer a performance advantage in the non-null case, when deciding to call this method care should be taken that the costs of creating the
* message supplier are less than the cost of just creating the string message directly.
*
* @param obj the object reference to check for nullity
* @param messageSupplier supplier of the detail message to be used in the event that a {@code NullPointerException} is thrown
* @param <T> the type of the reference
* @return {@code obj} if not {@code null}
* @throws NullPointerException if {@code obj} is {@code null}
* @since 1.8
*/
public static <T> T requireNonNull(T obj, Supplier<String> messageSupplier) {
return java.util.Objects.requireNonNull(obj, messageSupplier);
}
public static class Xml {
| private static ObjectXmls convertor = new ObjectXmls(null, true, Encoding.UTF_8, false, null);
|
agladysh/js-lua | lib/aelua/jslua/mnj/lua/PackageLib.java | // Path: lib/aelua/jslua/java/io/InputStream.java
// public abstract class InputStream {
// public abstract int read() throws IOException;
//
// public int read(byte[]buf, int start, int len) throws IOException {
//
// int end = start + len;
// for (int i = start; i < end; i++) {
// int r = read();
// if (r == -1) {
// return i == start ? -1 : i - start;
// }
// buf[i] = (byte) r;
// }
// return len;
// }
//
// public int read(byte[] buf) throws IOException {
// return read(buf, 0, buf.length);
// }
//
// public void close() throws IOException {
//
// }
// public void mark(int limit)
// {
// }
// public void reset() throws IOException
// {
// }
// }
//
// Path: lib/aelua/jslua/java/io/FileReader.java
// public class FileReader extends Reader{
//
// public FileReader(String s1) throws IOException
// {
// }
// public void mark(int l) throws IOException
// {
// }
//
// public void reset() throws IOException
// {
// }
//
// public int read() throws IOException
// {
// return 0;
// }
//
// public boolean markSupported()
// {
// return false;
// }
// }
| import java.io.InputStream;
import java.io.FileReader;
import java.io.IOException;
| L.call(1, 0);
}
}
/**
* Helper for module. <var>module</var> parameter replaces PUC-Rio
* use of passing it on the stack.
*/
private static void modinit(Lua L, Object module, String modname)
{
L.setField(module, "_M", module); // module._M = module
L.setField(module, "_NAME", modname);
int dot = modname.lastIndexOf('.'); // look for last dot in module name
// Surprisingly, ++dot works when '.' was found and when it wasn't.
++dot;
// set _PACKAGE as package name (full module name minus last part)
L.setField(module, "_PACKAGE", modname.substring(0, dot));
}
private static void loaderror(Lua L, String filename)
{
L.error("error loading module '" + L.toString(L.value(1)) +
"' from file '" + filename + "':\n\t" +
L.toString(L.value(-1)));
}
private static boolean readable(String filename)
{
try
{
| // Path: lib/aelua/jslua/java/io/InputStream.java
// public abstract class InputStream {
// public abstract int read() throws IOException;
//
// public int read(byte[]buf, int start, int len) throws IOException {
//
// int end = start + len;
// for (int i = start; i < end; i++) {
// int r = read();
// if (r == -1) {
// return i == start ? -1 : i - start;
// }
// buf[i] = (byte) r;
// }
// return len;
// }
//
// public int read(byte[] buf) throws IOException {
// return read(buf, 0, buf.length);
// }
//
// public void close() throws IOException {
//
// }
// public void mark(int limit)
// {
// }
// public void reset() throws IOException
// {
// }
// }
//
// Path: lib/aelua/jslua/java/io/FileReader.java
// public class FileReader extends Reader{
//
// public FileReader(String s1) throws IOException
// {
// }
// public void mark(int l) throws IOException
// {
// }
//
// public void reset() throws IOException
// {
// }
//
// public int read() throws IOException
// {
// return 0;
// }
//
// public boolean markSupported()
// {
// return false;
// }
// }
// Path: lib/aelua/jslua/mnj/lua/PackageLib.java
import java.io.InputStream;
import java.io.FileReader;
import java.io.IOException;
L.call(1, 0);
}
}
/**
* Helper for module. <var>module</var> parameter replaces PUC-Rio
* use of passing it on the stack.
*/
private static void modinit(Lua L, Object module, String modname)
{
L.setField(module, "_M", module); // module._M = module
L.setField(module, "_NAME", modname);
int dot = modname.lastIndexOf('.'); // look for last dot in module name
// Surprisingly, ++dot works when '.' was found and when it wasn't.
++dot;
// set _PACKAGE as package name (full module name minus last part)
L.setField(module, "_PACKAGE", modname.substring(0, dot));
}
private static void loaderror(Lua L, String filename)
{
L.error("error loading module '" + L.toString(L.value(1)) +
"' from file '" + filename + "':\n\t" +
L.toString(L.value(-1)));
}
private static boolean readable(String filename)
{
try
{
| FileReader f = new FileReader(filename);
|
agladysh/js-lua | lib/aelua/jslua/mnj/lua/Loader.java | // Path: lib/aelua/jslua/java/io/InputStream.java
// public abstract class InputStream {
// public abstract int read() throws IOException;
//
// public int read(byte[]buf, int start, int len) throws IOException {
//
// int end = start + len;
// for (int i = start; i < end; i++) {
// int r = read();
// if (r == -1) {
// return i == start ? -1 : i - start;
// }
// buf[i] = (byte) r;
// }
// return len;
// }
//
// public int read(byte[] buf) throws IOException {
// return read(buf, 0, buf.length);
// }
//
// public void close() throws IOException {
//
// }
// public void mark(int limit)
// {
// }
// public void reset() throws IOException
// {
// }
// }
| import java.io.EOFException;
import java.io.InputStream;
import java.io.IOException;
| /* $Header: //info.ravenbrook.com/project/jili/version/1.1/code/mnj/lua/Loader.java#1 $
* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject
* to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
* ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package mnj.lua;
/**
* Loads Lua 5.1 binary chunks.
* This loader is restricted to loading Lua 5.1 binary chunks where:
* <ul>
* <li><code>LUAC_VERSION</code> is <code>0x51</code>.</li>
* <li><code>int</code> is 32 bits.</li>
* <li><code>size_t</code> is 32 bits.</li>
* <li><code>Instruction</code> is 32 bits (this is a type defined in
* the PUC-Rio Lua).</li>
* <li><code>lua_Number</code> is an IEEE 754 64-bit double. Suitable
* for passing to {@link java.lang.Double#longBitsToDouble}.</li>
* <li>endianness does not matter (the loader swabs as appropriate).</li>
* </ul>
* Any Lua chunk compiled by a stock Lua 5.1 running on a 32-bit Windows
* PC or at 32-bit OS X machine should be fine.
*/
final class Loader
{
/**
* Whether integers in the binary chunk are stored big-endian or
* little-endian. Recall that the number 0x12345678 is stored: 0x12
* 0x34 0x56 0x78 in big-endian format; and, 0x78 0x56 0x34 0x12 in
* little-endian format.
*/
private boolean bigendian;
| // Path: lib/aelua/jslua/java/io/InputStream.java
// public abstract class InputStream {
// public abstract int read() throws IOException;
//
// public int read(byte[]buf, int start, int len) throws IOException {
//
// int end = start + len;
// for (int i = start; i < end; i++) {
// int r = read();
// if (r == -1) {
// return i == start ? -1 : i - start;
// }
// buf[i] = (byte) r;
// }
// return len;
// }
//
// public int read(byte[] buf) throws IOException {
// return read(buf, 0, buf.length);
// }
//
// public void close() throws IOException {
//
// }
// public void mark(int limit)
// {
// }
// public void reset() throws IOException
// {
// }
// }
// Path: lib/aelua/jslua/mnj/lua/Loader.java
import java.io.EOFException;
import java.io.InputStream;
import java.io.IOException;
/* $Header: //info.ravenbrook.com/project/jili/version/1.1/code/mnj/lua/Loader.java#1 $
* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject
* to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
* ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package mnj.lua;
/**
* Loads Lua 5.1 binary chunks.
* This loader is restricted to loading Lua 5.1 binary chunks where:
* <ul>
* <li><code>LUAC_VERSION</code> is <code>0x51</code>.</li>
* <li><code>int</code> is 32 bits.</li>
* <li><code>size_t</code> is 32 bits.</li>
* <li><code>Instruction</code> is 32 bits (this is a type defined in
* the PUC-Rio Lua).</li>
* <li><code>lua_Number</code> is an IEEE 754 64-bit double. Suitable
* for passing to {@link java.lang.Double#longBitsToDouble}.</li>
* <li>endianness does not matter (the loader swabs as appropriate).</li>
* </ul>
* Any Lua chunk compiled by a stock Lua 5.1 running on a 32-bit Windows
* PC or at 32-bit OS X machine should be fine.
*/
final class Loader
{
/**
* Whether integers in the binary chunk are stored big-endian or
* little-endian. Recall that the number 0x12345678 is stored: 0x12
* 0x34 0x56 0x78 in big-endian format; and, 0x78 0x56 0x34 0x12 in
* little-endian format.
*/
private boolean bigendian;
| private InputStream in;
|
agladysh/js-lua | lib/aelua/jslua/mnj/lua/Lua.java | // Path: lib/aelua/jslua/java/io/InputStream.java
// public abstract class InputStream {
// public abstract int read() throws IOException;
//
// public int read(byte[]buf, int start, int len) throws IOException {
//
// int end = start + len;
// for (int i = start; i < end; i++) {
// int r = read();
// if (r == -1) {
// return i == start ? -1 : i - start;
// }
// buf[i] = (byte) r;
// }
// return len;
// }
//
// public int read(byte[] buf) throws IOException {
// return read(buf, 0, buf.length);
// }
//
// public void close() throws IOException {
//
// }
// public void mark(int limit)
// {
// }
// public void reset() throws IOException
// {
// }
// }
//
// Path: lib/aelua/jslua/java/io/DataOutputStream.java
// public class DataOutputStream extends OutputStream implements DataOutput {
//
// // OutputStream os;
//
// public DataOutputStream (OutputStream os) {
// // this.os = os;
// }
//
// // @Override
// public void write(int b) throws IOException {
// // os.write(b);
// }
//
// public void write(byte[] b,int i,int j) throws IOException {
// // os.write(b);
// }
// public void write(byte[] b) throws IOException {
// // os.write(b);
// }
//
// public void writeBoolean(boolean v) throws IOException {
// // os.write(v ? 1 : 0);
// }
//
// public void writeByte(int v) throws IOException {
// // os.write(v);
// }
//
// public void writeBytes(String s) throws IOException {
// // int len = s.length();
// // for(int i = 0; i < len; i++) {
// // os.write(s.charAt(i) & 0xff);
// // }
// }
//
// public void writeChar(int v) throws IOException {
// // os.write(v >> 8);
// // os.write(v);
// }
//
// public void writeChars(String s) throws IOException {
// // throw new RuntimeException("writeChars NYI");
// }
//
// public void writeDouble(double v) throws IOException {
// // throw new RuntimeException("writeDouble");
// }
//
// public void writeFloat(float v) throws IOException {
// // writeInt(0);//Numbers.floatToIntBits(v));
// }
//
// public void writeInt(int v) throws IOException {
// // os.write(v >> 24);
// // os.write(v >> 16);
// // os.write(v >> 8);
// // os.write(v);
// }
//
// public void writeLong(long v) throws IOException {
// // writeInt((int) (v >> 32L));
// // writeInt((int) v);
// }
//
// public void writeShort(int v) throws IOException {
// // os.write(v >> 8);
// // os.write(v);
// }
//
// public void writeUTF(String s) throws IOException {
// /* ByteArrayOutputStream baos = new ByteArrayOutputStream();
// for (int i = 0; i < s.length(); i++) {
// char c = s.charAt(i);
// if (c > 0 && c < 80) {
// baos.write(c);
// } else if (c < '\u0800') {
// baos.write(0xc0 | (0x1f & (c >> 6)));
// baos.write(0x80 | (0x3f & c));
// } else {
// baos.write(0xe0 | (0x0f & (c >> 12)));
// baos.write(0x80 | (0x3f & (c >> 6)));
// baos.write(0x80 | (0x3f & c));
// }
// }
// writeShort(baos.count);
// os.write(baos.buf, 0, baos.count);
// */
// }
// public void flush() throws IOException {
// }
// }
//
// Path: lib/aelua/jslua/java/io/Reader.java
// public abstract class Reader {
// public void mark(int l) throws IOException
// {
// }
//
// public void reset() throws IOException
// {
// }
//
// public int read() throws IOException
// {
// return 0;
// }
//
// public boolean markSupported()
// {
// return false;
// }
// }
//
// Path: lib/aelua/jslua/java/io/FileReader.java
// public class FileReader extends Reader{
//
// public FileReader(String s1) throws IOException
// {
// }
// public void mark(int l) throws IOException
// {
// }
//
// public void reset() throws IOException
// {
// }
//
// public int read() throws IOException
// {
// return 0;
// }
//
// public boolean markSupported()
// {
// return false;
// }
// }
| import java.util.Enumeration;
import java.util.Stack;
import java.util.Vector;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.Reader;
import java.io.FileReader;
| * @param filename location of file.
* @return status code, as per {@link #load}.
*/
public int loadFile(String filename)
{
if (filename == null)
{
throw new NullPointerException();
}
/*
InputStream in = getClass().getResourceAsStream(filename);
if (in == null)
{
return errfile("open", filename, new IOException());
}
*/
int status = 0;
try
{
/*
in.mark(1);
int c = in.read();
if (c == '#') // Unix exec. file?
{
// :todo: handle this case
}
in.reset();
status = load(in, "@" + filename);
*/
| // Path: lib/aelua/jslua/java/io/InputStream.java
// public abstract class InputStream {
// public abstract int read() throws IOException;
//
// public int read(byte[]buf, int start, int len) throws IOException {
//
// int end = start + len;
// for (int i = start; i < end; i++) {
// int r = read();
// if (r == -1) {
// return i == start ? -1 : i - start;
// }
// buf[i] = (byte) r;
// }
// return len;
// }
//
// public int read(byte[] buf) throws IOException {
// return read(buf, 0, buf.length);
// }
//
// public void close() throws IOException {
//
// }
// public void mark(int limit)
// {
// }
// public void reset() throws IOException
// {
// }
// }
//
// Path: lib/aelua/jslua/java/io/DataOutputStream.java
// public class DataOutputStream extends OutputStream implements DataOutput {
//
// // OutputStream os;
//
// public DataOutputStream (OutputStream os) {
// // this.os = os;
// }
//
// // @Override
// public void write(int b) throws IOException {
// // os.write(b);
// }
//
// public void write(byte[] b,int i,int j) throws IOException {
// // os.write(b);
// }
// public void write(byte[] b) throws IOException {
// // os.write(b);
// }
//
// public void writeBoolean(boolean v) throws IOException {
// // os.write(v ? 1 : 0);
// }
//
// public void writeByte(int v) throws IOException {
// // os.write(v);
// }
//
// public void writeBytes(String s) throws IOException {
// // int len = s.length();
// // for(int i = 0; i < len; i++) {
// // os.write(s.charAt(i) & 0xff);
// // }
// }
//
// public void writeChar(int v) throws IOException {
// // os.write(v >> 8);
// // os.write(v);
// }
//
// public void writeChars(String s) throws IOException {
// // throw new RuntimeException("writeChars NYI");
// }
//
// public void writeDouble(double v) throws IOException {
// // throw new RuntimeException("writeDouble");
// }
//
// public void writeFloat(float v) throws IOException {
// // writeInt(0);//Numbers.floatToIntBits(v));
// }
//
// public void writeInt(int v) throws IOException {
// // os.write(v >> 24);
// // os.write(v >> 16);
// // os.write(v >> 8);
// // os.write(v);
// }
//
// public void writeLong(long v) throws IOException {
// // writeInt((int) (v >> 32L));
// // writeInt((int) v);
// }
//
// public void writeShort(int v) throws IOException {
// // os.write(v >> 8);
// // os.write(v);
// }
//
// public void writeUTF(String s) throws IOException {
// /* ByteArrayOutputStream baos = new ByteArrayOutputStream();
// for (int i = 0; i < s.length(); i++) {
// char c = s.charAt(i);
// if (c > 0 && c < 80) {
// baos.write(c);
// } else if (c < '\u0800') {
// baos.write(0xc0 | (0x1f & (c >> 6)));
// baos.write(0x80 | (0x3f & c));
// } else {
// baos.write(0xe0 | (0x0f & (c >> 12)));
// baos.write(0x80 | (0x3f & (c >> 6)));
// baos.write(0x80 | (0x3f & c));
// }
// }
// writeShort(baos.count);
// os.write(baos.buf, 0, baos.count);
// */
// }
// public void flush() throws IOException {
// }
// }
//
// Path: lib/aelua/jslua/java/io/Reader.java
// public abstract class Reader {
// public void mark(int l) throws IOException
// {
// }
//
// public void reset() throws IOException
// {
// }
//
// public int read() throws IOException
// {
// return 0;
// }
//
// public boolean markSupported()
// {
// return false;
// }
// }
//
// Path: lib/aelua/jslua/java/io/FileReader.java
// public class FileReader extends Reader{
//
// public FileReader(String s1) throws IOException
// {
// }
// public void mark(int l) throws IOException
// {
// }
//
// public void reset() throws IOException
// {
// }
//
// public int read() throws IOException
// {
// return 0;
// }
//
// public boolean markSupported()
// {
// return false;
// }
// }
// Path: lib/aelua/jslua/mnj/lua/Lua.java
import java.util.Enumeration;
import java.util.Stack;
import java.util.Vector;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.Reader;
import java.io.FileReader;
* @param filename location of file.
* @return status code, as per {@link #load}.
*/
public int loadFile(String filename)
{
if (filename == null)
{
throw new NullPointerException();
}
/*
InputStream in = getClass().getResourceAsStream(filename);
if (in == null)
{
return errfile("open", filename, new IOException());
}
*/
int status = 0;
try
{
/*
in.mark(1);
int c = in.read();
if (c == '#') // Unix exec. file?
{
// :todo: handle this case
}
in.reset();
status = load(in, "@" + filename);
*/
| status = load(new FileReader(filename), "@" + filename);
|
agladysh/js-lua | lib/aelua/jslua/mnj/lua/Lua.java | // Path: lib/aelua/jslua/java/io/InputStream.java
// public abstract class InputStream {
// public abstract int read() throws IOException;
//
// public int read(byte[]buf, int start, int len) throws IOException {
//
// int end = start + len;
// for (int i = start; i < end; i++) {
// int r = read();
// if (r == -1) {
// return i == start ? -1 : i - start;
// }
// buf[i] = (byte) r;
// }
// return len;
// }
//
// public int read(byte[] buf) throws IOException {
// return read(buf, 0, buf.length);
// }
//
// public void close() throws IOException {
//
// }
// public void mark(int limit)
// {
// }
// public void reset() throws IOException
// {
// }
// }
//
// Path: lib/aelua/jslua/java/io/DataOutputStream.java
// public class DataOutputStream extends OutputStream implements DataOutput {
//
// // OutputStream os;
//
// public DataOutputStream (OutputStream os) {
// // this.os = os;
// }
//
// // @Override
// public void write(int b) throws IOException {
// // os.write(b);
// }
//
// public void write(byte[] b,int i,int j) throws IOException {
// // os.write(b);
// }
// public void write(byte[] b) throws IOException {
// // os.write(b);
// }
//
// public void writeBoolean(boolean v) throws IOException {
// // os.write(v ? 1 : 0);
// }
//
// public void writeByte(int v) throws IOException {
// // os.write(v);
// }
//
// public void writeBytes(String s) throws IOException {
// // int len = s.length();
// // for(int i = 0; i < len; i++) {
// // os.write(s.charAt(i) & 0xff);
// // }
// }
//
// public void writeChar(int v) throws IOException {
// // os.write(v >> 8);
// // os.write(v);
// }
//
// public void writeChars(String s) throws IOException {
// // throw new RuntimeException("writeChars NYI");
// }
//
// public void writeDouble(double v) throws IOException {
// // throw new RuntimeException("writeDouble");
// }
//
// public void writeFloat(float v) throws IOException {
// // writeInt(0);//Numbers.floatToIntBits(v));
// }
//
// public void writeInt(int v) throws IOException {
// // os.write(v >> 24);
// // os.write(v >> 16);
// // os.write(v >> 8);
// // os.write(v);
// }
//
// public void writeLong(long v) throws IOException {
// // writeInt((int) (v >> 32L));
// // writeInt((int) v);
// }
//
// public void writeShort(int v) throws IOException {
// // os.write(v >> 8);
// // os.write(v);
// }
//
// public void writeUTF(String s) throws IOException {
// /* ByteArrayOutputStream baos = new ByteArrayOutputStream();
// for (int i = 0; i < s.length(); i++) {
// char c = s.charAt(i);
// if (c > 0 && c < 80) {
// baos.write(c);
// } else if (c < '\u0800') {
// baos.write(0xc0 | (0x1f & (c >> 6)));
// baos.write(0x80 | (0x3f & c));
// } else {
// baos.write(0xe0 | (0x0f & (c >> 12)));
// baos.write(0x80 | (0x3f & (c >> 6)));
// baos.write(0x80 | (0x3f & c));
// }
// }
// writeShort(baos.count);
// os.write(baos.buf, 0, baos.count);
// */
// }
// public void flush() throws IOException {
// }
// }
//
// Path: lib/aelua/jslua/java/io/Reader.java
// public abstract class Reader {
// public void mark(int l) throws IOException
// {
// }
//
// public void reset() throws IOException
// {
// }
//
// public int read() throws IOException
// {
// return 0;
// }
//
// public boolean markSupported()
// {
// return false;
// }
// }
//
// Path: lib/aelua/jslua/java/io/FileReader.java
// public class FileReader extends Reader{
//
// public FileReader(String s1) throws IOException
// {
// }
// public void mark(int l) throws IOException
// {
// }
//
// public void reset() throws IOException
// {
// }
//
// public int read() throws IOException
// {
// return 0;
// }
//
// public boolean markSupported()
// {
// return false;
// }
// }
| import java.util.Enumeration;
import java.util.Stack;
import java.util.Vector;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.Reader;
import java.io.FileReader;
| if (r != NUMBER)
{
return r;
}
return new Double(stack[idx].d);
}
/**
* Sets the stack element. Double instances are converted to double.
* @param o Object to store.
* @param idx absolute index into stack (0 <= idx < stackSize).
*/
private void setObjectAt(Object o, int idx)
{
if (o instanceof Double)
{
stack[idx].r = NUMBER;
stack[idx].d = ((Double)o).doubleValue();
return;
}
stack[idx].r = o;
}
/**
* Corresponds to ldump's luaU_dump method, but with data gone and writer
* replaced by OutputStream.
*/
static int uDump(Proto f, OutputStream writer, boolean strip)
throws IOException
{
| // Path: lib/aelua/jslua/java/io/InputStream.java
// public abstract class InputStream {
// public abstract int read() throws IOException;
//
// public int read(byte[]buf, int start, int len) throws IOException {
//
// int end = start + len;
// for (int i = start; i < end; i++) {
// int r = read();
// if (r == -1) {
// return i == start ? -1 : i - start;
// }
// buf[i] = (byte) r;
// }
// return len;
// }
//
// public int read(byte[] buf) throws IOException {
// return read(buf, 0, buf.length);
// }
//
// public void close() throws IOException {
//
// }
// public void mark(int limit)
// {
// }
// public void reset() throws IOException
// {
// }
// }
//
// Path: lib/aelua/jslua/java/io/DataOutputStream.java
// public class DataOutputStream extends OutputStream implements DataOutput {
//
// // OutputStream os;
//
// public DataOutputStream (OutputStream os) {
// // this.os = os;
// }
//
// // @Override
// public void write(int b) throws IOException {
// // os.write(b);
// }
//
// public void write(byte[] b,int i,int j) throws IOException {
// // os.write(b);
// }
// public void write(byte[] b) throws IOException {
// // os.write(b);
// }
//
// public void writeBoolean(boolean v) throws IOException {
// // os.write(v ? 1 : 0);
// }
//
// public void writeByte(int v) throws IOException {
// // os.write(v);
// }
//
// public void writeBytes(String s) throws IOException {
// // int len = s.length();
// // for(int i = 0; i < len; i++) {
// // os.write(s.charAt(i) & 0xff);
// // }
// }
//
// public void writeChar(int v) throws IOException {
// // os.write(v >> 8);
// // os.write(v);
// }
//
// public void writeChars(String s) throws IOException {
// // throw new RuntimeException("writeChars NYI");
// }
//
// public void writeDouble(double v) throws IOException {
// // throw new RuntimeException("writeDouble");
// }
//
// public void writeFloat(float v) throws IOException {
// // writeInt(0);//Numbers.floatToIntBits(v));
// }
//
// public void writeInt(int v) throws IOException {
// // os.write(v >> 24);
// // os.write(v >> 16);
// // os.write(v >> 8);
// // os.write(v);
// }
//
// public void writeLong(long v) throws IOException {
// // writeInt((int) (v >> 32L));
// // writeInt((int) v);
// }
//
// public void writeShort(int v) throws IOException {
// // os.write(v >> 8);
// // os.write(v);
// }
//
// public void writeUTF(String s) throws IOException {
// /* ByteArrayOutputStream baos = new ByteArrayOutputStream();
// for (int i = 0; i < s.length(); i++) {
// char c = s.charAt(i);
// if (c > 0 && c < 80) {
// baos.write(c);
// } else if (c < '\u0800') {
// baos.write(0xc0 | (0x1f & (c >> 6)));
// baos.write(0x80 | (0x3f & c));
// } else {
// baos.write(0xe0 | (0x0f & (c >> 12)));
// baos.write(0x80 | (0x3f & (c >> 6)));
// baos.write(0x80 | (0x3f & c));
// }
// }
// writeShort(baos.count);
// os.write(baos.buf, 0, baos.count);
// */
// }
// public void flush() throws IOException {
// }
// }
//
// Path: lib/aelua/jslua/java/io/Reader.java
// public abstract class Reader {
// public void mark(int l) throws IOException
// {
// }
//
// public void reset() throws IOException
// {
// }
//
// public int read() throws IOException
// {
// return 0;
// }
//
// public boolean markSupported()
// {
// return false;
// }
// }
//
// Path: lib/aelua/jslua/java/io/FileReader.java
// public class FileReader extends Reader{
//
// public FileReader(String s1) throws IOException
// {
// }
// public void mark(int l) throws IOException
// {
// }
//
// public void reset() throws IOException
// {
// }
//
// public int read() throws IOException
// {
// return 0;
// }
//
// public boolean markSupported()
// {
// return false;
// }
// }
// Path: lib/aelua/jslua/mnj/lua/Lua.java
import java.util.Enumeration;
import java.util.Stack;
import java.util.Vector;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.Reader;
import java.io.FileReader;
if (r != NUMBER)
{
return r;
}
return new Double(stack[idx].d);
}
/**
* Sets the stack element. Double instances are converted to double.
* @param o Object to store.
* @param idx absolute index into stack (0 <= idx < stackSize).
*/
private void setObjectAt(Object o, int idx)
{
if (o instanceof Double)
{
stack[idx].r = NUMBER;
stack[idx].d = ((Double)o).doubleValue();
return;
}
stack[idx].r = o;
}
/**
* Corresponds to ldump's luaU_dump method, but with data gone and writer
* replaced by OutputStream.
*/
static int uDump(Proto f, OutputStream writer, boolean strip)
throws IOException
{
| DumpState d = new DumpState(new DataOutputStream(writer), strip) ;
|
agladysh/js-lua | lib/aelua/jslua/mnj/lua/BaseLib.java | // Path: lib/aelua/jslua/java/io/Reader.java
// public abstract class Reader {
// public void mark(int l) throws IOException
// {
// }
//
// public void reset() throws IOException
// {
// }
//
// public int read() throws IOException
// {
// return 0;
// }
//
// public boolean markSupported()
// {
// return false;
// }
// }
| import java.io.PrintStream;
import java.io.Reader;
import java.util.Enumeration;
| return 1;
}
/** Implements getmetatable. */
private static int getmetatable(Lua L)
{
L.checkAny(1);
Object mt = L.getMetatable(L.value(1));
if (mt == null)
{
L.pushNil();
return 1;
}
Object protectedmt = L.getMetafield(L.value(1), "__metatable");
if (L.isNil(protectedmt))
{
L.push(mt); // return metatable
}
else
{
L.push(protectedmt); // return __metatable field
}
return 1;
}
/** Implements load. */
private static int load(Lua L)
{
String cname = L.optString(2, "=(load)");
L.checkType(1, Lua.TFUNCTION);
| // Path: lib/aelua/jslua/java/io/Reader.java
// public abstract class Reader {
// public void mark(int l) throws IOException
// {
// }
//
// public void reset() throws IOException
// {
// }
//
// public int read() throws IOException
// {
// return 0;
// }
//
// public boolean markSupported()
// {
// return false;
// }
// }
// Path: lib/aelua/jslua/mnj/lua/BaseLib.java
import java.io.PrintStream;
import java.io.Reader;
import java.util.Enumeration;
return 1;
}
/** Implements getmetatable. */
private static int getmetatable(Lua L)
{
L.checkAny(1);
Object mt = L.getMetatable(L.value(1));
if (mt == null)
{
L.pushNil();
return 1;
}
Object protectedmt = L.getMetafield(L.value(1), "__metatable");
if (L.isNil(protectedmt))
{
L.push(mt); // return metatable
}
else
{
L.push(protectedmt); // return __metatable field
}
return 1;
}
/** Implements load. */
private static int load(Lua L)
{
String cname = L.optString(2, "=(load)");
L.checkType(1, Lua.TFUNCTION);
| Reader r = new BaseLibReader(L, L.value(1));
|
agladysh/js-lua | lib/aelua/jslua/mnj/lua/MathLib.java | // Path: lib/aelua/jslua/java/util/Random.java
// public class Random {
//
// protected int next(int bits) {
// return com.google.gwt.user.client.Random.nextInt();
// }
//
// public int nextInt() {
// return com.google.gwt.user.client.Random.nextInt();
// }
//
// public int nextInt(int n) {
// return com.google.gwt.user.client.Random.nextInt(n);
// }
//
// public long nextLong() {
// return 0;
// }
// public void setSeed(long l) {
// }
//
// public boolean nextBoolean() {
// return com.google.gwt.user.client.Random.nextBoolean();
// }
//
// public float nextFloat() {
// return (float) com.google.gwt.user.client.Random.nextDouble();
// }
//
// public double nextDouble() {
// return com.google.gwt.user.client.Random.nextDouble();
// }
// }
| import java.util.Random;
| /* $Header: //info.ravenbrook.com/project/jili/version/1.1/code/mnj/lua/MathLib.java#1 $
* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject
* to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
* ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package mnj.lua;
/**
* Contains Lua's math library.
* The library can be opened using the {@link #open} method.
* Because this library is implemented on top of CLDC 1.1 it is not as
* complete as the PUC-Rio math library. Trigononmetric inverses
* (EG <code>acos</code>) and hyperbolic trigonometric functions (EG
* <code>cosh</code>) are not provided.
*/
public final class MathLib extends LuaJavaCallback
{
// Each function in the library corresponds to an instance of
// this class which is associated (the 'which' member) with an integer
// which is unique within this class. They are taken from the following
// set.
private static final int ABS = 1;
//private static final int acos = 2;
//private static final int asin = 3;
//private static final int atan2 = 4;
//private static final int atan = 5;
private static final int CEIL = 6;
//private static final int cosh = 7;
private static final int COS = 8;
private static final int DEG = 9;
private static final int EXP = 10;
private static final int FLOOR = 11;
private static final int FMOD = 12;
//private static final int frexp = 13;
//private static final int ldexp = 14;
//private static final int log = 15;
private static final int MAX = 16;
private static final int MIN = 17;
private static final int MODF = 18;
private static final int POW = 19;
private static final int RAD = 20;
private static final int RANDOM = 21;
private static final int RANDOMSEED = 22;
//private static final int sinh = 23;
private static final int SIN = 24;
private static final int SQRT = 25;
//private static final int tanh = 26;
private static final int TAN = 27;
| // Path: lib/aelua/jslua/java/util/Random.java
// public class Random {
//
// protected int next(int bits) {
// return com.google.gwt.user.client.Random.nextInt();
// }
//
// public int nextInt() {
// return com.google.gwt.user.client.Random.nextInt();
// }
//
// public int nextInt(int n) {
// return com.google.gwt.user.client.Random.nextInt(n);
// }
//
// public long nextLong() {
// return 0;
// }
// public void setSeed(long l) {
// }
//
// public boolean nextBoolean() {
// return com.google.gwt.user.client.Random.nextBoolean();
// }
//
// public float nextFloat() {
// return (float) com.google.gwt.user.client.Random.nextDouble();
// }
//
// public double nextDouble() {
// return com.google.gwt.user.client.Random.nextDouble();
// }
// }
// Path: lib/aelua/jslua/mnj/lua/MathLib.java
import java.util.Random;
/* $Header: //info.ravenbrook.com/project/jili/version/1.1/code/mnj/lua/MathLib.java#1 $
* Copyright (c) 2006 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject
* to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
* ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package mnj.lua;
/**
* Contains Lua's math library.
* The library can be opened using the {@link #open} method.
* Because this library is implemented on top of CLDC 1.1 it is not as
* complete as the PUC-Rio math library. Trigononmetric inverses
* (EG <code>acos</code>) and hyperbolic trigonometric functions (EG
* <code>cosh</code>) are not provided.
*/
public final class MathLib extends LuaJavaCallback
{
// Each function in the library corresponds to an instance of
// this class which is associated (the 'which' member) with an integer
// which is unique within this class. They are taken from the following
// set.
private static final int ABS = 1;
//private static final int acos = 2;
//private static final int asin = 3;
//private static final int atan2 = 4;
//private static final int atan = 5;
private static final int CEIL = 6;
//private static final int cosh = 7;
private static final int COS = 8;
private static final int DEG = 9;
private static final int EXP = 10;
private static final int FLOOR = 11;
private static final int FMOD = 12;
//private static final int frexp = 13;
//private static final int ldexp = 14;
//private static final int log = 15;
private static final int MAX = 16;
private static final int MIN = 17;
private static final int MODF = 18;
private static final int POW = 19;
private static final int RAD = 20;
private static final int RANDOM = 21;
private static final int RANDOMSEED = 22;
//private static final int sinh = 23;
private static final int SIN = 24;
private static final int SQRT = 25;
//private static final int tanh = 26;
private static final int TAN = 27;
| private static final Random rng = new Random();
|
agladysh/js-lua | lib/aelua/jslua/mnj/lua/StringLib.java | // Path: lib/aelua/jslua/java/io/ByteArrayOutputStream.java
// public class ByteArrayOutputStream extends OutputStream {
//
// // protected int count;
// // protected byte[] buf;
//
// public ByteArrayOutputStream() {
// // this(16);
// }
//
// public ByteArrayOutputStream(int initialSize) {
// // buf = new byte[initialSize];
// }
//
// // @Override
// public void write(int b) {
// /* if (buf.length == count) {
// byte[] newBuf = new byte[buf.length * 3 / 2];
// System.arraycopy(buf, 0, newBuf, 0, count);
// buf = newBuf;
// }
//
// buf[count++] = (byte) b;
// */
// }
//
// public byte[] toByteArray() {
// byte[] result = new byte[1];
// // System.arraycopy(buf, 0, result, 0, count);
// return result;
// }
//
//
// public int size() {
// return 1;
// }
// }
| import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Vector;
| int n = pose - posi + 1;
for (int i=0; i<n; ++i)
{
L.pushNumber(s.charAt(posi+i-1));
}
return n;
}
/** Implements string.char. Name mangled to avoid keyword. */
private static int charFunction(Lua L)
{
int n = L.getTop(); // number of arguments
StringBuffer b = new StringBuffer();
for (int i=1; i<=n; ++i)
{
int c = L.checkInt(i);
L.argCheck((char)c == c, i, "invalid value");
b.append((char)c);
}
L.push(b.toString());
return 1;
}
/** Implements string.dump. */
private static int dump(Lua L)
{
L.checkType(1, Lua.TFUNCTION);
L.setTop(1);
try
{
| // Path: lib/aelua/jslua/java/io/ByteArrayOutputStream.java
// public class ByteArrayOutputStream extends OutputStream {
//
// // protected int count;
// // protected byte[] buf;
//
// public ByteArrayOutputStream() {
// // this(16);
// }
//
// public ByteArrayOutputStream(int initialSize) {
// // buf = new byte[initialSize];
// }
//
// // @Override
// public void write(int b) {
// /* if (buf.length == count) {
// byte[] newBuf = new byte[buf.length * 3 / 2];
// System.arraycopy(buf, 0, newBuf, 0, count);
// buf = newBuf;
// }
//
// buf[count++] = (byte) b;
// */
// }
//
// public byte[] toByteArray() {
// byte[] result = new byte[1];
// // System.arraycopy(buf, 0, result, 0, count);
// return result;
// }
//
//
// public int size() {
// return 1;
// }
// }
// Path: lib/aelua/jslua/mnj/lua/StringLib.java
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Vector;
int n = pose - posi + 1;
for (int i=0; i<n; ++i)
{
L.pushNumber(s.charAt(posi+i-1));
}
return n;
}
/** Implements string.char. Name mangled to avoid keyword. */
private static int charFunction(Lua L)
{
int n = L.getTop(); // number of arguments
StringBuffer b = new StringBuffer();
for (int i=1; i<=n; ++i)
{
int c = L.checkInt(i);
L.argCheck((char)c == c, i, "invalid value");
b.append((char)c);
}
L.push(b.toString());
return 1;
}
/** Implements string.dump. */
private static int dump(Lua L)
{
L.checkType(1, Lua.TFUNCTION);
L.setTop(1);
try
{
| ByteArrayOutputStream s = new ByteArrayOutputStream();
|
six2six/fixture-factory | src/test/java/br/com/six2six/fixturefactory/ObjectFactoryTest.java | // Path: src/test/java/br/com/six2six/fixturefactory/model/User.java
// public class User implements Serializable {
//
// private static final long serialVersionUID = 6276678114928905392L;
//
// private String name;
// private String login;
// private String password;
// private Gender gender;
// private String email;
// private List<UserType> userTypes;
//
// public String getName() {
// return name;
// }
// public void setName(String name) {
// this.name = name;
// }
// public String getLogin() {
// return login;
// }
// public void setLogin(String login) {
// this.login = login;
// }
// public String getPassword() {
// return password;
// }
// public void setPassword(String password) {
// this.password = password;
// }
// public Gender getGender() {
// return gender;
// }
// public void setGender(Gender gender) {
// this.gender = gender;
// }
// public String getEmail() {
// return email;
// }
// public void setEmail(String email) {
// this.email = email;
// }
// public List<UserType> getUserTypes() {
// return userTypes;
// }
// public void setUserTypes(List<UserType> userTypes) {
// this.userTypes = userTypes;
// }
//
// }
| import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.Arrays;
import org.junit.Before;
import org.junit.Test;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import br.com.six2six.fixturefactory.model.User; | package br.com.six2six.fixturefactory;
public class ObjectFactoryTest {
private TemplateHolder templateHolder;
private ObjectFactory objectFactory;
@Before
public void setUp() {
templateHolder = mockTemplateHolder();
objectFactory = new ObjectFactory(templateHolder);
}
@Test(expected = IllegalArgumentException.class)
public void shouldThrowExceptionForGimmeWithQuantityAndWrongNumberOfTemplates() {
objectFactory.gimme(3, Arrays.asList("template1", "template2"));
}
//hack to workaround Mockito error when trying to return a Class<?>
private TemplateHolder mockTemplateHolder() {
TemplateHolder templateHolder = mock(TemplateHolder.class); | // Path: src/test/java/br/com/six2six/fixturefactory/model/User.java
// public class User implements Serializable {
//
// private static final long serialVersionUID = 6276678114928905392L;
//
// private String name;
// private String login;
// private String password;
// private Gender gender;
// private String email;
// private List<UserType> userTypes;
//
// public String getName() {
// return name;
// }
// public void setName(String name) {
// this.name = name;
// }
// public String getLogin() {
// return login;
// }
// public void setLogin(String login) {
// this.login = login;
// }
// public String getPassword() {
// return password;
// }
// public void setPassword(String password) {
// this.password = password;
// }
// public Gender getGender() {
// return gender;
// }
// public void setGender(Gender gender) {
// this.gender = gender;
// }
// public String getEmail() {
// return email;
// }
// public void setEmail(String email) {
// this.email = email;
// }
// public List<UserType> getUserTypes() {
// return userTypes;
// }
// public void setUserTypes(List<UserType> userTypes) {
// this.userTypes = userTypes;
// }
//
// }
// Path: src/test/java/br/com/six2six/fixturefactory/ObjectFactoryTest.java
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.Arrays;
import org.junit.Before;
import org.junit.Test;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import br.com.six2six.fixturefactory.model.User;
package br.com.six2six.fixturefactory;
public class ObjectFactoryTest {
private TemplateHolder templateHolder;
private ObjectFactory objectFactory;
@Before
public void setUp() {
templateHolder = mockTemplateHolder();
objectFactory = new ObjectFactory(templateHolder);
}
@Test(expected = IllegalArgumentException.class)
public void shouldThrowExceptionForGimmeWithQuantityAndWrongNumberOfTemplates() {
objectFactory.gimme(3, Arrays.asList("template1", "template2"));
}
//hack to workaround Mockito error when trying to return a Class<?>
private TemplateHolder mockTemplateHolder() {
TemplateHolder templateHolder = mock(TemplateHolder.class); | final Class<?> clazz = User.class; |
six2six/fixture-factory | src/main/java/br/com/six2six/fixturefactory/function/impl/CnpjFunction.java | // Path: src/main/java/br/com/six2six/fixturefactory/base/Range.java
// public class Range {
//
// private Number start;
//
// private Number end;
//
// public Range(Number start, Number end) {
// if (start.doubleValue() >= end.doubleValue()) {
// throw new IllegalArgumentException(String.format("incorrect range: [%d, %d]", start, end));
// }
//
// this.start = start;
// this.end = end;
// }
//
// public Number getStart() {
// return start;
// }
//
// public Number getEnd() {
// return end;
// }
//
// }
| import br.com.six2six.fixturefactory.base.Range;
import br.com.six2six.fixturefactory.function.AtomicFunction; | package br.com.six2six.fixturefactory.function.impl;
public class CnpjFunction implements AtomicFunction {
private boolean formatted;
public CnpjFunction() { }
public CnpjFunction(boolean formatted) {
this.formatted = formatted;
}
@Override
@SuppressWarnings("unchecked")
public <T> T generateValue() { | // Path: src/main/java/br/com/six2six/fixturefactory/base/Range.java
// public class Range {
//
// private Number start;
//
// private Number end;
//
// public Range(Number start, Number end) {
// if (start.doubleValue() >= end.doubleValue()) {
// throw new IllegalArgumentException(String.format("incorrect range: [%d, %d]", start, end));
// }
//
// this.start = start;
// this.end = end;
// }
//
// public Number getStart() {
// return start;
// }
//
// public Number getEnd() {
// return end;
// }
//
// }
// Path: src/main/java/br/com/six2six/fixturefactory/function/impl/CnpjFunction.java
import br.com.six2six.fixturefactory.base.Range;
import br.com.six2six.fixturefactory.function.AtomicFunction;
package br.com.six2six.fixturefactory.function.impl;
public class CnpjFunction implements AtomicFunction {
private boolean formatted;
public CnpjFunction() { }
public CnpjFunction(boolean formatted) {
this.formatted = formatted;
}
@Override
@SuppressWarnings("unchecked")
public <T> T generateValue() { | RandomFunction random = new RandomFunction(Integer.class, new Range(1, 9)); |
six2six/fixture-factory | src/test/java/br/com/six2six/fixturefactory/FixtureClientTest.java | // Path: src/main/java/br/com/six2six/fixturefactory/loader/FixtureFactoryLoader.java
// public class FixtureFactoryLoader {
//
// public static void loadTemplates(String basePackage) {
// for (Class<?> clazz : getClassesForPackage(basePackage)) {
// if (!clazz.isInterface() && TemplateLoader.class.isAssignableFrom(clazz)) {
// try {
// ((TemplateLoader) clazz.newInstance()).load();
// } catch (Exception e) {
// throw new RuntimeException(String.format("template %s not loaded", clazz.getName()), e);
// }
// }
// }
// }
// }
//
// Path: src/test/java/br/com/six2six/fixturefactory/model/Client.java
// public class Client implements Serializable {
//
// private static final long serialVersionUID = 6875996936038420202L;
//
// private Long id;
// private String name;
// private String nickname;
// private String email;
// private Calendar birthday;
// private String birthdayAsString;
// private Address address;
//
// private Client() { }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getNickname() {
// return nickname;
// }
//
// public void setNickname(String nickname) {
// this.nickname = nickname;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public Calendar getBirthday() {
// return birthday;
// }
//
// public void setBirthday(Calendar birthday) {
// this.birthday = birthday;
// }
//
// public Address getAddress() {
// return address;
// }
//
// public void setAddress(Address address) {
// this.address = address;
// }
// public String getBirthdayAsString() {
// return birthdayAsString;
// }
// public void setBirthdayAsString(String birthdayAsString) {
// this.birthdayAsString = birthdayAsString;
// }
//
// @Override
// public String toString() {
// return "Client [address=" + address + ", birthday=" + birthday + ", email=" + email + ", id=" + id + ", name=" + name + ", nickname=" + nickname + "]";
// }
//
// }
| import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import org.junit.BeforeClass;
import org.junit.Test;
import br.com.six2six.fixturefactory.loader.FixtureFactoryLoader;
import br.com.six2six.fixturefactory.model.Address;
import br.com.six2six.fixturefactory.model.Client;
| package br.com.six2six.fixturefactory;
public class FixtureClientTest {
@BeforeClass
public static void setUp() {
| // Path: src/main/java/br/com/six2six/fixturefactory/loader/FixtureFactoryLoader.java
// public class FixtureFactoryLoader {
//
// public static void loadTemplates(String basePackage) {
// for (Class<?> clazz : getClassesForPackage(basePackage)) {
// if (!clazz.isInterface() && TemplateLoader.class.isAssignableFrom(clazz)) {
// try {
// ((TemplateLoader) clazz.newInstance()).load();
// } catch (Exception e) {
// throw new RuntimeException(String.format("template %s not loaded", clazz.getName()), e);
// }
// }
// }
// }
// }
//
// Path: src/test/java/br/com/six2six/fixturefactory/model/Client.java
// public class Client implements Serializable {
//
// private static final long serialVersionUID = 6875996936038420202L;
//
// private Long id;
// private String name;
// private String nickname;
// private String email;
// private Calendar birthday;
// private String birthdayAsString;
// private Address address;
//
// private Client() { }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getNickname() {
// return nickname;
// }
//
// public void setNickname(String nickname) {
// this.nickname = nickname;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public Calendar getBirthday() {
// return birthday;
// }
//
// public void setBirthday(Calendar birthday) {
// this.birthday = birthday;
// }
//
// public Address getAddress() {
// return address;
// }
//
// public void setAddress(Address address) {
// this.address = address;
// }
// public String getBirthdayAsString() {
// return birthdayAsString;
// }
// public void setBirthdayAsString(String birthdayAsString) {
// this.birthdayAsString = birthdayAsString;
// }
//
// @Override
// public String toString() {
// return "Client [address=" + address + ", birthday=" + birthday + ", email=" + email + ", id=" + id + ", name=" + name + ", nickname=" + nickname + "]";
// }
//
// }
// Path: src/test/java/br/com/six2six/fixturefactory/FixtureClientTest.java
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import org.junit.BeforeClass;
import org.junit.Test;
import br.com.six2six.fixturefactory.loader.FixtureFactoryLoader;
import br.com.six2six.fixturefactory.model.Address;
import br.com.six2six.fixturefactory.model.Client;
package br.com.six2six.fixturefactory;
public class FixtureClientTest {
@BeforeClass
public static void setUp() {
| FixtureFactoryLoader.loadTemplates("br.com.six2six.template");
|
six2six/fixture-factory | src/test/java/br/com/six2six/fixturefactory/FixtureClientTest.java | // Path: src/main/java/br/com/six2six/fixturefactory/loader/FixtureFactoryLoader.java
// public class FixtureFactoryLoader {
//
// public static void loadTemplates(String basePackage) {
// for (Class<?> clazz : getClassesForPackage(basePackage)) {
// if (!clazz.isInterface() && TemplateLoader.class.isAssignableFrom(clazz)) {
// try {
// ((TemplateLoader) clazz.newInstance()).load();
// } catch (Exception e) {
// throw new RuntimeException(String.format("template %s not loaded", clazz.getName()), e);
// }
// }
// }
// }
// }
//
// Path: src/test/java/br/com/six2six/fixturefactory/model/Client.java
// public class Client implements Serializable {
//
// private static final long serialVersionUID = 6875996936038420202L;
//
// private Long id;
// private String name;
// private String nickname;
// private String email;
// private Calendar birthday;
// private String birthdayAsString;
// private Address address;
//
// private Client() { }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getNickname() {
// return nickname;
// }
//
// public void setNickname(String nickname) {
// this.nickname = nickname;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public Calendar getBirthday() {
// return birthday;
// }
//
// public void setBirthday(Calendar birthday) {
// this.birthday = birthday;
// }
//
// public Address getAddress() {
// return address;
// }
//
// public void setAddress(Address address) {
// this.address = address;
// }
// public String getBirthdayAsString() {
// return birthdayAsString;
// }
// public void setBirthdayAsString(String birthdayAsString) {
// this.birthdayAsString = birthdayAsString;
// }
//
// @Override
// public String toString() {
// return "Client [address=" + address + ", birthday=" + birthday + ", email=" + email + ", id=" + id + ", name=" + name + ", nickname=" + nickname + "]";
// }
//
// }
| import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import org.junit.BeforeClass;
import org.junit.Test;
import br.com.six2six.fixturefactory.loader.FixtureFactoryLoader;
import br.com.six2six.fixturefactory.model.Address;
import br.com.six2six.fixturefactory.model.Client;
| package br.com.six2six.fixturefactory;
public class FixtureClientTest {
@BeforeClass
public static void setUp() {
FixtureFactoryLoader.loadTemplates("br.com.six2six.template");
}
@Test
public void fixtureClient() {
| // Path: src/main/java/br/com/six2six/fixturefactory/loader/FixtureFactoryLoader.java
// public class FixtureFactoryLoader {
//
// public static void loadTemplates(String basePackage) {
// for (Class<?> clazz : getClassesForPackage(basePackage)) {
// if (!clazz.isInterface() && TemplateLoader.class.isAssignableFrom(clazz)) {
// try {
// ((TemplateLoader) clazz.newInstance()).load();
// } catch (Exception e) {
// throw new RuntimeException(String.format("template %s not loaded", clazz.getName()), e);
// }
// }
// }
// }
// }
//
// Path: src/test/java/br/com/six2six/fixturefactory/model/Client.java
// public class Client implements Serializable {
//
// private static final long serialVersionUID = 6875996936038420202L;
//
// private Long id;
// private String name;
// private String nickname;
// private String email;
// private Calendar birthday;
// private String birthdayAsString;
// private Address address;
//
// private Client() { }
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// public String getNickname() {
// return nickname;
// }
//
// public void setNickname(String nickname) {
// this.nickname = nickname;
// }
//
// public String getEmail() {
// return email;
// }
//
// public void setEmail(String email) {
// this.email = email;
// }
//
// public Calendar getBirthday() {
// return birthday;
// }
//
// public void setBirthday(Calendar birthday) {
// this.birthday = birthday;
// }
//
// public Address getAddress() {
// return address;
// }
//
// public void setAddress(Address address) {
// this.address = address;
// }
// public String getBirthdayAsString() {
// return birthdayAsString;
// }
// public void setBirthdayAsString(String birthdayAsString) {
// this.birthdayAsString = birthdayAsString;
// }
//
// @Override
// public String toString() {
// return "Client [address=" + address + ", birthday=" + birthday + ", email=" + email + ", id=" + id + ", name=" + name + ", nickname=" + nickname + "]";
// }
//
// }
// Path: src/test/java/br/com/six2six/fixturefactory/FixtureClientTest.java
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import org.junit.BeforeClass;
import org.junit.Test;
import br.com.six2six.fixturefactory.loader.FixtureFactoryLoader;
import br.com.six2six.fixturefactory.model.Address;
import br.com.six2six.fixturefactory.model.Client;
package br.com.six2six.fixturefactory;
public class FixtureClientTest {
@BeforeClass
public static void setUp() {
FixtureFactoryLoader.loadTemplates("br.com.six2six.template");
}
@Test
public void fixtureClient() {
| Client client = Fixture.from(Client.class).gimme("valid");
|
six2six/fixture-factory | src/main/java/br/com/six2six/fixturefactory/transformer/DateTimeTransformer.java | // Path: src/main/java/br/com/six2six/fixturefactory/util/DateTimeUtils.java
// public static java.time.ZonedDateTime toZonedDateTime(Calendar value) {
// return value.toInstant().atZone(value.getTimeZone().toZoneId());
// }
| import static br.com.six2six.fixturefactory.util.DateTimeUtils.toZonedDateTime;
import java.util.Calendar;
import org.apache.commons.lang.ClassUtils; | package br.com.six2six.fixturefactory.transformer;
public class DateTimeTransformer implements Transformer {
@Override
public <T> T transform(Object value, Class<T> type) {
Object returnValue = null;
if (value == null) {
return null;
}
if (ClassUtils.isAssignable(type, java.time.LocalDateTime.class)) { | // Path: src/main/java/br/com/six2six/fixturefactory/util/DateTimeUtils.java
// public static java.time.ZonedDateTime toZonedDateTime(Calendar value) {
// return value.toInstant().atZone(value.getTimeZone().toZoneId());
// }
// Path: src/main/java/br/com/six2six/fixturefactory/transformer/DateTimeTransformer.java
import static br.com.six2six.fixturefactory.util.DateTimeUtils.toZonedDateTime;
import java.util.Calendar;
import org.apache.commons.lang.ClassUtils;
package br.com.six2six.fixturefactory.transformer;
public class DateTimeTransformer implements Transformer {
@Override
public <T> T transform(Object value, Class<T> type) {
Object returnValue = null;
if (value == null) {
return null;
}
if (ClassUtils.isAssignable(type, java.time.LocalDateTime.class)) { | returnValue = toZonedDateTime((Calendar) value).toLocalDateTime(); |
six2six/fixture-factory | src/test/java/br/com/six2six/fixturefactory/FixtureLambdaPlaneTest.java | // Path: src/main/java/br/com/six2six/fixturefactory/loader/FixtureFactoryLoader.java
// public class FixtureFactoryLoader {
//
// public static void loadTemplates(String basePackage) {
// for (Class<?> clazz : getClassesForPackage(basePackage)) {
// if (!clazz.isInterface() && TemplateLoader.class.isAssignableFrom(clazz)) {
// try {
// ((TemplateLoader) clazz.newInstance()).load();
// } catch (Exception e) {
// throw new RuntimeException(String.format("template %s not loaded", clazz.getName()), e);
// }
// }
// }
// }
// }
//
// Path: src/test/java/br/com/six2six/fixturefactory/model/LambdaPlane.java
// public class LambdaPlane {
//
// private String tailNumber;
// private List<String> flightCrew;
//
// public LambdaPlane(String tailNumber, List<String> flightCrew) {
// this.tailNumber = tailNumber;
// this.flightCrew = flightCrew;
// }
//
// public String getTailNumber() {
// return tailNumber;
// }
//
// public List<String> getFlightCrew() {
// return flightCrew;
// }
//
// @Override
// public String toString() {
// return "LambdaPlane{" +
// "tailNumber='" + tailNumber + '\'' +
// ", flightCrew=" +
// flightCrew.stream()
// .map(p -> "Emp: " + p)
// .sorted()
// .collect(Collectors.joining(", "))
// +
// '}';
// }
// }
| import br.com.six2six.fixturefactory.loader.FixtureFactoryLoader;
import br.com.six2six.fixturefactory.model.LambdaPlane;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue; | package br.com.six2six.fixturefactory;
public class FixtureLambdaPlaneTest {
@BeforeClass
public static void beforeClass() { | // Path: src/main/java/br/com/six2six/fixturefactory/loader/FixtureFactoryLoader.java
// public class FixtureFactoryLoader {
//
// public static void loadTemplates(String basePackage) {
// for (Class<?> clazz : getClassesForPackage(basePackage)) {
// if (!clazz.isInterface() && TemplateLoader.class.isAssignableFrom(clazz)) {
// try {
// ((TemplateLoader) clazz.newInstance()).load();
// } catch (Exception e) {
// throw new RuntimeException(String.format("template %s not loaded", clazz.getName()), e);
// }
// }
// }
// }
// }
//
// Path: src/test/java/br/com/six2six/fixturefactory/model/LambdaPlane.java
// public class LambdaPlane {
//
// private String tailNumber;
// private List<String> flightCrew;
//
// public LambdaPlane(String tailNumber, List<String> flightCrew) {
// this.tailNumber = tailNumber;
// this.flightCrew = flightCrew;
// }
//
// public String getTailNumber() {
// return tailNumber;
// }
//
// public List<String> getFlightCrew() {
// return flightCrew;
// }
//
// @Override
// public String toString() {
// return "LambdaPlane{" +
// "tailNumber='" + tailNumber + '\'' +
// ", flightCrew=" +
// flightCrew.stream()
// .map(p -> "Emp: " + p)
// .sorted()
// .collect(Collectors.joining(", "))
// +
// '}';
// }
// }
// Path: src/test/java/br/com/six2six/fixturefactory/FixtureLambdaPlaneTest.java
import br.com.six2six.fixturefactory.loader.FixtureFactoryLoader;
import br.com.six2six.fixturefactory.model.LambdaPlane;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
package br.com.six2six.fixturefactory;
public class FixtureLambdaPlaneTest {
@BeforeClass
public static void beforeClass() { | FixtureFactoryLoader.loadTemplates("br.com.six2six.template"); |
six2six/fixture-factory | src/test/java/br/com/six2six/fixturefactory/FixtureLambdaPlaneTest.java | // Path: src/main/java/br/com/six2six/fixturefactory/loader/FixtureFactoryLoader.java
// public class FixtureFactoryLoader {
//
// public static void loadTemplates(String basePackage) {
// for (Class<?> clazz : getClassesForPackage(basePackage)) {
// if (!clazz.isInterface() && TemplateLoader.class.isAssignableFrom(clazz)) {
// try {
// ((TemplateLoader) clazz.newInstance()).load();
// } catch (Exception e) {
// throw new RuntimeException(String.format("template %s not loaded", clazz.getName()), e);
// }
// }
// }
// }
// }
//
// Path: src/test/java/br/com/six2six/fixturefactory/model/LambdaPlane.java
// public class LambdaPlane {
//
// private String tailNumber;
// private List<String> flightCrew;
//
// public LambdaPlane(String tailNumber, List<String> flightCrew) {
// this.tailNumber = tailNumber;
// this.flightCrew = flightCrew;
// }
//
// public String getTailNumber() {
// return tailNumber;
// }
//
// public List<String> getFlightCrew() {
// return flightCrew;
// }
//
// @Override
// public String toString() {
// return "LambdaPlane{" +
// "tailNumber='" + tailNumber + '\'' +
// ", flightCrew=" +
// flightCrew.stream()
// .map(p -> "Emp: " + p)
// .sorted()
// .collect(Collectors.joining(", "))
// +
// '}';
// }
// }
| import br.com.six2six.fixturefactory.loader.FixtureFactoryLoader;
import br.com.six2six.fixturefactory.model.LambdaPlane;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue; | package br.com.six2six.fixturefactory;
public class FixtureLambdaPlaneTest {
@BeforeClass
public static void beforeClass() {
FixtureFactoryLoader.loadTemplates("br.com.six2six.template");
}
@Test
public void shouldCreateInstanceInClassUsingLambda() throws Exception { | // Path: src/main/java/br/com/six2six/fixturefactory/loader/FixtureFactoryLoader.java
// public class FixtureFactoryLoader {
//
// public static void loadTemplates(String basePackage) {
// for (Class<?> clazz : getClassesForPackage(basePackage)) {
// if (!clazz.isInterface() && TemplateLoader.class.isAssignableFrom(clazz)) {
// try {
// ((TemplateLoader) clazz.newInstance()).load();
// } catch (Exception e) {
// throw new RuntimeException(String.format("template %s not loaded", clazz.getName()), e);
// }
// }
// }
// }
// }
//
// Path: src/test/java/br/com/six2six/fixturefactory/model/LambdaPlane.java
// public class LambdaPlane {
//
// private String tailNumber;
// private List<String> flightCrew;
//
// public LambdaPlane(String tailNumber, List<String> flightCrew) {
// this.tailNumber = tailNumber;
// this.flightCrew = flightCrew;
// }
//
// public String getTailNumber() {
// return tailNumber;
// }
//
// public List<String> getFlightCrew() {
// return flightCrew;
// }
//
// @Override
// public String toString() {
// return "LambdaPlane{" +
// "tailNumber='" + tailNumber + '\'' +
// ", flightCrew=" +
// flightCrew.stream()
// .map(p -> "Emp: " + p)
// .sorted()
// .collect(Collectors.joining(", "))
// +
// '}';
// }
// }
// Path: src/test/java/br/com/six2six/fixturefactory/FixtureLambdaPlaneTest.java
import br.com.six2six.fixturefactory.loader.FixtureFactoryLoader;
import br.com.six2six.fixturefactory.model.LambdaPlane;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
package br.com.six2six.fixturefactory;
public class FixtureLambdaPlaneTest {
@BeforeClass
public static void beforeClass() {
FixtureFactoryLoader.loadTemplates("br.com.six2six.template");
}
@Test
public void shouldCreateInstanceInClassUsingLambda() throws Exception { | LambdaPlane validPlane = Fixture.from(LambdaPlane.class).gimme("valid"); |
six2six/fixture-factory | src/main/java/br/com/six2six/fixturefactory/function/impl/RandomFunction.java | // Path: src/main/java/br/com/six2six/fixturefactory/base/Range.java
// public class Range {
//
// private Number start;
//
// private Number end;
//
// public Range(Number start, Number end) {
// if (start.doubleValue() >= end.doubleValue()) {
// throw new IllegalArgumentException(String.format("incorrect range: [%d, %d]", start, end));
// }
//
// this.start = start;
// this.end = end;
// }
//
// public Number getStart() {
// return start;
// }
//
// public Number getEnd() {
// return end;
// }
//
// }
| import br.com.six2six.fixturefactory.base.Range;
import br.com.six2six.fixturefactory.function.AtomicFunction;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.MathContext;
import java.math.RoundingMode;
import java.util.Random;
| package br.com.six2six.fixturefactory.function.impl;
public class RandomFunction implements AtomicFunction {
private Class<?> type;
private Object[] dataset;
private AtomicFunction[] functions;
| // Path: src/main/java/br/com/six2six/fixturefactory/base/Range.java
// public class Range {
//
// private Number start;
//
// private Number end;
//
// public Range(Number start, Number end) {
// if (start.doubleValue() >= end.doubleValue()) {
// throw new IllegalArgumentException(String.format("incorrect range: [%d, %d]", start, end));
// }
//
// this.start = start;
// this.end = end;
// }
//
// public Number getStart() {
// return start;
// }
//
// public Number getEnd() {
// return end;
// }
//
// }
// Path: src/main/java/br/com/six2six/fixturefactory/function/impl/RandomFunction.java
import br.com.six2six.fixturefactory.base.Range;
import br.com.six2six.fixturefactory.function.AtomicFunction;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.MathContext;
import java.math.RoundingMode;
import java.util.Random;
package br.com.six2six.fixturefactory.function.impl;
public class RandomFunction implements AtomicFunction {
private Class<?> type;
private Object[] dataset;
private AtomicFunction[] functions;
| private Range range;
|
six2six/fixture-factory | src/test/java/br/com/six2six/fixturefactory/FixtureXMLTransactionTest.java | // Path: src/main/java/br/com/six2six/fixturefactory/loader/FixtureFactoryLoader.java
// public class FixtureFactoryLoader {
//
// public static void loadTemplates(String basePackage) {
// for (Class<?> clazz : getClassesForPackage(basePackage)) {
// if (!clazz.isInterface() && TemplateLoader.class.isAssignableFrom(clazz)) {
// try {
// ((TemplateLoader) clazz.newInstance()).load();
// } catch (Exception e) {
// throw new RuntimeException(String.format("template %s not loaded", clazz.getName()), e);
// }
// }
// }
// }
// }
//
// Path: src/test/java/br/com/six2six/fixturefactory/model/XMLTransaction.java
// public class XMLTransaction implements Serializable {
//
// private static final long serialVersionUID = -4627755454446905456L;
//
// private String origin;
//
// private XMLGregorianCalendar date;
//
// private XMLGregorianCalendar hour;
//
// public String getOrigin() {
// return origin;
// }
//
// public void setOrigin(String origin) {
// this.origin = origin;
// }
//
// public XMLGregorianCalendar getDate() {
// return date;
// }
//
// public void setDate(XMLGregorianCalendar date) {
// this.date = date;
// }
//
// public XMLGregorianCalendar getHour() {
// return hour;
// }
//
// public void setHour(XMLGregorianCalendar hour) {
// this.hour = hour;
// }
//
// }
| import static org.junit.Assert.assertNotNull;
import org.junit.BeforeClass;
import org.junit.Test;
import br.com.six2six.fixturefactory.loader.FixtureFactoryLoader;
import br.com.six2six.fixturefactory.model.XMLTransaction; | package br.com.six2six.fixturefactory;
public class FixtureXMLTransactionTest {
@BeforeClass
public static void setUp() { | // Path: src/main/java/br/com/six2six/fixturefactory/loader/FixtureFactoryLoader.java
// public class FixtureFactoryLoader {
//
// public static void loadTemplates(String basePackage) {
// for (Class<?> clazz : getClassesForPackage(basePackage)) {
// if (!clazz.isInterface() && TemplateLoader.class.isAssignableFrom(clazz)) {
// try {
// ((TemplateLoader) clazz.newInstance()).load();
// } catch (Exception e) {
// throw new RuntimeException(String.format("template %s not loaded", clazz.getName()), e);
// }
// }
// }
// }
// }
//
// Path: src/test/java/br/com/six2six/fixturefactory/model/XMLTransaction.java
// public class XMLTransaction implements Serializable {
//
// private static final long serialVersionUID = -4627755454446905456L;
//
// private String origin;
//
// private XMLGregorianCalendar date;
//
// private XMLGregorianCalendar hour;
//
// public String getOrigin() {
// return origin;
// }
//
// public void setOrigin(String origin) {
// this.origin = origin;
// }
//
// public XMLGregorianCalendar getDate() {
// return date;
// }
//
// public void setDate(XMLGregorianCalendar date) {
// this.date = date;
// }
//
// public XMLGregorianCalendar getHour() {
// return hour;
// }
//
// public void setHour(XMLGregorianCalendar hour) {
// this.hour = hour;
// }
//
// }
// Path: src/test/java/br/com/six2six/fixturefactory/FixtureXMLTransactionTest.java
import static org.junit.Assert.assertNotNull;
import org.junit.BeforeClass;
import org.junit.Test;
import br.com.six2six.fixturefactory.loader.FixtureFactoryLoader;
import br.com.six2six.fixturefactory.model.XMLTransaction;
package br.com.six2six.fixturefactory;
public class FixtureXMLTransactionTest {
@BeforeClass
public static void setUp() { | FixtureFactoryLoader.loadTemplates("br.com.six2six.template"); |
six2six/fixture-factory | src/test/java/br/com/six2six/fixturefactory/FixtureXMLTransactionTest.java | // Path: src/main/java/br/com/six2six/fixturefactory/loader/FixtureFactoryLoader.java
// public class FixtureFactoryLoader {
//
// public static void loadTemplates(String basePackage) {
// for (Class<?> clazz : getClassesForPackage(basePackage)) {
// if (!clazz.isInterface() && TemplateLoader.class.isAssignableFrom(clazz)) {
// try {
// ((TemplateLoader) clazz.newInstance()).load();
// } catch (Exception e) {
// throw new RuntimeException(String.format("template %s not loaded", clazz.getName()), e);
// }
// }
// }
// }
// }
//
// Path: src/test/java/br/com/six2six/fixturefactory/model/XMLTransaction.java
// public class XMLTransaction implements Serializable {
//
// private static final long serialVersionUID = -4627755454446905456L;
//
// private String origin;
//
// private XMLGregorianCalendar date;
//
// private XMLGregorianCalendar hour;
//
// public String getOrigin() {
// return origin;
// }
//
// public void setOrigin(String origin) {
// this.origin = origin;
// }
//
// public XMLGregorianCalendar getDate() {
// return date;
// }
//
// public void setDate(XMLGregorianCalendar date) {
// this.date = date;
// }
//
// public XMLGregorianCalendar getHour() {
// return hour;
// }
//
// public void setHour(XMLGregorianCalendar hour) {
// this.hour = hour;
// }
//
// }
| import static org.junit.Assert.assertNotNull;
import org.junit.BeforeClass;
import org.junit.Test;
import br.com.six2six.fixturefactory.loader.FixtureFactoryLoader;
import br.com.six2six.fixturefactory.model.XMLTransaction; | package br.com.six2six.fixturefactory;
public class FixtureXMLTransactionTest {
@BeforeClass
public static void setUp() {
FixtureFactoryLoader.loadTemplates("br.com.six2six.template");
}
@Test
public void fixtureValidTransaction() { | // Path: src/main/java/br/com/six2six/fixturefactory/loader/FixtureFactoryLoader.java
// public class FixtureFactoryLoader {
//
// public static void loadTemplates(String basePackage) {
// for (Class<?> clazz : getClassesForPackage(basePackage)) {
// if (!clazz.isInterface() && TemplateLoader.class.isAssignableFrom(clazz)) {
// try {
// ((TemplateLoader) clazz.newInstance()).load();
// } catch (Exception e) {
// throw new RuntimeException(String.format("template %s not loaded", clazz.getName()), e);
// }
// }
// }
// }
// }
//
// Path: src/test/java/br/com/six2six/fixturefactory/model/XMLTransaction.java
// public class XMLTransaction implements Serializable {
//
// private static final long serialVersionUID = -4627755454446905456L;
//
// private String origin;
//
// private XMLGregorianCalendar date;
//
// private XMLGregorianCalendar hour;
//
// public String getOrigin() {
// return origin;
// }
//
// public void setOrigin(String origin) {
// this.origin = origin;
// }
//
// public XMLGregorianCalendar getDate() {
// return date;
// }
//
// public void setDate(XMLGregorianCalendar date) {
// this.date = date;
// }
//
// public XMLGregorianCalendar getHour() {
// return hour;
// }
//
// public void setHour(XMLGregorianCalendar hour) {
// this.hour = hour;
// }
//
// }
// Path: src/test/java/br/com/six2six/fixturefactory/FixtureXMLTransactionTest.java
import static org.junit.Assert.assertNotNull;
import org.junit.BeforeClass;
import org.junit.Test;
import br.com.six2six.fixturefactory.loader.FixtureFactoryLoader;
import br.com.six2six.fixturefactory.model.XMLTransaction;
package br.com.six2six.fixturefactory;
public class FixtureXMLTransactionTest {
@BeforeClass
public static void setUp() {
FixtureFactoryLoader.loadTemplates("br.com.six2six.template");
}
@Test
public void fixtureValidTransaction() { | XMLTransaction transaction = Fixture.from(XMLTransaction.class).gimme("validTransaction"); |
six2six/fixture-factory | src/test/java/br/com/six2six/fixturefactory/util/PropertySorterTest.java | // Path: src/main/java/br/com/six2six/fixturefactory/Property.java
// public class Property {
//
// private String name;
//
// private Function function;
//
// public Property(String name, Function function) {
// if (name == null) {
// throw new IllegalArgumentException("name must not be null");
// }
//
// if (function == null) {
// throw new IllegalArgumentException("function must not be null");
// }
//
// this.name = name;
// this.function = function;
// }
//
// public Property(String name, Object value) {
// this(name, new IdentityFunction(value));
// }
//
// public String getName() {
// return this.name;
// }
//
// public Object getValue() {
// return ((AtomicFunction) this.function).generateValue();
// }
//
// public Object getValue(Processor processor) {
// return ((RelationFunction) this.function).generateValue(processor);
// }
//
// public Object getValue(Object owner) {
// return ((RelationFunction) this.function).generateValue(owner);
// }
//
// public Object getValue(Object owner, Processor processor) {
// return ((RelationFunction) this.function).generateValue(owner, processor);
// }
//
// public boolean hasRelationFunction() {
// return this.function instanceof RelationFunction;
// }
//
// public String getRootAttribute() {
// int index = this.name.indexOf(".");
// return index > 0 ? this.name.substring(0, index) : this.name;
// }
//
// public Function getFunction() {
// return function;
// }
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + ((name == null) ? 0 : name.hashCode());
// return result;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (getClass() != obj.getClass())
// return false;
// Property other = (Property) obj;
// if (name == null) {
// if (other.name != null)
// return false;
// } else if (!name.equals(other.name))
// return false;
// return true;
// }
// }
| import br.com.six2six.fixturefactory.Property;
import org.junit.Test;
import java.util.LinkedHashSet;
import java.util.Set;
import static org.hamcrest.Matchers.contains;
import static org.junit.Assert.assertThat; | package br.com.six2six.fixturefactory.util;
public class PropertySorterTest {
@SuppressWarnings("serial")
@Test
public void shouldSortWithDependencies() throws Exception { | // Path: src/main/java/br/com/six2six/fixturefactory/Property.java
// public class Property {
//
// private String name;
//
// private Function function;
//
// public Property(String name, Function function) {
// if (name == null) {
// throw new IllegalArgumentException("name must not be null");
// }
//
// if (function == null) {
// throw new IllegalArgumentException("function must not be null");
// }
//
// this.name = name;
// this.function = function;
// }
//
// public Property(String name, Object value) {
// this(name, new IdentityFunction(value));
// }
//
// public String getName() {
// return this.name;
// }
//
// public Object getValue() {
// return ((AtomicFunction) this.function).generateValue();
// }
//
// public Object getValue(Processor processor) {
// return ((RelationFunction) this.function).generateValue(processor);
// }
//
// public Object getValue(Object owner) {
// return ((RelationFunction) this.function).generateValue(owner);
// }
//
// public Object getValue(Object owner, Processor processor) {
// return ((RelationFunction) this.function).generateValue(owner, processor);
// }
//
// public boolean hasRelationFunction() {
// return this.function instanceof RelationFunction;
// }
//
// public String getRootAttribute() {
// int index = this.name.indexOf(".");
// return index > 0 ? this.name.substring(0, index) : this.name;
// }
//
// public Function getFunction() {
// return function;
// }
//
// @Override
// public int hashCode() {
// final int prime = 31;
// int result = 1;
// result = prime * result + ((name == null) ? 0 : name.hashCode());
// return result;
// }
//
// @Override
// public boolean equals(Object obj) {
// if (this == obj)
// return true;
// if (obj == null)
// return false;
// if (getClass() != obj.getClass())
// return false;
// Property other = (Property) obj;
// if (name == null) {
// if (other.name != null)
// return false;
// } else if (!name.equals(other.name))
// return false;
// return true;
// }
// }
// Path: src/test/java/br/com/six2six/fixturefactory/util/PropertySorterTest.java
import br.com.six2six.fixturefactory.Property;
import org.junit.Test;
import java.util.LinkedHashSet;
import java.util.Set;
import static org.hamcrest.Matchers.contains;
import static org.junit.Assert.assertThat;
package br.com.six2six.fixturefactory.util;
public class PropertySorterTest {
@SuppressWarnings("serial")
@Test
public void shouldSortWithDependencies() throws Exception { | final Property firstName = new Property("firstName", "diego"); |
six2six/fixture-factory | src/main/java/br/com/six2six/fixturefactory/transformer/CalendarTransformer.java | // Path: src/main/java/br/com/six2six/fixturefactory/JavaVersion.java
// public class JavaVersion {
//
// public static final JavaVersion JAVA_8 = new JavaVersion("1.8");
// public static final JavaVersion JAVA_7 = new JavaVersion("1.7");
// public static final JavaVersion JAVA_6 = new JavaVersion("1.6");
//
// private int major;
// private int minor;
//
// public JavaVersion(String version) {
// String[] fields = version.split("\\.");
// this.major = Integer.parseInt(fields[0]);
// this.minor = Integer.parseInt(fields[1]);
// }
//
// public boolean gte(JavaVersion version) {
// return this.major >= version.major && this.minor >= version.minor;
// }
//
// public static JavaVersion current(){
// return new JavaVersion(System.getProperty("java.version"));
// }
//
// public int getMajor() {
// return major;
// }
//
// public void setMajor(int major) {
// this.major = major;
// }
//
// public int getMinor() {
// return minor;
// }
//
// public void setMinor(int minor) {
// this.minor = minor;
// }
//
// }
| import java.util.Calendar;
import java.util.GregorianCalendar;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
import org.apache.commons.lang.ClassUtils;
import br.com.six2six.fixturefactory.JavaVersion; | package br.com.six2six.fixturefactory.transformer;
public class CalendarTransformer implements Transformer {
public <T> T transform(Object value, Class<T> type) {
Object returnValue = null;
if (value == null) {
return null;
}
if (ClassUtils.isAssignable(type, XMLGregorianCalendar.class)) {
try {
returnValue = DatatypeFactory.newInstance().newXMLGregorianCalendar((GregorianCalendar) value);
} catch (DatatypeConfigurationException e) {
throw new IllegalArgumentException("Error parser Calendar to XMLGregorianCalendar", e);
}
} else if (ClassUtils.isAssignable(type, java.sql.Date.class)) {
returnValue = new java.sql.Date(((Calendar) value).getTimeInMillis());
} else if (ClassUtils.isAssignable(type, java.util.Date.class)) {
returnValue = ((Calendar) value).getTime();
} else if (ClassUtils.isAssignable(type, Calendar.class)) {
returnValue = value;
} else {
throw new IllegalArgumentException("Incorrect type for transformer: " + type.getCanonicalName());
}
return type.cast(returnValue);
}
public boolean accepts(Object value, Class<?> type) {
boolean instanceOfCalendar = value instanceof Calendar; | // Path: src/main/java/br/com/six2six/fixturefactory/JavaVersion.java
// public class JavaVersion {
//
// public static final JavaVersion JAVA_8 = new JavaVersion("1.8");
// public static final JavaVersion JAVA_7 = new JavaVersion("1.7");
// public static final JavaVersion JAVA_6 = new JavaVersion("1.6");
//
// private int major;
// private int minor;
//
// public JavaVersion(String version) {
// String[] fields = version.split("\\.");
// this.major = Integer.parseInt(fields[0]);
// this.minor = Integer.parseInt(fields[1]);
// }
//
// public boolean gte(JavaVersion version) {
// return this.major >= version.major && this.minor >= version.minor;
// }
//
// public static JavaVersion current(){
// return new JavaVersion(System.getProperty("java.version"));
// }
//
// public int getMajor() {
// return major;
// }
//
// public void setMajor(int major) {
// this.major = major;
// }
//
// public int getMinor() {
// return minor;
// }
//
// public void setMinor(int minor) {
// this.minor = minor;
// }
//
// }
// Path: src/main/java/br/com/six2six/fixturefactory/transformer/CalendarTransformer.java
import java.util.Calendar;
import java.util.GregorianCalendar;
import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
import org.apache.commons.lang.ClassUtils;
import br.com.six2six.fixturefactory.JavaVersion;
package br.com.six2six.fixturefactory.transformer;
public class CalendarTransformer implements Transformer {
public <T> T transform(Object value, Class<T> type) {
Object returnValue = null;
if (value == null) {
return null;
}
if (ClassUtils.isAssignable(type, XMLGregorianCalendar.class)) {
try {
returnValue = DatatypeFactory.newInstance().newXMLGregorianCalendar((GregorianCalendar) value);
} catch (DatatypeConfigurationException e) {
throw new IllegalArgumentException("Error parser Calendar to XMLGregorianCalendar", e);
}
} else if (ClassUtils.isAssignable(type, java.sql.Date.class)) {
returnValue = new java.sql.Date(((Calendar) value).getTimeInMillis());
} else if (ClassUtils.isAssignable(type, java.util.Date.class)) {
returnValue = ((Calendar) value).getTime();
} else if (ClassUtils.isAssignable(type, Calendar.class)) {
returnValue = value;
} else {
throw new IllegalArgumentException("Incorrect type for transformer: " + type.getCanonicalName());
}
return type.cast(returnValue);
}
public boolean accepts(Object value, Class<?> type) {
boolean instanceOfCalendar = value instanceof Calendar; | return JavaVersion.current().gte(JavaVersion.JAVA_8) ? instanceOfCalendar && !java.time.temporal.Temporal.class.isAssignableFrom(type) : instanceOfCalendar; |
six2six/fixture-factory | src/test/java/br/com/six2six/fixturefactory/function/UniqueRandomFunctionTest.java | // Path: src/main/java/br/com/six2six/fixturefactory/function/impl/UniqueRandomFunction.java
// public class UniqueRandomFunction implements AtomicFunction{
//
// private Object[] dataset;
//
// private int nextValueIndex = 0;
//
// public UniqueRandomFunction(int minValue, int maxValue) {
// if(minValue >= maxValue) {
// throw new IllegalArgumentException("maxValue cannot be greater than minValue.");
// }
// this.dataset = this.initIntegerDataset(minValue, maxValue);
// this.shuffleDataset();
// }
//
// public UniqueRandomFunction(Object[] dataset) {
// if(dataset.length == 0) {
// throw new IllegalArgumentException("provided dataset has no elements.");
// }
// this.dataset = dataset;
// this.shuffleDataset();
// }
//
// public UniqueRandomFunction(Class<? extends Enum<?>> clazz) {
// if(clazz.getEnumConstants().length == 0) {
// throw new IllegalArgumentException("Enum has no values.");
// }
// this.dataset = clazz.getEnumConstants();
// this.shuffleDataset();
// }
//
// private Object[] initIntegerDataset(int minValue, int maxValue) {
// Integer[] dataset = new Integer[maxValue - minValue + 1];
// int currValue = minValue;
// for(int i = 0; i < dataset.length; i++) {
// dataset[i] = currValue;
// currValue ++;
// }
//
// return dataset;
// }
//
// private void shuffleDataset() {
// Random random = new Random();
// for(int shufflePosition = 0, iterator = dataset.length - 1; iterator > 0; iterator--) {
// shufflePosition = random.nextInt(iterator);
// Object temp = dataset[iterator];
// dataset[iterator] = dataset[shufflePosition];
// dataset[shufflePosition] = temp;
// }
// }
//
// @Override
// @SuppressWarnings("unchecked")
// public <T> T generateValue() {
//
// if(this.nextValueIndex >= this.dataset.length) {
// this.nextValueIndex = 0;
// }
//
// Object nextValue = this.dataset[this.nextValueIndex];
// this.nextValueIndex ++;
// return (T)nextValue;
//
// }
// }
| import static org.junit.Assert.*;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import org.junit.Test;
import br.com.six2six.fixturefactory.function.impl.UniqueRandomFunction; | package br.com.six2six.fixturefactory.function;
public class UniqueRandomFunctionTest {
private enum EnumMock {
A,
B,
C,
D,
E,
F,
G,
H,
I,
J
}
@Test
public void shouldGenerate1000UniqueIntegers() {
Set<Integer> integers = new HashSet<Integer>();
for(int i = 0; i <= 1000; i++) {
integers.add(i);
} | // Path: src/main/java/br/com/six2six/fixturefactory/function/impl/UniqueRandomFunction.java
// public class UniqueRandomFunction implements AtomicFunction{
//
// private Object[] dataset;
//
// private int nextValueIndex = 0;
//
// public UniqueRandomFunction(int minValue, int maxValue) {
// if(minValue >= maxValue) {
// throw new IllegalArgumentException("maxValue cannot be greater than minValue.");
// }
// this.dataset = this.initIntegerDataset(minValue, maxValue);
// this.shuffleDataset();
// }
//
// public UniqueRandomFunction(Object[] dataset) {
// if(dataset.length == 0) {
// throw new IllegalArgumentException("provided dataset has no elements.");
// }
// this.dataset = dataset;
// this.shuffleDataset();
// }
//
// public UniqueRandomFunction(Class<? extends Enum<?>> clazz) {
// if(clazz.getEnumConstants().length == 0) {
// throw new IllegalArgumentException("Enum has no values.");
// }
// this.dataset = clazz.getEnumConstants();
// this.shuffleDataset();
// }
//
// private Object[] initIntegerDataset(int minValue, int maxValue) {
// Integer[] dataset = new Integer[maxValue - minValue + 1];
// int currValue = minValue;
// for(int i = 0; i < dataset.length; i++) {
// dataset[i] = currValue;
// currValue ++;
// }
//
// return dataset;
// }
//
// private void shuffleDataset() {
// Random random = new Random();
// for(int shufflePosition = 0, iterator = dataset.length - 1; iterator > 0; iterator--) {
// shufflePosition = random.nextInt(iterator);
// Object temp = dataset[iterator];
// dataset[iterator] = dataset[shufflePosition];
// dataset[shufflePosition] = temp;
// }
// }
//
// @Override
// @SuppressWarnings("unchecked")
// public <T> T generateValue() {
//
// if(this.nextValueIndex >= this.dataset.length) {
// this.nextValueIndex = 0;
// }
//
// Object nextValue = this.dataset[this.nextValueIndex];
// this.nextValueIndex ++;
// return (T)nextValue;
//
// }
// }
// Path: src/test/java/br/com/six2six/fixturefactory/function/UniqueRandomFunctionTest.java
import static org.junit.Assert.*;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import org.junit.Test;
import br.com.six2six.fixturefactory.function.impl.UniqueRandomFunction;
package br.com.six2six.fixturefactory.function;
public class UniqueRandomFunctionTest {
private enum EnumMock {
A,
B,
C,
D,
E,
F,
G,
H,
I,
J
}
@Test
public void shouldGenerate1000UniqueIntegers() {
Set<Integer> integers = new HashSet<Integer>();
for(int i = 0; i <= 1000; i++) {
integers.add(i);
} | UniqueRandomFunction function = new UniqueRandomFunction(0, 1000); |
six2six/fixture-factory | src/test/java/br/com/six2six/fixturefactory/transformer/PlaceholderTransformerTest.java | // Path: src/test/java/br/com/six2six/fixturefactory/model/User.java
// public class User implements Serializable {
//
// private static final long serialVersionUID = 6276678114928905392L;
//
// private String name;
// private String login;
// private String password;
// private Gender gender;
// private String email;
// private List<UserType> userTypes;
//
// public String getName() {
// return name;
// }
// public void setName(String name) {
// this.name = name;
// }
// public String getLogin() {
// return login;
// }
// public void setLogin(String login) {
// this.login = login;
// }
// public String getPassword() {
// return password;
// }
// public void setPassword(String password) {
// this.password = password;
// }
// public Gender getGender() {
// return gender;
// }
// public void setGender(Gender gender) {
// this.gender = gender;
// }
// public String getEmail() {
// return email;
// }
// public void setEmail(String email) {
// this.email = email;
// }
// public List<UserType> getUserTypes() {
// return userTypes;
// }
// public void setUserTypes(List<UserType> userTypes) {
// this.userTypes = userTypes;
// }
//
// }
| import static org.junit.Assert.assertEquals;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
import br.com.six2six.fixturefactory.model.User; | package br.com.six2six.fixturefactory.transformer;
public class PlaceholderTransformerTest {
@Test
public void shouldTransformParameterPlaceholder() {
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("name", "someone");
String result = new ParameterPlaceholderTransformer(parameters).transform("${name}@domain.com", String.class);
assertEquals("someone@domain.com", result);
}
@Test
public void shouldTransformPropertyPlaceholder() { | // Path: src/test/java/br/com/six2six/fixturefactory/model/User.java
// public class User implements Serializable {
//
// private static final long serialVersionUID = 6276678114928905392L;
//
// private String name;
// private String login;
// private String password;
// private Gender gender;
// private String email;
// private List<UserType> userTypes;
//
// public String getName() {
// return name;
// }
// public void setName(String name) {
// this.name = name;
// }
// public String getLogin() {
// return login;
// }
// public void setLogin(String login) {
// this.login = login;
// }
// public String getPassword() {
// return password;
// }
// public void setPassword(String password) {
// this.password = password;
// }
// public Gender getGender() {
// return gender;
// }
// public void setGender(Gender gender) {
// this.gender = gender;
// }
// public String getEmail() {
// return email;
// }
// public void setEmail(String email) {
// this.email = email;
// }
// public List<UserType> getUserTypes() {
// return userTypes;
// }
// public void setUserTypes(List<UserType> userTypes) {
// this.userTypes = userTypes;
// }
//
// }
// Path: src/test/java/br/com/six2six/fixturefactory/transformer/PlaceholderTransformerTest.java
import static org.junit.Assert.assertEquals;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
import br.com.six2six.fixturefactory.model.User;
package br.com.six2six.fixturefactory.transformer;
public class PlaceholderTransformerTest {
@Test
public void shouldTransformParameterPlaceholder() {
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("name", "someone");
String result = new ParameterPlaceholderTransformer(parameters).transform("${name}@domain.com", String.class);
assertEquals("someone@domain.com", result);
}
@Test
public void shouldTransformPropertyPlaceholder() { | User user = new User(); |
six2six/fixture-factory | src/test/java/br/com/six2six/fixturefactory/function/CalendarSequenceFunctionTest.java | // Path: src/main/java/br/com/six2six/fixturefactory/base/CalendarInterval.java
// public class CalendarInterval implements Serializable {
//
// private static final long serialVersionUID = 2223542302515335884L;
//
// private int calendarField;
// private int value;
//
// public CalendarInterval(int interval, int calendarField) {
// this.calendarField = calendarField;
// this.value = interval;
// }
//
// public int getCalendarField() {
// return this.calendarField;
// }
//
// public int getValue() {
// return this.value;
// }
// }
//
// Path: src/main/java/br/com/six2six/fixturefactory/base/CalendarSequence.java
// public class CalendarSequence implements Sequence<Calendar> {
//
// private Calendar baseCalendar;
// private CalendarInterval interval;
// private int multiplier;
//
// public CalendarSequence(Calendar baseCalendar, CalendarInterval interval) {
// this.baseCalendar = (Calendar) baseCalendar.clone();
// this.interval = interval;
// }
//
// @Override
// public Calendar nextValue() {
// Calendar result = (Calendar) this.baseCalendar.clone();
// result.add(this.interval.getCalendarField(), this.interval.getValue() * this.multiplier);
//
// this.multiplier++;
// return result;
// }
// }
//
// Path: src/main/java/br/com/six2six/fixturefactory/function/impl/SequenceFunction.java
// public class SequenceFunction implements AtomicFunction {
//
// private Sequence<?> sequence;
//
// public SequenceFunction(Sequence<?> sequence) {
// this.sequence = sequence;
// }
//
// @Override
// @SuppressWarnings("unchecked")
// public <T> T generateValue() {
// return (T) sequence.nextValue();
// }
// }
//
// Path: src/main/java/br/com/six2six/fixturefactory/util/DateTimeUtils.java
// public class DateTimeUtils {
//
// public static Calendar toCalendar(String source, DateFormat format) {
// Calendar date = Calendar.getInstance();
// try {
// date.setTimeInMillis(format.parse(source).getTime());
// } catch (ParseException e) {
// throw new IllegalArgumentException(e);
// }
// return date;
// }
//
// public static java.time.ZonedDateTime toZonedDateTime(Calendar value) {
// return value.toInstant().atZone(value.getTimeZone().toZoneId());
// }
//
// }
| import static org.junit.Assert.assertEquals;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import org.junit.Test;
import br.com.six2six.fixturefactory.base.CalendarInterval;
import br.com.six2six.fixturefactory.base.CalendarSequence;
import br.com.six2six.fixturefactory.function.impl.SequenceFunction;
import br.com.six2six.fixturefactory.util.DateTimeUtils; | package br.com.six2six.fixturefactory.function;
public class CalendarSequenceFunctionTest {
@Test
public void addOneDay() { | // Path: src/main/java/br/com/six2six/fixturefactory/base/CalendarInterval.java
// public class CalendarInterval implements Serializable {
//
// private static final long serialVersionUID = 2223542302515335884L;
//
// private int calendarField;
// private int value;
//
// public CalendarInterval(int interval, int calendarField) {
// this.calendarField = calendarField;
// this.value = interval;
// }
//
// public int getCalendarField() {
// return this.calendarField;
// }
//
// public int getValue() {
// return this.value;
// }
// }
//
// Path: src/main/java/br/com/six2six/fixturefactory/base/CalendarSequence.java
// public class CalendarSequence implements Sequence<Calendar> {
//
// private Calendar baseCalendar;
// private CalendarInterval interval;
// private int multiplier;
//
// public CalendarSequence(Calendar baseCalendar, CalendarInterval interval) {
// this.baseCalendar = (Calendar) baseCalendar.clone();
// this.interval = interval;
// }
//
// @Override
// public Calendar nextValue() {
// Calendar result = (Calendar) this.baseCalendar.clone();
// result.add(this.interval.getCalendarField(), this.interval.getValue() * this.multiplier);
//
// this.multiplier++;
// return result;
// }
// }
//
// Path: src/main/java/br/com/six2six/fixturefactory/function/impl/SequenceFunction.java
// public class SequenceFunction implements AtomicFunction {
//
// private Sequence<?> sequence;
//
// public SequenceFunction(Sequence<?> sequence) {
// this.sequence = sequence;
// }
//
// @Override
// @SuppressWarnings("unchecked")
// public <T> T generateValue() {
// return (T) sequence.nextValue();
// }
// }
//
// Path: src/main/java/br/com/six2six/fixturefactory/util/DateTimeUtils.java
// public class DateTimeUtils {
//
// public static Calendar toCalendar(String source, DateFormat format) {
// Calendar date = Calendar.getInstance();
// try {
// date.setTimeInMillis(format.parse(source).getTime());
// } catch (ParseException e) {
// throw new IllegalArgumentException(e);
// }
// return date;
// }
//
// public static java.time.ZonedDateTime toZonedDateTime(Calendar value) {
// return value.toInstant().atZone(value.getTimeZone().toZoneId());
// }
//
// }
// Path: src/test/java/br/com/six2six/fixturefactory/function/CalendarSequenceFunctionTest.java
import static org.junit.Assert.assertEquals;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import org.junit.Test;
import br.com.six2six.fixturefactory.base.CalendarInterval;
import br.com.six2six.fixturefactory.base.CalendarSequence;
import br.com.six2six.fixturefactory.function.impl.SequenceFunction;
import br.com.six2six.fixturefactory.util.DateTimeUtils;
package br.com.six2six.fixturefactory.function;
public class CalendarSequenceFunctionTest {
@Test
public void addOneDay() { | Calendar baseCalendar = DateTimeUtils.toCalendar("2011-04-09", new SimpleDateFormat("yyyy-MM-dd")); |
six2six/fixture-factory | src/test/java/br/com/six2six/fixturefactory/function/CalendarSequenceFunctionTest.java | // Path: src/main/java/br/com/six2six/fixturefactory/base/CalendarInterval.java
// public class CalendarInterval implements Serializable {
//
// private static final long serialVersionUID = 2223542302515335884L;
//
// private int calendarField;
// private int value;
//
// public CalendarInterval(int interval, int calendarField) {
// this.calendarField = calendarField;
// this.value = interval;
// }
//
// public int getCalendarField() {
// return this.calendarField;
// }
//
// public int getValue() {
// return this.value;
// }
// }
//
// Path: src/main/java/br/com/six2six/fixturefactory/base/CalendarSequence.java
// public class CalendarSequence implements Sequence<Calendar> {
//
// private Calendar baseCalendar;
// private CalendarInterval interval;
// private int multiplier;
//
// public CalendarSequence(Calendar baseCalendar, CalendarInterval interval) {
// this.baseCalendar = (Calendar) baseCalendar.clone();
// this.interval = interval;
// }
//
// @Override
// public Calendar nextValue() {
// Calendar result = (Calendar) this.baseCalendar.clone();
// result.add(this.interval.getCalendarField(), this.interval.getValue() * this.multiplier);
//
// this.multiplier++;
// return result;
// }
// }
//
// Path: src/main/java/br/com/six2six/fixturefactory/function/impl/SequenceFunction.java
// public class SequenceFunction implements AtomicFunction {
//
// private Sequence<?> sequence;
//
// public SequenceFunction(Sequence<?> sequence) {
// this.sequence = sequence;
// }
//
// @Override
// @SuppressWarnings("unchecked")
// public <T> T generateValue() {
// return (T) sequence.nextValue();
// }
// }
//
// Path: src/main/java/br/com/six2six/fixturefactory/util/DateTimeUtils.java
// public class DateTimeUtils {
//
// public static Calendar toCalendar(String source, DateFormat format) {
// Calendar date = Calendar.getInstance();
// try {
// date.setTimeInMillis(format.parse(source).getTime());
// } catch (ParseException e) {
// throw new IllegalArgumentException(e);
// }
// return date;
// }
//
// public static java.time.ZonedDateTime toZonedDateTime(Calendar value) {
// return value.toInstant().atZone(value.getTimeZone().toZoneId());
// }
//
// }
| import static org.junit.Assert.assertEquals;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import org.junit.Test;
import br.com.six2six.fixturefactory.base.CalendarInterval;
import br.com.six2six.fixturefactory.base.CalendarSequence;
import br.com.six2six.fixturefactory.function.impl.SequenceFunction;
import br.com.six2six.fixturefactory.util.DateTimeUtils; | package br.com.six2six.fixturefactory.function;
public class CalendarSequenceFunctionTest {
@Test
public void addOneDay() {
Calendar baseCalendar = DateTimeUtils.toCalendar("2011-04-09", new SimpleDateFormat("yyyy-MM-dd")); | // Path: src/main/java/br/com/six2six/fixturefactory/base/CalendarInterval.java
// public class CalendarInterval implements Serializable {
//
// private static final long serialVersionUID = 2223542302515335884L;
//
// private int calendarField;
// private int value;
//
// public CalendarInterval(int interval, int calendarField) {
// this.calendarField = calendarField;
// this.value = interval;
// }
//
// public int getCalendarField() {
// return this.calendarField;
// }
//
// public int getValue() {
// return this.value;
// }
// }
//
// Path: src/main/java/br/com/six2six/fixturefactory/base/CalendarSequence.java
// public class CalendarSequence implements Sequence<Calendar> {
//
// private Calendar baseCalendar;
// private CalendarInterval interval;
// private int multiplier;
//
// public CalendarSequence(Calendar baseCalendar, CalendarInterval interval) {
// this.baseCalendar = (Calendar) baseCalendar.clone();
// this.interval = interval;
// }
//
// @Override
// public Calendar nextValue() {
// Calendar result = (Calendar) this.baseCalendar.clone();
// result.add(this.interval.getCalendarField(), this.interval.getValue() * this.multiplier);
//
// this.multiplier++;
// return result;
// }
// }
//
// Path: src/main/java/br/com/six2six/fixturefactory/function/impl/SequenceFunction.java
// public class SequenceFunction implements AtomicFunction {
//
// private Sequence<?> sequence;
//
// public SequenceFunction(Sequence<?> sequence) {
// this.sequence = sequence;
// }
//
// @Override
// @SuppressWarnings("unchecked")
// public <T> T generateValue() {
// return (T) sequence.nextValue();
// }
// }
//
// Path: src/main/java/br/com/six2six/fixturefactory/util/DateTimeUtils.java
// public class DateTimeUtils {
//
// public static Calendar toCalendar(String source, DateFormat format) {
// Calendar date = Calendar.getInstance();
// try {
// date.setTimeInMillis(format.parse(source).getTime());
// } catch (ParseException e) {
// throw new IllegalArgumentException(e);
// }
// return date;
// }
//
// public static java.time.ZonedDateTime toZonedDateTime(Calendar value) {
// return value.toInstant().atZone(value.getTimeZone().toZoneId());
// }
//
// }
// Path: src/test/java/br/com/six2six/fixturefactory/function/CalendarSequenceFunctionTest.java
import static org.junit.Assert.assertEquals;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import org.junit.Test;
import br.com.six2six.fixturefactory.base.CalendarInterval;
import br.com.six2six.fixturefactory.base.CalendarSequence;
import br.com.six2six.fixturefactory.function.impl.SequenceFunction;
import br.com.six2six.fixturefactory.util.DateTimeUtils;
package br.com.six2six.fixturefactory.function;
public class CalendarSequenceFunctionTest {
@Test
public void addOneDay() {
Calendar baseCalendar = DateTimeUtils.toCalendar("2011-04-09", new SimpleDateFormat("yyyy-MM-dd")); | SequenceFunction sequenceFunction = new SequenceFunction(new CalendarSequence(baseCalendar, new CalendarInterval(1, Calendar.DAY_OF_MONTH))); |
six2six/fixture-factory | src/test/java/br/com/six2six/fixturefactory/function/CalendarSequenceFunctionTest.java | // Path: src/main/java/br/com/six2six/fixturefactory/base/CalendarInterval.java
// public class CalendarInterval implements Serializable {
//
// private static final long serialVersionUID = 2223542302515335884L;
//
// private int calendarField;
// private int value;
//
// public CalendarInterval(int interval, int calendarField) {
// this.calendarField = calendarField;
// this.value = interval;
// }
//
// public int getCalendarField() {
// return this.calendarField;
// }
//
// public int getValue() {
// return this.value;
// }
// }
//
// Path: src/main/java/br/com/six2six/fixturefactory/base/CalendarSequence.java
// public class CalendarSequence implements Sequence<Calendar> {
//
// private Calendar baseCalendar;
// private CalendarInterval interval;
// private int multiplier;
//
// public CalendarSequence(Calendar baseCalendar, CalendarInterval interval) {
// this.baseCalendar = (Calendar) baseCalendar.clone();
// this.interval = interval;
// }
//
// @Override
// public Calendar nextValue() {
// Calendar result = (Calendar) this.baseCalendar.clone();
// result.add(this.interval.getCalendarField(), this.interval.getValue() * this.multiplier);
//
// this.multiplier++;
// return result;
// }
// }
//
// Path: src/main/java/br/com/six2six/fixturefactory/function/impl/SequenceFunction.java
// public class SequenceFunction implements AtomicFunction {
//
// private Sequence<?> sequence;
//
// public SequenceFunction(Sequence<?> sequence) {
// this.sequence = sequence;
// }
//
// @Override
// @SuppressWarnings("unchecked")
// public <T> T generateValue() {
// return (T) sequence.nextValue();
// }
// }
//
// Path: src/main/java/br/com/six2six/fixturefactory/util/DateTimeUtils.java
// public class DateTimeUtils {
//
// public static Calendar toCalendar(String source, DateFormat format) {
// Calendar date = Calendar.getInstance();
// try {
// date.setTimeInMillis(format.parse(source).getTime());
// } catch (ParseException e) {
// throw new IllegalArgumentException(e);
// }
// return date;
// }
//
// public static java.time.ZonedDateTime toZonedDateTime(Calendar value) {
// return value.toInstant().atZone(value.getTimeZone().toZoneId());
// }
//
// }
| import static org.junit.Assert.assertEquals;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import org.junit.Test;
import br.com.six2six.fixturefactory.base.CalendarInterval;
import br.com.six2six.fixturefactory.base.CalendarSequence;
import br.com.six2six.fixturefactory.function.impl.SequenceFunction;
import br.com.six2six.fixturefactory.util.DateTimeUtils; | package br.com.six2six.fixturefactory.function;
public class CalendarSequenceFunctionTest {
@Test
public void addOneDay() {
Calendar baseCalendar = DateTimeUtils.toCalendar("2011-04-09", new SimpleDateFormat("yyyy-MM-dd")); | // Path: src/main/java/br/com/six2six/fixturefactory/base/CalendarInterval.java
// public class CalendarInterval implements Serializable {
//
// private static final long serialVersionUID = 2223542302515335884L;
//
// private int calendarField;
// private int value;
//
// public CalendarInterval(int interval, int calendarField) {
// this.calendarField = calendarField;
// this.value = interval;
// }
//
// public int getCalendarField() {
// return this.calendarField;
// }
//
// public int getValue() {
// return this.value;
// }
// }
//
// Path: src/main/java/br/com/six2six/fixturefactory/base/CalendarSequence.java
// public class CalendarSequence implements Sequence<Calendar> {
//
// private Calendar baseCalendar;
// private CalendarInterval interval;
// private int multiplier;
//
// public CalendarSequence(Calendar baseCalendar, CalendarInterval interval) {
// this.baseCalendar = (Calendar) baseCalendar.clone();
// this.interval = interval;
// }
//
// @Override
// public Calendar nextValue() {
// Calendar result = (Calendar) this.baseCalendar.clone();
// result.add(this.interval.getCalendarField(), this.interval.getValue() * this.multiplier);
//
// this.multiplier++;
// return result;
// }
// }
//
// Path: src/main/java/br/com/six2six/fixturefactory/function/impl/SequenceFunction.java
// public class SequenceFunction implements AtomicFunction {
//
// private Sequence<?> sequence;
//
// public SequenceFunction(Sequence<?> sequence) {
// this.sequence = sequence;
// }
//
// @Override
// @SuppressWarnings("unchecked")
// public <T> T generateValue() {
// return (T) sequence.nextValue();
// }
// }
//
// Path: src/main/java/br/com/six2six/fixturefactory/util/DateTimeUtils.java
// public class DateTimeUtils {
//
// public static Calendar toCalendar(String source, DateFormat format) {
// Calendar date = Calendar.getInstance();
// try {
// date.setTimeInMillis(format.parse(source).getTime());
// } catch (ParseException e) {
// throw new IllegalArgumentException(e);
// }
// return date;
// }
//
// public static java.time.ZonedDateTime toZonedDateTime(Calendar value) {
// return value.toInstant().atZone(value.getTimeZone().toZoneId());
// }
//
// }
// Path: src/test/java/br/com/six2six/fixturefactory/function/CalendarSequenceFunctionTest.java
import static org.junit.Assert.assertEquals;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import org.junit.Test;
import br.com.six2six.fixturefactory.base.CalendarInterval;
import br.com.six2six.fixturefactory.base.CalendarSequence;
import br.com.six2six.fixturefactory.function.impl.SequenceFunction;
import br.com.six2six.fixturefactory.util.DateTimeUtils;
package br.com.six2six.fixturefactory.function;
public class CalendarSequenceFunctionTest {
@Test
public void addOneDay() {
Calendar baseCalendar = DateTimeUtils.toCalendar("2011-04-09", new SimpleDateFormat("yyyy-MM-dd")); | SequenceFunction sequenceFunction = new SequenceFunction(new CalendarSequence(baseCalendar, new CalendarInterval(1, Calendar.DAY_OF_MONTH))); |
six2six/fixture-factory | src/test/java/br/com/six2six/fixturefactory/function/CalendarSequenceFunctionTest.java | // Path: src/main/java/br/com/six2six/fixturefactory/base/CalendarInterval.java
// public class CalendarInterval implements Serializable {
//
// private static final long serialVersionUID = 2223542302515335884L;
//
// private int calendarField;
// private int value;
//
// public CalendarInterval(int interval, int calendarField) {
// this.calendarField = calendarField;
// this.value = interval;
// }
//
// public int getCalendarField() {
// return this.calendarField;
// }
//
// public int getValue() {
// return this.value;
// }
// }
//
// Path: src/main/java/br/com/six2six/fixturefactory/base/CalendarSequence.java
// public class CalendarSequence implements Sequence<Calendar> {
//
// private Calendar baseCalendar;
// private CalendarInterval interval;
// private int multiplier;
//
// public CalendarSequence(Calendar baseCalendar, CalendarInterval interval) {
// this.baseCalendar = (Calendar) baseCalendar.clone();
// this.interval = interval;
// }
//
// @Override
// public Calendar nextValue() {
// Calendar result = (Calendar) this.baseCalendar.clone();
// result.add(this.interval.getCalendarField(), this.interval.getValue() * this.multiplier);
//
// this.multiplier++;
// return result;
// }
// }
//
// Path: src/main/java/br/com/six2six/fixturefactory/function/impl/SequenceFunction.java
// public class SequenceFunction implements AtomicFunction {
//
// private Sequence<?> sequence;
//
// public SequenceFunction(Sequence<?> sequence) {
// this.sequence = sequence;
// }
//
// @Override
// @SuppressWarnings("unchecked")
// public <T> T generateValue() {
// return (T) sequence.nextValue();
// }
// }
//
// Path: src/main/java/br/com/six2six/fixturefactory/util/DateTimeUtils.java
// public class DateTimeUtils {
//
// public static Calendar toCalendar(String source, DateFormat format) {
// Calendar date = Calendar.getInstance();
// try {
// date.setTimeInMillis(format.parse(source).getTime());
// } catch (ParseException e) {
// throw new IllegalArgumentException(e);
// }
// return date;
// }
//
// public static java.time.ZonedDateTime toZonedDateTime(Calendar value) {
// return value.toInstant().atZone(value.getTimeZone().toZoneId());
// }
//
// }
| import static org.junit.Assert.assertEquals;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import org.junit.Test;
import br.com.six2six.fixturefactory.base.CalendarInterval;
import br.com.six2six.fixturefactory.base.CalendarSequence;
import br.com.six2six.fixturefactory.function.impl.SequenceFunction;
import br.com.six2six.fixturefactory.util.DateTimeUtils; | package br.com.six2six.fixturefactory.function;
public class CalendarSequenceFunctionTest {
@Test
public void addOneDay() {
Calendar baseCalendar = DateTimeUtils.toCalendar("2011-04-09", new SimpleDateFormat("yyyy-MM-dd")); | // Path: src/main/java/br/com/six2six/fixturefactory/base/CalendarInterval.java
// public class CalendarInterval implements Serializable {
//
// private static final long serialVersionUID = 2223542302515335884L;
//
// private int calendarField;
// private int value;
//
// public CalendarInterval(int interval, int calendarField) {
// this.calendarField = calendarField;
// this.value = interval;
// }
//
// public int getCalendarField() {
// return this.calendarField;
// }
//
// public int getValue() {
// return this.value;
// }
// }
//
// Path: src/main/java/br/com/six2six/fixturefactory/base/CalendarSequence.java
// public class CalendarSequence implements Sequence<Calendar> {
//
// private Calendar baseCalendar;
// private CalendarInterval interval;
// private int multiplier;
//
// public CalendarSequence(Calendar baseCalendar, CalendarInterval interval) {
// this.baseCalendar = (Calendar) baseCalendar.clone();
// this.interval = interval;
// }
//
// @Override
// public Calendar nextValue() {
// Calendar result = (Calendar) this.baseCalendar.clone();
// result.add(this.interval.getCalendarField(), this.interval.getValue() * this.multiplier);
//
// this.multiplier++;
// return result;
// }
// }
//
// Path: src/main/java/br/com/six2six/fixturefactory/function/impl/SequenceFunction.java
// public class SequenceFunction implements AtomicFunction {
//
// private Sequence<?> sequence;
//
// public SequenceFunction(Sequence<?> sequence) {
// this.sequence = sequence;
// }
//
// @Override
// @SuppressWarnings("unchecked")
// public <T> T generateValue() {
// return (T) sequence.nextValue();
// }
// }
//
// Path: src/main/java/br/com/six2six/fixturefactory/util/DateTimeUtils.java
// public class DateTimeUtils {
//
// public static Calendar toCalendar(String source, DateFormat format) {
// Calendar date = Calendar.getInstance();
// try {
// date.setTimeInMillis(format.parse(source).getTime());
// } catch (ParseException e) {
// throw new IllegalArgumentException(e);
// }
// return date;
// }
//
// public static java.time.ZonedDateTime toZonedDateTime(Calendar value) {
// return value.toInstant().atZone(value.getTimeZone().toZoneId());
// }
//
// }
// Path: src/test/java/br/com/six2six/fixturefactory/function/CalendarSequenceFunctionTest.java
import static org.junit.Assert.assertEquals;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import org.junit.Test;
import br.com.six2six.fixturefactory.base.CalendarInterval;
import br.com.six2six.fixturefactory.base.CalendarSequence;
import br.com.six2six.fixturefactory.function.impl.SequenceFunction;
import br.com.six2six.fixturefactory.util.DateTimeUtils;
package br.com.six2six.fixturefactory.function;
public class CalendarSequenceFunctionTest {
@Test
public void addOneDay() {
Calendar baseCalendar = DateTimeUtils.toCalendar("2011-04-09", new SimpleDateFormat("yyyy-MM-dd")); | SequenceFunction sequenceFunction = new SequenceFunction(new CalendarSequence(baseCalendar, new CalendarInterval(1, Calendar.DAY_OF_MONTH))); |
six2six/fixture-factory | src/test/java/br/com/six2six/fixturefactory/FixtureStudentTest.java | // Path: src/main/java/br/com/six2six/fixturefactory/loader/FixtureFactoryLoader.java
// public class FixtureFactoryLoader {
//
// public static void loadTemplates(String basePackage) {
// for (Class<?> clazz : getClassesForPackage(basePackage)) {
// if (!clazz.isInterface() && TemplateLoader.class.isAssignableFrom(clazz)) {
// try {
// ((TemplateLoader) clazz.newInstance()).load();
// } catch (Exception e) {
// throw new RuntimeException(String.format("template %s not loaded", clazz.getName()), e);
// }
// }
// }
// }
// }
| import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.util.List;
import org.junit.BeforeClass;
import org.junit.Test;
import br.com.six2six.bfgex.Gender;
import br.com.six2six.fixturefactory.loader.FixtureFactoryLoader;
import br.com.six2six.fixturefactory.model.Student; | package br.com.six2six.fixturefactory;
public class FixtureStudentTest {
@BeforeClass
public static void setUp() { | // Path: src/main/java/br/com/six2six/fixturefactory/loader/FixtureFactoryLoader.java
// public class FixtureFactoryLoader {
//
// public static void loadTemplates(String basePackage) {
// for (Class<?> clazz : getClassesForPackage(basePackage)) {
// if (!clazz.isInterface() && TemplateLoader.class.isAssignableFrom(clazz)) {
// try {
// ((TemplateLoader) clazz.newInstance()).load();
// } catch (Exception e) {
// throw new RuntimeException(String.format("template %s not loaded", clazz.getName()), e);
// }
// }
// }
// }
// }
// Path: src/test/java/br/com/six2six/fixturefactory/FixtureStudentTest.java
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.util.List;
import org.junit.BeforeClass;
import org.junit.Test;
import br.com.six2six.bfgex.Gender;
import br.com.six2six.fixturefactory.loader.FixtureFactoryLoader;
import br.com.six2six.fixturefactory.model.Student;
package br.com.six2six.fixturefactory;
public class FixtureStudentTest {
@BeforeClass
public static void setUp() { | FixtureFactoryLoader.loadTemplates("br.com.six2six.template"); |
six2six/fixture-factory | src/test/java/br/com/six2six/fixturefactory/BeanWithPlaceholderTest.java | // Path: src/main/java/br/com/six2six/fixturefactory/loader/FixtureFactoryLoader.java
// public class FixtureFactoryLoader {
//
// public static void loadTemplates(String basePackage) {
// for (Class<?> clazz : getClassesForPackage(basePackage)) {
// if (!clazz.isInterface() && TemplateLoader.class.isAssignableFrom(clazz)) {
// try {
// ((TemplateLoader) clazz.newInstance()).load();
// } catch (Exception e) {
// throw new RuntimeException(String.format("template %s not loaded", clazz.getName()), e);
// }
// }
// }
// }
// }
//
// Path: src/test/java/br/com/six2six/fixturefactory/model/BeanWithPlaceholder.java
// public abstract class BeanWithPlaceholder {
//
//
// protected String attrOne;
//
// protected String attrTwo;
//
// protected String attrThree;
//
// public String getAttrOne() {
// return attrOne;
// }
//
// public String getAttrTwo() {
// return attrTwo;
// }
//
// public String getAttrThree() {
// return attrThree;
// }
//
// public static class Immutable extends BeanWithPlaceholder {
//
// public Immutable(String attrOne, String attrTwo, String attrThree) {
// this.attrOne = attrOne;
// this.attrTwo = attrTwo;
// this.attrThree = attrThree;
// }
// }
//
// public static class Mutable extends BeanWithPlaceholder {
//
// public void setAttrOne(String attrOne) {
// this.attrOne = attrOne;
// }
//
// public void setAttrTwo(String attrTwo) {
// this.attrTwo = attrTwo;
// }
//
// public void setAttrThree(String attrThree) {
// this.attrThree = attrThree;
// }
// }
// }
| import static java.lang.String.format;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
import org.junit.BeforeClass;
import org.junit.Test;
import br.com.six2six.fixturefactory.loader.FixtureFactoryLoader;
import br.com.six2six.fixturefactory.model.BeanWithPlaceholder; | package br.com.six2six.fixturefactory;
public class BeanWithPlaceholderTest {
@BeforeClass
public static void setUp() { | // Path: src/main/java/br/com/six2six/fixturefactory/loader/FixtureFactoryLoader.java
// public class FixtureFactoryLoader {
//
// public static void loadTemplates(String basePackage) {
// for (Class<?> clazz : getClassesForPackage(basePackage)) {
// if (!clazz.isInterface() && TemplateLoader.class.isAssignableFrom(clazz)) {
// try {
// ((TemplateLoader) clazz.newInstance()).load();
// } catch (Exception e) {
// throw new RuntimeException(String.format("template %s not loaded", clazz.getName()), e);
// }
// }
// }
// }
// }
//
// Path: src/test/java/br/com/six2six/fixturefactory/model/BeanWithPlaceholder.java
// public abstract class BeanWithPlaceholder {
//
//
// protected String attrOne;
//
// protected String attrTwo;
//
// protected String attrThree;
//
// public String getAttrOne() {
// return attrOne;
// }
//
// public String getAttrTwo() {
// return attrTwo;
// }
//
// public String getAttrThree() {
// return attrThree;
// }
//
// public static class Immutable extends BeanWithPlaceholder {
//
// public Immutable(String attrOne, String attrTwo, String attrThree) {
// this.attrOne = attrOne;
// this.attrTwo = attrTwo;
// this.attrThree = attrThree;
// }
// }
//
// public static class Mutable extends BeanWithPlaceholder {
//
// public void setAttrOne(String attrOne) {
// this.attrOne = attrOne;
// }
//
// public void setAttrTwo(String attrTwo) {
// this.attrTwo = attrTwo;
// }
//
// public void setAttrThree(String attrThree) {
// this.attrThree = attrThree;
// }
// }
// }
// Path: src/test/java/br/com/six2six/fixturefactory/BeanWithPlaceholderTest.java
import static java.lang.String.format;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
import org.junit.BeforeClass;
import org.junit.Test;
import br.com.six2six.fixturefactory.loader.FixtureFactoryLoader;
import br.com.six2six.fixturefactory.model.BeanWithPlaceholder;
package br.com.six2six.fixturefactory;
public class BeanWithPlaceholderTest {
@BeforeClass
public static void setUp() { | FixtureFactoryLoader.loadTemplates("br.com.six2six.template"); |
six2six/fixture-factory | src/test/java/br/com/six2six/fixturefactory/BeanWithPlaceholderTest.java | // Path: src/main/java/br/com/six2six/fixturefactory/loader/FixtureFactoryLoader.java
// public class FixtureFactoryLoader {
//
// public static void loadTemplates(String basePackage) {
// for (Class<?> clazz : getClassesForPackage(basePackage)) {
// if (!clazz.isInterface() && TemplateLoader.class.isAssignableFrom(clazz)) {
// try {
// ((TemplateLoader) clazz.newInstance()).load();
// } catch (Exception e) {
// throw new RuntimeException(String.format("template %s not loaded", clazz.getName()), e);
// }
// }
// }
// }
// }
//
// Path: src/test/java/br/com/six2six/fixturefactory/model/BeanWithPlaceholder.java
// public abstract class BeanWithPlaceholder {
//
//
// protected String attrOne;
//
// protected String attrTwo;
//
// protected String attrThree;
//
// public String getAttrOne() {
// return attrOne;
// }
//
// public String getAttrTwo() {
// return attrTwo;
// }
//
// public String getAttrThree() {
// return attrThree;
// }
//
// public static class Immutable extends BeanWithPlaceholder {
//
// public Immutable(String attrOne, String attrTwo, String attrThree) {
// this.attrOne = attrOne;
// this.attrTwo = attrTwo;
// this.attrThree = attrThree;
// }
// }
//
// public static class Mutable extends BeanWithPlaceholder {
//
// public void setAttrOne(String attrOne) {
// this.attrOne = attrOne;
// }
//
// public void setAttrTwo(String attrTwo) {
// this.attrTwo = attrTwo;
// }
//
// public void setAttrThree(String attrThree) {
// this.attrThree = attrThree;
// }
// }
// }
| import static java.lang.String.format;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
import org.junit.BeforeClass;
import org.junit.Test;
import br.com.six2six.fixturefactory.loader.FixtureFactoryLoader;
import br.com.six2six.fixturefactory.model.BeanWithPlaceholder; | package br.com.six2six.fixturefactory;
public class BeanWithPlaceholderTest {
@BeforeClass
public static void setUp() {
FixtureFactoryLoader.loadTemplates("br.com.six2six.template");
}
@Test
public void shouldSubstituteOnePlaceholderViaConstructor() { | // Path: src/main/java/br/com/six2six/fixturefactory/loader/FixtureFactoryLoader.java
// public class FixtureFactoryLoader {
//
// public static void loadTemplates(String basePackage) {
// for (Class<?> clazz : getClassesForPackage(basePackage)) {
// if (!clazz.isInterface() && TemplateLoader.class.isAssignableFrom(clazz)) {
// try {
// ((TemplateLoader) clazz.newInstance()).load();
// } catch (Exception e) {
// throw new RuntimeException(String.format("template %s not loaded", clazz.getName()), e);
// }
// }
// }
// }
// }
//
// Path: src/test/java/br/com/six2six/fixturefactory/model/BeanWithPlaceholder.java
// public abstract class BeanWithPlaceholder {
//
//
// protected String attrOne;
//
// protected String attrTwo;
//
// protected String attrThree;
//
// public String getAttrOne() {
// return attrOne;
// }
//
// public String getAttrTwo() {
// return attrTwo;
// }
//
// public String getAttrThree() {
// return attrThree;
// }
//
// public static class Immutable extends BeanWithPlaceholder {
//
// public Immutable(String attrOne, String attrTwo, String attrThree) {
// this.attrOne = attrOne;
// this.attrTwo = attrTwo;
// this.attrThree = attrThree;
// }
// }
//
// public static class Mutable extends BeanWithPlaceholder {
//
// public void setAttrOne(String attrOne) {
// this.attrOne = attrOne;
// }
//
// public void setAttrTwo(String attrTwo) {
// this.attrTwo = attrTwo;
// }
//
// public void setAttrThree(String attrThree) {
// this.attrThree = attrThree;
// }
// }
// }
// Path: src/test/java/br/com/six2six/fixturefactory/BeanWithPlaceholderTest.java
import static java.lang.String.format;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
import org.junit.BeforeClass;
import org.junit.Test;
import br.com.six2six.fixturefactory.loader.FixtureFactoryLoader;
import br.com.six2six.fixturefactory.model.BeanWithPlaceholder;
package br.com.six2six.fixturefactory;
public class BeanWithPlaceholderTest {
@BeforeClass
public static void setUp() {
FixtureFactoryLoader.loadTemplates("br.com.six2six.template");
}
@Test
public void shouldSubstituteOnePlaceholderViaConstructor() { | BeanWithPlaceholder result = Fixture.from(BeanWithPlaceholder.Immutable.class).gimme("one-placeholder"); |
six2six/fixture-factory | src/test/java/br/com/six2six/fixturefactory/FixtureInvoiceTest.java | // Path: src/main/java/br/com/six2six/fixturefactory/loader/FixtureFactoryLoader.java
// public class FixtureFactoryLoader {
//
// public static void loadTemplates(String basePackage) {
// for (Class<?> clazz : getClassesForPackage(basePackage)) {
// if (!clazz.isInterface() && TemplateLoader.class.isAssignableFrom(clazz)) {
// try {
// ((TemplateLoader) clazz.newInstance()).load();
// } catch (Exception e) {
// throw new RuntimeException(String.format("template %s not loaded", clazz.getName()), e);
// }
// }
// }
// }
// }
//
// Path: src/main/java/br/com/six2six/fixturefactory/util/DateTimeUtils.java
// public class DateTimeUtils {
//
// public static Calendar toCalendar(String source, DateFormat format) {
// Calendar date = Calendar.getInstance();
// try {
// date.setTimeInMillis(format.parse(source).getTime());
// } catch (ParseException e) {
// throw new IllegalArgumentException(e);
// }
// return date;
// }
//
// public static java.time.ZonedDateTime toZonedDateTime(Calendar value) {
// return value.toInstant().atZone(value.getTimeZone().toZoneId());
// }
//
// }
| import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import org.junit.BeforeClass;
import org.junit.Test;
import br.com.six2six.fixturefactory.loader.FixtureFactoryLoader;
import br.com.six2six.fixturefactory.model.Invoice;
import br.com.six2six.fixturefactory.util.DateTimeUtils; | package br.com.six2six.fixturefactory;
public class FixtureInvoiceTest {
@BeforeClass
public static void setUp() { | // Path: src/main/java/br/com/six2six/fixturefactory/loader/FixtureFactoryLoader.java
// public class FixtureFactoryLoader {
//
// public static void loadTemplates(String basePackage) {
// for (Class<?> clazz : getClassesForPackage(basePackage)) {
// if (!clazz.isInterface() && TemplateLoader.class.isAssignableFrom(clazz)) {
// try {
// ((TemplateLoader) clazz.newInstance()).load();
// } catch (Exception e) {
// throw new RuntimeException(String.format("template %s not loaded", clazz.getName()), e);
// }
// }
// }
// }
// }
//
// Path: src/main/java/br/com/six2six/fixturefactory/util/DateTimeUtils.java
// public class DateTimeUtils {
//
// public static Calendar toCalendar(String source, DateFormat format) {
// Calendar date = Calendar.getInstance();
// try {
// date.setTimeInMillis(format.parse(source).getTime());
// } catch (ParseException e) {
// throw new IllegalArgumentException(e);
// }
// return date;
// }
//
// public static java.time.ZonedDateTime toZonedDateTime(Calendar value) {
// return value.toInstant().atZone(value.getTimeZone().toZoneId());
// }
//
// }
// Path: src/test/java/br/com/six2six/fixturefactory/FixtureInvoiceTest.java
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import org.junit.BeforeClass;
import org.junit.Test;
import br.com.six2six.fixturefactory.loader.FixtureFactoryLoader;
import br.com.six2six.fixturefactory.model.Invoice;
import br.com.six2six.fixturefactory.util.DateTimeUtils;
package br.com.six2six.fixturefactory;
public class FixtureInvoiceTest {
@BeforeClass
public static void setUp() { | FixtureFactoryLoader.loadTemplates("br.com.six2six.template"); |
six2six/fixture-factory | src/test/java/br/com/six2six/fixturefactory/FixtureInvoiceTest.java | // Path: src/main/java/br/com/six2six/fixturefactory/loader/FixtureFactoryLoader.java
// public class FixtureFactoryLoader {
//
// public static void loadTemplates(String basePackage) {
// for (Class<?> clazz : getClassesForPackage(basePackage)) {
// if (!clazz.isInterface() && TemplateLoader.class.isAssignableFrom(clazz)) {
// try {
// ((TemplateLoader) clazz.newInstance()).load();
// } catch (Exception e) {
// throw new RuntimeException(String.format("template %s not loaded", clazz.getName()), e);
// }
// }
// }
// }
// }
//
// Path: src/main/java/br/com/six2six/fixturefactory/util/DateTimeUtils.java
// public class DateTimeUtils {
//
// public static Calendar toCalendar(String source, DateFormat format) {
// Calendar date = Calendar.getInstance();
// try {
// date.setTimeInMillis(format.parse(source).getTime());
// } catch (ParseException e) {
// throw new IllegalArgumentException(e);
// }
// return date;
// }
//
// public static java.time.ZonedDateTime toZonedDateTime(Calendar value) {
// return value.toInstant().atZone(value.getTimeZone().toZoneId());
// }
//
// }
| import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import org.junit.BeforeClass;
import org.junit.Test;
import br.com.six2six.fixturefactory.loader.FixtureFactoryLoader;
import br.com.six2six.fixturefactory.model.Invoice;
import br.com.six2six.fixturefactory.util.DateTimeUtils; | package br.com.six2six.fixturefactory;
public class FixtureInvoiceTest {
@BeforeClass
public static void setUp() {
FixtureFactoryLoader.loadTemplates("br.com.six2six.template");
}
@Test
public void fixtureInvoice() {
Invoice invoice = Fixture.from(Invoice.class).gimme("valid");
assertNotNull("Invoice should not be null", invoice);
assertEquals("Invoice ammout should have precision of 2", 2, invoice.getAmmount().precision());
}
@Test
public void fixturePreviousInvoices() {
List<Invoice> invoices = Fixture.from(Invoice.class).gimme(3, "previousInvoices");
assertNotNull("Invoice list should not be null", invoices);
assertTrue("Invoice list should not be empty", !invoices.isEmpty());
| // Path: src/main/java/br/com/six2six/fixturefactory/loader/FixtureFactoryLoader.java
// public class FixtureFactoryLoader {
//
// public static void loadTemplates(String basePackage) {
// for (Class<?> clazz : getClassesForPackage(basePackage)) {
// if (!clazz.isInterface() && TemplateLoader.class.isAssignableFrom(clazz)) {
// try {
// ((TemplateLoader) clazz.newInstance()).load();
// } catch (Exception e) {
// throw new RuntimeException(String.format("template %s not loaded", clazz.getName()), e);
// }
// }
// }
// }
// }
//
// Path: src/main/java/br/com/six2six/fixturefactory/util/DateTimeUtils.java
// public class DateTimeUtils {
//
// public static Calendar toCalendar(String source, DateFormat format) {
// Calendar date = Calendar.getInstance();
// try {
// date.setTimeInMillis(format.parse(source).getTime());
// } catch (ParseException e) {
// throw new IllegalArgumentException(e);
// }
// return date;
// }
//
// public static java.time.ZonedDateTime toZonedDateTime(Calendar value) {
// return value.toInstant().atZone(value.getTimeZone().toZoneId());
// }
//
// }
// Path: src/test/java/br/com/six2six/fixturefactory/FixtureInvoiceTest.java
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import org.junit.BeforeClass;
import org.junit.Test;
import br.com.six2six.fixturefactory.loader.FixtureFactoryLoader;
import br.com.six2six.fixturefactory.model.Invoice;
import br.com.six2six.fixturefactory.util.DateTimeUtils;
package br.com.six2six.fixturefactory;
public class FixtureInvoiceTest {
@BeforeClass
public static void setUp() {
FixtureFactoryLoader.loadTemplates("br.com.six2six.template");
}
@Test
public void fixtureInvoice() {
Invoice invoice = Fixture.from(Invoice.class).gimme("valid");
assertNotNull("Invoice should not be null", invoice);
assertEquals("Invoice ammout should have precision of 2", 2, invoice.getAmmount().precision());
}
@Test
public void fixturePreviousInvoices() {
List<Invoice> invoices = Fixture.from(Invoice.class).gimme(3, "previousInvoices");
assertNotNull("Invoice list should not be null", invoices);
assertTrue("Invoice list should not be empty", !invoices.isEmpty());
| Calendar calendar = DateTimeUtils.toCalendar("2011-04-01", new SimpleDateFormat("yyyy-MM-dd")); |
six2six/fixture-factory | src/test/java/br/com/six2six/fixturefactory/transformer/TransformerChainTest.java | // Path: src/main/java/br/com/six2six/fixturefactory/transformer/Transformer.java
// public interface Transformer {
//
// <T> T transform(Object value, Class<T> type);
//
// boolean accepts(Object value, Class<?> type);
// }
//
// Path: src/main/java/br/com/six2six/fixturefactory/transformer/TransformerChain.java
// public class TransformerChain {
//
// private Transformer transformer;
// private TransformerChain next;
//
// public TransformerChain(Transformer transformer) {
// this.transformer = transformer;
// }
//
// public Object transform(Object value, Class<?> type) {
// if (transformer.accepts(value, type)) {
// value = transformer.transform(value, type);
// }
//
// if (next != null) {
// value = next.transform(value, type);
// }
//
// return value;
// }
//
// public void add(Transformer transformer) {
// if (this.next == null) {
// this.next = new TransformerChain(transformer);
// } else {
// this.next.add(transformer);
// }
// }
// }
| import static org.junit.Assert.assertEquals;
import org.junit.Test;
import br.com.six2six.fixturefactory.transformer.Transformer;
import br.com.six2six.fixturefactory.transformer.TransformerChain; | package br.com.six2six.fixturefactory.transformer;
public class TransformerChainTest {
@Test
public void shouldUseFirstTransformer() { | // Path: src/main/java/br/com/six2six/fixturefactory/transformer/Transformer.java
// public interface Transformer {
//
// <T> T transform(Object value, Class<T> type);
//
// boolean accepts(Object value, Class<?> type);
// }
//
// Path: src/main/java/br/com/six2six/fixturefactory/transformer/TransformerChain.java
// public class TransformerChain {
//
// private Transformer transformer;
// private TransformerChain next;
//
// public TransformerChain(Transformer transformer) {
// this.transformer = transformer;
// }
//
// public Object transform(Object value, Class<?> type) {
// if (transformer.accepts(value, type)) {
// value = transformer.transform(value, type);
// }
//
// if (next != null) {
// value = next.transform(value, type);
// }
//
// return value;
// }
//
// public void add(Transformer transformer) {
// if (this.next == null) {
// this.next = new TransformerChain(transformer);
// } else {
// this.next.add(transformer);
// }
// }
// }
// Path: src/test/java/br/com/six2six/fixturefactory/transformer/TransformerChainTest.java
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import br.com.six2six.fixturefactory.transformer.Transformer;
import br.com.six2six.fixturefactory.transformer.TransformerChain;
package br.com.six2six.fixturefactory.transformer;
public class TransformerChainTest {
@Test
public void shouldUseFirstTransformer() { | TransformerChain transformerChain = new TransformerChain(new FirstTransformer()); |
six2six/fixture-factory | src/test/java/br/com/six2six/fixturefactory/transformer/TransformerChainTest.java | // Path: src/main/java/br/com/six2six/fixturefactory/transformer/Transformer.java
// public interface Transformer {
//
// <T> T transform(Object value, Class<T> type);
//
// boolean accepts(Object value, Class<?> type);
// }
//
// Path: src/main/java/br/com/six2six/fixturefactory/transformer/TransformerChain.java
// public class TransformerChain {
//
// private Transformer transformer;
// private TransformerChain next;
//
// public TransformerChain(Transformer transformer) {
// this.transformer = transformer;
// }
//
// public Object transform(Object value, Class<?> type) {
// if (transformer.accepts(value, type)) {
// value = transformer.transform(value, type);
// }
//
// if (next != null) {
// value = next.transform(value, type);
// }
//
// return value;
// }
//
// public void add(Transformer transformer) {
// if (this.next == null) {
// this.next = new TransformerChain(transformer);
// } else {
// this.next.add(transformer);
// }
// }
// }
| import static org.junit.Assert.assertEquals;
import org.junit.Test;
import br.com.six2six.fixturefactory.transformer.Transformer;
import br.com.six2six.fixturefactory.transformer.TransformerChain; | package br.com.six2six.fixturefactory.transformer;
public class TransformerChainTest {
@Test
public void shouldUseFirstTransformer() {
TransformerChain transformerChain = new TransformerChain(new FirstTransformer());
assertEquals("A1", transformerChain.transform("A", String.class));
}
@Test
public void shouldUseSecondTransformer() {
TransformerChain transformerChain = new TransformerChain(new FirstTransformer());
transformerChain.add(new SecondTransformer());
assertEquals("B2", transformerChain.transform("B", String.class));
}
@Test
public void shouldUseBothTransformersInOrderOfInclusion() {
TransformerChain transformerChain = new TransformerChain(new FirstTransformer());
transformerChain.add(new SecondTransformer());
assertEquals("AB12", transformerChain.transform("AB", String.class));
}
@Test
public void shouldNotUseAnyOfTheTransformers() {
TransformerChain transformerChain = new TransformerChain(new FirstTransformer());
transformerChain.add(new SecondTransformer());
assertEquals("C", transformerChain.transform("C", String.class));
}
}
| // Path: src/main/java/br/com/six2six/fixturefactory/transformer/Transformer.java
// public interface Transformer {
//
// <T> T transform(Object value, Class<T> type);
//
// boolean accepts(Object value, Class<?> type);
// }
//
// Path: src/main/java/br/com/six2six/fixturefactory/transformer/TransformerChain.java
// public class TransformerChain {
//
// private Transformer transformer;
// private TransformerChain next;
//
// public TransformerChain(Transformer transformer) {
// this.transformer = transformer;
// }
//
// public Object transform(Object value, Class<?> type) {
// if (transformer.accepts(value, type)) {
// value = transformer.transform(value, type);
// }
//
// if (next != null) {
// value = next.transform(value, type);
// }
//
// return value;
// }
//
// public void add(Transformer transformer) {
// if (this.next == null) {
// this.next = new TransformerChain(transformer);
// } else {
// this.next.add(transformer);
// }
// }
// }
// Path: src/test/java/br/com/six2six/fixturefactory/transformer/TransformerChainTest.java
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import br.com.six2six.fixturefactory.transformer.Transformer;
import br.com.six2six.fixturefactory.transformer.TransformerChain;
package br.com.six2six.fixturefactory.transformer;
public class TransformerChainTest {
@Test
public void shouldUseFirstTransformer() {
TransformerChain transformerChain = new TransformerChain(new FirstTransformer());
assertEquals("A1", transformerChain.transform("A", String.class));
}
@Test
public void shouldUseSecondTransformer() {
TransformerChain transformerChain = new TransformerChain(new FirstTransformer());
transformerChain.add(new SecondTransformer());
assertEquals("B2", transformerChain.transform("B", String.class));
}
@Test
public void shouldUseBothTransformersInOrderOfInclusion() {
TransformerChain transformerChain = new TransformerChain(new FirstTransformer());
transformerChain.add(new SecondTransformer());
assertEquals("AB12", transformerChain.transform("AB", String.class));
}
@Test
public void shouldNotUseAnyOfTheTransformers() {
TransformerChain transformerChain = new TransformerChain(new FirstTransformer());
transformerChain.add(new SecondTransformer());
assertEquals("C", transformerChain.transform("C", String.class));
}
}
| class FirstTransformer implements Transformer { |
six2six/fixture-factory | src/test/java/br/com/six2six/fixturefactory/FixtureUserTest.java | // Path: src/main/java/br/com/six2six/fixturefactory/loader/FixtureFactoryLoader.java
// public class FixtureFactoryLoader {
//
// public static void loadTemplates(String basePackage) {
// for (Class<?> clazz : getClassesForPackage(basePackage)) {
// if (!clazz.isInterface() && TemplateLoader.class.isAssignableFrom(clazz)) {
// try {
// ((TemplateLoader) clazz.newInstance()).load();
// } catch (Exception e) {
// throw new RuntimeException(String.format("template %s not loaded", clazz.getName()), e);
// }
// }
// }
// }
// }
//
// Path: src/test/java/br/com/six2six/fixturefactory/model/User.java
// public class User implements Serializable {
//
// private static final long serialVersionUID = 6276678114928905392L;
//
// private String name;
// private String login;
// private String password;
// private Gender gender;
// private String email;
// private List<UserType> userTypes;
//
// public String getName() {
// return name;
// }
// public void setName(String name) {
// this.name = name;
// }
// public String getLogin() {
// return login;
// }
// public void setLogin(String login) {
// this.login = login;
// }
// public String getPassword() {
// return password;
// }
// public void setPassword(String password) {
// this.password = password;
// }
// public Gender getGender() {
// return gender;
// }
// public void setGender(Gender gender) {
// this.gender = gender;
// }
// public String getEmail() {
// return email;
// }
// public void setEmail(String email) {
// this.email = email;
// }
// public List<UserType> getUserTypes() {
// return userTypes;
// }
// public void setUserTypes(List<UserType> userTypes) {
// this.userTypes = userTypes;
// }
//
// }
| import static org.junit.Assert.assertNotNull;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import org.junit.BeforeClass;
import org.junit.Test;
import br.com.six2six.fixturefactory.loader.FixtureFactoryLoader;
import br.com.six2six.fixturefactory.model.User; | package br.com.six2six.fixturefactory;
public class FixtureUserTest {
@BeforeClass
public static void setUp() { | // Path: src/main/java/br/com/six2six/fixturefactory/loader/FixtureFactoryLoader.java
// public class FixtureFactoryLoader {
//
// public static void loadTemplates(String basePackage) {
// for (Class<?> clazz : getClassesForPackage(basePackage)) {
// if (!clazz.isInterface() && TemplateLoader.class.isAssignableFrom(clazz)) {
// try {
// ((TemplateLoader) clazz.newInstance()).load();
// } catch (Exception e) {
// throw new RuntimeException(String.format("template %s not loaded", clazz.getName()), e);
// }
// }
// }
// }
// }
//
// Path: src/test/java/br/com/six2six/fixturefactory/model/User.java
// public class User implements Serializable {
//
// private static final long serialVersionUID = 6276678114928905392L;
//
// private String name;
// private String login;
// private String password;
// private Gender gender;
// private String email;
// private List<UserType> userTypes;
//
// public String getName() {
// return name;
// }
// public void setName(String name) {
// this.name = name;
// }
// public String getLogin() {
// return login;
// }
// public void setLogin(String login) {
// this.login = login;
// }
// public String getPassword() {
// return password;
// }
// public void setPassword(String password) {
// this.password = password;
// }
// public Gender getGender() {
// return gender;
// }
// public void setGender(Gender gender) {
// this.gender = gender;
// }
// public String getEmail() {
// return email;
// }
// public void setEmail(String email) {
// this.email = email;
// }
// public List<UserType> getUserTypes() {
// return userTypes;
// }
// public void setUserTypes(List<UserType> userTypes) {
// this.userTypes = userTypes;
// }
//
// }
// Path: src/test/java/br/com/six2six/fixturefactory/FixtureUserTest.java
import static org.junit.Assert.assertNotNull;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import org.junit.BeforeClass;
import org.junit.Test;
import br.com.six2six.fixturefactory.loader.FixtureFactoryLoader;
import br.com.six2six.fixturefactory.model.User;
package br.com.six2six.fixturefactory;
public class FixtureUserTest {
@BeforeClass
public static void setUp() { | FixtureFactoryLoader.loadTemplates("br.com.six2six.template"); |
six2six/fixture-factory | src/test/java/br/com/six2six/fixturefactory/FixtureUserTest.java | // Path: src/main/java/br/com/six2six/fixturefactory/loader/FixtureFactoryLoader.java
// public class FixtureFactoryLoader {
//
// public static void loadTemplates(String basePackage) {
// for (Class<?> clazz : getClassesForPackage(basePackage)) {
// if (!clazz.isInterface() && TemplateLoader.class.isAssignableFrom(clazz)) {
// try {
// ((TemplateLoader) clazz.newInstance()).load();
// } catch (Exception e) {
// throw new RuntimeException(String.format("template %s not loaded", clazz.getName()), e);
// }
// }
// }
// }
// }
//
// Path: src/test/java/br/com/six2six/fixturefactory/model/User.java
// public class User implements Serializable {
//
// private static final long serialVersionUID = 6276678114928905392L;
//
// private String name;
// private String login;
// private String password;
// private Gender gender;
// private String email;
// private List<UserType> userTypes;
//
// public String getName() {
// return name;
// }
// public void setName(String name) {
// this.name = name;
// }
// public String getLogin() {
// return login;
// }
// public void setLogin(String login) {
// this.login = login;
// }
// public String getPassword() {
// return password;
// }
// public void setPassword(String password) {
// this.password = password;
// }
// public Gender getGender() {
// return gender;
// }
// public void setGender(Gender gender) {
// this.gender = gender;
// }
// public String getEmail() {
// return email;
// }
// public void setEmail(String email) {
// this.email = email;
// }
// public List<UserType> getUserTypes() {
// return userTypes;
// }
// public void setUserTypes(List<UserType> userTypes) {
// this.userTypes = userTypes;
// }
//
// }
| import static org.junit.Assert.assertNotNull;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import org.junit.BeforeClass;
import org.junit.Test;
import br.com.six2six.fixturefactory.loader.FixtureFactoryLoader;
import br.com.six2six.fixturefactory.model.User; | package br.com.six2six.fixturefactory;
public class FixtureUserTest {
@BeforeClass
public static void setUp() {
FixtureFactoryLoader.loadTemplates("br.com.six2six.template");
}
@Test
public void fixtureAnyUser() { | // Path: src/main/java/br/com/six2six/fixturefactory/loader/FixtureFactoryLoader.java
// public class FixtureFactoryLoader {
//
// public static void loadTemplates(String basePackage) {
// for (Class<?> clazz : getClassesForPackage(basePackage)) {
// if (!clazz.isInterface() && TemplateLoader.class.isAssignableFrom(clazz)) {
// try {
// ((TemplateLoader) clazz.newInstance()).load();
// } catch (Exception e) {
// throw new RuntimeException(String.format("template %s not loaded", clazz.getName()), e);
// }
// }
// }
// }
// }
//
// Path: src/test/java/br/com/six2six/fixturefactory/model/User.java
// public class User implements Serializable {
//
// private static final long serialVersionUID = 6276678114928905392L;
//
// private String name;
// private String login;
// private String password;
// private Gender gender;
// private String email;
// private List<UserType> userTypes;
//
// public String getName() {
// return name;
// }
// public void setName(String name) {
// this.name = name;
// }
// public String getLogin() {
// return login;
// }
// public void setLogin(String login) {
// this.login = login;
// }
// public String getPassword() {
// return password;
// }
// public void setPassword(String password) {
// this.password = password;
// }
// public Gender getGender() {
// return gender;
// }
// public void setGender(Gender gender) {
// this.gender = gender;
// }
// public String getEmail() {
// return email;
// }
// public void setEmail(String email) {
// this.email = email;
// }
// public List<UserType> getUserTypes() {
// return userTypes;
// }
// public void setUserTypes(List<UserType> userTypes) {
// this.userTypes = userTypes;
// }
//
// }
// Path: src/test/java/br/com/six2six/fixturefactory/FixtureUserTest.java
import static org.junit.Assert.assertNotNull;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import org.junit.BeforeClass;
import org.junit.Test;
import br.com.six2six.fixturefactory.loader.FixtureFactoryLoader;
import br.com.six2six.fixturefactory.model.User;
package br.com.six2six.fixturefactory;
public class FixtureUserTest {
@BeforeClass
public static void setUp() {
FixtureFactoryLoader.loadTemplates("br.com.six2six.template");
}
@Test
public void fixtureAnyUser() { | User user = Fixture.from(User.class).gimme("anyValidUser"); |
six2six/fixture-factory | src/main/java/br/com/six2six/fixturefactory/Property.java | // Path: src/main/java/br/com/six2six/fixturefactory/function/impl/IdentityFunction.java
// public class IdentityFunction implements AtomicFunction {
//
// private Object value;
//
// public IdentityFunction(Object value) {
// this.value = value;
// }
//
// @Override
// @SuppressWarnings("unchecked")
// public <T> T generateValue() {
// return (T) this.value;
// }
// }
//
// Path: src/main/java/br/com/six2six/fixturefactory/processor/Processor.java
// public interface Processor {
//
// void execute(Object result);
// }
| import br.com.six2six.fixturefactory.function.AtomicFunction;
import br.com.six2six.fixturefactory.function.Function;
import br.com.six2six.fixturefactory.function.RelationFunction;
import br.com.six2six.fixturefactory.function.impl.IdentityFunction;
import br.com.six2six.fixturefactory.processor.Processor;
| package br.com.six2six.fixturefactory;
public class Property {
private String name;
private Function function;
public Property(String name, Function function) {
if (name == null) {
throw new IllegalArgumentException("name must not be null");
}
if (function == null) {
throw new IllegalArgumentException("function must not be null");
}
this.name = name;
this.function = function;
}
public Property(String name, Object value) {
| // Path: src/main/java/br/com/six2six/fixturefactory/function/impl/IdentityFunction.java
// public class IdentityFunction implements AtomicFunction {
//
// private Object value;
//
// public IdentityFunction(Object value) {
// this.value = value;
// }
//
// @Override
// @SuppressWarnings("unchecked")
// public <T> T generateValue() {
// return (T) this.value;
// }
// }
//
// Path: src/main/java/br/com/six2six/fixturefactory/processor/Processor.java
// public interface Processor {
//
// void execute(Object result);
// }
// Path: src/main/java/br/com/six2six/fixturefactory/Property.java
import br.com.six2six.fixturefactory.function.AtomicFunction;
import br.com.six2six.fixturefactory.function.Function;
import br.com.six2six.fixturefactory.function.RelationFunction;
import br.com.six2six.fixturefactory.function.impl.IdentityFunction;
import br.com.six2six.fixturefactory.processor.Processor;
package br.com.six2six.fixturefactory;
public class Property {
private String name;
private Function function;
public Property(String name, Function function) {
if (name == null) {
throw new IllegalArgumentException("name must not be null");
}
if (function == null) {
throw new IllegalArgumentException("function must not be null");
}
this.name = name;
this.function = function;
}
public Property(String name, Object value) {
| this(name, new IdentityFunction(value));
|
six2six/fixture-factory | src/main/java/br/com/six2six/fixturefactory/Property.java | // Path: src/main/java/br/com/six2six/fixturefactory/function/impl/IdentityFunction.java
// public class IdentityFunction implements AtomicFunction {
//
// private Object value;
//
// public IdentityFunction(Object value) {
// this.value = value;
// }
//
// @Override
// @SuppressWarnings("unchecked")
// public <T> T generateValue() {
// return (T) this.value;
// }
// }
//
// Path: src/main/java/br/com/six2six/fixturefactory/processor/Processor.java
// public interface Processor {
//
// void execute(Object result);
// }
| import br.com.six2six.fixturefactory.function.AtomicFunction;
import br.com.six2six.fixturefactory.function.Function;
import br.com.six2six.fixturefactory.function.RelationFunction;
import br.com.six2six.fixturefactory.function.impl.IdentityFunction;
import br.com.six2six.fixturefactory.processor.Processor;
| package br.com.six2six.fixturefactory;
public class Property {
private String name;
private Function function;
public Property(String name, Function function) {
if (name == null) {
throw new IllegalArgumentException("name must not be null");
}
if (function == null) {
throw new IllegalArgumentException("function must not be null");
}
this.name = name;
this.function = function;
}
public Property(String name, Object value) {
this(name, new IdentityFunction(value));
}
public String getName() {
return this.name;
}
public Object getValue() {
return ((AtomicFunction) this.function).generateValue();
}
| // Path: src/main/java/br/com/six2six/fixturefactory/function/impl/IdentityFunction.java
// public class IdentityFunction implements AtomicFunction {
//
// private Object value;
//
// public IdentityFunction(Object value) {
// this.value = value;
// }
//
// @Override
// @SuppressWarnings("unchecked")
// public <T> T generateValue() {
// return (T) this.value;
// }
// }
//
// Path: src/main/java/br/com/six2six/fixturefactory/processor/Processor.java
// public interface Processor {
//
// void execute(Object result);
// }
// Path: src/main/java/br/com/six2six/fixturefactory/Property.java
import br.com.six2six.fixturefactory.function.AtomicFunction;
import br.com.six2six.fixturefactory.function.Function;
import br.com.six2six.fixturefactory.function.RelationFunction;
import br.com.six2six.fixturefactory.function.impl.IdentityFunction;
import br.com.six2six.fixturefactory.processor.Processor;
package br.com.six2six.fixturefactory;
public class Property {
private String name;
private Function function;
public Property(String name, Function function) {
if (name == null) {
throw new IllegalArgumentException("name must not be null");
}
if (function == null) {
throw new IllegalArgumentException("function must not be null");
}
this.name = name;
this.function = function;
}
public Property(String name, Object value) {
this(name, new IdentityFunction(value));
}
public String getName() {
return this.name;
}
public Object getValue() {
return ((AtomicFunction) this.function).generateValue();
}
| public Object getValue(Processor processor) {
|
six2six/fixture-factory | src/test/java/br/com/six2six/fixturefactory/FixtureSetHolderTest.java | // Path: src/main/java/br/com/six2six/fixturefactory/loader/FixtureFactoryLoader.java
// public class FixtureFactoryLoader {
//
// public static void loadTemplates(String basePackage) {
// for (Class<?> clazz : getClassesForPackage(basePackage)) {
// if (!clazz.isInterface() && TemplateLoader.class.isAssignableFrom(clazz)) {
// try {
// ((TemplateLoader) clazz.newInstance()).load();
// } catch (Exception e) {
// throw new RuntimeException(String.format("template %s not loaded", clazz.getName()), e);
// }
// }
// }
// }
// }
//
// Path: src/test/java/br/com/six2six/fixturefactory/model/SetHolder.java
// public class SetHolder implements Serializable {
//
// private static final long serialVersionUID = 7764593702512737207L;
//
// private LinkedHashSet<Attribute> attributes;
//
// public LinkedHashSet<Attribute> getAttributes() {
// return this.attributes;
// }
//
// public void setAttributes(LinkedHashSet<Attribute> attributes) {
// this.attributes = attributes;
// }
// }
| import static org.junit.Assert.assertEquals;
import org.junit.BeforeClass;
import org.junit.Test;
import br.com.six2six.fixturefactory.loader.FixtureFactoryLoader;
import br.com.six2six.fixturefactory.model.SetHolder; | package br.com.six2six.fixturefactory;
public class FixtureSetHolderTest {
@BeforeClass
public static void setUp() { | // Path: src/main/java/br/com/six2six/fixturefactory/loader/FixtureFactoryLoader.java
// public class FixtureFactoryLoader {
//
// public static void loadTemplates(String basePackage) {
// for (Class<?> clazz : getClassesForPackage(basePackage)) {
// if (!clazz.isInterface() && TemplateLoader.class.isAssignableFrom(clazz)) {
// try {
// ((TemplateLoader) clazz.newInstance()).load();
// } catch (Exception e) {
// throw new RuntimeException(String.format("template %s not loaded", clazz.getName()), e);
// }
// }
// }
// }
// }
//
// Path: src/test/java/br/com/six2six/fixturefactory/model/SetHolder.java
// public class SetHolder implements Serializable {
//
// private static final long serialVersionUID = 7764593702512737207L;
//
// private LinkedHashSet<Attribute> attributes;
//
// public LinkedHashSet<Attribute> getAttributes() {
// return this.attributes;
// }
//
// public void setAttributes(LinkedHashSet<Attribute> attributes) {
// this.attributes = attributes;
// }
// }
// Path: src/test/java/br/com/six2six/fixturefactory/FixtureSetHolderTest.java
import static org.junit.Assert.assertEquals;
import org.junit.BeforeClass;
import org.junit.Test;
import br.com.six2six.fixturefactory.loader.FixtureFactoryLoader;
import br.com.six2six.fixturefactory.model.SetHolder;
package br.com.six2six.fixturefactory;
public class FixtureSetHolderTest {
@BeforeClass
public static void setUp() { | FixtureFactoryLoader.loadTemplates("br.com.six2six.template"); |
six2six/fixture-factory | src/test/java/br/com/six2six/fixturefactory/FixtureSetHolderTest.java | // Path: src/main/java/br/com/six2six/fixturefactory/loader/FixtureFactoryLoader.java
// public class FixtureFactoryLoader {
//
// public static void loadTemplates(String basePackage) {
// for (Class<?> clazz : getClassesForPackage(basePackage)) {
// if (!clazz.isInterface() && TemplateLoader.class.isAssignableFrom(clazz)) {
// try {
// ((TemplateLoader) clazz.newInstance()).load();
// } catch (Exception e) {
// throw new RuntimeException(String.format("template %s not loaded", clazz.getName()), e);
// }
// }
// }
// }
// }
//
// Path: src/test/java/br/com/six2six/fixturefactory/model/SetHolder.java
// public class SetHolder implements Serializable {
//
// private static final long serialVersionUID = 7764593702512737207L;
//
// private LinkedHashSet<Attribute> attributes;
//
// public LinkedHashSet<Attribute> getAttributes() {
// return this.attributes;
// }
//
// public void setAttributes(LinkedHashSet<Attribute> attributes) {
// this.attributes = attributes;
// }
// }
| import static org.junit.Assert.assertEquals;
import org.junit.BeforeClass;
import org.junit.Test;
import br.com.six2six.fixturefactory.loader.FixtureFactoryLoader;
import br.com.six2six.fixturefactory.model.SetHolder; | package br.com.six2six.fixturefactory;
public class FixtureSetHolderTest {
@BeforeClass
public static void setUp() {
FixtureFactoryLoader.loadTemplates("br.com.six2six.template");
}
@Test
public void fixtureSortedSet() { | // Path: src/main/java/br/com/six2six/fixturefactory/loader/FixtureFactoryLoader.java
// public class FixtureFactoryLoader {
//
// public static void loadTemplates(String basePackage) {
// for (Class<?> clazz : getClassesForPackage(basePackage)) {
// if (!clazz.isInterface() && TemplateLoader.class.isAssignableFrom(clazz)) {
// try {
// ((TemplateLoader) clazz.newInstance()).load();
// } catch (Exception e) {
// throw new RuntimeException(String.format("template %s not loaded", clazz.getName()), e);
// }
// }
// }
// }
// }
//
// Path: src/test/java/br/com/six2six/fixturefactory/model/SetHolder.java
// public class SetHolder implements Serializable {
//
// private static final long serialVersionUID = 7764593702512737207L;
//
// private LinkedHashSet<Attribute> attributes;
//
// public LinkedHashSet<Attribute> getAttributes() {
// return this.attributes;
// }
//
// public void setAttributes(LinkedHashSet<Attribute> attributes) {
// this.attributes = attributes;
// }
// }
// Path: src/test/java/br/com/six2six/fixturefactory/FixtureSetHolderTest.java
import static org.junit.Assert.assertEquals;
import org.junit.BeforeClass;
import org.junit.Test;
import br.com.six2six.fixturefactory.loader.FixtureFactoryLoader;
import br.com.six2six.fixturefactory.model.SetHolder;
package br.com.six2six.fixturefactory;
public class FixtureSetHolderTest {
@BeforeClass
public static void setUp() {
FixtureFactoryLoader.loadTemplates("br.com.six2six.template");
}
@Test
public void fixtureSortedSet() { | SetHolder holder = Fixture.from(SetHolder.class).gimme("has-n"); |
six2six/fixture-factory | src/main/java/br/com/six2six/fixturefactory/loader/FixtureFactoryLoader.java | // Path: src/main/java/br/com/six2six/fixturefactory/util/ClassLoaderUtils.java
// public static Set<Class<?>> getClassesForPackage(String packageName) {
// Set<Class<?>> classes = new HashSet<Class<?>>();
//
// JarInputStream jarInputStream = null;
// try {
// ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
//
// Enumeration<URL> resources = classLoader.getResources(packageName.replace('.', '/'));
// while (resources.hasMoreElements()) {
// URL res = resources.nextElement();
//
// if (res.getProtocol().matches("(jar|zip)")) {
// res = new URL((res.getProtocol().equals("zip") || !res.getFile().contains("file:") ?
// "file:".concat(res.getFile().startsWith("/") ? "": "/") : "").concat(res.getFile().split("!")[0]));
// }
// if (res.getFile().contains(".jar")) {
// jarInputStream = new JarInputStream(res.openStream());
// JarEntry entry = jarInputStream.getNextJarEntry();
//
//
// while (entry != null) {
// if (entry.getName().startsWith(packageName.replace('.', '/')) && entry.getName().endsWith(".class") && !entry.getName().contains("$")) {
// classes.add(Class.forName(entry.getName().replace(".class","").replace("/",".")));
// }
//
// entry = jarInputStream.getNextJarEntry();
// }
// } else {
// classes.addAll(scanClassesFromDirectory(new File(URLDecoder.decode(res.getPath(), "UTF-8")), packageName));
// }
// }
// } catch (Exception x) {
// throw new IllegalArgumentException("invalid package");
// } finally {
// if(jarInputStream != null){
// try {
// jarInputStream.close();
// } catch (IOException e) {
// throw new IllegalStateException(e.getMessage());
// }
// }
// }
//
// return classes;
// }
| import static br.com.six2six.fixturefactory.util.ClassLoaderUtils.getClassesForPackage; | package br.com.six2six.fixturefactory.loader;
public class FixtureFactoryLoader {
public static void loadTemplates(String basePackage) { | // Path: src/main/java/br/com/six2six/fixturefactory/util/ClassLoaderUtils.java
// public static Set<Class<?>> getClassesForPackage(String packageName) {
// Set<Class<?>> classes = new HashSet<Class<?>>();
//
// JarInputStream jarInputStream = null;
// try {
// ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
//
// Enumeration<URL> resources = classLoader.getResources(packageName.replace('.', '/'));
// while (resources.hasMoreElements()) {
// URL res = resources.nextElement();
//
// if (res.getProtocol().matches("(jar|zip)")) {
// res = new URL((res.getProtocol().equals("zip") || !res.getFile().contains("file:") ?
// "file:".concat(res.getFile().startsWith("/") ? "": "/") : "").concat(res.getFile().split("!")[0]));
// }
// if (res.getFile().contains(".jar")) {
// jarInputStream = new JarInputStream(res.openStream());
// JarEntry entry = jarInputStream.getNextJarEntry();
//
//
// while (entry != null) {
// if (entry.getName().startsWith(packageName.replace('.', '/')) && entry.getName().endsWith(".class") && !entry.getName().contains("$")) {
// classes.add(Class.forName(entry.getName().replace(".class","").replace("/",".")));
// }
//
// entry = jarInputStream.getNextJarEntry();
// }
// } else {
// classes.addAll(scanClassesFromDirectory(new File(URLDecoder.decode(res.getPath(), "UTF-8")), packageName));
// }
// }
// } catch (Exception x) {
// throw new IllegalArgumentException("invalid package");
// } finally {
// if(jarInputStream != null){
// try {
// jarInputStream.close();
// } catch (IOException e) {
// throw new IllegalStateException(e.getMessage());
// }
// }
// }
//
// return classes;
// }
// Path: src/main/java/br/com/six2six/fixturefactory/loader/FixtureFactoryLoader.java
import static br.com.six2six.fixturefactory.util.ClassLoaderUtils.getClassesForPackage;
package br.com.six2six.fixturefactory.loader;
public class FixtureFactoryLoader {
public static void loadTemplates(String basePackage) { | for (Class<?> clazz : getClassesForPackage(basePackage)) { |
six2six/fixture-factory | src/test/java/br/com/six2six/fixturefactory/FixtureCircularReferenceTest.java | // Path: src/main/java/br/com/six2six/fixturefactory/loader/FixtureFactoryLoader.java
// public class FixtureFactoryLoader {
//
// public static void loadTemplates(String basePackage) {
// for (Class<?> clazz : getClassesForPackage(basePackage)) {
// if (!clazz.isInterface() && TemplateLoader.class.isAssignableFrom(clazz)) {
// try {
// ((TemplateLoader) clazz.newInstance()).load();
// } catch (Exception e) {
// throw new RuntimeException(String.format("template %s not loaded", clazz.getName()), e);
// }
// }
// }
// }
// }
//
// Path: src/test/java/br/com/six2six/fixturefactory/model/Item.java
// public class Item implements Serializable {
//
// private static final long serialVersionUID = -8679257032342835407L;
//
// private Order order;
//
// private Integer productId;
//
// public Order getOrder() {
// return order;
// }
//
// public void setOrder(Order order) {
// this.order = order;
// }
//
// public Integer getProductId() {
// return productId;
// }
//
// public void setProductId(Integer productId) {
// this.productId = productId;
// }
// }
//
// Path: src/test/java/br/com/six2six/fixturefactory/model/Order.java
// public class Order implements Serializable {
//
// private static final long serialVersionUID = -3858669033991459168L;
//
// private Long id;
//
// private LocalDateTime registerDate;
//
// private LocalDate sendDate;
//
// private List<Item> items;
//
// private Payment payment;
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public List<Item> getItems() {
// return items;
// }
//
// public void setItems(List<Item> items) {
// this.items = items;
// }
//
// public Payment getPayment() {
// return payment;
// }
//
// public void setPayment(Payment payment) {
// this.payment = payment;
// }
//
// public LocalDateTime getRegisterDate() {
// return registerDate;
// }
//
// public void setRegisterDate(LocalDateTime registerDate) {
// this.registerDate = registerDate;
// }
//
// public LocalDate getSendDate() {
// return sendDate;
// }
//
// public void setSendDate(LocalDate sendDate) {
// this.sendDate = sendDate;
// }
//
// }
| import static org.junit.Assert.assertTrue;
import org.junit.BeforeClass;
import org.junit.Test;
import br.com.six2six.fixturefactory.loader.FixtureFactoryLoader;
import br.com.six2six.fixturefactory.model.Item;
import br.com.six2six.fixturefactory.model.Order; | package br.com.six2six.fixturefactory;
public class FixtureCircularReferenceTest {
@BeforeClass
public static void setUp() { | // Path: src/main/java/br/com/six2six/fixturefactory/loader/FixtureFactoryLoader.java
// public class FixtureFactoryLoader {
//
// public static void loadTemplates(String basePackage) {
// for (Class<?> clazz : getClassesForPackage(basePackage)) {
// if (!clazz.isInterface() && TemplateLoader.class.isAssignableFrom(clazz)) {
// try {
// ((TemplateLoader) clazz.newInstance()).load();
// } catch (Exception e) {
// throw new RuntimeException(String.format("template %s not loaded", clazz.getName()), e);
// }
// }
// }
// }
// }
//
// Path: src/test/java/br/com/six2six/fixturefactory/model/Item.java
// public class Item implements Serializable {
//
// private static final long serialVersionUID = -8679257032342835407L;
//
// private Order order;
//
// private Integer productId;
//
// public Order getOrder() {
// return order;
// }
//
// public void setOrder(Order order) {
// this.order = order;
// }
//
// public Integer getProductId() {
// return productId;
// }
//
// public void setProductId(Integer productId) {
// this.productId = productId;
// }
// }
//
// Path: src/test/java/br/com/six2six/fixturefactory/model/Order.java
// public class Order implements Serializable {
//
// private static final long serialVersionUID = -3858669033991459168L;
//
// private Long id;
//
// private LocalDateTime registerDate;
//
// private LocalDate sendDate;
//
// private List<Item> items;
//
// private Payment payment;
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public List<Item> getItems() {
// return items;
// }
//
// public void setItems(List<Item> items) {
// this.items = items;
// }
//
// public Payment getPayment() {
// return payment;
// }
//
// public void setPayment(Payment payment) {
// this.payment = payment;
// }
//
// public LocalDateTime getRegisterDate() {
// return registerDate;
// }
//
// public void setRegisterDate(LocalDateTime registerDate) {
// this.registerDate = registerDate;
// }
//
// public LocalDate getSendDate() {
// return sendDate;
// }
//
// public void setSendDate(LocalDate sendDate) {
// this.sendDate = sendDate;
// }
//
// }
// Path: src/test/java/br/com/six2six/fixturefactory/FixtureCircularReferenceTest.java
import static org.junit.Assert.assertTrue;
import org.junit.BeforeClass;
import org.junit.Test;
import br.com.six2six.fixturefactory.loader.FixtureFactoryLoader;
import br.com.six2six.fixturefactory.model.Item;
import br.com.six2six.fixturefactory.model.Order;
package br.com.six2six.fixturefactory;
public class FixtureCircularReferenceTest {
@BeforeClass
public static void setUp() { | FixtureFactoryLoader.loadTemplates("br.com.six2six.template"); |
six2six/fixture-factory | src/test/java/br/com/six2six/fixturefactory/FixtureCircularReferenceTest.java | // Path: src/main/java/br/com/six2six/fixturefactory/loader/FixtureFactoryLoader.java
// public class FixtureFactoryLoader {
//
// public static void loadTemplates(String basePackage) {
// for (Class<?> clazz : getClassesForPackage(basePackage)) {
// if (!clazz.isInterface() && TemplateLoader.class.isAssignableFrom(clazz)) {
// try {
// ((TemplateLoader) clazz.newInstance()).load();
// } catch (Exception e) {
// throw new RuntimeException(String.format("template %s not loaded", clazz.getName()), e);
// }
// }
// }
// }
// }
//
// Path: src/test/java/br/com/six2six/fixturefactory/model/Item.java
// public class Item implements Serializable {
//
// private static final long serialVersionUID = -8679257032342835407L;
//
// private Order order;
//
// private Integer productId;
//
// public Order getOrder() {
// return order;
// }
//
// public void setOrder(Order order) {
// this.order = order;
// }
//
// public Integer getProductId() {
// return productId;
// }
//
// public void setProductId(Integer productId) {
// this.productId = productId;
// }
// }
//
// Path: src/test/java/br/com/six2six/fixturefactory/model/Order.java
// public class Order implements Serializable {
//
// private static final long serialVersionUID = -3858669033991459168L;
//
// private Long id;
//
// private LocalDateTime registerDate;
//
// private LocalDate sendDate;
//
// private List<Item> items;
//
// private Payment payment;
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public List<Item> getItems() {
// return items;
// }
//
// public void setItems(List<Item> items) {
// this.items = items;
// }
//
// public Payment getPayment() {
// return payment;
// }
//
// public void setPayment(Payment payment) {
// this.payment = payment;
// }
//
// public LocalDateTime getRegisterDate() {
// return registerDate;
// }
//
// public void setRegisterDate(LocalDateTime registerDate) {
// this.registerDate = registerDate;
// }
//
// public LocalDate getSendDate() {
// return sendDate;
// }
//
// public void setSendDate(LocalDate sendDate) {
// this.sendDate = sendDate;
// }
//
// }
| import static org.junit.Assert.assertTrue;
import org.junit.BeforeClass;
import org.junit.Test;
import br.com.six2six.fixturefactory.loader.FixtureFactoryLoader;
import br.com.six2six.fixturefactory.model.Item;
import br.com.six2six.fixturefactory.model.Order; | package br.com.six2six.fixturefactory;
public class FixtureCircularReferenceTest {
@BeforeClass
public static void setUp() {
FixtureFactoryLoader.loadTemplates("br.com.six2six.template");
}
@Test
public void circularReference() { | // Path: src/main/java/br/com/six2six/fixturefactory/loader/FixtureFactoryLoader.java
// public class FixtureFactoryLoader {
//
// public static void loadTemplates(String basePackage) {
// for (Class<?> clazz : getClassesForPackage(basePackage)) {
// if (!clazz.isInterface() && TemplateLoader.class.isAssignableFrom(clazz)) {
// try {
// ((TemplateLoader) clazz.newInstance()).load();
// } catch (Exception e) {
// throw new RuntimeException(String.format("template %s not loaded", clazz.getName()), e);
// }
// }
// }
// }
// }
//
// Path: src/test/java/br/com/six2six/fixturefactory/model/Item.java
// public class Item implements Serializable {
//
// private static final long serialVersionUID = -8679257032342835407L;
//
// private Order order;
//
// private Integer productId;
//
// public Order getOrder() {
// return order;
// }
//
// public void setOrder(Order order) {
// this.order = order;
// }
//
// public Integer getProductId() {
// return productId;
// }
//
// public void setProductId(Integer productId) {
// this.productId = productId;
// }
// }
//
// Path: src/test/java/br/com/six2six/fixturefactory/model/Order.java
// public class Order implements Serializable {
//
// private static final long serialVersionUID = -3858669033991459168L;
//
// private Long id;
//
// private LocalDateTime registerDate;
//
// private LocalDate sendDate;
//
// private List<Item> items;
//
// private Payment payment;
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public List<Item> getItems() {
// return items;
// }
//
// public void setItems(List<Item> items) {
// this.items = items;
// }
//
// public Payment getPayment() {
// return payment;
// }
//
// public void setPayment(Payment payment) {
// this.payment = payment;
// }
//
// public LocalDateTime getRegisterDate() {
// return registerDate;
// }
//
// public void setRegisterDate(LocalDateTime registerDate) {
// this.registerDate = registerDate;
// }
//
// public LocalDate getSendDate() {
// return sendDate;
// }
//
// public void setSendDate(LocalDate sendDate) {
// this.sendDate = sendDate;
// }
//
// }
// Path: src/test/java/br/com/six2six/fixturefactory/FixtureCircularReferenceTest.java
import static org.junit.Assert.assertTrue;
import org.junit.BeforeClass;
import org.junit.Test;
import br.com.six2six.fixturefactory.loader.FixtureFactoryLoader;
import br.com.six2six.fixturefactory.model.Item;
import br.com.six2six.fixturefactory.model.Order;
package br.com.six2six.fixturefactory;
public class FixtureCircularReferenceTest {
@BeforeClass
public static void setUp() {
FixtureFactoryLoader.loadTemplates("br.com.six2six.template");
}
@Test
public void circularReference() { | Order order = Fixture.from(Order.class).gimme("valid"); |
six2six/fixture-factory | src/test/java/br/com/six2six/fixturefactory/FixtureCircularReferenceTest.java | // Path: src/main/java/br/com/six2six/fixturefactory/loader/FixtureFactoryLoader.java
// public class FixtureFactoryLoader {
//
// public static void loadTemplates(String basePackage) {
// for (Class<?> clazz : getClassesForPackage(basePackage)) {
// if (!clazz.isInterface() && TemplateLoader.class.isAssignableFrom(clazz)) {
// try {
// ((TemplateLoader) clazz.newInstance()).load();
// } catch (Exception e) {
// throw new RuntimeException(String.format("template %s not loaded", clazz.getName()), e);
// }
// }
// }
// }
// }
//
// Path: src/test/java/br/com/six2six/fixturefactory/model/Item.java
// public class Item implements Serializable {
//
// private static final long serialVersionUID = -8679257032342835407L;
//
// private Order order;
//
// private Integer productId;
//
// public Order getOrder() {
// return order;
// }
//
// public void setOrder(Order order) {
// this.order = order;
// }
//
// public Integer getProductId() {
// return productId;
// }
//
// public void setProductId(Integer productId) {
// this.productId = productId;
// }
// }
//
// Path: src/test/java/br/com/six2six/fixturefactory/model/Order.java
// public class Order implements Serializable {
//
// private static final long serialVersionUID = -3858669033991459168L;
//
// private Long id;
//
// private LocalDateTime registerDate;
//
// private LocalDate sendDate;
//
// private List<Item> items;
//
// private Payment payment;
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public List<Item> getItems() {
// return items;
// }
//
// public void setItems(List<Item> items) {
// this.items = items;
// }
//
// public Payment getPayment() {
// return payment;
// }
//
// public void setPayment(Payment payment) {
// this.payment = payment;
// }
//
// public LocalDateTime getRegisterDate() {
// return registerDate;
// }
//
// public void setRegisterDate(LocalDateTime registerDate) {
// this.registerDate = registerDate;
// }
//
// public LocalDate getSendDate() {
// return sendDate;
// }
//
// public void setSendDate(LocalDate sendDate) {
// this.sendDate = sendDate;
// }
//
// }
| import static org.junit.Assert.assertTrue;
import org.junit.BeforeClass;
import org.junit.Test;
import br.com.six2six.fixturefactory.loader.FixtureFactoryLoader;
import br.com.six2six.fixturefactory.model.Item;
import br.com.six2six.fixturefactory.model.Order; | package br.com.six2six.fixturefactory;
public class FixtureCircularReferenceTest {
@BeforeClass
public static void setUp() {
FixtureFactoryLoader.loadTemplates("br.com.six2six.template");
}
@Test
public void circularReference() {
Order order = Fixture.from(Order.class).gimme("valid");
| // Path: src/main/java/br/com/six2six/fixturefactory/loader/FixtureFactoryLoader.java
// public class FixtureFactoryLoader {
//
// public static void loadTemplates(String basePackage) {
// for (Class<?> clazz : getClassesForPackage(basePackage)) {
// if (!clazz.isInterface() && TemplateLoader.class.isAssignableFrom(clazz)) {
// try {
// ((TemplateLoader) clazz.newInstance()).load();
// } catch (Exception e) {
// throw new RuntimeException(String.format("template %s not loaded", clazz.getName()), e);
// }
// }
// }
// }
// }
//
// Path: src/test/java/br/com/six2six/fixturefactory/model/Item.java
// public class Item implements Serializable {
//
// private static final long serialVersionUID = -8679257032342835407L;
//
// private Order order;
//
// private Integer productId;
//
// public Order getOrder() {
// return order;
// }
//
// public void setOrder(Order order) {
// this.order = order;
// }
//
// public Integer getProductId() {
// return productId;
// }
//
// public void setProductId(Integer productId) {
// this.productId = productId;
// }
// }
//
// Path: src/test/java/br/com/six2six/fixturefactory/model/Order.java
// public class Order implements Serializable {
//
// private static final long serialVersionUID = -3858669033991459168L;
//
// private Long id;
//
// private LocalDateTime registerDate;
//
// private LocalDate sendDate;
//
// private List<Item> items;
//
// private Payment payment;
//
// public Long getId() {
// return id;
// }
//
// public void setId(Long id) {
// this.id = id;
// }
//
// public List<Item> getItems() {
// return items;
// }
//
// public void setItems(List<Item> items) {
// this.items = items;
// }
//
// public Payment getPayment() {
// return payment;
// }
//
// public void setPayment(Payment payment) {
// this.payment = payment;
// }
//
// public LocalDateTime getRegisterDate() {
// return registerDate;
// }
//
// public void setRegisterDate(LocalDateTime registerDate) {
// this.registerDate = registerDate;
// }
//
// public LocalDate getSendDate() {
// return sendDate;
// }
//
// public void setSendDate(LocalDate sendDate) {
// this.sendDate = sendDate;
// }
//
// }
// Path: src/test/java/br/com/six2six/fixturefactory/FixtureCircularReferenceTest.java
import static org.junit.Assert.assertTrue;
import org.junit.BeforeClass;
import org.junit.Test;
import br.com.six2six.fixturefactory.loader.FixtureFactoryLoader;
import br.com.six2six.fixturefactory.model.Item;
import br.com.six2six.fixturefactory.model.Order;
package br.com.six2six.fixturefactory;
public class FixtureCircularReferenceTest {
@BeforeClass
public static void setUp() {
FixtureFactoryLoader.loadTemplates("br.com.six2six.template");
}
@Test
public void circularReference() {
Order order = Fixture.from(Order.class).gimme("valid");
| for (Item item : order.getItems()) { |
six2six/fixture-factory | src/test/java/br/com/six2six/fixturefactory/function/NumberSequenceFunctionTest.java | // Path: src/main/java/br/com/six2six/fixturefactory/function/impl/SequenceFunction.java
// public class SequenceFunction implements AtomicFunction {
//
// private Sequence<?> sequence;
//
// public SequenceFunction(Sequence<?> sequence) {
// this.sequence = sequence;
// }
//
// @Override
// @SuppressWarnings("unchecked")
// public <T> T generateValue() {
// return (T) sequence.nextValue();
// }
// }
| import br.com.six2six.fixturefactory.function.impl.NumberSequence;
import br.com.six2six.fixturefactory.function.impl.SequenceFunction;
import org.junit.Test;
import static org.junit.Assert.assertEquals; | package br.com.six2six.fixturefactory.function;
public class NumberSequenceFunctionTest {
@Test
public void intSequence() { | // Path: src/main/java/br/com/six2six/fixturefactory/function/impl/SequenceFunction.java
// public class SequenceFunction implements AtomicFunction {
//
// private Sequence<?> sequence;
//
// public SequenceFunction(Sequence<?> sequence) {
// this.sequence = sequence;
// }
//
// @Override
// @SuppressWarnings("unchecked")
// public <T> T generateValue() {
// return (T) sequence.nextValue();
// }
// }
// Path: src/test/java/br/com/six2six/fixturefactory/function/NumberSequenceFunctionTest.java
import br.com.six2six.fixturefactory.function.impl.NumberSequence;
import br.com.six2six.fixturefactory.function.impl.SequenceFunction;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
package br.com.six2six.fixturefactory.function;
public class NumberSequenceFunctionTest {
@Test
public void intSequence() { | SequenceFunction function = new SequenceFunction(new NumberSequence(0, 1)); |
six2six/fixture-factory | src/test/java/br/com/six2six/fixturefactory/function/EnumFunctionTest.java | // Path: src/main/java/br/com/six2six/fixturefactory/function/impl/EnumFunction.java
// public class EnumFunction implements AtomicFunction {
//
// private Class<? extends Enum<?>> clazz;
// private int quantity;
//
// public EnumFunction(Class<? extends Enum<?>> clazz, int quantity) {
// this.clazz = clazz;
// this.quantity = quantity;
// }
//
// @SuppressWarnings("unchecked")
// @Override
// public <T> T generateValue() {
// List<T> results = new ArrayList<T>();
// AtomicFunction function = new RandomFunction(clazz);
// for (int i = 0; i < quantity; i++) {
// results.add((T) function.generateValue());
// }
//
// return (T) results;
// }
// }
//
// Path: src/test/java/br/com/six2six/fixturefactory/model/UserType.java
// public enum UserType {
// ADMIN, DEFAULT
// }
| import static org.junit.Assert.assertEquals;
import java.util.List;
import org.junit.Test;
import br.com.six2six.fixturefactory.function.impl.EnumFunction;
import br.com.six2six.fixturefactory.model.UserType; | package br.com.six2six.fixturefactory.function;
public class EnumFunctionTest {
@Test
public void shouldGenerateRandomEnumValues() { | // Path: src/main/java/br/com/six2six/fixturefactory/function/impl/EnumFunction.java
// public class EnumFunction implements AtomicFunction {
//
// private Class<? extends Enum<?>> clazz;
// private int quantity;
//
// public EnumFunction(Class<? extends Enum<?>> clazz, int quantity) {
// this.clazz = clazz;
// this.quantity = quantity;
// }
//
// @SuppressWarnings("unchecked")
// @Override
// public <T> T generateValue() {
// List<T> results = new ArrayList<T>();
// AtomicFunction function = new RandomFunction(clazz);
// for (int i = 0; i < quantity; i++) {
// results.add((T) function.generateValue());
// }
//
// return (T) results;
// }
// }
//
// Path: src/test/java/br/com/six2six/fixturefactory/model/UserType.java
// public enum UserType {
// ADMIN, DEFAULT
// }
// Path: src/test/java/br/com/six2six/fixturefactory/function/EnumFunctionTest.java
import static org.junit.Assert.assertEquals;
import java.util.List;
import org.junit.Test;
import br.com.six2six.fixturefactory.function.impl.EnumFunction;
import br.com.six2six.fixturefactory.model.UserType;
package br.com.six2six.fixturefactory.function;
public class EnumFunctionTest {
@Test
public void shouldGenerateRandomEnumValues() { | List<UserType> userTypes = new EnumFunction(UserType.class, 2).generateValue(); |
six2six/fixture-factory | src/test/java/br/com/six2six/fixturefactory/function/EnumFunctionTest.java | // Path: src/main/java/br/com/six2six/fixturefactory/function/impl/EnumFunction.java
// public class EnumFunction implements AtomicFunction {
//
// private Class<? extends Enum<?>> clazz;
// private int quantity;
//
// public EnumFunction(Class<? extends Enum<?>> clazz, int quantity) {
// this.clazz = clazz;
// this.quantity = quantity;
// }
//
// @SuppressWarnings("unchecked")
// @Override
// public <T> T generateValue() {
// List<T> results = new ArrayList<T>();
// AtomicFunction function = new RandomFunction(clazz);
// for (int i = 0; i < quantity; i++) {
// results.add((T) function.generateValue());
// }
//
// return (T) results;
// }
// }
//
// Path: src/test/java/br/com/six2six/fixturefactory/model/UserType.java
// public enum UserType {
// ADMIN, DEFAULT
// }
| import static org.junit.Assert.assertEquals;
import java.util.List;
import org.junit.Test;
import br.com.six2six.fixturefactory.function.impl.EnumFunction;
import br.com.six2six.fixturefactory.model.UserType; | package br.com.six2six.fixturefactory.function;
public class EnumFunctionTest {
@Test
public void shouldGenerateRandomEnumValues() { | // Path: src/main/java/br/com/six2six/fixturefactory/function/impl/EnumFunction.java
// public class EnumFunction implements AtomicFunction {
//
// private Class<? extends Enum<?>> clazz;
// private int quantity;
//
// public EnumFunction(Class<? extends Enum<?>> clazz, int quantity) {
// this.clazz = clazz;
// this.quantity = quantity;
// }
//
// @SuppressWarnings("unchecked")
// @Override
// public <T> T generateValue() {
// List<T> results = new ArrayList<T>();
// AtomicFunction function = new RandomFunction(clazz);
// for (int i = 0; i < quantity; i++) {
// results.add((T) function.generateValue());
// }
//
// return (T) results;
// }
// }
//
// Path: src/test/java/br/com/six2six/fixturefactory/model/UserType.java
// public enum UserType {
// ADMIN, DEFAULT
// }
// Path: src/test/java/br/com/six2six/fixturefactory/function/EnumFunctionTest.java
import static org.junit.Assert.assertEquals;
import java.util.List;
import org.junit.Test;
import br.com.six2six.fixturefactory.function.impl.EnumFunction;
import br.com.six2six.fixturefactory.model.UserType;
package br.com.six2six.fixturefactory.function;
public class EnumFunctionTest {
@Test
public void shouldGenerateRandomEnumValues() { | List<UserType> userTypes = new EnumFunction(UserType.class, 2).generateValue(); |
six2six/fixture-factory | src/test/java/br/com/six2six/fixturefactory/FixtureInnerClassTest.java | // Path: src/main/java/br/com/six2six/fixturefactory/loader/FixtureFactoryLoader.java
// public class FixtureFactoryLoader {
//
// public static void loadTemplates(String basePackage) {
// for (Class<?> clazz : getClassesForPackage(basePackage)) {
// if (!clazz.isInterface() && TemplateLoader.class.isAssignableFrom(clazz)) {
// try {
// ((TemplateLoader) clazz.newInstance()).load();
// } catch (Exception e) {
// throw new RuntimeException(String.format("template %s not loaded", clazz.getName()), e);
// }
// }
// }
// }
// }
//
// Path: src/test/java/br/com/six2six/fixturefactory/model/Owner.java
// public class Owner {
//
// public String id;
//
// private Inner inner;
//
// public Inner getInner() {
// return inner;
// }
//
// public void setInner(Inner inner) {
// this.inner = inner;
// }
//
// public class Inner {
// private String id;
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public Owner getOwner() {
// return Owner.this;
// }
// }
// }
| import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
import org.junit.BeforeClass;
import org.junit.Test;
import br.com.six2six.fixturefactory.loader.FixtureFactoryLoader;
import br.com.six2six.fixturefactory.model.Owner;
| package br.com.six2six.fixturefactory;
public class FixtureInnerClassTest {
@BeforeClass
public static void setUp() {
| // Path: src/main/java/br/com/six2six/fixturefactory/loader/FixtureFactoryLoader.java
// public class FixtureFactoryLoader {
//
// public static void loadTemplates(String basePackage) {
// for (Class<?> clazz : getClassesForPackage(basePackage)) {
// if (!clazz.isInterface() && TemplateLoader.class.isAssignableFrom(clazz)) {
// try {
// ((TemplateLoader) clazz.newInstance()).load();
// } catch (Exception e) {
// throw new RuntimeException(String.format("template %s not loaded", clazz.getName()), e);
// }
// }
// }
// }
// }
//
// Path: src/test/java/br/com/six2six/fixturefactory/model/Owner.java
// public class Owner {
//
// public String id;
//
// private Inner inner;
//
// public Inner getInner() {
// return inner;
// }
//
// public void setInner(Inner inner) {
// this.inner = inner;
// }
//
// public class Inner {
// private String id;
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public Owner getOwner() {
// return Owner.this;
// }
// }
// }
// Path: src/test/java/br/com/six2six/fixturefactory/FixtureInnerClassTest.java
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
import org.junit.BeforeClass;
import org.junit.Test;
import br.com.six2six.fixturefactory.loader.FixtureFactoryLoader;
import br.com.six2six.fixturefactory.model.Owner;
package br.com.six2six.fixturefactory;
public class FixtureInnerClassTest {
@BeforeClass
public static void setUp() {
| FixtureFactoryLoader.loadTemplates("br.com.six2six.template");
|
six2six/fixture-factory | src/test/java/br/com/six2six/fixturefactory/FixtureInnerClassTest.java | // Path: src/main/java/br/com/six2six/fixturefactory/loader/FixtureFactoryLoader.java
// public class FixtureFactoryLoader {
//
// public static void loadTemplates(String basePackage) {
// for (Class<?> clazz : getClassesForPackage(basePackage)) {
// if (!clazz.isInterface() && TemplateLoader.class.isAssignableFrom(clazz)) {
// try {
// ((TemplateLoader) clazz.newInstance()).load();
// } catch (Exception e) {
// throw new RuntimeException(String.format("template %s not loaded", clazz.getName()), e);
// }
// }
// }
// }
// }
//
// Path: src/test/java/br/com/six2six/fixturefactory/model/Owner.java
// public class Owner {
//
// public String id;
//
// private Inner inner;
//
// public Inner getInner() {
// return inner;
// }
//
// public void setInner(Inner inner) {
// this.inner = inner;
// }
//
// public class Inner {
// private String id;
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public Owner getOwner() {
// return Owner.this;
// }
// }
// }
| import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
import org.junit.BeforeClass;
import org.junit.Test;
import br.com.six2six.fixturefactory.loader.FixtureFactoryLoader;
import br.com.six2six.fixturefactory.model.Owner;
| package br.com.six2six.fixturefactory;
public class FixtureInnerClassTest {
@BeforeClass
public static void setUp() {
FixtureFactoryLoader.loadTemplates("br.com.six2six.template");
}
@Test
public void shouldCreateObjectWithInnerClass() {
| // Path: src/main/java/br/com/six2six/fixturefactory/loader/FixtureFactoryLoader.java
// public class FixtureFactoryLoader {
//
// public static void loadTemplates(String basePackage) {
// for (Class<?> clazz : getClassesForPackage(basePackage)) {
// if (!clazz.isInterface() && TemplateLoader.class.isAssignableFrom(clazz)) {
// try {
// ((TemplateLoader) clazz.newInstance()).load();
// } catch (Exception e) {
// throw new RuntimeException(String.format("template %s not loaded", clazz.getName()), e);
// }
// }
// }
// }
// }
//
// Path: src/test/java/br/com/six2six/fixturefactory/model/Owner.java
// public class Owner {
//
// public String id;
//
// private Inner inner;
//
// public Inner getInner() {
// return inner;
// }
//
// public void setInner(Inner inner) {
// this.inner = inner;
// }
//
// public class Inner {
// private String id;
//
// public String getId() {
// return id;
// }
//
// public void setId(String id) {
// this.id = id;
// }
//
// public Owner getOwner() {
// return Owner.this;
// }
// }
// }
// Path: src/test/java/br/com/six2six/fixturefactory/FixtureInnerClassTest.java
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
import org.junit.BeforeClass;
import org.junit.Test;
import br.com.six2six.fixturefactory.loader.FixtureFactoryLoader;
import br.com.six2six.fixturefactory.model.Owner;
package br.com.six2six.fixturefactory;
public class FixtureInnerClassTest {
@BeforeClass
public static void setUp() {
FixtureFactoryLoader.loadTemplates("br.com.six2six.template");
}
@Test
public void shouldCreateObjectWithInnerClass() {
| Owner owner = Fixture.from(Owner.class).gimme("valid");
|
six2six/fixture-factory | src/test/java/br/com/six2six/fixturefactory/function/CnpjFunctionTest.java | // Path: src/main/java/br/com/six2six/fixturefactory/function/impl/CnpjFunction.java
// public class CnpjFunction implements AtomicFunction {
//
// private boolean formatted;
//
// public CnpjFunction() { }
//
// public CnpjFunction(boolean formatted) {
// this.formatted = formatted;
// }
//
// @Override
// @SuppressWarnings("unchecked")
// public <T> T generateValue() {
// RandomFunction random = new RandomFunction(Integer.class, new Range(1, 9));
// Integer a = random.generateValue();
// Integer b = random.generateValue();
// Integer c = random.generateValue();
// Integer d = random.generateValue();
// Integer e = random.generateValue();
// Integer f = random.generateValue();
// Integer g = random.generateValue();
// Integer h = random.generateValue();
// Integer i = 0;
// Integer j = 0;
// Integer l = 0;
// Integer m = 1;
//
// int n = m*2+l*3+j*4+i*5+h*6+g*7+f*8+e*9+d*2+c*3+b*4+a*5;
// n = n % 11 < 2 ? 0 : 11 - (n % 11);
//
// int o = n*2+m*3+l*4+j*5+i*6+h*7+g*8+f*9+e*2+d*3+c*4+b*5+a*6;
// o = o % 11 < 2 ? 0 : 11 - (o % 11);
//
// return (T) String.format(formatted? "%d%d.%d%d%d.%d%d%d/%d%d%d%d-%d%d" : "%d%d%d%d%d%d%d%d%d%d%d%d%d%d", a, b, c, d, e, f, g, h, i, j, l, m, n, o);
// }
// }
| import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.util.regex.Pattern;
import org.junit.Test;
import br.com.six2six.fixturefactory.function.impl.CnpjFunction; | package br.com.six2six.fixturefactory.function;
public class CnpjFunctionTest {
@Test
public void randomCnpj() { | // Path: src/main/java/br/com/six2six/fixturefactory/function/impl/CnpjFunction.java
// public class CnpjFunction implements AtomicFunction {
//
// private boolean formatted;
//
// public CnpjFunction() { }
//
// public CnpjFunction(boolean formatted) {
// this.formatted = formatted;
// }
//
// @Override
// @SuppressWarnings("unchecked")
// public <T> T generateValue() {
// RandomFunction random = new RandomFunction(Integer.class, new Range(1, 9));
// Integer a = random.generateValue();
// Integer b = random.generateValue();
// Integer c = random.generateValue();
// Integer d = random.generateValue();
// Integer e = random.generateValue();
// Integer f = random.generateValue();
// Integer g = random.generateValue();
// Integer h = random.generateValue();
// Integer i = 0;
// Integer j = 0;
// Integer l = 0;
// Integer m = 1;
//
// int n = m*2+l*3+j*4+i*5+h*6+g*7+f*8+e*9+d*2+c*3+b*4+a*5;
// n = n % 11 < 2 ? 0 : 11 - (n % 11);
//
// int o = n*2+m*3+l*4+j*5+i*6+h*7+g*8+f*9+e*2+d*3+c*4+b*5+a*6;
// o = o % 11 < 2 ? 0 : 11 - (o % 11);
//
// return (T) String.format(formatted? "%d%d.%d%d%d.%d%d%d/%d%d%d%d-%d%d" : "%d%d%d%d%d%d%d%d%d%d%d%d%d%d", a, b, c, d, e, f, g, h, i, j, l, m, n, o);
// }
// }
// Path: src/test/java/br/com/six2six/fixturefactory/function/CnpjFunctionTest.java
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.util.regex.Pattern;
import org.junit.Test;
import br.com.six2six.fixturefactory.function.impl.CnpjFunction;
package br.com.six2six.fixturefactory.function;
public class CnpjFunctionTest {
@Test
public void randomCnpj() { | String value = new CnpjFunction().generateValue(); |
longdivision/hex | app/src/test/java/com/hexfornh/hex/adapter/helper/TextHelperTest.java | // Path: app/src/main/java/com/hexforhn/hex/adapter/helper/TextHelper.java
// public class TextHelper {
//
// public static CharSequence removeTrailingNewlinesFromText(CharSequence text) {
// if (text == null || text.length() < 1) {
// return "";
// }
//
// if (text.charAt(text.length() - 1) == "\n".charAt(0)) {
// return removeTrailingNewlinesFromText(text.subSequence(0, text.length() - 1));
// }
//
// return text;
// }
// }
| import com.hexforhn.hex.adapter.helper.TextHelper;
import org.junit.Test;
import static junit.framework.Assert.assertEquals; | package com.hexfornh.hex.adapter.helper;
public class TextHelperTest {
@Test
public void removesTrailingNewlinesFromText() throws Exception { | // Path: app/src/main/java/com/hexforhn/hex/adapter/helper/TextHelper.java
// public class TextHelper {
//
// public static CharSequence removeTrailingNewlinesFromText(CharSequence text) {
// if (text == null || text.length() < 1) {
// return "";
// }
//
// if (text.charAt(text.length() - 1) == "\n".charAt(0)) {
// return removeTrailingNewlinesFromText(text.subSequence(0, text.length() - 1));
// }
//
// return text;
// }
// }
// Path: app/src/test/java/com/hexfornh/hex/adapter/helper/TextHelperTest.java
import com.hexforhn.hex.adapter.helper.TextHelper;
import org.junit.Test;
import static junit.framework.Assert.assertEquals;
package com.hexfornh.hex.adapter.helper;
public class TextHelperTest {
@Test
public void removesTrailingNewlinesFromText() throws Exception { | assertEquals("", TextHelper.removeTrailingNewlinesFromText(null)); |
longdivision/hex | app/src/main/java/com/hexforhn/hex/adapter/FrontPageListAdapter.java | // Path: app/src/main/java/com/hexforhn/hex/listener/ClickListener.java
// public interface ClickListener {
//
// /**
// * Called when the view is clicked.
// *
// * @param v view that is clicked
// * @param position of the clicked item
// * @param isLongClick true if long click, false otherwise
// */
// void onClick(View v, int position, boolean isLongClick);
// }
//
// Path: app/src/main/java/com/hexforhn/hex/viewmodel/StoryListItemViewModel.java
// public class StoryListItemViewModel {
//
// private final String mTitle;
// private final String mDomain;
// private final int mScore;
// private final int mCommentCount;
// private final Date mDate;
//
// public StoryListItemViewModel(String title, String domain, int score, int commentCount, Date date) {
// this.mTitle = title;
// this.mDomain = domain;
// this.mScore = score;
// this.mCommentCount = commentCount;
// this.mDate = date;
// }
//
// public String getTitle() {
// return this.mTitle;
// }
//
// public String getDomain() {
// return this.mDomain;
// }
//
// public String getScore() {
// return String.valueOf(this.mScore);
// }
//
// public String getCommentCount() {
// return String.valueOf(this.mCommentCount);
// }
//
// public String getRelativeTime() {
// return DateUtils.getRelativeTimeSpanString(mDate.getTime(), System.currentTimeMillis(), 0)
// .toString();
//
// }
// }
| import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.hexforhn.hex.R;
import com.hexforhn.hex.listener.ClickListener;
import com.hexforhn.hex.viewmodel.StoryListItemViewModel;
import com.squareup.picasso.Picasso;
import java.util.List; | package com.hexforhn.hex.adapter;
public class FrontPageListAdapter extends RecyclerView.Adapter<ViewHolder> {
private final List<StoryListItemViewModel> mDataset; | // Path: app/src/main/java/com/hexforhn/hex/listener/ClickListener.java
// public interface ClickListener {
//
// /**
// * Called when the view is clicked.
// *
// * @param v view that is clicked
// * @param position of the clicked item
// * @param isLongClick true if long click, false otherwise
// */
// void onClick(View v, int position, boolean isLongClick);
// }
//
// Path: app/src/main/java/com/hexforhn/hex/viewmodel/StoryListItemViewModel.java
// public class StoryListItemViewModel {
//
// private final String mTitle;
// private final String mDomain;
// private final int mScore;
// private final int mCommentCount;
// private final Date mDate;
//
// public StoryListItemViewModel(String title, String domain, int score, int commentCount, Date date) {
// this.mTitle = title;
// this.mDomain = domain;
// this.mScore = score;
// this.mCommentCount = commentCount;
// this.mDate = date;
// }
//
// public String getTitle() {
// return this.mTitle;
// }
//
// public String getDomain() {
// return this.mDomain;
// }
//
// public String getScore() {
// return String.valueOf(this.mScore);
// }
//
// public String getCommentCount() {
// return String.valueOf(this.mCommentCount);
// }
//
// public String getRelativeTime() {
// return DateUtils.getRelativeTimeSpanString(mDate.getTime(), System.currentTimeMillis(), 0)
// .toString();
//
// }
// }
// Path: app/src/main/java/com/hexforhn/hex/adapter/FrontPageListAdapter.java
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.hexforhn.hex.R;
import com.hexforhn.hex.listener.ClickListener;
import com.hexforhn.hex.viewmodel.StoryListItemViewModel;
import com.squareup.picasso.Picasso;
import java.util.List;
package com.hexforhn.hex.adapter;
public class FrontPageListAdapter extends RecyclerView.Adapter<ViewHolder> {
private final List<StoryListItemViewModel> mDataset; | private final ClickListener mClickListener; |
longdivision/hex | app/src/main/java/com/hexforhn/hex/adapter/ViewHolder.java | // Path: app/src/main/java/com/hexforhn/hex/listener/ClickListener.java
// public interface ClickListener {
//
// /**
// * Called when the view is clicked.
// *
// * @param v view that is clicked
// * @param position of the clicked item
// * @param isLongClick true if long click, false otherwise
// */
// void onClick(View v, int position, boolean isLongClick);
// }
| import android.support.v7.widget.RecyclerView;
import android.view.View;
import com.hexforhn.hex.listener.ClickListener; | package com.hexforhn.hex.adapter;
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public final View mView; | // Path: app/src/main/java/com/hexforhn/hex/listener/ClickListener.java
// public interface ClickListener {
//
// /**
// * Called when the view is clicked.
// *
// * @param v view that is clicked
// * @param position of the clicked item
// * @param isLongClick true if long click, false otherwise
// */
// void onClick(View v, int position, boolean isLongClick);
// }
// Path: app/src/main/java/com/hexforhn/hex/adapter/ViewHolder.java
import android.support.v7.widget.RecyclerView;
import android.view.View;
import com.hexforhn.hex.listener.ClickListener;
package com.hexforhn.hex.adapter;
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public final View mView; | private ClickListener clickListener; |
longdivision/hex | app/src/main/java/com/hexforhn/hex/fragment/ArticleFragment.java | // Path: app/src/main/java/com/hexforhn/hex/HexApplication.java
// public class HexApplication extends Application {
//
// private RequestQueue mRequestQueue;
//
// public final String apiBaseUrl = "https://hex-api.herokuapp.com";
//
// public void onCreate() {
// super.onCreate();
// setupAnalytics();
// }
//
// public RequestQueue getRequestQueue() {
// if (mRequestQueue == null) {
// int MEGABYTE = 1024 * 1024;
// Cache cache = new DiskBasedCache(getCacheDir(), MEGABYTE);
// Network network = new BasicNetwork(new HurlStack());
// mRequestQueue = new RequestQueue(cache, network);
// mRequestQueue.start();
// }
//
// return mRequestQueue;
// }
//
// private void setupAnalytics() {
// GoogleAnalytics analytics = GoogleAnalytics.getInstance(this);
// Tracker tracker = analytics.newTracker(R.xml.global_tracker);
// tracker.enableAutoActivityTracking(true);
// tracker.enableExceptionReporting(true);
// }
// }
//
// Path: app/src/main/java/com/hexforhn/hex/model/Story.java
// public class Story implements Item {
//
// private final String mId;
// private final String mTitle;
// private final String mUrl;
// private final String mCommentsUrl;
// private final String mUser;
// private final String mDomain;
// private final int mScore;
// private final int mCommentCount;
// private final Date mDate;
// private final List<Comment> mComments;
//
// public Story(String id, String title, String url, String commentsUrl, String user, String domain,
// int score, int commentCount, Date date) {
// this.mId = id;
// this.mTitle = title;
// this.mUrl = url;
// this.mCommentsUrl = commentsUrl;
// this.mUser = user;
// this.mDomain = domain;
// this.mScore = score;
// this.mCommentCount = commentCount;
// this.mDate = date;
// this.mComments = new ArrayList<>();
// }
//
// public Story(String id, String title, String url, String commentsUrl, String user, String domain,
// int score, int commentCount, Date date, List<Comment> comments) {
// this.mId = id;
// this.mTitle = title;
// this.mUrl = url;
// this.mCommentsUrl = commentsUrl;
// this.mUser = user;
// this.mDomain = domain;
// this.mScore = score;
// this.mCommentCount = commentCount;
// this.mDate = date;
// this.mComments = comments;
// }
//
// public String getId() {
// return this.mId;
// }
//
// public String getTitle() {
// return this.mTitle;
// }
//
// public String getUrl() {
// return this.mUrl;
// }
//
// public String getCommentsUrl() {
// return this.mCommentsUrl;
// }
//
// public String getUser() {
// return this.mUser;
// }
//
// public String getDomain() {
// return this.mDomain;
// }
//
// public int getScore() {
// return this.mScore;
// }
//
// public int getCommentCount() {
// return this.mCommentCount;
// }
//
// public Date getDate() {
// return this.mDate;
// }
//
// public List<Comment> getComments() {
// return this.mComments;
// }
// }
//
// Path: app/src/main/java/com/hexforhn/hex/net/hexapi/StoryService.java
// public class StoryService {
//
// private final RequestQueue mRequestQueue;
// private final String mApiBaseUrl;
//
// public StoryService(RequestQueue requestQueue, String apiUrl) {
// this.mRequestQueue = requestQueue;
// mApiBaseUrl = apiUrl;
// }
//
// public Story getStory(String storyId) {
// String STORY_PATH = "/story";
// String storyPath = mApiBaseUrl + STORY_PATH + "/" + storyId;
//
// RequestFuture<JSONObject> future = RequestFuture.newFuture();
// JsonObjectRequest request = new JsonObjectRequest(storyPath, future, future);
// request.setRetryPolicy(RetryPolicyFactory.build());
// mRequestQueue.add(request);
//
// try {
// JSONObject response = future.get();
// return StoryMarshaller.marshall(response);
// } catch (Exception e) {
// return null;
// }
// }
// }
| import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.TextView;
import com.hexforhn.hex.HexApplication;
import com.hexforhn.hex.R;
import com.hexforhn.hex.model.Story;
import com.hexforhn.hex.net.hexapi.StoryService;
import io.reactivex.Single;
import io.reactivex.SingleObserver;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import java.util.concurrent.Callable; | hideArticleUnavailable();
mSwipeRefreshLayout.setRefreshing(true);
}
public void onPageFinished(WebView view, String url) {
swipeRefreshLayout.setRefreshing(false);
}
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
if (!request.isForMainFrame()) {
return;
}
swipeRefreshLayout.setRefreshing(false);
showArticleUnavailable();
}
});
return webView;
}
private SwipeRefreshLayout setupSwipeRefreshLayout(View rootView) {
SwipeRefreshLayout refreshLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.refresh);
refreshLayout.setEnabled(false);
return refreshLayout;
}
private void loadArticle() { | // Path: app/src/main/java/com/hexforhn/hex/HexApplication.java
// public class HexApplication extends Application {
//
// private RequestQueue mRequestQueue;
//
// public final String apiBaseUrl = "https://hex-api.herokuapp.com";
//
// public void onCreate() {
// super.onCreate();
// setupAnalytics();
// }
//
// public RequestQueue getRequestQueue() {
// if (mRequestQueue == null) {
// int MEGABYTE = 1024 * 1024;
// Cache cache = new DiskBasedCache(getCacheDir(), MEGABYTE);
// Network network = new BasicNetwork(new HurlStack());
// mRequestQueue = new RequestQueue(cache, network);
// mRequestQueue.start();
// }
//
// return mRequestQueue;
// }
//
// private void setupAnalytics() {
// GoogleAnalytics analytics = GoogleAnalytics.getInstance(this);
// Tracker tracker = analytics.newTracker(R.xml.global_tracker);
// tracker.enableAutoActivityTracking(true);
// tracker.enableExceptionReporting(true);
// }
// }
//
// Path: app/src/main/java/com/hexforhn/hex/model/Story.java
// public class Story implements Item {
//
// private final String mId;
// private final String mTitle;
// private final String mUrl;
// private final String mCommentsUrl;
// private final String mUser;
// private final String mDomain;
// private final int mScore;
// private final int mCommentCount;
// private final Date mDate;
// private final List<Comment> mComments;
//
// public Story(String id, String title, String url, String commentsUrl, String user, String domain,
// int score, int commentCount, Date date) {
// this.mId = id;
// this.mTitle = title;
// this.mUrl = url;
// this.mCommentsUrl = commentsUrl;
// this.mUser = user;
// this.mDomain = domain;
// this.mScore = score;
// this.mCommentCount = commentCount;
// this.mDate = date;
// this.mComments = new ArrayList<>();
// }
//
// public Story(String id, String title, String url, String commentsUrl, String user, String domain,
// int score, int commentCount, Date date, List<Comment> comments) {
// this.mId = id;
// this.mTitle = title;
// this.mUrl = url;
// this.mCommentsUrl = commentsUrl;
// this.mUser = user;
// this.mDomain = domain;
// this.mScore = score;
// this.mCommentCount = commentCount;
// this.mDate = date;
// this.mComments = comments;
// }
//
// public String getId() {
// return this.mId;
// }
//
// public String getTitle() {
// return this.mTitle;
// }
//
// public String getUrl() {
// return this.mUrl;
// }
//
// public String getCommentsUrl() {
// return this.mCommentsUrl;
// }
//
// public String getUser() {
// return this.mUser;
// }
//
// public String getDomain() {
// return this.mDomain;
// }
//
// public int getScore() {
// return this.mScore;
// }
//
// public int getCommentCount() {
// return this.mCommentCount;
// }
//
// public Date getDate() {
// return this.mDate;
// }
//
// public List<Comment> getComments() {
// return this.mComments;
// }
// }
//
// Path: app/src/main/java/com/hexforhn/hex/net/hexapi/StoryService.java
// public class StoryService {
//
// private final RequestQueue mRequestQueue;
// private final String mApiBaseUrl;
//
// public StoryService(RequestQueue requestQueue, String apiUrl) {
// this.mRequestQueue = requestQueue;
// mApiBaseUrl = apiUrl;
// }
//
// public Story getStory(String storyId) {
// String STORY_PATH = "/story";
// String storyPath = mApiBaseUrl + STORY_PATH + "/" + storyId;
//
// RequestFuture<JSONObject> future = RequestFuture.newFuture();
// JsonObjectRequest request = new JsonObjectRequest(storyPath, future, future);
// request.setRetryPolicy(RetryPolicyFactory.build());
// mRequestQueue.add(request);
//
// try {
// JSONObject response = future.get();
// return StoryMarshaller.marshall(response);
// } catch (Exception e) {
// return null;
// }
// }
// }
// Path: app/src/main/java/com/hexforhn/hex/fragment/ArticleFragment.java
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.TextView;
import com.hexforhn.hex.HexApplication;
import com.hexforhn.hex.R;
import com.hexforhn.hex.model.Story;
import com.hexforhn.hex.net.hexapi.StoryService;
import io.reactivex.Single;
import io.reactivex.SingleObserver;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import java.util.concurrent.Callable;
hideArticleUnavailable();
mSwipeRefreshLayout.setRefreshing(true);
}
public void onPageFinished(WebView view, String url) {
swipeRefreshLayout.setRefreshing(false);
}
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
if (!request.isForMainFrame()) {
return;
}
swipeRefreshLayout.setRefreshing(false);
showArticleUnavailable();
}
});
return webView;
}
private SwipeRefreshLayout setupSwipeRefreshLayout(View rootView) {
SwipeRefreshLayout refreshLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.refresh);
refreshLayout.setEnabled(false);
return refreshLayout;
}
private void loadArticle() { | SingleObserver observer = new SingleObserver<Story>() { |
longdivision/hex | app/src/main/java/com/hexforhn/hex/fragment/ArticleFragment.java | // Path: app/src/main/java/com/hexforhn/hex/HexApplication.java
// public class HexApplication extends Application {
//
// private RequestQueue mRequestQueue;
//
// public final String apiBaseUrl = "https://hex-api.herokuapp.com";
//
// public void onCreate() {
// super.onCreate();
// setupAnalytics();
// }
//
// public RequestQueue getRequestQueue() {
// if (mRequestQueue == null) {
// int MEGABYTE = 1024 * 1024;
// Cache cache = new DiskBasedCache(getCacheDir(), MEGABYTE);
// Network network = new BasicNetwork(new HurlStack());
// mRequestQueue = new RequestQueue(cache, network);
// mRequestQueue.start();
// }
//
// return mRequestQueue;
// }
//
// private void setupAnalytics() {
// GoogleAnalytics analytics = GoogleAnalytics.getInstance(this);
// Tracker tracker = analytics.newTracker(R.xml.global_tracker);
// tracker.enableAutoActivityTracking(true);
// tracker.enableExceptionReporting(true);
// }
// }
//
// Path: app/src/main/java/com/hexforhn/hex/model/Story.java
// public class Story implements Item {
//
// private final String mId;
// private final String mTitle;
// private final String mUrl;
// private final String mCommentsUrl;
// private final String mUser;
// private final String mDomain;
// private final int mScore;
// private final int mCommentCount;
// private final Date mDate;
// private final List<Comment> mComments;
//
// public Story(String id, String title, String url, String commentsUrl, String user, String domain,
// int score, int commentCount, Date date) {
// this.mId = id;
// this.mTitle = title;
// this.mUrl = url;
// this.mCommentsUrl = commentsUrl;
// this.mUser = user;
// this.mDomain = domain;
// this.mScore = score;
// this.mCommentCount = commentCount;
// this.mDate = date;
// this.mComments = new ArrayList<>();
// }
//
// public Story(String id, String title, String url, String commentsUrl, String user, String domain,
// int score, int commentCount, Date date, List<Comment> comments) {
// this.mId = id;
// this.mTitle = title;
// this.mUrl = url;
// this.mCommentsUrl = commentsUrl;
// this.mUser = user;
// this.mDomain = domain;
// this.mScore = score;
// this.mCommentCount = commentCount;
// this.mDate = date;
// this.mComments = comments;
// }
//
// public String getId() {
// return this.mId;
// }
//
// public String getTitle() {
// return this.mTitle;
// }
//
// public String getUrl() {
// return this.mUrl;
// }
//
// public String getCommentsUrl() {
// return this.mCommentsUrl;
// }
//
// public String getUser() {
// return this.mUser;
// }
//
// public String getDomain() {
// return this.mDomain;
// }
//
// public int getScore() {
// return this.mScore;
// }
//
// public int getCommentCount() {
// return this.mCommentCount;
// }
//
// public Date getDate() {
// return this.mDate;
// }
//
// public List<Comment> getComments() {
// return this.mComments;
// }
// }
//
// Path: app/src/main/java/com/hexforhn/hex/net/hexapi/StoryService.java
// public class StoryService {
//
// private final RequestQueue mRequestQueue;
// private final String mApiBaseUrl;
//
// public StoryService(RequestQueue requestQueue, String apiUrl) {
// this.mRequestQueue = requestQueue;
// mApiBaseUrl = apiUrl;
// }
//
// public Story getStory(String storyId) {
// String STORY_PATH = "/story";
// String storyPath = mApiBaseUrl + STORY_PATH + "/" + storyId;
//
// RequestFuture<JSONObject> future = RequestFuture.newFuture();
// JsonObjectRequest request = new JsonObjectRequest(storyPath, future, future);
// request.setRetryPolicy(RetryPolicyFactory.build());
// mRequestQueue.add(request);
//
// try {
// JSONObject response = future.get();
// return StoryMarshaller.marshall(response);
// } catch (Exception e) {
// return null;
// }
// }
// }
| import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.TextView;
import com.hexforhn.hex.HexApplication;
import com.hexforhn.hex.R;
import com.hexforhn.hex.model.Story;
import com.hexforhn.hex.net.hexapi.StoryService;
import io.reactivex.Single;
import io.reactivex.SingleObserver;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import java.util.concurrent.Callable; | @Override
public void onClick(View v) {
loadArticle();
mSwipeRefreshLayout.setRefreshing(true);
}
});
}
private String getStoryId() {
return this.getArguments().getString("STORY_ID");
}
private void showArticleUnavailable() {
View view = getView();
view.findViewById(R.id.webView).setVisibility(View.GONE);
view.findViewById(R.id.content_unavailable).setVisibility(View.VISIBLE);
}
private void hideArticleUnavailable() {
View view = getView();
view.findViewById(R.id.webView).setVisibility(View.VISIBLE);
view.findViewById(R.id.content_unavailable).setVisibility(View.GONE);
}
private Single getStory() {
return Single.fromCallable(new Callable<Story>() {
@Override
public Story call() { | // Path: app/src/main/java/com/hexforhn/hex/HexApplication.java
// public class HexApplication extends Application {
//
// private RequestQueue mRequestQueue;
//
// public final String apiBaseUrl = "https://hex-api.herokuapp.com";
//
// public void onCreate() {
// super.onCreate();
// setupAnalytics();
// }
//
// public RequestQueue getRequestQueue() {
// if (mRequestQueue == null) {
// int MEGABYTE = 1024 * 1024;
// Cache cache = new DiskBasedCache(getCacheDir(), MEGABYTE);
// Network network = new BasicNetwork(new HurlStack());
// mRequestQueue = new RequestQueue(cache, network);
// mRequestQueue.start();
// }
//
// return mRequestQueue;
// }
//
// private void setupAnalytics() {
// GoogleAnalytics analytics = GoogleAnalytics.getInstance(this);
// Tracker tracker = analytics.newTracker(R.xml.global_tracker);
// tracker.enableAutoActivityTracking(true);
// tracker.enableExceptionReporting(true);
// }
// }
//
// Path: app/src/main/java/com/hexforhn/hex/model/Story.java
// public class Story implements Item {
//
// private final String mId;
// private final String mTitle;
// private final String mUrl;
// private final String mCommentsUrl;
// private final String mUser;
// private final String mDomain;
// private final int mScore;
// private final int mCommentCount;
// private final Date mDate;
// private final List<Comment> mComments;
//
// public Story(String id, String title, String url, String commentsUrl, String user, String domain,
// int score, int commentCount, Date date) {
// this.mId = id;
// this.mTitle = title;
// this.mUrl = url;
// this.mCommentsUrl = commentsUrl;
// this.mUser = user;
// this.mDomain = domain;
// this.mScore = score;
// this.mCommentCount = commentCount;
// this.mDate = date;
// this.mComments = new ArrayList<>();
// }
//
// public Story(String id, String title, String url, String commentsUrl, String user, String domain,
// int score, int commentCount, Date date, List<Comment> comments) {
// this.mId = id;
// this.mTitle = title;
// this.mUrl = url;
// this.mCommentsUrl = commentsUrl;
// this.mUser = user;
// this.mDomain = domain;
// this.mScore = score;
// this.mCommentCount = commentCount;
// this.mDate = date;
// this.mComments = comments;
// }
//
// public String getId() {
// return this.mId;
// }
//
// public String getTitle() {
// return this.mTitle;
// }
//
// public String getUrl() {
// return this.mUrl;
// }
//
// public String getCommentsUrl() {
// return this.mCommentsUrl;
// }
//
// public String getUser() {
// return this.mUser;
// }
//
// public String getDomain() {
// return this.mDomain;
// }
//
// public int getScore() {
// return this.mScore;
// }
//
// public int getCommentCount() {
// return this.mCommentCount;
// }
//
// public Date getDate() {
// return this.mDate;
// }
//
// public List<Comment> getComments() {
// return this.mComments;
// }
// }
//
// Path: app/src/main/java/com/hexforhn/hex/net/hexapi/StoryService.java
// public class StoryService {
//
// private final RequestQueue mRequestQueue;
// private final String mApiBaseUrl;
//
// public StoryService(RequestQueue requestQueue, String apiUrl) {
// this.mRequestQueue = requestQueue;
// mApiBaseUrl = apiUrl;
// }
//
// public Story getStory(String storyId) {
// String STORY_PATH = "/story";
// String storyPath = mApiBaseUrl + STORY_PATH + "/" + storyId;
//
// RequestFuture<JSONObject> future = RequestFuture.newFuture();
// JsonObjectRequest request = new JsonObjectRequest(storyPath, future, future);
// request.setRetryPolicy(RetryPolicyFactory.build());
// mRequestQueue.add(request);
//
// try {
// JSONObject response = future.get();
// return StoryMarshaller.marshall(response);
// } catch (Exception e) {
// return null;
// }
// }
// }
// Path: app/src/main/java/com/hexforhn/hex/fragment/ArticleFragment.java
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.TextView;
import com.hexforhn.hex.HexApplication;
import com.hexforhn.hex.R;
import com.hexforhn.hex.model.Story;
import com.hexforhn.hex.net.hexapi.StoryService;
import io.reactivex.Single;
import io.reactivex.SingleObserver;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import java.util.concurrent.Callable;
@Override
public void onClick(View v) {
loadArticle();
mSwipeRefreshLayout.setRefreshing(true);
}
});
}
private String getStoryId() {
return this.getArguments().getString("STORY_ID");
}
private void showArticleUnavailable() {
View view = getView();
view.findViewById(R.id.webView).setVisibility(View.GONE);
view.findViewById(R.id.content_unavailable).setVisibility(View.VISIBLE);
}
private void hideArticleUnavailable() {
View view = getView();
view.findViewById(R.id.webView).setVisibility(View.VISIBLE);
view.findViewById(R.id.content_unavailable).setVisibility(View.GONE);
}
private Single getStory() {
return Single.fromCallable(new Callable<Story>() {
@Override
public Story call() { | HexApplication application = (HexApplication) getActivity().getApplication(); |
longdivision/hex | app/src/main/java/com/hexforhn/hex/fragment/ArticleFragment.java | // Path: app/src/main/java/com/hexforhn/hex/HexApplication.java
// public class HexApplication extends Application {
//
// private RequestQueue mRequestQueue;
//
// public final String apiBaseUrl = "https://hex-api.herokuapp.com";
//
// public void onCreate() {
// super.onCreate();
// setupAnalytics();
// }
//
// public RequestQueue getRequestQueue() {
// if (mRequestQueue == null) {
// int MEGABYTE = 1024 * 1024;
// Cache cache = new DiskBasedCache(getCacheDir(), MEGABYTE);
// Network network = new BasicNetwork(new HurlStack());
// mRequestQueue = new RequestQueue(cache, network);
// mRequestQueue.start();
// }
//
// return mRequestQueue;
// }
//
// private void setupAnalytics() {
// GoogleAnalytics analytics = GoogleAnalytics.getInstance(this);
// Tracker tracker = analytics.newTracker(R.xml.global_tracker);
// tracker.enableAutoActivityTracking(true);
// tracker.enableExceptionReporting(true);
// }
// }
//
// Path: app/src/main/java/com/hexforhn/hex/model/Story.java
// public class Story implements Item {
//
// private final String mId;
// private final String mTitle;
// private final String mUrl;
// private final String mCommentsUrl;
// private final String mUser;
// private final String mDomain;
// private final int mScore;
// private final int mCommentCount;
// private final Date mDate;
// private final List<Comment> mComments;
//
// public Story(String id, String title, String url, String commentsUrl, String user, String domain,
// int score, int commentCount, Date date) {
// this.mId = id;
// this.mTitle = title;
// this.mUrl = url;
// this.mCommentsUrl = commentsUrl;
// this.mUser = user;
// this.mDomain = domain;
// this.mScore = score;
// this.mCommentCount = commentCount;
// this.mDate = date;
// this.mComments = new ArrayList<>();
// }
//
// public Story(String id, String title, String url, String commentsUrl, String user, String domain,
// int score, int commentCount, Date date, List<Comment> comments) {
// this.mId = id;
// this.mTitle = title;
// this.mUrl = url;
// this.mCommentsUrl = commentsUrl;
// this.mUser = user;
// this.mDomain = domain;
// this.mScore = score;
// this.mCommentCount = commentCount;
// this.mDate = date;
// this.mComments = comments;
// }
//
// public String getId() {
// return this.mId;
// }
//
// public String getTitle() {
// return this.mTitle;
// }
//
// public String getUrl() {
// return this.mUrl;
// }
//
// public String getCommentsUrl() {
// return this.mCommentsUrl;
// }
//
// public String getUser() {
// return this.mUser;
// }
//
// public String getDomain() {
// return this.mDomain;
// }
//
// public int getScore() {
// return this.mScore;
// }
//
// public int getCommentCount() {
// return this.mCommentCount;
// }
//
// public Date getDate() {
// return this.mDate;
// }
//
// public List<Comment> getComments() {
// return this.mComments;
// }
// }
//
// Path: app/src/main/java/com/hexforhn/hex/net/hexapi/StoryService.java
// public class StoryService {
//
// private final RequestQueue mRequestQueue;
// private final String mApiBaseUrl;
//
// public StoryService(RequestQueue requestQueue, String apiUrl) {
// this.mRequestQueue = requestQueue;
// mApiBaseUrl = apiUrl;
// }
//
// public Story getStory(String storyId) {
// String STORY_PATH = "/story";
// String storyPath = mApiBaseUrl + STORY_PATH + "/" + storyId;
//
// RequestFuture<JSONObject> future = RequestFuture.newFuture();
// JsonObjectRequest request = new JsonObjectRequest(storyPath, future, future);
// request.setRetryPolicy(RetryPolicyFactory.build());
// mRequestQueue.add(request);
//
// try {
// JSONObject response = future.get();
// return StoryMarshaller.marshall(response);
// } catch (Exception e) {
// return null;
// }
// }
// }
| import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.TextView;
import com.hexforhn.hex.HexApplication;
import com.hexforhn.hex.R;
import com.hexforhn.hex.model.Story;
import com.hexforhn.hex.net.hexapi.StoryService;
import io.reactivex.Single;
import io.reactivex.SingleObserver;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import java.util.concurrent.Callable; | public void onClick(View v) {
loadArticle();
mSwipeRefreshLayout.setRefreshing(true);
}
});
}
private String getStoryId() {
return this.getArguments().getString("STORY_ID");
}
private void showArticleUnavailable() {
View view = getView();
view.findViewById(R.id.webView).setVisibility(View.GONE);
view.findViewById(R.id.content_unavailable).setVisibility(View.VISIBLE);
}
private void hideArticleUnavailable() {
View view = getView();
view.findViewById(R.id.webView).setVisibility(View.VISIBLE);
view.findViewById(R.id.content_unavailable).setVisibility(View.GONE);
}
private Single getStory() {
return Single.fromCallable(new Callable<Story>() {
@Override
public Story call() {
HexApplication application = (HexApplication) getActivity().getApplication(); | // Path: app/src/main/java/com/hexforhn/hex/HexApplication.java
// public class HexApplication extends Application {
//
// private RequestQueue mRequestQueue;
//
// public final String apiBaseUrl = "https://hex-api.herokuapp.com";
//
// public void onCreate() {
// super.onCreate();
// setupAnalytics();
// }
//
// public RequestQueue getRequestQueue() {
// if (mRequestQueue == null) {
// int MEGABYTE = 1024 * 1024;
// Cache cache = new DiskBasedCache(getCacheDir(), MEGABYTE);
// Network network = new BasicNetwork(new HurlStack());
// mRequestQueue = new RequestQueue(cache, network);
// mRequestQueue.start();
// }
//
// return mRequestQueue;
// }
//
// private void setupAnalytics() {
// GoogleAnalytics analytics = GoogleAnalytics.getInstance(this);
// Tracker tracker = analytics.newTracker(R.xml.global_tracker);
// tracker.enableAutoActivityTracking(true);
// tracker.enableExceptionReporting(true);
// }
// }
//
// Path: app/src/main/java/com/hexforhn/hex/model/Story.java
// public class Story implements Item {
//
// private final String mId;
// private final String mTitle;
// private final String mUrl;
// private final String mCommentsUrl;
// private final String mUser;
// private final String mDomain;
// private final int mScore;
// private final int mCommentCount;
// private final Date mDate;
// private final List<Comment> mComments;
//
// public Story(String id, String title, String url, String commentsUrl, String user, String domain,
// int score, int commentCount, Date date) {
// this.mId = id;
// this.mTitle = title;
// this.mUrl = url;
// this.mCommentsUrl = commentsUrl;
// this.mUser = user;
// this.mDomain = domain;
// this.mScore = score;
// this.mCommentCount = commentCount;
// this.mDate = date;
// this.mComments = new ArrayList<>();
// }
//
// public Story(String id, String title, String url, String commentsUrl, String user, String domain,
// int score, int commentCount, Date date, List<Comment> comments) {
// this.mId = id;
// this.mTitle = title;
// this.mUrl = url;
// this.mCommentsUrl = commentsUrl;
// this.mUser = user;
// this.mDomain = domain;
// this.mScore = score;
// this.mCommentCount = commentCount;
// this.mDate = date;
// this.mComments = comments;
// }
//
// public String getId() {
// return this.mId;
// }
//
// public String getTitle() {
// return this.mTitle;
// }
//
// public String getUrl() {
// return this.mUrl;
// }
//
// public String getCommentsUrl() {
// return this.mCommentsUrl;
// }
//
// public String getUser() {
// return this.mUser;
// }
//
// public String getDomain() {
// return this.mDomain;
// }
//
// public int getScore() {
// return this.mScore;
// }
//
// public int getCommentCount() {
// return this.mCommentCount;
// }
//
// public Date getDate() {
// return this.mDate;
// }
//
// public List<Comment> getComments() {
// return this.mComments;
// }
// }
//
// Path: app/src/main/java/com/hexforhn/hex/net/hexapi/StoryService.java
// public class StoryService {
//
// private final RequestQueue mRequestQueue;
// private final String mApiBaseUrl;
//
// public StoryService(RequestQueue requestQueue, String apiUrl) {
// this.mRequestQueue = requestQueue;
// mApiBaseUrl = apiUrl;
// }
//
// public Story getStory(String storyId) {
// String STORY_PATH = "/story";
// String storyPath = mApiBaseUrl + STORY_PATH + "/" + storyId;
//
// RequestFuture<JSONObject> future = RequestFuture.newFuture();
// JsonObjectRequest request = new JsonObjectRequest(storyPath, future, future);
// request.setRetryPolicy(RetryPolicyFactory.build());
// mRequestQueue.add(request);
//
// try {
// JSONObject response = future.get();
// return StoryMarshaller.marshall(response);
// } catch (Exception e) {
// return null;
// }
// }
// }
// Path: app/src/main/java/com/hexforhn/hex/fragment/ArticleFragment.java
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.TextView;
import com.hexforhn.hex.HexApplication;
import com.hexforhn.hex.R;
import com.hexforhn.hex.model.Story;
import com.hexforhn.hex.net.hexapi.StoryService;
import io.reactivex.Single;
import io.reactivex.SingleObserver;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import java.util.concurrent.Callable;
public void onClick(View v) {
loadArticle();
mSwipeRefreshLayout.setRefreshing(true);
}
});
}
private String getStoryId() {
return this.getArguments().getString("STORY_ID");
}
private void showArticleUnavailable() {
View view = getView();
view.findViewById(R.id.webView).setVisibility(View.GONE);
view.findViewById(R.id.content_unavailable).setVisibility(View.VISIBLE);
}
private void hideArticleUnavailable() {
View view = getView();
view.findViewById(R.id.webView).setVisibility(View.VISIBLE);
view.findViewById(R.id.content_unavailable).setVisibility(View.GONE);
}
private Single getStory() {
return Single.fromCallable(new Callable<Story>() {
@Override
public Story call() {
HexApplication application = (HexApplication) getActivity().getApplication(); | StoryService service = new StoryService(application.getRequestQueue(), application.apiBaseUrl); |
longdivision/hex | app/src/main/java/com/hexforhn/hex/activity/SettingsActivity.java | // Path: app/src/main/java/com/hexforhn/hex/fragment/SettingsFragment.java
// public class SettingsFragment extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener {
// @Override
// public void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
//
// addPreferencesFromResource(R.xml.preferences);
//
// getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
// }
//
// @Override
// public void onDestroy() {
// super.onDestroy();
// getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
// }
//
// @Override
// public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
// // Apply theme changes instantly by immediately re-creating the parent activity
// if (key.equals(getString(R.string.enableDarkThemeSettingKey))) {
// getActivity().recreate();
// }
// }
// }
//
// Path: app/src/main/java/com/hexforhn/hex/util/ThemeHelper.java
// public class ThemeHelper {
// public static void applyTheme(Activity activity) {
// if (shouldSetTheme(activity)) {
// activity.setTheme(getDesiredTheme(activity));
// }
// }
//
// public static void updateTheme(Activity activity) {
// if (shouldSetTheme(activity)) {
// activity.recreate();
// }
// }
//
// private static boolean shouldSetTheme(Activity activity) {
// return getCurrentTheme(activity) != getDesiredTheme(activity);
// }
//
// private static int getDesiredTheme(Activity activity) {
// SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(activity);
// boolean useDarkTheme = sharedPref.getBoolean(activity.getString(R.string.enableDarkThemeSettingKey), false);
//
// return useDarkTheme ? R.style.AppThemeDark : R.style.AppThemeLight;
// }
//
// private static int getCurrentTheme(Activity activity) {
// TypedValue outValue = new TypedValue();
// activity.getTheme().resolveAttribute(R.attr.themeName, outValue, true);
//
// return outValue.string.toString().equals("AppThemeDark") ? R.style.AppThemeDark : R.style.AppThemeLight;
// }
// }
| import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import com.hexforhn.hex.R;
import com.hexforhn.hex.fragment.SettingsFragment;
import com.hexforhn.hex.util.ThemeHelper; | package com.hexforhn.hex.activity;
public class SettingsActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); | // Path: app/src/main/java/com/hexforhn/hex/fragment/SettingsFragment.java
// public class SettingsFragment extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener {
// @Override
// public void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
//
// addPreferencesFromResource(R.xml.preferences);
//
// getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
// }
//
// @Override
// public void onDestroy() {
// super.onDestroy();
// getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
// }
//
// @Override
// public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
// // Apply theme changes instantly by immediately re-creating the parent activity
// if (key.equals(getString(R.string.enableDarkThemeSettingKey))) {
// getActivity().recreate();
// }
// }
// }
//
// Path: app/src/main/java/com/hexforhn/hex/util/ThemeHelper.java
// public class ThemeHelper {
// public static void applyTheme(Activity activity) {
// if (shouldSetTheme(activity)) {
// activity.setTheme(getDesiredTheme(activity));
// }
// }
//
// public static void updateTheme(Activity activity) {
// if (shouldSetTheme(activity)) {
// activity.recreate();
// }
// }
//
// private static boolean shouldSetTheme(Activity activity) {
// return getCurrentTheme(activity) != getDesiredTheme(activity);
// }
//
// private static int getDesiredTheme(Activity activity) {
// SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(activity);
// boolean useDarkTheme = sharedPref.getBoolean(activity.getString(R.string.enableDarkThemeSettingKey), false);
//
// return useDarkTheme ? R.style.AppThemeDark : R.style.AppThemeLight;
// }
//
// private static int getCurrentTheme(Activity activity) {
// TypedValue outValue = new TypedValue();
// activity.getTheme().resolveAttribute(R.attr.themeName, outValue, true);
//
// return outValue.string.toString().equals("AppThemeDark") ? R.style.AppThemeDark : R.style.AppThemeLight;
// }
// }
// Path: app/src/main/java/com/hexforhn/hex/activity/SettingsActivity.java
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import com.hexforhn.hex.R;
import com.hexforhn.hex.fragment.SettingsFragment;
import com.hexforhn.hex.util.ThemeHelper;
package com.hexforhn.hex.activity;
public class SettingsActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); | ThemeHelper.applyTheme(this); |
longdivision/hex | app/src/main/java/com/hexforhn/hex/activity/SettingsActivity.java | // Path: app/src/main/java/com/hexforhn/hex/fragment/SettingsFragment.java
// public class SettingsFragment extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener {
// @Override
// public void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
//
// addPreferencesFromResource(R.xml.preferences);
//
// getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
// }
//
// @Override
// public void onDestroy() {
// super.onDestroy();
// getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
// }
//
// @Override
// public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
// // Apply theme changes instantly by immediately re-creating the parent activity
// if (key.equals(getString(R.string.enableDarkThemeSettingKey))) {
// getActivity().recreate();
// }
// }
// }
//
// Path: app/src/main/java/com/hexforhn/hex/util/ThemeHelper.java
// public class ThemeHelper {
// public static void applyTheme(Activity activity) {
// if (shouldSetTheme(activity)) {
// activity.setTheme(getDesiredTheme(activity));
// }
// }
//
// public static void updateTheme(Activity activity) {
// if (shouldSetTheme(activity)) {
// activity.recreate();
// }
// }
//
// private static boolean shouldSetTheme(Activity activity) {
// return getCurrentTheme(activity) != getDesiredTheme(activity);
// }
//
// private static int getDesiredTheme(Activity activity) {
// SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(activity);
// boolean useDarkTheme = sharedPref.getBoolean(activity.getString(R.string.enableDarkThemeSettingKey), false);
//
// return useDarkTheme ? R.style.AppThemeDark : R.style.AppThemeLight;
// }
//
// private static int getCurrentTheme(Activity activity) {
// TypedValue outValue = new TypedValue();
// activity.getTheme().resolveAttribute(R.attr.themeName, outValue, true);
//
// return outValue.string.toString().equals("AppThemeDark") ? R.style.AppThemeDark : R.style.AppThemeLight;
// }
// }
| import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import com.hexforhn.hex.R;
import com.hexforhn.hex.fragment.SettingsFragment;
import com.hexforhn.hex.util.ThemeHelper; | package com.hexforhn.hex.activity;
public class SettingsActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ThemeHelper.applyTheme(this);
setContentView(R.layout.activity_settings);
setupToolbar();
getFragmentManager().beginTransaction() | // Path: app/src/main/java/com/hexforhn/hex/fragment/SettingsFragment.java
// public class SettingsFragment extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener {
// @Override
// public void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
//
// addPreferencesFromResource(R.xml.preferences);
//
// getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
// }
//
// @Override
// public void onDestroy() {
// super.onDestroy();
// getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
// }
//
// @Override
// public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
// // Apply theme changes instantly by immediately re-creating the parent activity
// if (key.equals(getString(R.string.enableDarkThemeSettingKey))) {
// getActivity().recreate();
// }
// }
// }
//
// Path: app/src/main/java/com/hexforhn/hex/util/ThemeHelper.java
// public class ThemeHelper {
// public static void applyTheme(Activity activity) {
// if (shouldSetTheme(activity)) {
// activity.setTheme(getDesiredTheme(activity));
// }
// }
//
// public static void updateTheme(Activity activity) {
// if (shouldSetTheme(activity)) {
// activity.recreate();
// }
// }
//
// private static boolean shouldSetTheme(Activity activity) {
// return getCurrentTheme(activity) != getDesiredTheme(activity);
// }
//
// private static int getDesiredTheme(Activity activity) {
// SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(activity);
// boolean useDarkTheme = sharedPref.getBoolean(activity.getString(R.string.enableDarkThemeSettingKey), false);
//
// return useDarkTheme ? R.style.AppThemeDark : R.style.AppThemeLight;
// }
//
// private static int getCurrentTheme(Activity activity) {
// TypedValue outValue = new TypedValue();
// activity.getTheme().resolveAttribute(R.attr.themeName, outValue, true);
//
// return outValue.string.toString().equals("AppThemeDark") ? R.style.AppThemeDark : R.style.AppThemeLight;
// }
// }
// Path: app/src/main/java/com/hexforhn/hex/activity/SettingsActivity.java
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import com.hexforhn.hex.R;
import com.hexforhn.hex.fragment.SettingsFragment;
import com.hexforhn.hex.util.ThemeHelper;
package com.hexforhn.hex.activity;
public class SettingsActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ThemeHelper.applyTheme(this);
setContentView(R.layout.activity_settings);
setupToolbar();
getFragmentManager().beginTransaction() | .replace(R.id.settingsContent, new SettingsFragment()) |
longdivision/hex | app/src/main/java/com/hexforhn/hex/net/hexapi/StoryService.java | // Path: app/src/main/java/com/hexforhn/hex/model/Story.java
// public class Story implements Item {
//
// private final String mId;
// private final String mTitle;
// private final String mUrl;
// private final String mCommentsUrl;
// private final String mUser;
// private final String mDomain;
// private final int mScore;
// private final int mCommentCount;
// private final Date mDate;
// private final List<Comment> mComments;
//
// public Story(String id, String title, String url, String commentsUrl, String user, String domain,
// int score, int commentCount, Date date) {
// this.mId = id;
// this.mTitle = title;
// this.mUrl = url;
// this.mCommentsUrl = commentsUrl;
// this.mUser = user;
// this.mDomain = domain;
// this.mScore = score;
// this.mCommentCount = commentCount;
// this.mDate = date;
// this.mComments = new ArrayList<>();
// }
//
// public Story(String id, String title, String url, String commentsUrl, String user, String domain,
// int score, int commentCount, Date date, List<Comment> comments) {
// this.mId = id;
// this.mTitle = title;
// this.mUrl = url;
// this.mCommentsUrl = commentsUrl;
// this.mUser = user;
// this.mDomain = domain;
// this.mScore = score;
// this.mCommentCount = commentCount;
// this.mDate = date;
// this.mComments = comments;
// }
//
// public String getId() {
// return this.mId;
// }
//
// public String getTitle() {
// return this.mTitle;
// }
//
// public String getUrl() {
// return this.mUrl;
// }
//
// public String getCommentsUrl() {
// return this.mCommentsUrl;
// }
//
// public String getUser() {
// return this.mUser;
// }
//
// public String getDomain() {
// return this.mDomain;
// }
//
// public int getScore() {
// return this.mScore;
// }
//
// public int getCommentCount() {
// return this.mCommentCount;
// }
//
// public Date getDate() {
// return this.mDate;
// }
//
// public List<Comment> getComments() {
// return this.mComments;
// }
// }
//
// Path: app/src/main/java/com/hexforhn/hex/net/hexapi/marshall/StoryMarshaller.java
// public class StoryMarshaller {
//
// public static Story marshall(JSONObject rawStory) {
// try {
// String id = rawStory.getString("id");
// String title = rawStory.getString("title");
// String url = rawStory.getString("url");
// String commentsUrl = rawStory.getString("commentsUrl");
// String author = rawStory.getString("author");
// String domain = rawStory.getString("domain");
// int score = rawStory.getInt("score");
// int commentCount = rawStory.getInt("commentCount");
// Date date = new DateTime(rawStory.getString("time")).toDate();
//
// JSONArray rawComments = rawStory.has("comments") ? rawStory.getJSONArray("comments") : null;
// List<Comment> comments = new ArrayList<>();
// if (rawComments != null) {
// comments = marshallComments(rawComments);
// }
//
// return new Story(id, title, url, commentsUrl, author, domain, score, commentCount, date, comments);
// } catch (Exception e) {
// e.printStackTrace();
// return null;
// }
// }
//
// private static List<Comment> marshallComments(JSONArray rawComments) {
// List<Comment> comments = new ArrayList<>();
//
// for (int i = 0; i < rawComments.length(); i++) {
// try {
// JSONObject rawComment = rawComments.getJSONObject(i);
// List<Comment> childComments = new ArrayList<>();
// JSONArray rawChildComments = rawComment.getJSONArray("comments");
//
// if (rawChildComments != null) {
// childComments = marshallComments(rawComment.getJSONArray("comments"));
// }
//
// String text = rawComment.getString("text");
// String author = rawComment.getString("author");
// int commentCount = rawComment.getInt("commentCount");
// Date date = new DateTime(rawComment.getString("time")).toDate();
// comments.add(new Comment(text, author, childComments, commentCount, date));
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
//
// return comments;
// }
// }
//
// Path: app/src/main/java/com/hexforhn/hex/net/hexapi/util/RetryPolicyFactory.java
// public class RetryPolicyFactory {
// private static final int SOCKET_TIMEOUT_MS = 2500;
// private static final int MAX_RETRIES = 3;
// private static final int BACKOFF_MULTIPLIER = 2;
//
// public static RetryPolicy build() {
// return new DefaultRetryPolicy(SOCKET_TIMEOUT_MS, MAX_RETRIES, BACKOFF_MULTIPLIER);
// }
// }
| import com.android.volley.RequestQueue;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.RequestFuture;
import com.hexforhn.hex.model.Story;
import com.hexforhn.hex.net.hexapi.marshall.StoryMarshaller;
import com.hexforhn.hex.net.hexapi.util.RetryPolicyFactory;
import org.json.JSONObject; | package com.hexforhn.hex.net.hexapi;
public class StoryService {
private final RequestQueue mRequestQueue;
private final String mApiBaseUrl;
public StoryService(RequestQueue requestQueue, String apiUrl) {
this.mRequestQueue = requestQueue;
mApiBaseUrl = apiUrl;
}
| // Path: app/src/main/java/com/hexforhn/hex/model/Story.java
// public class Story implements Item {
//
// private final String mId;
// private final String mTitle;
// private final String mUrl;
// private final String mCommentsUrl;
// private final String mUser;
// private final String mDomain;
// private final int mScore;
// private final int mCommentCount;
// private final Date mDate;
// private final List<Comment> mComments;
//
// public Story(String id, String title, String url, String commentsUrl, String user, String domain,
// int score, int commentCount, Date date) {
// this.mId = id;
// this.mTitle = title;
// this.mUrl = url;
// this.mCommentsUrl = commentsUrl;
// this.mUser = user;
// this.mDomain = domain;
// this.mScore = score;
// this.mCommentCount = commentCount;
// this.mDate = date;
// this.mComments = new ArrayList<>();
// }
//
// public Story(String id, String title, String url, String commentsUrl, String user, String domain,
// int score, int commentCount, Date date, List<Comment> comments) {
// this.mId = id;
// this.mTitle = title;
// this.mUrl = url;
// this.mCommentsUrl = commentsUrl;
// this.mUser = user;
// this.mDomain = domain;
// this.mScore = score;
// this.mCommentCount = commentCount;
// this.mDate = date;
// this.mComments = comments;
// }
//
// public String getId() {
// return this.mId;
// }
//
// public String getTitle() {
// return this.mTitle;
// }
//
// public String getUrl() {
// return this.mUrl;
// }
//
// public String getCommentsUrl() {
// return this.mCommentsUrl;
// }
//
// public String getUser() {
// return this.mUser;
// }
//
// public String getDomain() {
// return this.mDomain;
// }
//
// public int getScore() {
// return this.mScore;
// }
//
// public int getCommentCount() {
// return this.mCommentCount;
// }
//
// public Date getDate() {
// return this.mDate;
// }
//
// public List<Comment> getComments() {
// return this.mComments;
// }
// }
//
// Path: app/src/main/java/com/hexforhn/hex/net/hexapi/marshall/StoryMarshaller.java
// public class StoryMarshaller {
//
// public static Story marshall(JSONObject rawStory) {
// try {
// String id = rawStory.getString("id");
// String title = rawStory.getString("title");
// String url = rawStory.getString("url");
// String commentsUrl = rawStory.getString("commentsUrl");
// String author = rawStory.getString("author");
// String domain = rawStory.getString("domain");
// int score = rawStory.getInt("score");
// int commentCount = rawStory.getInt("commentCount");
// Date date = new DateTime(rawStory.getString("time")).toDate();
//
// JSONArray rawComments = rawStory.has("comments") ? rawStory.getJSONArray("comments") : null;
// List<Comment> comments = new ArrayList<>();
// if (rawComments != null) {
// comments = marshallComments(rawComments);
// }
//
// return new Story(id, title, url, commentsUrl, author, domain, score, commentCount, date, comments);
// } catch (Exception e) {
// e.printStackTrace();
// return null;
// }
// }
//
// private static List<Comment> marshallComments(JSONArray rawComments) {
// List<Comment> comments = new ArrayList<>();
//
// for (int i = 0; i < rawComments.length(); i++) {
// try {
// JSONObject rawComment = rawComments.getJSONObject(i);
// List<Comment> childComments = new ArrayList<>();
// JSONArray rawChildComments = rawComment.getJSONArray("comments");
//
// if (rawChildComments != null) {
// childComments = marshallComments(rawComment.getJSONArray("comments"));
// }
//
// String text = rawComment.getString("text");
// String author = rawComment.getString("author");
// int commentCount = rawComment.getInt("commentCount");
// Date date = new DateTime(rawComment.getString("time")).toDate();
// comments.add(new Comment(text, author, childComments, commentCount, date));
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
//
// return comments;
// }
// }
//
// Path: app/src/main/java/com/hexforhn/hex/net/hexapi/util/RetryPolicyFactory.java
// public class RetryPolicyFactory {
// private static final int SOCKET_TIMEOUT_MS = 2500;
// private static final int MAX_RETRIES = 3;
// private static final int BACKOFF_MULTIPLIER = 2;
//
// public static RetryPolicy build() {
// return new DefaultRetryPolicy(SOCKET_TIMEOUT_MS, MAX_RETRIES, BACKOFF_MULTIPLIER);
// }
// }
// Path: app/src/main/java/com/hexforhn/hex/net/hexapi/StoryService.java
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.RequestFuture;
import com.hexforhn.hex.model.Story;
import com.hexforhn.hex.net.hexapi.marshall.StoryMarshaller;
import com.hexforhn.hex.net.hexapi.util.RetryPolicyFactory;
import org.json.JSONObject;
package com.hexforhn.hex.net.hexapi;
public class StoryService {
private final RequestQueue mRequestQueue;
private final String mApiBaseUrl;
public StoryService(RequestQueue requestQueue, String apiUrl) {
this.mRequestQueue = requestQueue;
mApiBaseUrl = apiUrl;
}
| public Story getStory(String storyId) { |
longdivision/hex | app/src/main/java/com/hexforhn/hex/net/hexapi/StoryService.java | // Path: app/src/main/java/com/hexforhn/hex/model/Story.java
// public class Story implements Item {
//
// private final String mId;
// private final String mTitle;
// private final String mUrl;
// private final String mCommentsUrl;
// private final String mUser;
// private final String mDomain;
// private final int mScore;
// private final int mCommentCount;
// private final Date mDate;
// private final List<Comment> mComments;
//
// public Story(String id, String title, String url, String commentsUrl, String user, String domain,
// int score, int commentCount, Date date) {
// this.mId = id;
// this.mTitle = title;
// this.mUrl = url;
// this.mCommentsUrl = commentsUrl;
// this.mUser = user;
// this.mDomain = domain;
// this.mScore = score;
// this.mCommentCount = commentCount;
// this.mDate = date;
// this.mComments = new ArrayList<>();
// }
//
// public Story(String id, String title, String url, String commentsUrl, String user, String domain,
// int score, int commentCount, Date date, List<Comment> comments) {
// this.mId = id;
// this.mTitle = title;
// this.mUrl = url;
// this.mCommentsUrl = commentsUrl;
// this.mUser = user;
// this.mDomain = domain;
// this.mScore = score;
// this.mCommentCount = commentCount;
// this.mDate = date;
// this.mComments = comments;
// }
//
// public String getId() {
// return this.mId;
// }
//
// public String getTitle() {
// return this.mTitle;
// }
//
// public String getUrl() {
// return this.mUrl;
// }
//
// public String getCommentsUrl() {
// return this.mCommentsUrl;
// }
//
// public String getUser() {
// return this.mUser;
// }
//
// public String getDomain() {
// return this.mDomain;
// }
//
// public int getScore() {
// return this.mScore;
// }
//
// public int getCommentCount() {
// return this.mCommentCount;
// }
//
// public Date getDate() {
// return this.mDate;
// }
//
// public List<Comment> getComments() {
// return this.mComments;
// }
// }
//
// Path: app/src/main/java/com/hexforhn/hex/net/hexapi/marshall/StoryMarshaller.java
// public class StoryMarshaller {
//
// public static Story marshall(JSONObject rawStory) {
// try {
// String id = rawStory.getString("id");
// String title = rawStory.getString("title");
// String url = rawStory.getString("url");
// String commentsUrl = rawStory.getString("commentsUrl");
// String author = rawStory.getString("author");
// String domain = rawStory.getString("domain");
// int score = rawStory.getInt("score");
// int commentCount = rawStory.getInt("commentCount");
// Date date = new DateTime(rawStory.getString("time")).toDate();
//
// JSONArray rawComments = rawStory.has("comments") ? rawStory.getJSONArray("comments") : null;
// List<Comment> comments = new ArrayList<>();
// if (rawComments != null) {
// comments = marshallComments(rawComments);
// }
//
// return new Story(id, title, url, commentsUrl, author, domain, score, commentCount, date, comments);
// } catch (Exception e) {
// e.printStackTrace();
// return null;
// }
// }
//
// private static List<Comment> marshallComments(JSONArray rawComments) {
// List<Comment> comments = new ArrayList<>();
//
// for (int i = 0; i < rawComments.length(); i++) {
// try {
// JSONObject rawComment = rawComments.getJSONObject(i);
// List<Comment> childComments = new ArrayList<>();
// JSONArray rawChildComments = rawComment.getJSONArray("comments");
//
// if (rawChildComments != null) {
// childComments = marshallComments(rawComment.getJSONArray("comments"));
// }
//
// String text = rawComment.getString("text");
// String author = rawComment.getString("author");
// int commentCount = rawComment.getInt("commentCount");
// Date date = new DateTime(rawComment.getString("time")).toDate();
// comments.add(new Comment(text, author, childComments, commentCount, date));
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
//
// return comments;
// }
// }
//
// Path: app/src/main/java/com/hexforhn/hex/net/hexapi/util/RetryPolicyFactory.java
// public class RetryPolicyFactory {
// private static final int SOCKET_TIMEOUT_MS = 2500;
// private static final int MAX_RETRIES = 3;
// private static final int BACKOFF_MULTIPLIER = 2;
//
// public static RetryPolicy build() {
// return new DefaultRetryPolicy(SOCKET_TIMEOUT_MS, MAX_RETRIES, BACKOFF_MULTIPLIER);
// }
// }
| import com.android.volley.RequestQueue;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.RequestFuture;
import com.hexforhn.hex.model.Story;
import com.hexforhn.hex.net.hexapi.marshall.StoryMarshaller;
import com.hexforhn.hex.net.hexapi.util.RetryPolicyFactory;
import org.json.JSONObject; | package com.hexforhn.hex.net.hexapi;
public class StoryService {
private final RequestQueue mRequestQueue;
private final String mApiBaseUrl;
public StoryService(RequestQueue requestQueue, String apiUrl) {
this.mRequestQueue = requestQueue;
mApiBaseUrl = apiUrl;
}
public Story getStory(String storyId) {
String STORY_PATH = "/story";
String storyPath = mApiBaseUrl + STORY_PATH + "/" + storyId;
RequestFuture<JSONObject> future = RequestFuture.newFuture();
JsonObjectRequest request = new JsonObjectRequest(storyPath, future, future); | // Path: app/src/main/java/com/hexforhn/hex/model/Story.java
// public class Story implements Item {
//
// private final String mId;
// private final String mTitle;
// private final String mUrl;
// private final String mCommentsUrl;
// private final String mUser;
// private final String mDomain;
// private final int mScore;
// private final int mCommentCount;
// private final Date mDate;
// private final List<Comment> mComments;
//
// public Story(String id, String title, String url, String commentsUrl, String user, String domain,
// int score, int commentCount, Date date) {
// this.mId = id;
// this.mTitle = title;
// this.mUrl = url;
// this.mCommentsUrl = commentsUrl;
// this.mUser = user;
// this.mDomain = domain;
// this.mScore = score;
// this.mCommentCount = commentCount;
// this.mDate = date;
// this.mComments = new ArrayList<>();
// }
//
// public Story(String id, String title, String url, String commentsUrl, String user, String domain,
// int score, int commentCount, Date date, List<Comment> comments) {
// this.mId = id;
// this.mTitle = title;
// this.mUrl = url;
// this.mCommentsUrl = commentsUrl;
// this.mUser = user;
// this.mDomain = domain;
// this.mScore = score;
// this.mCommentCount = commentCount;
// this.mDate = date;
// this.mComments = comments;
// }
//
// public String getId() {
// return this.mId;
// }
//
// public String getTitle() {
// return this.mTitle;
// }
//
// public String getUrl() {
// return this.mUrl;
// }
//
// public String getCommentsUrl() {
// return this.mCommentsUrl;
// }
//
// public String getUser() {
// return this.mUser;
// }
//
// public String getDomain() {
// return this.mDomain;
// }
//
// public int getScore() {
// return this.mScore;
// }
//
// public int getCommentCount() {
// return this.mCommentCount;
// }
//
// public Date getDate() {
// return this.mDate;
// }
//
// public List<Comment> getComments() {
// return this.mComments;
// }
// }
//
// Path: app/src/main/java/com/hexforhn/hex/net/hexapi/marshall/StoryMarshaller.java
// public class StoryMarshaller {
//
// public static Story marshall(JSONObject rawStory) {
// try {
// String id = rawStory.getString("id");
// String title = rawStory.getString("title");
// String url = rawStory.getString("url");
// String commentsUrl = rawStory.getString("commentsUrl");
// String author = rawStory.getString("author");
// String domain = rawStory.getString("domain");
// int score = rawStory.getInt("score");
// int commentCount = rawStory.getInt("commentCount");
// Date date = new DateTime(rawStory.getString("time")).toDate();
//
// JSONArray rawComments = rawStory.has("comments") ? rawStory.getJSONArray("comments") : null;
// List<Comment> comments = new ArrayList<>();
// if (rawComments != null) {
// comments = marshallComments(rawComments);
// }
//
// return new Story(id, title, url, commentsUrl, author, domain, score, commentCount, date, comments);
// } catch (Exception e) {
// e.printStackTrace();
// return null;
// }
// }
//
// private static List<Comment> marshallComments(JSONArray rawComments) {
// List<Comment> comments = new ArrayList<>();
//
// for (int i = 0; i < rawComments.length(); i++) {
// try {
// JSONObject rawComment = rawComments.getJSONObject(i);
// List<Comment> childComments = new ArrayList<>();
// JSONArray rawChildComments = rawComment.getJSONArray("comments");
//
// if (rawChildComments != null) {
// childComments = marshallComments(rawComment.getJSONArray("comments"));
// }
//
// String text = rawComment.getString("text");
// String author = rawComment.getString("author");
// int commentCount = rawComment.getInt("commentCount");
// Date date = new DateTime(rawComment.getString("time")).toDate();
// comments.add(new Comment(text, author, childComments, commentCount, date));
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
//
// return comments;
// }
// }
//
// Path: app/src/main/java/com/hexforhn/hex/net/hexapi/util/RetryPolicyFactory.java
// public class RetryPolicyFactory {
// private static final int SOCKET_TIMEOUT_MS = 2500;
// private static final int MAX_RETRIES = 3;
// private static final int BACKOFF_MULTIPLIER = 2;
//
// public static RetryPolicy build() {
// return new DefaultRetryPolicy(SOCKET_TIMEOUT_MS, MAX_RETRIES, BACKOFF_MULTIPLIER);
// }
// }
// Path: app/src/main/java/com/hexforhn/hex/net/hexapi/StoryService.java
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.RequestFuture;
import com.hexforhn.hex.model.Story;
import com.hexforhn.hex.net.hexapi.marshall.StoryMarshaller;
import com.hexforhn.hex.net.hexapi.util.RetryPolicyFactory;
import org.json.JSONObject;
package com.hexforhn.hex.net.hexapi;
public class StoryService {
private final RequestQueue mRequestQueue;
private final String mApiBaseUrl;
public StoryService(RequestQueue requestQueue, String apiUrl) {
this.mRequestQueue = requestQueue;
mApiBaseUrl = apiUrl;
}
public Story getStory(String storyId) {
String STORY_PATH = "/story";
String storyPath = mApiBaseUrl + STORY_PATH + "/" + storyId;
RequestFuture<JSONObject> future = RequestFuture.newFuture();
JsonObjectRequest request = new JsonObjectRequest(storyPath, future, future); | request.setRetryPolicy(RetryPolicyFactory.build()); |
longdivision/hex | app/src/main/java/com/hexforhn/hex/net/hexapi/StoryService.java | // Path: app/src/main/java/com/hexforhn/hex/model/Story.java
// public class Story implements Item {
//
// private final String mId;
// private final String mTitle;
// private final String mUrl;
// private final String mCommentsUrl;
// private final String mUser;
// private final String mDomain;
// private final int mScore;
// private final int mCommentCount;
// private final Date mDate;
// private final List<Comment> mComments;
//
// public Story(String id, String title, String url, String commentsUrl, String user, String domain,
// int score, int commentCount, Date date) {
// this.mId = id;
// this.mTitle = title;
// this.mUrl = url;
// this.mCommentsUrl = commentsUrl;
// this.mUser = user;
// this.mDomain = domain;
// this.mScore = score;
// this.mCommentCount = commentCount;
// this.mDate = date;
// this.mComments = new ArrayList<>();
// }
//
// public Story(String id, String title, String url, String commentsUrl, String user, String domain,
// int score, int commentCount, Date date, List<Comment> comments) {
// this.mId = id;
// this.mTitle = title;
// this.mUrl = url;
// this.mCommentsUrl = commentsUrl;
// this.mUser = user;
// this.mDomain = domain;
// this.mScore = score;
// this.mCommentCount = commentCount;
// this.mDate = date;
// this.mComments = comments;
// }
//
// public String getId() {
// return this.mId;
// }
//
// public String getTitle() {
// return this.mTitle;
// }
//
// public String getUrl() {
// return this.mUrl;
// }
//
// public String getCommentsUrl() {
// return this.mCommentsUrl;
// }
//
// public String getUser() {
// return this.mUser;
// }
//
// public String getDomain() {
// return this.mDomain;
// }
//
// public int getScore() {
// return this.mScore;
// }
//
// public int getCommentCount() {
// return this.mCommentCount;
// }
//
// public Date getDate() {
// return this.mDate;
// }
//
// public List<Comment> getComments() {
// return this.mComments;
// }
// }
//
// Path: app/src/main/java/com/hexforhn/hex/net/hexapi/marshall/StoryMarshaller.java
// public class StoryMarshaller {
//
// public static Story marshall(JSONObject rawStory) {
// try {
// String id = rawStory.getString("id");
// String title = rawStory.getString("title");
// String url = rawStory.getString("url");
// String commentsUrl = rawStory.getString("commentsUrl");
// String author = rawStory.getString("author");
// String domain = rawStory.getString("domain");
// int score = rawStory.getInt("score");
// int commentCount = rawStory.getInt("commentCount");
// Date date = new DateTime(rawStory.getString("time")).toDate();
//
// JSONArray rawComments = rawStory.has("comments") ? rawStory.getJSONArray("comments") : null;
// List<Comment> comments = new ArrayList<>();
// if (rawComments != null) {
// comments = marshallComments(rawComments);
// }
//
// return new Story(id, title, url, commentsUrl, author, domain, score, commentCount, date, comments);
// } catch (Exception e) {
// e.printStackTrace();
// return null;
// }
// }
//
// private static List<Comment> marshallComments(JSONArray rawComments) {
// List<Comment> comments = new ArrayList<>();
//
// for (int i = 0; i < rawComments.length(); i++) {
// try {
// JSONObject rawComment = rawComments.getJSONObject(i);
// List<Comment> childComments = new ArrayList<>();
// JSONArray rawChildComments = rawComment.getJSONArray("comments");
//
// if (rawChildComments != null) {
// childComments = marshallComments(rawComment.getJSONArray("comments"));
// }
//
// String text = rawComment.getString("text");
// String author = rawComment.getString("author");
// int commentCount = rawComment.getInt("commentCount");
// Date date = new DateTime(rawComment.getString("time")).toDate();
// comments.add(new Comment(text, author, childComments, commentCount, date));
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
//
// return comments;
// }
// }
//
// Path: app/src/main/java/com/hexforhn/hex/net/hexapi/util/RetryPolicyFactory.java
// public class RetryPolicyFactory {
// private static final int SOCKET_TIMEOUT_MS = 2500;
// private static final int MAX_RETRIES = 3;
// private static final int BACKOFF_MULTIPLIER = 2;
//
// public static RetryPolicy build() {
// return new DefaultRetryPolicy(SOCKET_TIMEOUT_MS, MAX_RETRIES, BACKOFF_MULTIPLIER);
// }
// }
| import com.android.volley.RequestQueue;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.RequestFuture;
import com.hexforhn.hex.model.Story;
import com.hexforhn.hex.net.hexapi.marshall.StoryMarshaller;
import com.hexforhn.hex.net.hexapi.util.RetryPolicyFactory;
import org.json.JSONObject; | package com.hexforhn.hex.net.hexapi;
public class StoryService {
private final RequestQueue mRequestQueue;
private final String mApiBaseUrl;
public StoryService(RequestQueue requestQueue, String apiUrl) {
this.mRequestQueue = requestQueue;
mApiBaseUrl = apiUrl;
}
public Story getStory(String storyId) {
String STORY_PATH = "/story";
String storyPath = mApiBaseUrl + STORY_PATH + "/" + storyId;
RequestFuture<JSONObject> future = RequestFuture.newFuture();
JsonObjectRequest request = new JsonObjectRequest(storyPath, future, future);
request.setRetryPolicy(RetryPolicyFactory.build());
mRequestQueue.add(request);
try {
JSONObject response = future.get(); | // Path: app/src/main/java/com/hexforhn/hex/model/Story.java
// public class Story implements Item {
//
// private final String mId;
// private final String mTitle;
// private final String mUrl;
// private final String mCommentsUrl;
// private final String mUser;
// private final String mDomain;
// private final int mScore;
// private final int mCommentCount;
// private final Date mDate;
// private final List<Comment> mComments;
//
// public Story(String id, String title, String url, String commentsUrl, String user, String domain,
// int score, int commentCount, Date date) {
// this.mId = id;
// this.mTitle = title;
// this.mUrl = url;
// this.mCommentsUrl = commentsUrl;
// this.mUser = user;
// this.mDomain = domain;
// this.mScore = score;
// this.mCommentCount = commentCount;
// this.mDate = date;
// this.mComments = new ArrayList<>();
// }
//
// public Story(String id, String title, String url, String commentsUrl, String user, String domain,
// int score, int commentCount, Date date, List<Comment> comments) {
// this.mId = id;
// this.mTitle = title;
// this.mUrl = url;
// this.mCommentsUrl = commentsUrl;
// this.mUser = user;
// this.mDomain = domain;
// this.mScore = score;
// this.mCommentCount = commentCount;
// this.mDate = date;
// this.mComments = comments;
// }
//
// public String getId() {
// return this.mId;
// }
//
// public String getTitle() {
// return this.mTitle;
// }
//
// public String getUrl() {
// return this.mUrl;
// }
//
// public String getCommentsUrl() {
// return this.mCommentsUrl;
// }
//
// public String getUser() {
// return this.mUser;
// }
//
// public String getDomain() {
// return this.mDomain;
// }
//
// public int getScore() {
// return this.mScore;
// }
//
// public int getCommentCount() {
// return this.mCommentCount;
// }
//
// public Date getDate() {
// return this.mDate;
// }
//
// public List<Comment> getComments() {
// return this.mComments;
// }
// }
//
// Path: app/src/main/java/com/hexforhn/hex/net/hexapi/marshall/StoryMarshaller.java
// public class StoryMarshaller {
//
// public static Story marshall(JSONObject rawStory) {
// try {
// String id = rawStory.getString("id");
// String title = rawStory.getString("title");
// String url = rawStory.getString("url");
// String commentsUrl = rawStory.getString("commentsUrl");
// String author = rawStory.getString("author");
// String domain = rawStory.getString("domain");
// int score = rawStory.getInt("score");
// int commentCount = rawStory.getInt("commentCount");
// Date date = new DateTime(rawStory.getString("time")).toDate();
//
// JSONArray rawComments = rawStory.has("comments") ? rawStory.getJSONArray("comments") : null;
// List<Comment> comments = new ArrayList<>();
// if (rawComments != null) {
// comments = marshallComments(rawComments);
// }
//
// return new Story(id, title, url, commentsUrl, author, domain, score, commentCount, date, comments);
// } catch (Exception e) {
// e.printStackTrace();
// return null;
// }
// }
//
// private static List<Comment> marshallComments(JSONArray rawComments) {
// List<Comment> comments = new ArrayList<>();
//
// for (int i = 0; i < rawComments.length(); i++) {
// try {
// JSONObject rawComment = rawComments.getJSONObject(i);
// List<Comment> childComments = new ArrayList<>();
// JSONArray rawChildComments = rawComment.getJSONArray("comments");
//
// if (rawChildComments != null) {
// childComments = marshallComments(rawComment.getJSONArray("comments"));
// }
//
// String text = rawComment.getString("text");
// String author = rawComment.getString("author");
// int commentCount = rawComment.getInt("commentCount");
// Date date = new DateTime(rawComment.getString("time")).toDate();
// comments.add(new Comment(text, author, childComments, commentCount, date));
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
//
// return comments;
// }
// }
//
// Path: app/src/main/java/com/hexforhn/hex/net/hexapi/util/RetryPolicyFactory.java
// public class RetryPolicyFactory {
// private static final int SOCKET_TIMEOUT_MS = 2500;
// private static final int MAX_RETRIES = 3;
// private static final int BACKOFF_MULTIPLIER = 2;
//
// public static RetryPolicy build() {
// return new DefaultRetryPolicy(SOCKET_TIMEOUT_MS, MAX_RETRIES, BACKOFF_MULTIPLIER);
// }
// }
// Path: app/src/main/java/com/hexforhn/hex/net/hexapi/StoryService.java
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.RequestFuture;
import com.hexforhn.hex.model.Story;
import com.hexforhn.hex.net.hexapi.marshall.StoryMarshaller;
import com.hexforhn.hex.net.hexapi.util.RetryPolicyFactory;
import org.json.JSONObject;
package com.hexforhn.hex.net.hexapi;
public class StoryService {
private final RequestQueue mRequestQueue;
private final String mApiBaseUrl;
public StoryService(RequestQueue requestQueue, String apiUrl) {
this.mRequestQueue = requestQueue;
mApiBaseUrl = apiUrl;
}
public Story getStory(String storyId) {
String STORY_PATH = "/story";
String storyPath = mApiBaseUrl + STORY_PATH + "/" + storyId;
RequestFuture<JSONObject> future = RequestFuture.newFuture();
JsonObjectRequest request = new JsonObjectRequest(storyPath, future, future);
request.setRetryPolicy(RetryPolicyFactory.build());
mRequestQueue.add(request);
try {
JSONObject response = future.get(); | return StoryMarshaller.marshall(response); |
longdivision/hex | app/src/main/java/com/hexforhn/hex/net/hexapi/marshall/StoryMarshaller.java | // Path: app/src/main/java/com/hexforhn/hex/model/Comment.java
// public class Comment {
//
// private final int mCommentCount;
// private final String mText;
// private final String mUser;
// private final List<Comment> mChildComments;
// private final Date mDate;
//
// public Comment(String text, String user, List<Comment> childComments, int commentCount,
// Date date) {
// this.mText = text;
// this.mUser = user;
// this.mChildComments = childComments;
// this.mCommentCount = commentCount;
// this.mDate = date;
// }
//
// public String getText(){
// return this.mText;
// }
//
// public String getUser() {
// return this.mUser;
// }
//
// public List<Comment> getChildComments() {
// return this.mChildComments;
// }
//
// public int getCommentCount() {
// return mCommentCount;
// }
//
// public Date getDate() {
// return this.mDate;
// }
// }
//
// Path: app/src/main/java/com/hexforhn/hex/model/Story.java
// public class Story implements Item {
//
// private final String mId;
// private final String mTitle;
// private final String mUrl;
// private final String mCommentsUrl;
// private final String mUser;
// private final String mDomain;
// private final int mScore;
// private final int mCommentCount;
// private final Date mDate;
// private final List<Comment> mComments;
//
// public Story(String id, String title, String url, String commentsUrl, String user, String domain,
// int score, int commentCount, Date date) {
// this.mId = id;
// this.mTitle = title;
// this.mUrl = url;
// this.mCommentsUrl = commentsUrl;
// this.mUser = user;
// this.mDomain = domain;
// this.mScore = score;
// this.mCommentCount = commentCount;
// this.mDate = date;
// this.mComments = new ArrayList<>();
// }
//
// public Story(String id, String title, String url, String commentsUrl, String user, String domain,
// int score, int commentCount, Date date, List<Comment> comments) {
// this.mId = id;
// this.mTitle = title;
// this.mUrl = url;
// this.mCommentsUrl = commentsUrl;
// this.mUser = user;
// this.mDomain = domain;
// this.mScore = score;
// this.mCommentCount = commentCount;
// this.mDate = date;
// this.mComments = comments;
// }
//
// public String getId() {
// return this.mId;
// }
//
// public String getTitle() {
// return this.mTitle;
// }
//
// public String getUrl() {
// return this.mUrl;
// }
//
// public String getCommentsUrl() {
// return this.mCommentsUrl;
// }
//
// public String getUser() {
// return this.mUser;
// }
//
// public String getDomain() {
// return this.mDomain;
// }
//
// public int getScore() {
// return this.mScore;
// }
//
// public int getCommentCount() {
// return this.mCommentCount;
// }
//
// public Date getDate() {
// return this.mDate;
// }
//
// public List<Comment> getComments() {
// return this.mComments;
// }
// }
| import com.hexforhn.hex.model.Comment;
import com.hexforhn.hex.model.Story;
import org.joda.time.DateTime;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Date;
import java.util.List; | package com.hexforhn.hex.net.hexapi.marshall;
public class StoryMarshaller {
public static Story marshall(JSONObject rawStory) {
try {
String id = rawStory.getString("id");
String title = rawStory.getString("title");
String url = rawStory.getString("url");
String commentsUrl = rawStory.getString("commentsUrl");
String author = rawStory.getString("author");
String domain = rawStory.getString("domain");
int score = rawStory.getInt("score");
int commentCount = rawStory.getInt("commentCount");
Date date = new DateTime(rawStory.getString("time")).toDate();
JSONArray rawComments = rawStory.has("comments") ? rawStory.getJSONArray("comments") : null; | // Path: app/src/main/java/com/hexforhn/hex/model/Comment.java
// public class Comment {
//
// private final int mCommentCount;
// private final String mText;
// private final String mUser;
// private final List<Comment> mChildComments;
// private final Date mDate;
//
// public Comment(String text, String user, List<Comment> childComments, int commentCount,
// Date date) {
// this.mText = text;
// this.mUser = user;
// this.mChildComments = childComments;
// this.mCommentCount = commentCount;
// this.mDate = date;
// }
//
// public String getText(){
// return this.mText;
// }
//
// public String getUser() {
// return this.mUser;
// }
//
// public List<Comment> getChildComments() {
// return this.mChildComments;
// }
//
// public int getCommentCount() {
// return mCommentCount;
// }
//
// public Date getDate() {
// return this.mDate;
// }
// }
//
// Path: app/src/main/java/com/hexforhn/hex/model/Story.java
// public class Story implements Item {
//
// private final String mId;
// private final String mTitle;
// private final String mUrl;
// private final String mCommentsUrl;
// private final String mUser;
// private final String mDomain;
// private final int mScore;
// private final int mCommentCount;
// private final Date mDate;
// private final List<Comment> mComments;
//
// public Story(String id, String title, String url, String commentsUrl, String user, String domain,
// int score, int commentCount, Date date) {
// this.mId = id;
// this.mTitle = title;
// this.mUrl = url;
// this.mCommentsUrl = commentsUrl;
// this.mUser = user;
// this.mDomain = domain;
// this.mScore = score;
// this.mCommentCount = commentCount;
// this.mDate = date;
// this.mComments = new ArrayList<>();
// }
//
// public Story(String id, String title, String url, String commentsUrl, String user, String domain,
// int score, int commentCount, Date date, List<Comment> comments) {
// this.mId = id;
// this.mTitle = title;
// this.mUrl = url;
// this.mCommentsUrl = commentsUrl;
// this.mUser = user;
// this.mDomain = domain;
// this.mScore = score;
// this.mCommentCount = commentCount;
// this.mDate = date;
// this.mComments = comments;
// }
//
// public String getId() {
// return this.mId;
// }
//
// public String getTitle() {
// return this.mTitle;
// }
//
// public String getUrl() {
// return this.mUrl;
// }
//
// public String getCommentsUrl() {
// return this.mCommentsUrl;
// }
//
// public String getUser() {
// return this.mUser;
// }
//
// public String getDomain() {
// return this.mDomain;
// }
//
// public int getScore() {
// return this.mScore;
// }
//
// public int getCommentCount() {
// return this.mCommentCount;
// }
//
// public Date getDate() {
// return this.mDate;
// }
//
// public List<Comment> getComments() {
// return this.mComments;
// }
// }
// Path: app/src/main/java/com/hexforhn/hex/net/hexapi/marshall/StoryMarshaller.java
import com.hexforhn.hex.model.Comment;
import com.hexforhn.hex.model.Story;
import org.joda.time.DateTime;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
package com.hexforhn.hex.net.hexapi.marshall;
public class StoryMarshaller {
public static Story marshall(JSONObject rawStory) {
try {
String id = rawStory.getString("id");
String title = rawStory.getString("title");
String url = rawStory.getString("url");
String commentsUrl = rawStory.getString("commentsUrl");
String author = rawStory.getString("author");
String domain = rawStory.getString("domain");
int score = rawStory.getInt("score");
int commentCount = rawStory.getInt("commentCount");
Date date = new DateTime(rawStory.getString("time")).toDate();
JSONArray rawComments = rawStory.has("comments") ? rawStory.getJSONArray("comments") : null; | List<Comment> comments = new ArrayList<>(); |
longdivision/hex | app/src/main/java/com/hexforhn/hex/adapter/CommentListAdapter.java | // Path: app/src/main/java/com/hexforhn/hex/adapter/helper/CommentListManager.java
// public class CommentListManager {
// private final List<CommentViewModel> mComments;
//
// public CommentListManager(List<CommentViewModel> comments) {
// mComments = comments;
// }
//
// public List<CommentViewModel> getVisibleComments() {
// List<CommentViewModel> comments = new ArrayList<>();
// int commentCount = mComments.size();
//
// for (int i = 0; i < commentCount; i++) {
// CommentViewModel comment = mComments.get(i);
//
// if (comment.isVisible()) {
// comments.add(comment);
// }
// }
//
// return comments;
// }
//
// public void toggleCommentAtPosition(int position) {
// CommentViewModel commentToToggle = getVisibleComments().get(position);
// int commentCount = mComments.size();
//
// commentToToggle.toggleCollapsed();
//
// int toggledCommentDepth = commentToToggle.getDepth();
// boolean collapsedState = commentToToggle.isCollapsed();
//
// position = mComments.indexOf(commentToToggle);
//
// for (int i = position + 1; i < commentCount; i++) {
// CommentViewModel comment = mComments.get(i);
//
// if (comment.getDepth() > toggledCommentDepth) {
// comment.setVisible(!collapsedState);
// comment.setCollapsed(collapsedState);
// } else {
// break;
// }
// }
// }
//
// }
//
// Path: app/src/main/java/com/hexforhn/hex/adapter/helper/TextHelper.java
// public class TextHelper {
//
// public static CharSequence removeTrailingNewlinesFromText(CharSequence text) {
// if (text == null || text.length() < 1) {
// return "";
// }
//
// if (text.charAt(text.length() - 1) == "\n".charAt(0)) {
// return removeTrailingNewlinesFromText(text.subSequence(0, text.length() - 1));
// }
//
// return text;
// }
// }
//
// Path: app/src/main/java/com/hexforhn/hex/listener/ClickListener.java
// public interface ClickListener {
//
// /**
// * Called when the view is clicked.
// *
// * @param v view that is clicked
// * @param position of the clicked item
// * @param isLongClick true if long click, false otherwise
// */
// void onClick(View v, int position, boolean isLongClick);
// }
//
// Path: app/src/main/java/com/hexforhn/hex/viewmodel/CommentViewModel.java
// public class CommentViewModel {
//
// private final int mCommentCount;
// private final String mText;
// private final String mUser;
// private final int mDepth;
// private final Date mDate;
// private Boolean mCollapsed;
// private boolean mVisible;
//
// public CommentViewModel(String user, String text, int depth, int commentCount, Date date) {
// this.mUser = user;
// this.mText = text;
// this.mDepth = depth;
// this.mCommentCount = commentCount;
// this.mDate = date;
// this.mVisible = true;
// this.mCollapsed = false;
// }
//
// public String getText() {
// return this.mText;
// }
//
// public String getUser() {
// return this.mUser;
// }
//
// public int getDepth() {
// return this.mDepth;
// }
//
// public int getCommentCount() {
// return this.mCommentCount;
// }
//
// public String getRelativeTime() {
// return DateUtils.getRelativeTimeSpanString(mDate.getTime(), System.currentTimeMillis(), 0)
// .toString();
// }
//
// public boolean isVisible() {
// return this.mVisible;
// }
//
// public boolean isCollapsed() {
// return this.mCollapsed;
// }
//
// public void setVisible(boolean visible) {
// this.mVisible = visible;
// }
//
// public void toggleCollapsed() {
// this.mCollapsed = !this.mCollapsed;
// }
//
// public void setCollapsed(boolean collapsed) {
// this.mCollapsed = collapsed;
// }
//
// }
| import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.hexforhn.hex.R;
import com.hexforhn.hex.adapter.helper.CommentListManager;
import com.hexforhn.hex.adapter.helper.TextHelper;
import com.hexforhn.hex.listener.ClickListener;
import com.hexforhn.hex.viewmodel.CommentViewModel;
import java.util.List; | package com.hexforhn.hex.adapter;
public class CommentListAdapter extends RecyclerView.Adapter<ViewHolder> implements ClickListener {
private final static int INDENT_SIZE = 5;
private final Context mContext; | // Path: app/src/main/java/com/hexforhn/hex/adapter/helper/CommentListManager.java
// public class CommentListManager {
// private final List<CommentViewModel> mComments;
//
// public CommentListManager(List<CommentViewModel> comments) {
// mComments = comments;
// }
//
// public List<CommentViewModel> getVisibleComments() {
// List<CommentViewModel> comments = new ArrayList<>();
// int commentCount = mComments.size();
//
// for (int i = 0; i < commentCount; i++) {
// CommentViewModel comment = mComments.get(i);
//
// if (comment.isVisible()) {
// comments.add(comment);
// }
// }
//
// return comments;
// }
//
// public void toggleCommentAtPosition(int position) {
// CommentViewModel commentToToggle = getVisibleComments().get(position);
// int commentCount = mComments.size();
//
// commentToToggle.toggleCollapsed();
//
// int toggledCommentDepth = commentToToggle.getDepth();
// boolean collapsedState = commentToToggle.isCollapsed();
//
// position = mComments.indexOf(commentToToggle);
//
// for (int i = position + 1; i < commentCount; i++) {
// CommentViewModel comment = mComments.get(i);
//
// if (comment.getDepth() > toggledCommentDepth) {
// comment.setVisible(!collapsedState);
// comment.setCollapsed(collapsedState);
// } else {
// break;
// }
// }
// }
//
// }
//
// Path: app/src/main/java/com/hexforhn/hex/adapter/helper/TextHelper.java
// public class TextHelper {
//
// public static CharSequence removeTrailingNewlinesFromText(CharSequence text) {
// if (text == null || text.length() < 1) {
// return "";
// }
//
// if (text.charAt(text.length() - 1) == "\n".charAt(0)) {
// return removeTrailingNewlinesFromText(text.subSequence(0, text.length() - 1));
// }
//
// return text;
// }
// }
//
// Path: app/src/main/java/com/hexforhn/hex/listener/ClickListener.java
// public interface ClickListener {
//
// /**
// * Called when the view is clicked.
// *
// * @param v view that is clicked
// * @param position of the clicked item
// * @param isLongClick true if long click, false otherwise
// */
// void onClick(View v, int position, boolean isLongClick);
// }
//
// Path: app/src/main/java/com/hexforhn/hex/viewmodel/CommentViewModel.java
// public class CommentViewModel {
//
// private final int mCommentCount;
// private final String mText;
// private final String mUser;
// private final int mDepth;
// private final Date mDate;
// private Boolean mCollapsed;
// private boolean mVisible;
//
// public CommentViewModel(String user, String text, int depth, int commentCount, Date date) {
// this.mUser = user;
// this.mText = text;
// this.mDepth = depth;
// this.mCommentCount = commentCount;
// this.mDate = date;
// this.mVisible = true;
// this.mCollapsed = false;
// }
//
// public String getText() {
// return this.mText;
// }
//
// public String getUser() {
// return this.mUser;
// }
//
// public int getDepth() {
// return this.mDepth;
// }
//
// public int getCommentCount() {
// return this.mCommentCount;
// }
//
// public String getRelativeTime() {
// return DateUtils.getRelativeTimeSpanString(mDate.getTime(), System.currentTimeMillis(), 0)
// .toString();
// }
//
// public boolean isVisible() {
// return this.mVisible;
// }
//
// public boolean isCollapsed() {
// return this.mCollapsed;
// }
//
// public void setVisible(boolean visible) {
// this.mVisible = visible;
// }
//
// public void toggleCollapsed() {
// this.mCollapsed = !this.mCollapsed;
// }
//
// public void setCollapsed(boolean collapsed) {
// this.mCollapsed = collapsed;
// }
//
// }
// Path: app/src/main/java/com/hexforhn/hex/adapter/CommentListAdapter.java
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.hexforhn.hex.R;
import com.hexforhn.hex.adapter.helper.CommentListManager;
import com.hexforhn.hex.adapter.helper.TextHelper;
import com.hexforhn.hex.listener.ClickListener;
import com.hexforhn.hex.viewmodel.CommentViewModel;
import java.util.List;
package com.hexforhn.hex.adapter;
public class CommentListAdapter extends RecyclerView.Adapter<ViewHolder> implements ClickListener {
private final static int INDENT_SIZE = 5;
private final Context mContext; | private final CommentListManager mCommentListManager; |
longdivision/hex | app/src/main/java/com/hexforhn/hex/adapter/CommentListAdapter.java | // Path: app/src/main/java/com/hexforhn/hex/adapter/helper/CommentListManager.java
// public class CommentListManager {
// private final List<CommentViewModel> mComments;
//
// public CommentListManager(List<CommentViewModel> comments) {
// mComments = comments;
// }
//
// public List<CommentViewModel> getVisibleComments() {
// List<CommentViewModel> comments = new ArrayList<>();
// int commentCount = mComments.size();
//
// for (int i = 0; i < commentCount; i++) {
// CommentViewModel comment = mComments.get(i);
//
// if (comment.isVisible()) {
// comments.add(comment);
// }
// }
//
// return comments;
// }
//
// public void toggleCommentAtPosition(int position) {
// CommentViewModel commentToToggle = getVisibleComments().get(position);
// int commentCount = mComments.size();
//
// commentToToggle.toggleCollapsed();
//
// int toggledCommentDepth = commentToToggle.getDepth();
// boolean collapsedState = commentToToggle.isCollapsed();
//
// position = mComments.indexOf(commentToToggle);
//
// for (int i = position + 1; i < commentCount; i++) {
// CommentViewModel comment = mComments.get(i);
//
// if (comment.getDepth() > toggledCommentDepth) {
// comment.setVisible(!collapsedState);
// comment.setCollapsed(collapsedState);
// } else {
// break;
// }
// }
// }
//
// }
//
// Path: app/src/main/java/com/hexforhn/hex/adapter/helper/TextHelper.java
// public class TextHelper {
//
// public static CharSequence removeTrailingNewlinesFromText(CharSequence text) {
// if (text == null || text.length() < 1) {
// return "";
// }
//
// if (text.charAt(text.length() - 1) == "\n".charAt(0)) {
// return removeTrailingNewlinesFromText(text.subSequence(0, text.length() - 1));
// }
//
// return text;
// }
// }
//
// Path: app/src/main/java/com/hexforhn/hex/listener/ClickListener.java
// public interface ClickListener {
//
// /**
// * Called when the view is clicked.
// *
// * @param v view that is clicked
// * @param position of the clicked item
// * @param isLongClick true if long click, false otherwise
// */
// void onClick(View v, int position, boolean isLongClick);
// }
//
// Path: app/src/main/java/com/hexforhn/hex/viewmodel/CommentViewModel.java
// public class CommentViewModel {
//
// private final int mCommentCount;
// private final String mText;
// private final String mUser;
// private final int mDepth;
// private final Date mDate;
// private Boolean mCollapsed;
// private boolean mVisible;
//
// public CommentViewModel(String user, String text, int depth, int commentCount, Date date) {
// this.mUser = user;
// this.mText = text;
// this.mDepth = depth;
// this.mCommentCount = commentCount;
// this.mDate = date;
// this.mVisible = true;
// this.mCollapsed = false;
// }
//
// public String getText() {
// return this.mText;
// }
//
// public String getUser() {
// return this.mUser;
// }
//
// public int getDepth() {
// return this.mDepth;
// }
//
// public int getCommentCount() {
// return this.mCommentCount;
// }
//
// public String getRelativeTime() {
// return DateUtils.getRelativeTimeSpanString(mDate.getTime(), System.currentTimeMillis(), 0)
// .toString();
// }
//
// public boolean isVisible() {
// return this.mVisible;
// }
//
// public boolean isCollapsed() {
// return this.mCollapsed;
// }
//
// public void setVisible(boolean visible) {
// this.mVisible = visible;
// }
//
// public void toggleCollapsed() {
// this.mCollapsed = !this.mCollapsed;
// }
//
// public void setCollapsed(boolean collapsed) {
// this.mCollapsed = collapsed;
// }
//
// }
| import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.hexforhn.hex.R;
import com.hexforhn.hex.adapter.helper.CommentListManager;
import com.hexforhn.hex.adapter.helper.TextHelper;
import com.hexforhn.hex.listener.ClickListener;
import com.hexforhn.hex.viewmodel.CommentViewModel;
import java.util.List; | package com.hexforhn.hex.adapter;
public class CommentListAdapter extends RecyclerView.Adapter<ViewHolder> implements ClickListener {
private final static int INDENT_SIZE = 5;
private final Context mContext;
private final CommentListManager mCommentListManager;
| // Path: app/src/main/java/com/hexforhn/hex/adapter/helper/CommentListManager.java
// public class CommentListManager {
// private final List<CommentViewModel> mComments;
//
// public CommentListManager(List<CommentViewModel> comments) {
// mComments = comments;
// }
//
// public List<CommentViewModel> getVisibleComments() {
// List<CommentViewModel> comments = new ArrayList<>();
// int commentCount = mComments.size();
//
// for (int i = 0; i < commentCount; i++) {
// CommentViewModel comment = mComments.get(i);
//
// if (comment.isVisible()) {
// comments.add(comment);
// }
// }
//
// return comments;
// }
//
// public void toggleCommentAtPosition(int position) {
// CommentViewModel commentToToggle = getVisibleComments().get(position);
// int commentCount = mComments.size();
//
// commentToToggle.toggleCollapsed();
//
// int toggledCommentDepth = commentToToggle.getDepth();
// boolean collapsedState = commentToToggle.isCollapsed();
//
// position = mComments.indexOf(commentToToggle);
//
// for (int i = position + 1; i < commentCount; i++) {
// CommentViewModel comment = mComments.get(i);
//
// if (comment.getDepth() > toggledCommentDepth) {
// comment.setVisible(!collapsedState);
// comment.setCollapsed(collapsedState);
// } else {
// break;
// }
// }
// }
//
// }
//
// Path: app/src/main/java/com/hexforhn/hex/adapter/helper/TextHelper.java
// public class TextHelper {
//
// public static CharSequence removeTrailingNewlinesFromText(CharSequence text) {
// if (text == null || text.length() < 1) {
// return "";
// }
//
// if (text.charAt(text.length() - 1) == "\n".charAt(0)) {
// return removeTrailingNewlinesFromText(text.subSequence(0, text.length() - 1));
// }
//
// return text;
// }
// }
//
// Path: app/src/main/java/com/hexforhn/hex/listener/ClickListener.java
// public interface ClickListener {
//
// /**
// * Called when the view is clicked.
// *
// * @param v view that is clicked
// * @param position of the clicked item
// * @param isLongClick true if long click, false otherwise
// */
// void onClick(View v, int position, boolean isLongClick);
// }
//
// Path: app/src/main/java/com/hexforhn/hex/viewmodel/CommentViewModel.java
// public class CommentViewModel {
//
// private final int mCommentCount;
// private final String mText;
// private final String mUser;
// private final int mDepth;
// private final Date mDate;
// private Boolean mCollapsed;
// private boolean mVisible;
//
// public CommentViewModel(String user, String text, int depth, int commentCount, Date date) {
// this.mUser = user;
// this.mText = text;
// this.mDepth = depth;
// this.mCommentCount = commentCount;
// this.mDate = date;
// this.mVisible = true;
// this.mCollapsed = false;
// }
//
// public String getText() {
// return this.mText;
// }
//
// public String getUser() {
// return this.mUser;
// }
//
// public int getDepth() {
// return this.mDepth;
// }
//
// public int getCommentCount() {
// return this.mCommentCount;
// }
//
// public String getRelativeTime() {
// return DateUtils.getRelativeTimeSpanString(mDate.getTime(), System.currentTimeMillis(), 0)
// .toString();
// }
//
// public boolean isVisible() {
// return this.mVisible;
// }
//
// public boolean isCollapsed() {
// return this.mCollapsed;
// }
//
// public void setVisible(boolean visible) {
// this.mVisible = visible;
// }
//
// public void toggleCollapsed() {
// this.mCollapsed = !this.mCollapsed;
// }
//
// public void setCollapsed(boolean collapsed) {
// this.mCollapsed = collapsed;
// }
//
// }
// Path: app/src/main/java/com/hexforhn/hex/adapter/CommentListAdapter.java
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.hexforhn.hex.R;
import com.hexforhn.hex.adapter.helper.CommentListManager;
import com.hexforhn.hex.adapter.helper.TextHelper;
import com.hexforhn.hex.listener.ClickListener;
import com.hexforhn.hex.viewmodel.CommentViewModel;
import java.util.List;
package com.hexforhn.hex.adapter;
public class CommentListAdapter extends RecyclerView.Adapter<ViewHolder> implements ClickListener {
private final static int INDENT_SIZE = 5;
private final Context mContext;
private final CommentListManager mCommentListManager;
| public CommentListAdapter(Context context, List<CommentViewModel> comments) { |
longdivision/hex | app/src/main/java/com/hexforhn/hex/adapter/CommentListAdapter.java | // Path: app/src/main/java/com/hexforhn/hex/adapter/helper/CommentListManager.java
// public class CommentListManager {
// private final List<CommentViewModel> mComments;
//
// public CommentListManager(List<CommentViewModel> comments) {
// mComments = comments;
// }
//
// public List<CommentViewModel> getVisibleComments() {
// List<CommentViewModel> comments = new ArrayList<>();
// int commentCount = mComments.size();
//
// for (int i = 0; i < commentCount; i++) {
// CommentViewModel comment = mComments.get(i);
//
// if (comment.isVisible()) {
// comments.add(comment);
// }
// }
//
// return comments;
// }
//
// public void toggleCommentAtPosition(int position) {
// CommentViewModel commentToToggle = getVisibleComments().get(position);
// int commentCount = mComments.size();
//
// commentToToggle.toggleCollapsed();
//
// int toggledCommentDepth = commentToToggle.getDepth();
// boolean collapsedState = commentToToggle.isCollapsed();
//
// position = mComments.indexOf(commentToToggle);
//
// for (int i = position + 1; i < commentCount; i++) {
// CommentViewModel comment = mComments.get(i);
//
// if (comment.getDepth() > toggledCommentDepth) {
// comment.setVisible(!collapsedState);
// comment.setCollapsed(collapsedState);
// } else {
// break;
// }
// }
// }
//
// }
//
// Path: app/src/main/java/com/hexforhn/hex/adapter/helper/TextHelper.java
// public class TextHelper {
//
// public static CharSequence removeTrailingNewlinesFromText(CharSequence text) {
// if (text == null || text.length() < 1) {
// return "";
// }
//
// if (text.charAt(text.length() - 1) == "\n".charAt(0)) {
// return removeTrailingNewlinesFromText(text.subSequence(0, text.length() - 1));
// }
//
// return text;
// }
// }
//
// Path: app/src/main/java/com/hexforhn/hex/listener/ClickListener.java
// public interface ClickListener {
//
// /**
// * Called when the view is clicked.
// *
// * @param v view that is clicked
// * @param position of the clicked item
// * @param isLongClick true if long click, false otherwise
// */
// void onClick(View v, int position, boolean isLongClick);
// }
//
// Path: app/src/main/java/com/hexforhn/hex/viewmodel/CommentViewModel.java
// public class CommentViewModel {
//
// private final int mCommentCount;
// private final String mText;
// private final String mUser;
// private final int mDepth;
// private final Date mDate;
// private Boolean mCollapsed;
// private boolean mVisible;
//
// public CommentViewModel(String user, String text, int depth, int commentCount, Date date) {
// this.mUser = user;
// this.mText = text;
// this.mDepth = depth;
// this.mCommentCount = commentCount;
// this.mDate = date;
// this.mVisible = true;
// this.mCollapsed = false;
// }
//
// public String getText() {
// return this.mText;
// }
//
// public String getUser() {
// return this.mUser;
// }
//
// public int getDepth() {
// return this.mDepth;
// }
//
// public int getCommentCount() {
// return this.mCommentCount;
// }
//
// public String getRelativeTime() {
// return DateUtils.getRelativeTimeSpanString(mDate.getTime(), System.currentTimeMillis(), 0)
// .toString();
// }
//
// public boolean isVisible() {
// return this.mVisible;
// }
//
// public boolean isCollapsed() {
// return this.mCollapsed;
// }
//
// public void setVisible(boolean visible) {
// this.mVisible = visible;
// }
//
// public void toggleCollapsed() {
// this.mCollapsed = !this.mCollapsed;
// }
//
// public void setCollapsed(boolean collapsed) {
// this.mCollapsed = collapsed;
// }
//
// }
| import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.hexforhn.hex.R;
import com.hexforhn.hex.adapter.helper.CommentListManager;
import com.hexforhn.hex.adapter.helper.TextHelper;
import com.hexforhn.hex.listener.ClickListener;
import com.hexforhn.hex.viewmodel.CommentViewModel;
import java.util.List; |
return viewHolder;
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
CommentViewModel comment = mCommentListManager.getVisibleComments().get(position);
renderCommentIntoView(comment, holder.mView);
}
@Override
public int getItemCount() {
return mCommentListManager.getVisibleComments().size();
}
@Override
public void onClick(View view, int position, boolean isLongClick) {
mCommentListManager.toggleCommentAtPosition(position);
notifyDataSetChanged();
}
private void renderCommentIntoView(CommentViewModel comment, View commentView) {
TextView usernameView = (TextView) commentView.findViewById(R.id.username);
TextView relativeTimeView = (TextView) commentView.findViewById(R.id.relativeTime);
final TextView textView = (TextView) commentView.findViewById(R.id.text);
LinearLayout indentView = (LinearLayout) commentView.findViewById(R.id.indent);
View childCommentsHidden = commentView.findViewById(R.id.hiddenChildCommentsMarker);
usernameView.setText(comment.getUser());
relativeTimeView.setText(comment.getRelativeTime()); | // Path: app/src/main/java/com/hexforhn/hex/adapter/helper/CommentListManager.java
// public class CommentListManager {
// private final List<CommentViewModel> mComments;
//
// public CommentListManager(List<CommentViewModel> comments) {
// mComments = comments;
// }
//
// public List<CommentViewModel> getVisibleComments() {
// List<CommentViewModel> comments = new ArrayList<>();
// int commentCount = mComments.size();
//
// for (int i = 0; i < commentCount; i++) {
// CommentViewModel comment = mComments.get(i);
//
// if (comment.isVisible()) {
// comments.add(comment);
// }
// }
//
// return comments;
// }
//
// public void toggleCommentAtPosition(int position) {
// CommentViewModel commentToToggle = getVisibleComments().get(position);
// int commentCount = mComments.size();
//
// commentToToggle.toggleCollapsed();
//
// int toggledCommentDepth = commentToToggle.getDepth();
// boolean collapsedState = commentToToggle.isCollapsed();
//
// position = mComments.indexOf(commentToToggle);
//
// for (int i = position + 1; i < commentCount; i++) {
// CommentViewModel comment = mComments.get(i);
//
// if (comment.getDepth() > toggledCommentDepth) {
// comment.setVisible(!collapsedState);
// comment.setCollapsed(collapsedState);
// } else {
// break;
// }
// }
// }
//
// }
//
// Path: app/src/main/java/com/hexforhn/hex/adapter/helper/TextHelper.java
// public class TextHelper {
//
// public static CharSequence removeTrailingNewlinesFromText(CharSequence text) {
// if (text == null || text.length() < 1) {
// return "";
// }
//
// if (text.charAt(text.length() - 1) == "\n".charAt(0)) {
// return removeTrailingNewlinesFromText(text.subSequence(0, text.length() - 1));
// }
//
// return text;
// }
// }
//
// Path: app/src/main/java/com/hexforhn/hex/listener/ClickListener.java
// public interface ClickListener {
//
// /**
// * Called when the view is clicked.
// *
// * @param v view that is clicked
// * @param position of the clicked item
// * @param isLongClick true if long click, false otherwise
// */
// void onClick(View v, int position, boolean isLongClick);
// }
//
// Path: app/src/main/java/com/hexforhn/hex/viewmodel/CommentViewModel.java
// public class CommentViewModel {
//
// private final int mCommentCount;
// private final String mText;
// private final String mUser;
// private final int mDepth;
// private final Date mDate;
// private Boolean mCollapsed;
// private boolean mVisible;
//
// public CommentViewModel(String user, String text, int depth, int commentCount, Date date) {
// this.mUser = user;
// this.mText = text;
// this.mDepth = depth;
// this.mCommentCount = commentCount;
// this.mDate = date;
// this.mVisible = true;
// this.mCollapsed = false;
// }
//
// public String getText() {
// return this.mText;
// }
//
// public String getUser() {
// return this.mUser;
// }
//
// public int getDepth() {
// return this.mDepth;
// }
//
// public int getCommentCount() {
// return this.mCommentCount;
// }
//
// public String getRelativeTime() {
// return DateUtils.getRelativeTimeSpanString(mDate.getTime(), System.currentTimeMillis(), 0)
// .toString();
// }
//
// public boolean isVisible() {
// return this.mVisible;
// }
//
// public boolean isCollapsed() {
// return this.mCollapsed;
// }
//
// public void setVisible(boolean visible) {
// this.mVisible = visible;
// }
//
// public void toggleCollapsed() {
// this.mCollapsed = !this.mCollapsed;
// }
//
// public void setCollapsed(boolean collapsed) {
// this.mCollapsed = collapsed;
// }
//
// }
// Path: app/src/main/java/com/hexforhn/hex/adapter/CommentListAdapter.java
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.hexforhn.hex.R;
import com.hexforhn.hex.adapter.helper.CommentListManager;
import com.hexforhn.hex.adapter.helper.TextHelper;
import com.hexforhn.hex.listener.ClickListener;
import com.hexforhn.hex.viewmodel.CommentViewModel;
import java.util.List;
return viewHolder;
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
CommentViewModel comment = mCommentListManager.getVisibleComments().get(position);
renderCommentIntoView(comment, holder.mView);
}
@Override
public int getItemCount() {
return mCommentListManager.getVisibleComments().size();
}
@Override
public void onClick(View view, int position, boolean isLongClick) {
mCommentListManager.toggleCommentAtPosition(position);
notifyDataSetChanged();
}
private void renderCommentIntoView(CommentViewModel comment, View commentView) {
TextView usernameView = (TextView) commentView.findViewById(R.id.username);
TextView relativeTimeView = (TextView) commentView.findViewById(R.id.relativeTime);
final TextView textView = (TextView) commentView.findViewById(R.id.text);
LinearLayout indentView = (LinearLayout) commentView.findViewById(R.id.indent);
View childCommentsHidden = commentView.findViewById(R.id.hiddenChildCommentsMarker);
usernameView.setText(comment.getUser());
relativeTimeView.setText(comment.getRelativeTime()); | textView.setText(TextHelper.removeTrailingNewlinesFromText(Html.fromHtml(comment.getText()))); |
longdivision/hex | app/src/main/java/com/hexforhn/hex/activity/AboutActivity.java | // Path: app/src/main/java/com/hexforhn/hex/util/ThemeHelper.java
// public class ThemeHelper {
// public static void applyTheme(Activity activity) {
// if (shouldSetTheme(activity)) {
// activity.setTheme(getDesiredTheme(activity));
// }
// }
//
// public static void updateTheme(Activity activity) {
// if (shouldSetTheme(activity)) {
// activity.recreate();
// }
// }
//
// private static boolean shouldSetTheme(Activity activity) {
// return getCurrentTheme(activity) != getDesiredTheme(activity);
// }
//
// private static int getDesiredTheme(Activity activity) {
// SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(activity);
// boolean useDarkTheme = sharedPref.getBoolean(activity.getString(R.string.enableDarkThemeSettingKey), false);
//
// return useDarkTheme ? R.style.AppThemeDark : R.style.AppThemeLight;
// }
//
// private static int getCurrentTheme(Activity activity) {
// TypedValue outValue = new TypedValue();
// activity.getTheme().resolveAttribute(R.attr.themeName, outValue, true);
//
// return outValue.string.toString().equals("AppThemeDark") ? R.style.AppThemeDark : R.style.AppThemeLight;
// }
// }
| import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.method.LinkMovementMethod;
import android.widget.TextView;
import com.hexforhn.hex.R;
import com.hexforhn.hex.util.ThemeHelper; | package com.hexforhn.hex.activity;
public class AboutActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); | // Path: app/src/main/java/com/hexforhn/hex/util/ThemeHelper.java
// public class ThemeHelper {
// public static void applyTheme(Activity activity) {
// if (shouldSetTheme(activity)) {
// activity.setTheme(getDesiredTheme(activity));
// }
// }
//
// public static void updateTheme(Activity activity) {
// if (shouldSetTheme(activity)) {
// activity.recreate();
// }
// }
//
// private static boolean shouldSetTheme(Activity activity) {
// return getCurrentTheme(activity) != getDesiredTheme(activity);
// }
//
// private static int getDesiredTheme(Activity activity) {
// SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(activity);
// boolean useDarkTheme = sharedPref.getBoolean(activity.getString(R.string.enableDarkThemeSettingKey), false);
//
// return useDarkTheme ? R.style.AppThemeDark : R.style.AppThemeLight;
// }
//
// private static int getCurrentTheme(Activity activity) {
// TypedValue outValue = new TypedValue();
// activity.getTheme().resolveAttribute(R.attr.themeName, outValue, true);
//
// return outValue.string.toString().equals("AppThemeDark") ? R.style.AppThemeDark : R.style.AppThemeLight;
// }
// }
// Path: app/src/main/java/com/hexforhn/hex/activity/AboutActivity.java
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.method.LinkMovementMethod;
import android.widget.TextView;
import com.hexforhn.hex.R;
import com.hexforhn.hex.util.ThemeHelper;
package com.hexforhn.hex.activity;
public class AboutActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); | ThemeHelper.applyTheme(this); |
longdivision/hex | app/src/main/java/com/hexforhn/hex/net/hexapi/StoryCollectionService.java | // Path: app/src/main/java/com/hexforhn/hex/model/Story.java
// public class Story implements Item {
//
// private final String mId;
// private final String mTitle;
// private final String mUrl;
// private final String mCommentsUrl;
// private final String mUser;
// private final String mDomain;
// private final int mScore;
// private final int mCommentCount;
// private final Date mDate;
// private final List<Comment> mComments;
//
// public Story(String id, String title, String url, String commentsUrl, String user, String domain,
// int score, int commentCount, Date date) {
// this.mId = id;
// this.mTitle = title;
// this.mUrl = url;
// this.mCommentsUrl = commentsUrl;
// this.mUser = user;
// this.mDomain = domain;
// this.mScore = score;
// this.mCommentCount = commentCount;
// this.mDate = date;
// this.mComments = new ArrayList<>();
// }
//
// public Story(String id, String title, String url, String commentsUrl, String user, String domain,
// int score, int commentCount, Date date, List<Comment> comments) {
// this.mId = id;
// this.mTitle = title;
// this.mUrl = url;
// this.mCommentsUrl = commentsUrl;
// this.mUser = user;
// this.mDomain = domain;
// this.mScore = score;
// this.mCommentCount = commentCount;
// this.mDate = date;
// this.mComments = comments;
// }
//
// public String getId() {
// return this.mId;
// }
//
// public String getTitle() {
// return this.mTitle;
// }
//
// public String getUrl() {
// return this.mUrl;
// }
//
// public String getCommentsUrl() {
// return this.mCommentsUrl;
// }
//
// public String getUser() {
// return this.mUser;
// }
//
// public String getDomain() {
// return this.mDomain;
// }
//
// public int getScore() {
// return this.mScore;
// }
//
// public int getCommentCount() {
// return this.mCommentCount;
// }
//
// public Date getDate() {
// return this.mDate;
// }
//
// public List<Comment> getComments() {
// return this.mComments;
// }
// }
//
// Path: app/src/main/java/com/hexforhn/hex/net/hexapi/marshall/FrontPageMarshaller.java
// public class FrontPageMarshaller {
//
// public static List<Story> marshall(JSONArray rawStories) {
// List<Story> frontPageStories = new ArrayList<>();
//
// for (int i = 0; i < rawStories.length(); i++) {
// try {
// frontPageStories.add(StoryMarshaller.marshall(rawStories.getJSONObject(i)));
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
//
// return frontPageStories;
// }
// }
//
// Path: app/src/main/java/com/hexforhn/hex/net/hexapi/util/RetryPolicyFactory.java
// public class RetryPolicyFactory {
// private static final int SOCKET_TIMEOUT_MS = 2500;
// private static final int MAX_RETRIES = 3;
// private static final int BACKOFF_MULTIPLIER = 2;
//
// public static RetryPolicy build() {
// return new DefaultRetryPolicy(SOCKET_TIMEOUT_MS, MAX_RETRIES, BACKOFF_MULTIPLIER);
// }
// }
| import com.android.volley.RequestQueue;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.RequestFuture;
import com.hexforhn.hex.model.Story;
import com.hexforhn.hex.net.hexapi.marshall.FrontPageMarshaller;
import com.hexforhn.hex.net.hexapi.util.RetryPolicyFactory;
import org.json.JSONArray;
import java.util.List; | package com.hexforhn.hex.net.hexapi;
public class StoryCollectionService {
private final RequestQueue mRequestQueue;
private final String mApiBaseUrl;
public enum Collection {
Top, New, Ask, Show, Jobs
}
public StoryCollectionService(RequestQueue requestQueue, String apiBaseUrl) {
mRequestQueue = requestQueue;
mApiBaseUrl = apiBaseUrl;
}
| // Path: app/src/main/java/com/hexforhn/hex/model/Story.java
// public class Story implements Item {
//
// private final String mId;
// private final String mTitle;
// private final String mUrl;
// private final String mCommentsUrl;
// private final String mUser;
// private final String mDomain;
// private final int mScore;
// private final int mCommentCount;
// private final Date mDate;
// private final List<Comment> mComments;
//
// public Story(String id, String title, String url, String commentsUrl, String user, String domain,
// int score, int commentCount, Date date) {
// this.mId = id;
// this.mTitle = title;
// this.mUrl = url;
// this.mCommentsUrl = commentsUrl;
// this.mUser = user;
// this.mDomain = domain;
// this.mScore = score;
// this.mCommentCount = commentCount;
// this.mDate = date;
// this.mComments = new ArrayList<>();
// }
//
// public Story(String id, String title, String url, String commentsUrl, String user, String domain,
// int score, int commentCount, Date date, List<Comment> comments) {
// this.mId = id;
// this.mTitle = title;
// this.mUrl = url;
// this.mCommentsUrl = commentsUrl;
// this.mUser = user;
// this.mDomain = domain;
// this.mScore = score;
// this.mCommentCount = commentCount;
// this.mDate = date;
// this.mComments = comments;
// }
//
// public String getId() {
// return this.mId;
// }
//
// public String getTitle() {
// return this.mTitle;
// }
//
// public String getUrl() {
// return this.mUrl;
// }
//
// public String getCommentsUrl() {
// return this.mCommentsUrl;
// }
//
// public String getUser() {
// return this.mUser;
// }
//
// public String getDomain() {
// return this.mDomain;
// }
//
// public int getScore() {
// return this.mScore;
// }
//
// public int getCommentCount() {
// return this.mCommentCount;
// }
//
// public Date getDate() {
// return this.mDate;
// }
//
// public List<Comment> getComments() {
// return this.mComments;
// }
// }
//
// Path: app/src/main/java/com/hexforhn/hex/net/hexapi/marshall/FrontPageMarshaller.java
// public class FrontPageMarshaller {
//
// public static List<Story> marshall(JSONArray rawStories) {
// List<Story> frontPageStories = new ArrayList<>();
//
// for (int i = 0; i < rawStories.length(); i++) {
// try {
// frontPageStories.add(StoryMarshaller.marshall(rawStories.getJSONObject(i)));
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
//
// return frontPageStories;
// }
// }
//
// Path: app/src/main/java/com/hexforhn/hex/net/hexapi/util/RetryPolicyFactory.java
// public class RetryPolicyFactory {
// private static final int SOCKET_TIMEOUT_MS = 2500;
// private static final int MAX_RETRIES = 3;
// private static final int BACKOFF_MULTIPLIER = 2;
//
// public static RetryPolicy build() {
// return new DefaultRetryPolicy(SOCKET_TIMEOUT_MS, MAX_RETRIES, BACKOFF_MULTIPLIER);
// }
// }
// Path: app/src/main/java/com/hexforhn/hex/net/hexapi/StoryCollectionService.java
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.RequestFuture;
import com.hexforhn.hex.model.Story;
import com.hexforhn.hex.net.hexapi.marshall.FrontPageMarshaller;
import com.hexforhn.hex.net.hexapi.util.RetryPolicyFactory;
import org.json.JSONArray;
import java.util.List;
package com.hexforhn.hex.net.hexapi;
public class StoryCollectionService {
private final RequestQueue mRequestQueue;
private final String mApiBaseUrl;
public enum Collection {
Top, New, Ask, Show, Jobs
}
public StoryCollectionService(RequestQueue requestQueue, String apiBaseUrl) {
mRequestQueue = requestQueue;
mApiBaseUrl = apiBaseUrl;
}
| public List<Story> getStories(Collection collection) { |
longdivision/hex | app/src/main/java/com/hexforhn/hex/net/hexapi/StoryCollectionService.java | // Path: app/src/main/java/com/hexforhn/hex/model/Story.java
// public class Story implements Item {
//
// private final String mId;
// private final String mTitle;
// private final String mUrl;
// private final String mCommentsUrl;
// private final String mUser;
// private final String mDomain;
// private final int mScore;
// private final int mCommentCount;
// private final Date mDate;
// private final List<Comment> mComments;
//
// public Story(String id, String title, String url, String commentsUrl, String user, String domain,
// int score, int commentCount, Date date) {
// this.mId = id;
// this.mTitle = title;
// this.mUrl = url;
// this.mCommentsUrl = commentsUrl;
// this.mUser = user;
// this.mDomain = domain;
// this.mScore = score;
// this.mCommentCount = commentCount;
// this.mDate = date;
// this.mComments = new ArrayList<>();
// }
//
// public Story(String id, String title, String url, String commentsUrl, String user, String domain,
// int score, int commentCount, Date date, List<Comment> comments) {
// this.mId = id;
// this.mTitle = title;
// this.mUrl = url;
// this.mCommentsUrl = commentsUrl;
// this.mUser = user;
// this.mDomain = domain;
// this.mScore = score;
// this.mCommentCount = commentCount;
// this.mDate = date;
// this.mComments = comments;
// }
//
// public String getId() {
// return this.mId;
// }
//
// public String getTitle() {
// return this.mTitle;
// }
//
// public String getUrl() {
// return this.mUrl;
// }
//
// public String getCommentsUrl() {
// return this.mCommentsUrl;
// }
//
// public String getUser() {
// return this.mUser;
// }
//
// public String getDomain() {
// return this.mDomain;
// }
//
// public int getScore() {
// return this.mScore;
// }
//
// public int getCommentCount() {
// return this.mCommentCount;
// }
//
// public Date getDate() {
// return this.mDate;
// }
//
// public List<Comment> getComments() {
// return this.mComments;
// }
// }
//
// Path: app/src/main/java/com/hexforhn/hex/net/hexapi/marshall/FrontPageMarshaller.java
// public class FrontPageMarshaller {
//
// public static List<Story> marshall(JSONArray rawStories) {
// List<Story> frontPageStories = new ArrayList<>();
//
// for (int i = 0; i < rawStories.length(); i++) {
// try {
// frontPageStories.add(StoryMarshaller.marshall(rawStories.getJSONObject(i)));
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
//
// return frontPageStories;
// }
// }
//
// Path: app/src/main/java/com/hexforhn/hex/net/hexapi/util/RetryPolicyFactory.java
// public class RetryPolicyFactory {
// private static final int SOCKET_TIMEOUT_MS = 2500;
// private static final int MAX_RETRIES = 3;
// private static final int BACKOFF_MULTIPLIER = 2;
//
// public static RetryPolicy build() {
// return new DefaultRetryPolicy(SOCKET_TIMEOUT_MS, MAX_RETRIES, BACKOFF_MULTIPLIER);
// }
// }
| import com.android.volley.RequestQueue;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.RequestFuture;
import com.hexforhn.hex.model.Story;
import com.hexforhn.hex.net.hexapi.marshall.FrontPageMarshaller;
import com.hexforhn.hex.net.hexapi.util.RetryPolicyFactory;
import org.json.JSONArray;
import java.util.List; | package com.hexforhn.hex.net.hexapi;
public class StoryCollectionService {
private final RequestQueue mRequestQueue;
private final String mApiBaseUrl;
public enum Collection {
Top, New, Ask, Show, Jobs
}
public StoryCollectionService(RequestQueue requestQueue, String apiBaseUrl) {
mRequestQueue = requestQueue;
mApiBaseUrl = apiBaseUrl;
}
public List<Story> getStories(Collection collection) {
String apiUrl = getUrlForCollection(collection);
RequestFuture<JSONArray> future = RequestFuture.newFuture();
JsonArrayRequest request = new JsonArrayRequest(mApiBaseUrl + apiUrl, future, future); | // Path: app/src/main/java/com/hexforhn/hex/model/Story.java
// public class Story implements Item {
//
// private final String mId;
// private final String mTitle;
// private final String mUrl;
// private final String mCommentsUrl;
// private final String mUser;
// private final String mDomain;
// private final int mScore;
// private final int mCommentCount;
// private final Date mDate;
// private final List<Comment> mComments;
//
// public Story(String id, String title, String url, String commentsUrl, String user, String domain,
// int score, int commentCount, Date date) {
// this.mId = id;
// this.mTitle = title;
// this.mUrl = url;
// this.mCommentsUrl = commentsUrl;
// this.mUser = user;
// this.mDomain = domain;
// this.mScore = score;
// this.mCommentCount = commentCount;
// this.mDate = date;
// this.mComments = new ArrayList<>();
// }
//
// public Story(String id, String title, String url, String commentsUrl, String user, String domain,
// int score, int commentCount, Date date, List<Comment> comments) {
// this.mId = id;
// this.mTitle = title;
// this.mUrl = url;
// this.mCommentsUrl = commentsUrl;
// this.mUser = user;
// this.mDomain = domain;
// this.mScore = score;
// this.mCommentCount = commentCount;
// this.mDate = date;
// this.mComments = comments;
// }
//
// public String getId() {
// return this.mId;
// }
//
// public String getTitle() {
// return this.mTitle;
// }
//
// public String getUrl() {
// return this.mUrl;
// }
//
// public String getCommentsUrl() {
// return this.mCommentsUrl;
// }
//
// public String getUser() {
// return this.mUser;
// }
//
// public String getDomain() {
// return this.mDomain;
// }
//
// public int getScore() {
// return this.mScore;
// }
//
// public int getCommentCount() {
// return this.mCommentCount;
// }
//
// public Date getDate() {
// return this.mDate;
// }
//
// public List<Comment> getComments() {
// return this.mComments;
// }
// }
//
// Path: app/src/main/java/com/hexforhn/hex/net/hexapi/marshall/FrontPageMarshaller.java
// public class FrontPageMarshaller {
//
// public static List<Story> marshall(JSONArray rawStories) {
// List<Story> frontPageStories = new ArrayList<>();
//
// for (int i = 0; i < rawStories.length(); i++) {
// try {
// frontPageStories.add(StoryMarshaller.marshall(rawStories.getJSONObject(i)));
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
//
// return frontPageStories;
// }
// }
//
// Path: app/src/main/java/com/hexforhn/hex/net/hexapi/util/RetryPolicyFactory.java
// public class RetryPolicyFactory {
// private static final int SOCKET_TIMEOUT_MS = 2500;
// private static final int MAX_RETRIES = 3;
// private static final int BACKOFF_MULTIPLIER = 2;
//
// public static RetryPolicy build() {
// return new DefaultRetryPolicy(SOCKET_TIMEOUT_MS, MAX_RETRIES, BACKOFF_MULTIPLIER);
// }
// }
// Path: app/src/main/java/com/hexforhn/hex/net/hexapi/StoryCollectionService.java
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.RequestFuture;
import com.hexforhn.hex.model.Story;
import com.hexforhn.hex.net.hexapi.marshall.FrontPageMarshaller;
import com.hexforhn.hex.net.hexapi.util.RetryPolicyFactory;
import org.json.JSONArray;
import java.util.List;
package com.hexforhn.hex.net.hexapi;
public class StoryCollectionService {
private final RequestQueue mRequestQueue;
private final String mApiBaseUrl;
public enum Collection {
Top, New, Ask, Show, Jobs
}
public StoryCollectionService(RequestQueue requestQueue, String apiBaseUrl) {
mRequestQueue = requestQueue;
mApiBaseUrl = apiBaseUrl;
}
public List<Story> getStories(Collection collection) {
String apiUrl = getUrlForCollection(collection);
RequestFuture<JSONArray> future = RequestFuture.newFuture();
JsonArrayRequest request = new JsonArrayRequest(mApiBaseUrl + apiUrl, future, future); | request.setRetryPolicy(RetryPolicyFactory.build()); |
longdivision/hex | app/src/main/java/com/hexforhn/hex/net/hexapi/StoryCollectionService.java | // Path: app/src/main/java/com/hexforhn/hex/model/Story.java
// public class Story implements Item {
//
// private final String mId;
// private final String mTitle;
// private final String mUrl;
// private final String mCommentsUrl;
// private final String mUser;
// private final String mDomain;
// private final int mScore;
// private final int mCommentCount;
// private final Date mDate;
// private final List<Comment> mComments;
//
// public Story(String id, String title, String url, String commentsUrl, String user, String domain,
// int score, int commentCount, Date date) {
// this.mId = id;
// this.mTitle = title;
// this.mUrl = url;
// this.mCommentsUrl = commentsUrl;
// this.mUser = user;
// this.mDomain = domain;
// this.mScore = score;
// this.mCommentCount = commentCount;
// this.mDate = date;
// this.mComments = new ArrayList<>();
// }
//
// public Story(String id, String title, String url, String commentsUrl, String user, String domain,
// int score, int commentCount, Date date, List<Comment> comments) {
// this.mId = id;
// this.mTitle = title;
// this.mUrl = url;
// this.mCommentsUrl = commentsUrl;
// this.mUser = user;
// this.mDomain = domain;
// this.mScore = score;
// this.mCommentCount = commentCount;
// this.mDate = date;
// this.mComments = comments;
// }
//
// public String getId() {
// return this.mId;
// }
//
// public String getTitle() {
// return this.mTitle;
// }
//
// public String getUrl() {
// return this.mUrl;
// }
//
// public String getCommentsUrl() {
// return this.mCommentsUrl;
// }
//
// public String getUser() {
// return this.mUser;
// }
//
// public String getDomain() {
// return this.mDomain;
// }
//
// public int getScore() {
// return this.mScore;
// }
//
// public int getCommentCount() {
// return this.mCommentCount;
// }
//
// public Date getDate() {
// return this.mDate;
// }
//
// public List<Comment> getComments() {
// return this.mComments;
// }
// }
//
// Path: app/src/main/java/com/hexforhn/hex/net/hexapi/marshall/FrontPageMarshaller.java
// public class FrontPageMarshaller {
//
// public static List<Story> marshall(JSONArray rawStories) {
// List<Story> frontPageStories = new ArrayList<>();
//
// for (int i = 0; i < rawStories.length(); i++) {
// try {
// frontPageStories.add(StoryMarshaller.marshall(rawStories.getJSONObject(i)));
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
//
// return frontPageStories;
// }
// }
//
// Path: app/src/main/java/com/hexforhn/hex/net/hexapi/util/RetryPolicyFactory.java
// public class RetryPolicyFactory {
// private static final int SOCKET_TIMEOUT_MS = 2500;
// private static final int MAX_RETRIES = 3;
// private static final int BACKOFF_MULTIPLIER = 2;
//
// public static RetryPolicy build() {
// return new DefaultRetryPolicy(SOCKET_TIMEOUT_MS, MAX_RETRIES, BACKOFF_MULTIPLIER);
// }
// }
| import com.android.volley.RequestQueue;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.RequestFuture;
import com.hexforhn.hex.model.Story;
import com.hexforhn.hex.net.hexapi.marshall.FrontPageMarshaller;
import com.hexforhn.hex.net.hexapi.util.RetryPolicyFactory;
import org.json.JSONArray;
import java.util.List; | package com.hexforhn.hex.net.hexapi;
public class StoryCollectionService {
private final RequestQueue mRequestQueue;
private final String mApiBaseUrl;
public enum Collection {
Top, New, Ask, Show, Jobs
}
public StoryCollectionService(RequestQueue requestQueue, String apiBaseUrl) {
mRequestQueue = requestQueue;
mApiBaseUrl = apiBaseUrl;
}
public List<Story> getStories(Collection collection) {
String apiUrl = getUrlForCollection(collection);
RequestFuture<JSONArray> future = RequestFuture.newFuture();
JsonArrayRequest request = new JsonArrayRequest(mApiBaseUrl + apiUrl, future, future);
request.setRetryPolicy(RetryPolicyFactory.build());
mRequestQueue.add(request);
try {
JSONArray response = future.get(); | // Path: app/src/main/java/com/hexforhn/hex/model/Story.java
// public class Story implements Item {
//
// private final String mId;
// private final String mTitle;
// private final String mUrl;
// private final String mCommentsUrl;
// private final String mUser;
// private final String mDomain;
// private final int mScore;
// private final int mCommentCount;
// private final Date mDate;
// private final List<Comment> mComments;
//
// public Story(String id, String title, String url, String commentsUrl, String user, String domain,
// int score, int commentCount, Date date) {
// this.mId = id;
// this.mTitle = title;
// this.mUrl = url;
// this.mCommentsUrl = commentsUrl;
// this.mUser = user;
// this.mDomain = domain;
// this.mScore = score;
// this.mCommentCount = commentCount;
// this.mDate = date;
// this.mComments = new ArrayList<>();
// }
//
// public Story(String id, String title, String url, String commentsUrl, String user, String domain,
// int score, int commentCount, Date date, List<Comment> comments) {
// this.mId = id;
// this.mTitle = title;
// this.mUrl = url;
// this.mCommentsUrl = commentsUrl;
// this.mUser = user;
// this.mDomain = domain;
// this.mScore = score;
// this.mCommentCount = commentCount;
// this.mDate = date;
// this.mComments = comments;
// }
//
// public String getId() {
// return this.mId;
// }
//
// public String getTitle() {
// return this.mTitle;
// }
//
// public String getUrl() {
// return this.mUrl;
// }
//
// public String getCommentsUrl() {
// return this.mCommentsUrl;
// }
//
// public String getUser() {
// return this.mUser;
// }
//
// public String getDomain() {
// return this.mDomain;
// }
//
// public int getScore() {
// return this.mScore;
// }
//
// public int getCommentCount() {
// return this.mCommentCount;
// }
//
// public Date getDate() {
// return this.mDate;
// }
//
// public List<Comment> getComments() {
// return this.mComments;
// }
// }
//
// Path: app/src/main/java/com/hexforhn/hex/net/hexapi/marshall/FrontPageMarshaller.java
// public class FrontPageMarshaller {
//
// public static List<Story> marshall(JSONArray rawStories) {
// List<Story> frontPageStories = new ArrayList<>();
//
// for (int i = 0; i < rawStories.length(); i++) {
// try {
// frontPageStories.add(StoryMarshaller.marshall(rawStories.getJSONObject(i)));
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
//
// return frontPageStories;
// }
// }
//
// Path: app/src/main/java/com/hexforhn/hex/net/hexapi/util/RetryPolicyFactory.java
// public class RetryPolicyFactory {
// private static final int SOCKET_TIMEOUT_MS = 2500;
// private static final int MAX_RETRIES = 3;
// private static final int BACKOFF_MULTIPLIER = 2;
//
// public static RetryPolicy build() {
// return new DefaultRetryPolicy(SOCKET_TIMEOUT_MS, MAX_RETRIES, BACKOFF_MULTIPLIER);
// }
// }
// Path: app/src/main/java/com/hexforhn/hex/net/hexapi/StoryCollectionService.java
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.RequestFuture;
import com.hexforhn.hex.model.Story;
import com.hexforhn.hex.net.hexapi.marshall.FrontPageMarshaller;
import com.hexforhn.hex.net.hexapi.util.RetryPolicyFactory;
import org.json.JSONArray;
import java.util.List;
package com.hexforhn.hex.net.hexapi;
public class StoryCollectionService {
private final RequestQueue mRequestQueue;
private final String mApiBaseUrl;
public enum Collection {
Top, New, Ask, Show, Jobs
}
public StoryCollectionService(RequestQueue requestQueue, String apiBaseUrl) {
mRequestQueue = requestQueue;
mApiBaseUrl = apiBaseUrl;
}
public List<Story> getStories(Collection collection) {
String apiUrl = getUrlForCollection(collection);
RequestFuture<JSONArray> future = RequestFuture.newFuture();
JsonArrayRequest request = new JsonArrayRequest(mApiBaseUrl + apiUrl, future, future);
request.setRetryPolicy(RetryPolicyFactory.build());
mRequestQueue.add(request);
try {
JSONArray response = future.get(); | return FrontPageMarshaller.marshall(response); |
longdivision/hex | app/src/main/java/com/hexforhn/hex/viewmodel/factory/StoryListItemFactory.java | // Path: app/src/main/java/com/hexforhn/hex/model/Item.java
// public interface Item {
//
// String getId();
//
// }
//
// Path: app/src/main/java/com/hexforhn/hex/model/Story.java
// public class Story implements Item {
//
// private final String mId;
// private final String mTitle;
// private final String mUrl;
// private final String mCommentsUrl;
// private final String mUser;
// private final String mDomain;
// private final int mScore;
// private final int mCommentCount;
// private final Date mDate;
// private final List<Comment> mComments;
//
// public Story(String id, String title, String url, String commentsUrl, String user, String domain,
// int score, int commentCount, Date date) {
// this.mId = id;
// this.mTitle = title;
// this.mUrl = url;
// this.mCommentsUrl = commentsUrl;
// this.mUser = user;
// this.mDomain = domain;
// this.mScore = score;
// this.mCommentCount = commentCount;
// this.mDate = date;
// this.mComments = new ArrayList<>();
// }
//
// public Story(String id, String title, String url, String commentsUrl, String user, String domain,
// int score, int commentCount, Date date, List<Comment> comments) {
// this.mId = id;
// this.mTitle = title;
// this.mUrl = url;
// this.mCommentsUrl = commentsUrl;
// this.mUser = user;
// this.mDomain = domain;
// this.mScore = score;
// this.mCommentCount = commentCount;
// this.mDate = date;
// this.mComments = comments;
// }
//
// public String getId() {
// return this.mId;
// }
//
// public String getTitle() {
// return this.mTitle;
// }
//
// public String getUrl() {
// return this.mUrl;
// }
//
// public String getCommentsUrl() {
// return this.mCommentsUrl;
// }
//
// public String getUser() {
// return this.mUser;
// }
//
// public String getDomain() {
// return this.mDomain;
// }
//
// public int getScore() {
// return this.mScore;
// }
//
// public int getCommentCount() {
// return this.mCommentCount;
// }
//
// public Date getDate() {
// return this.mDate;
// }
//
// public List<Comment> getComments() {
// return this.mComments;
// }
// }
//
// Path: app/src/main/java/com/hexforhn/hex/viewmodel/StoryListItemViewModel.java
// public class StoryListItemViewModel {
//
// private final String mTitle;
// private final String mDomain;
// private final int mScore;
// private final int mCommentCount;
// private final Date mDate;
//
// public StoryListItemViewModel(String title, String domain, int score, int commentCount, Date date) {
// this.mTitle = title;
// this.mDomain = domain;
// this.mScore = score;
// this.mCommentCount = commentCount;
// this.mDate = date;
// }
//
// public String getTitle() {
// return this.mTitle;
// }
//
// public String getDomain() {
// return this.mDomain;
// }
//
// public String getScore() {
// return String.valueOf(this.mScore);
// }
//
// public String getCommentCount() {
// return String.valueOf(this.mCommentCount);
// }
//
// public String getRelativeTime() {
// return DateUtils.getRelativeTimeSpanString(mDate.getTime(), System.currentTimeMillis(), 0)
// .toString();
//
// }
// }
| import com.hexforhn.hex.model.Item;
import com.hexforhn.hex.model.Story;
import com.hexforhn.hex.viewmodel.StoryListItemViewModel;
import java.util.ArrayList;
import java.util.List; | package com.hexforhn.hex.viewmodel.factory;
public class StoryListItemFactory {
public static ArrayList<StoryListItemViewModel> createItemListItems(List<? extends Item> items) {
ArrayList<StoryListItemViewModel> itemListItems = new ArrayList<>();
if (items == null) {
return itemListItems;
}
for (Object item : items) { | // Path: app/src/main/java/com/hexforhn/hex/model/Item.java
// public interface Item {
//
// String getId();
//
// }
//
// Path: app/src/main/java/com/hexforhn/hex/model/Story.java
// public class Story implements Item {
//
// private final String mId;
// private final String mTitle;
// private final String mUrl;
// private final String mCommentsUrl;
// private final String mUser;
// private final String mDomain;
// private final int mScore;
// private final int mCommentCount;
// private final Date mDate;
// private final List<Comment> mComments;
//
// public Story(String id, String title, String url, String commentsUrl, String user, String domain,
// int score, int commentCount, Date date) {
// this.mId = id;
// this.mTitle = title;
// this.mUrl = url;
// this.mCommentsUrl = commentsUrl;
// this.mUser = user;
// this.mDomain = domain;
// this.mScore = score;
// this.mCommentCount = commentCount;
// this.mDate = date;
// this.mComments = new ArrayList<>();
// }
//
// public Story(String id, String title, String url, String commentsUrl, String user, String domain,
// int score, int commentCount, Date date, List<Comment> comments) {
// this.mId = id;
// this.mTitle = title;
// this.mUrl = url;
// this.mCommentsUrl = commentsUrl;
// this.mUser = user;
// this.mDomain = domain;
// this.mScore = score;
// this.mCommentCount = commentCount;
// this.mDate = date;
// this.mComments = comments;
// }
//
// public String getId() {
// return this.mId;
// }
//
// public String getTitle() {
// return this.mTitle;
// }
//
// public String getUrl() {
// return this.mUrl;
// }
//
// public String getCommentsUrl() {
// return this.mCommentsUrl;
// }
//
// public String getUser() {
// return this.mUser;
// }
//
// public String getDomain() {
// return this.mDomain;
// }
//
// public int getScore() {
// return this.mScore;
// }
//
// public int getCommentCount() {
// return this.mCommentCount;
// }
//
// public Date getDate() {
// return this.mDate;
// }
//
// public List<Comment> getComments() {
// return this.mComments;
// }
// }
//
// Path: app/src/main/java/com/hexforhn/hex/viewmodel/StoryListItemViewModel.java
// public class StoryListItemViewModel {
//
// private final String mTitle;
// private final String mDomain;
// private final int mScore;
// private final int mCommentCount;
// private final Date mDate;
//
// public StoryListItemViewModel(String title, String domain, int score, int commentCount, Date date) {
// this.mTitle = title;
// this.mDomain = domain;
// this.mScore = score;
// this.mCommentCount = commentCount;
// this.mDate = date;
// }
//
// public String getTitle() {
// return this.mTitle;
// }
//
// public String getDomain() {
// return this.mDomain;
// }
//
// public String getScore() {
// return String.valueOf(this.mScore);
// }
//
// public String getCommentCount() {
// return String.valueOf(this.mCommentCount);
// }
//
// public String getRelativeTime() {
// return DateUtils.getRelativeTimeSpanString(mDate.getTime(), System.currentTimeMillis(), 0)
// .toString();
//
// }
// }
// Path: app/src/main/java/com/hexforhn/hex/viewmodel/factory/StoryListItemFactory.java
import com.hexforhn.hex.model.Item;
import com.hexforhn.hex.model.Story;
import com.hexforhn.hex.viewmodel.StoryListItemViewModel;
import java.util.ArrayList;
import java.util.List;
package com.hexforhn.hex.viewmodel.factory;
public class StoryListItemFactory {
public static ArrayList<StoryListItemViewModel> createItemListItems(List<? extends Item> items) {
ArrayList<StoryListItemViewModel> itemListItems = new ArrayList<>();
if (items == null) {
return itemListItems;
}
for (Object item : items) { | if (item instanceof Story) { |
Kaysoro/KaellyBot | src/main/java/data/OrderUser.java | // Path: src/main/java/enums/City.java
// public enum City {
//
// BONTA("city.bonta", "<:bonta:411236938771857431>"), BRAKMAR("city.brakmar", "<:brakmar:411237228736675860>");
//
// private static Map<String, City> cities;
// private String name;
// private String logo;
//
// City(String name, String logo){ this.name = name; this.logo = logo;}
//
// public String getName(){
// return name;
// }
//
// public String getLogo(){
// return logo;
// }
//
// public String getLabel(Language lg){
// return Translator.getLabel(lg, getName());
// }
//
// public static City getCity(String name){
// if (cities == null){
// cities = new HashMap<>();
// for(City city : City.values())
// cities.put(city.getName(), city);
// }
//
// if (cities.containsKey(name))
// return cities.get(name);
// throw new IllegalArgumentException("No city found for \"" + name + "\".");
// }
// }
//
// Path: src/main/java/enums/Language.java
// public enum Language {
//
// FR("Français", "FR"), EN("English", "EN"), ES("Español", "ES");
//
// private String name;
// private String abrev;
//
// Language(String name, String abrev){
// this.name = name;
// this.abrev = abrev;
// }
//
// public String getName() {
// return name;
// }
//
// public String getAbrev() {
// return abrev;
// }
//
// @Override
// public String toString(){
// return name;
// }
// }
//
// Path: src/main/java/enums/Order.java
// public enum Order {
//
// COEUR("order.heart", ":heart:"), ESPRIT("order.spirit", ":ghost:"), OEIL("order.eye", ":eye:");
//
// private static Map<String, Order> orders;
// private String name;
// private String logo;
//
// Order(String name, String logo){ this.name = name; this.logo = logo;}
//
// public String getName(){
// return name;
// }
//
// public String getLogo(){
// return logo;
// }
//
// public String getLabel(Language lg){
// return Translator.getLabel(lg, getName());
// }
//
// public static Order getOrder(String name){
// if (orders == null){
// orders = new HashMap<>();
// for(Order order : Order.values())
// orders.put(order.getName(), order);
// }
//
// if (orders.containsKey(name))
// return orders.get(name);
// throw new IllegalArgumentException("Aucun ordre trouvé pour \"" + name + "\".");
// }
// }
| import discord4j.common.util.Snowflake;
import discord4j.core.object.entity.Member;
import discord4j.core.object.presence.Presence;
import discord4j.core.object.presence.Status;
import discord4j.core.spec.EmbedCreateSpec;
import enums.City;
import enums.Language;
import enums.Order;
import java.awt.Color;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import util.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;
import java.util.function.Consumer; | package data;
/**
* Created by steve on 19/02/2018.
*/
public class OrderUser extends ObjectUser {
private final static Logger LOG = LoggerFactory.getLogger(OrderUser.class);
private static final String ORDER_PREFIX = "align";
private static MultiKeySearch<OrderUser> orders;
private static final int NUMBER_FIELD = 4;
private static final int LEVEL_MAX = 100; | // Path: src/main/java/enums/City.java
// public enum City {
//
// BONTA("city.bonta", "<:bonta:411236938771857431>"), BRAKMAR("city.brakmar", "<:brakmar:411237228736675860>");
//
// private static Map<String, City> cities;
// private String name;
// private String logo;
//
// City(String name, String logo){ this.name = name; this.logo = logo;}
//
// public String getName(){
// return name;
// }
//
// public String getLogo(){
// return logo;
// }
//
// public String getLabel(Language lg){
// return Translator.getLabel(lg, getName());
// }
//
// public static City getCity(String name){
// if (cities == null){
// cities = new HashMap<>();
// for(City city : City.values())
// cities.put(city.getName(), city);
// }
//
// if (cities.containsKey(name))
// return cities.get(name);
// throw new IllegalArgumentException("No city found for \"" + name + "\".");
// }
// }
//
// Path: src/main/java/enums/Language.java
// public enum Language {
//
// FR("Français", "FR"), EN("English", "EN"), ES("Español", "ES");
//
// private String name;
// private String abrev;
//
// Language(String name, String abrev){
// this.name = name;
// this.abrev = abrev;
// }
//
// public String getName() {
// return name;
// }
//
// public String getAbrev() {
// return abrev;
// }
//
// @Override
// public String toString(){
// return name;
// }
// }
//
// Path: src/main/java/enums/Order.java
// public enum Order {
//
// COEUR("order.heart", ":heart:"), ESPRIT("order.spirit", ":ghost:"), OEIL("order.eye", ":eye:");
//
// private static Map<String, Order> orders;
// private String name;
// private String logo;
//
// Order(String name, String logo){ this.name = name; this.logo = logo;}
//
// public String getName(){
// return name;
// }
//
// public String getLogo(){
// return logo;
// }
//
// public String getLabel(Language lg){
// return Translator.getLabel(lg, getName());
// }
//
// public static Order getOrder(String name){
// if (orders == null){
// orders = new HashMap<>();
// for(Order order : Order.values())
// orders.put(order.getName(), order);
// }
//
// if (orders.containsKey(name))
// return orders.get(name);
// throw new IllegalArgumentException("Aucun ordre trouvé pour \"" + name + "\".");
// }
// }
// Path: src/main/java/data/OrderUser.java
import discord4j.common.util.Snowflake;
import discord4j.core.object.entity.Member;
import discord4j.core.object.presence.Presence;
import discord4j.core.object.presence.Status;
import discord4j.core.spec.EmbedCreateSpec;
import enums.City;
import enums.Language;
import enums.Order;
import java.awt.Color;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import util.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;
import java.util.function.Consumer;
package data;
/**
* Created by steve on 19/02/2018.
*/
public class OrderUser extends ObjectUser {
private final static Logger LOG = LoggerFactory.getLogger(OrderUser.class);
private static final String ORDER_PREFIX = "align";
private static MultiKeySearch<OrderUser> orders;
private static final int NUMBER_FIELD = 4;
private static final int LEVEL_MAX = 100; | private City city; |
Kaysoro/KaellyBot | src/main/java/data/OrderUser.java | // Path: src/main/java/enums/City.java
// public enum City {
//
// BONTA("city.bonta", "<:bonta:411236938771857431>"), BRAKMAR("city.brakmar", "<:brakmar:411237228736675860>");
//
// private static Map<String, City> cities;
// private String name;
// private String logo;
//
// City(String name, String logo){ this.name = name; this.logo = logo;}
//
// public String getName(){
// return name;
// }
//
// public String getLogo(){
// return logo;
// }
//
// public String getLabel(Language lg){
// return Translator.getLabel(lg, getName());
// }
//
// public static City getCity(String name){
// if (cities == null){
// cities = new HashMap<>();
// for(City city : City.values())
// cities.put(city.getName(), city);
// }
//
// if (cities.containsKey(name))
// return cities.get(name);
// throw new IllegalArgumentException("No city found for \"" + name + "\".");
// }
// }
//
// Path: src/main/java/enums/Language.java
// public enum Language {
//
// FR("Français", "FR"), EN("English", "EN"), ES("Español", "ES");
//
// private String name;
// private String abrev;
//
// Language(String name, String abrev){
// this.name = name;
// this.abrev = abrev;
// }
//
// public String getName() {
// return name;
// }
//
// public String getAbrev() {
// return abrev;
// }
//
// @Override
// public String toString(){
// return name;
// }
// }
//
// Path: src/main/java/enums/Order.java
// public enum Order {
//
// COEUR("order.heart", ":heart:"), ESPRIT("order.spirit", ":ghost:"), OEIL("order.eye", ":eye:");
//
// private static Map<String, Order> orders;
// private String name;
// private String logo;
//
// Order(String name, String logo){ this.name = name; this.logo = logo;}
//
// public String getName(){
// return name;
// }
//
// public String getLogo(){
// return logo;
// }
//
// public String getLabel(Language lg){
// return Translator.getLabel(lg, getName());
// }
//
// public static Order getOrder(String name){
// if (orders == null){
// orders = new HashMap<>();
// for(Order order : Order.values())
// orders.put(order.getName(), order);
// }
//
// if (orders.containsKey(name))
// return orders.get(name);
// throw new IllegalArgumentException("Aucun ordre trouvé pour \"" + name + "\".");
// }
// }
| import discord4j.common.util.Snowflake;
import discord4j.core.object.entity.Member;
import discord4j.core.object.presence.Presence;
import discord4j.core.object.presence.Status;
import discord4j.core.spec.EmbedCreateSpec;
import enums.City;
import enums.Language;
import enums.Order;
import java.awt.Color;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import util.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;
import java.util.function.Consumer; | package data;
/**
* Created by steve on 19/02/2018.
*/
public class OrderUser extends ObjectUser {
private final static Logger LOG = LoggerFactory.getLogger(OrderUser.class);
private static final String ORDER_PREFIX = "align";
private static MultiKeySearch<OrderUser> orders;
private static final int NUMBER_FIELD = 4;
private static final int LEVEL_MAX = 100;
private City city; | // Path: src/main/java/enums/City.java
// public enum City {
//
// BONTA("city.bonta", "<:bonta:411236938771857431>"), BRAKMAR("city.brakmar", "<:brakmar:411237228736675860>");
//
// private static Map<String, City> cities;
// private String name;
// private String logo;
//
// City(String name, String logo){ this.name = name; this.logo = logo;}
//
// public String getName(){
// return name;
// }
//
// public String getLogo(){
// return logo;
// }
//
// public String getLabel(Language lg){
// return Translator.getLabel(lg, getName());
// }
//
// public static City getCity(String name){
// if (cities == null){
// cities = new HashMap<>();
// for(City city : City.values())
// cities.put(city.getName(), city);
// }
//
// if (cities.containsKey(name))
// return cities.get(name);
// throw new IllegalArgumentException("No city found for \"" + name + "\".");
// }
// }
//
// Path: src/main/java/enums/Language.java
// public enum Language {
//
// FR("Français", "FR"), EN("English", "EN"), ES("Español", "ES");
//
// private String name;
// private String abrev;
//
// Language(String name, String abrev){
// this.name = name;
// this.abrev = abrev;
// }
//
// public String getName() {
// return name;
// }
//
// public String getAbrev() {
// return abrev;
// }
//
// @Override
// public String toString(){
// return name;
// }
// }
//
// Path: src/main/java/enums/Order.java
// public enum Order {
//
// COEUR("order.heart", ":heart:"), ESPRIT("order.spirit", ":ghost:"), OEIL("order.eye", ":eye:");
//
// private static Map<String, Order> orders;
// private String name;
// private String logo;
//
// Order(String name, String logo){ this.name = name; this.logo = logo;}
//
// public String getName(){
// return name;
// }
//
// public String getLogo(){
// return logo;
// }
//
// public String getLabel(Language lg){
// return Translator.getLabel(lg, getName());
// }
//
// public static Order getOrder(String name){
// if (orders == null){
// orders = new HashMap<>();
// for(Order order : Order.values())
// orders.put(order.getName(), order);
// }
//
// if (orders.containsKey(name))
// return orders.get(name);
// throw new IllegalArgumentException("Aucun ordre trouvé pour \"" + name + "\".");
// }
// }
// Path: src/main/java/data/OrderUser.java
import discord4j.common.util.Snowflake;
import discord4j.core.object.entity.Member;
import discord4j.core.object.presence.Presence;
import discord4j.core.object.presence.Status;
import discord4j.core.spec.EmbedCreateSpec;
import enums.City;
import enums.Language;
import enums.Order;
import java.awt.Color;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import util.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;
import java.util.function.Consumer;
package data;
/**
* Created by steve on 19/02/2018.
*/
public class OrderUser extends ObjectUser {
private final static Logger LOG = LoggerFactory.getLogger(OrderUser.class);
private static final String ORDER_PREFIX = "align";
private static MultiKeySearch<OrderUser> orders;
private static final int NUMBER_FIELD = 4;
private static final int LEVEL_MAX = 100;
private City city; | private Order order; |
Kaysoro/KaellyBot | src/main/java/data/OrderUser.java | // Path: src/main/java/enums/City.java
// public enum City {
//
// BONTA("city.bonta", "<:bonta:411236938771857431>"), BRAKMAR("city.brakmar", "<:brakmar:411237228736675860>");
//
// private static Map<String, City> cities;
// private String name;
// private String logo;
//
// City(String name, String logo){ this.name = name; this.logo = logo;}
//
// public String getName(){
// return name;
// }
//
// public String getLogo(){
// return logo;
// }
//
// public String getLabel(Language lg){
// return Translator.getLabel(lg, getName());
// }
//
// public static City getCity(String name){
// if (cities == null){
// cities = new HashMap<>();
// for(City city : City.values())
// cities.put(city.getName(), city);
// }
//
// if (cities.containsKey(name))
// return cities.get(name);
// throw new IllegalArgumentException("No city found for \"" + name + "\".");
// }
// }
//
// Path: src/main/java/enums/Language.java
// public enum Language {
//
// FR("Français", "FR"), EN("English", "EN"), ES("Español", "ES");
//
// private String name;
// private String abrev;
//
// Language(String name, String abrev){
// this.name = name;
// this.abrev = abrev;
// }
//
// public String getName() {
// return name;
// }
//
// public String getAbrev() {
// return abrev;
// }
//
// @Override
// public String toString(){
// return name;
// }
// }
//
// Path: src/main/java/enums/Order.java
// public enum Order {
//
// COEUR("order.heart", ":heart:"), ESPRIT("order.spirit", ":ghost:"), OEIL("order.eye", ":eye:");
//
// private static Map<String, Order> orders;
// private String name;
// private String logo;
//
// Order(String name, String logo){ this.name = name; this.logo = logo;}
//
// public String getName(){
// return name;
// }
//
// public String getLogo(){
// return logo;
// }
//
// public String getLabel(Language lg){
// return Translator.getLabel(lg, getName());
// }
//
// public static Order getOrder(String name){
// if (orders == null){
// orders = new HashMap<>();
// for(Order order : Order.values())
// orders.put(order.getName(), order);
// }
//
// if (orders.containsKey(name))
// return orders.get(name);
// throw new IllegalArgumentException("Aucun ordre trouvé pour \"" + name + "\".");
// }
// }
| import discord4j.common.util.Snowflake;
import discord4j.core.object.entity.Member;
import discord4j.core.object.presence.Presence;
import discord4j.core.object.presence.Status;
import discord4j.core.spec.EmbedCreateSpec;
import enums.City;
import enums.Language;
import enums.Order;
import java.awt.Color;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import util.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;
import java.util.function.Consumer; | getOrders().add(this, idUser, server, city, order);
Connexion connexion = Connexion.getInstance();
Connection connection = connexion.getConnection();
try {
PreparedStatement preparedStatement = connection.prepareStatement(
"INSERT INTO Order_User(id_user, server_dofus, name_city, name_order, level) "
+ "VALUES(?, ?, ?, ?, ?);");
preparedStatement.setString(1, String.valueOf(idUser));
preparedStatement.setString(2, server.getName());
preparedStatement.setString(3, city.getName());
preparedStatement.setString(4, order.getName());
preparedStatement.setInt(5, level);
preparedStatement.executeUpdate();
} catch (SQLException e) {
LOG.error("addToDatabase", e);
}
}
}
private City getCity() {
return city;
}
private Order getOrder() {
return order;
}
@Override | // Path: src/main/java/enums/City.java
// public enum City {
//
// BONTA("city.bonta", "<:bonta:411236938771857431>"), BRAKMAR("city.brakmar", "<:brakmar:411237228736675860>");
//
// private static Map<String, City> cities;
// private String name;
// private String logo;
//
// City(String name, String logo){ this.name = name; this.logo = logo;}
//
// public String getName(){
// return name;
// }
//
// public String getLogo(){
// return logo;
// }
//
// public String getLabel(Language lg){
// return Translator.getLabel(lg, getName());
// }
//
// public static City getCity(String name){
// if (cities == null){
// cities = new HashMap<>();
// for(City city : City.values())
// cities.put(city.getName(), city);
// }
//
// if (cities.containsKey(name))
// return cities.get(name);
// throw new IllegalArgumentException("No city found for \"" + name + "\".");
// }
// }
//
// Path: src/main/java/enums/Language.java
// public enum Language {
//
// FR("Français", "FR"), EN("English", "EN"), ES("Español", "ES");
//
// private String name;
// private String abrev;
//
// Language(String name, String abrev){
// this.name = name;
// this.abrev = abrev;
// }
//
// public String getName() {
// return name;
// }
//
// public String getAbrev() {
// return abrev;
// }
//
// @Override
// public String toString(){
// return name;
// }
// }
//
// Path: src/main/java/enums/Order.java
// public enum Order {
//
// COEUR("order.heart", ":heart:"), ESPRIT("order.spirit", ":ghost:"), OEIL("order.eye", ":eye:");
//
// private static Map<String, Order> orders;
// private String name;
// private String logo;
//
// Order(String name, String logo){ this.name = name; this.logo = logo;}
//
// public String getName(){
// return name;
// }
//
// public String getLogo(){
// return logo;
// }
//
// public String getLabel(Language lg){
// return Translator.getLabel(lg, getName());
// }
//
// public static Order getOrder(String name){
// if (orders == null){
// orders = new HashMap<>();
// for(Order order : Order.values())
// orders.put(order.getName(), order);
// }
//
// if (orders.containsKey(name))
// return orders.get(name);
// throw new IllegalArgumentException("Aucun ordre trouvé pour \"" + name + "\".");
// }
// }
// Path: src/main/java/data/OrderUser.java
import discord4j.common.util.Snowflake;
import discord4j.core.object.entity.Member;
import discord4j.core.object.presence.Presence;
import discord4j.core.object.presence.Status;
import discord4j.core.spec.EmbedCreateSpec;
import enums.City;
import enums.Language;
import enums.Order;
import java.awt.Color;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import util.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;
import java.util.function.Consumer;
getOrders().add(this, idUser, server, city, order);
Connexion connexion = Connexion.getInstance();
Connection connection = connexion.getConnection();
try {
PreparedStatement preparedStatement = connection.prepareStatement(
"INSERT INTO Order_User(id_user, server_dofus, name_city, name_order, level) "
+ "VALUES(?, ?, ?, ?, ?);");
preparedStatement.setString(1, String.valueOf(idUser));
preparedStatement.setString(2, server.getName());
preparedStatement.setString(3, city.getName());
preparedStatement.setString(4, order.getName());
preparedStatement.setInt(5, level);
preparedStatement.executeUpdate();
} catch (SQLException e) {
LOG.error("addToDatabase", e);
}
}
}
private City getCity() {
return city;
}
private Order getOrder() {
return order;
}
@Override | protected String displayLine(discord4j.core.object.entity.Guild guild, Language lg) { |
Kaysoro/KaellyBot | src/main/java/commands/model/FetchCommand.java | // Path: src/main/java/enums/Language.java
// public enum Language {
//
// FR("Français", "FR"), EN("English", "EN"), ES("Español", "ES");
//
// private String name;
// private String abrev;
//
// Language(String name, String abrev){
// this.name = name;
// this.abrev = abrev;
// }
//
// public String getName() {
// return name;
// }
//
// public String getAbrev() {
// return abrev;
// }
//
// @Override
// public String toString(){
// return name;
// }
// }
//
// Path: src/main/java/exceptions/DiscordException.java
// public interface DiscordException {
//
// void throwException(Message message, Command command, Language lg, Object... arguments);
// }
//
// Path: src/main/java/exceptions/NotFoundDiscordException.java
// public class NotFoundDiscordException implements DiscordException {
//
// private String objectKey;
//
// public NotFoundDiscordException(String objectKey){
// this.objectKey = objectKey;
// }
//
// @Override
// public void throwException(Message message, Command command, Language lg, Object... arguments) {
// AnkamaBug bug = null;
// if (command instanceof WhoisCommand)
// bug = AnkamaBug.CHARACTER_NOT_FOUND;
// else if (command instanceof GuildCommand)
// bug = AnkamaBug.GUILD_NOT_FOUND;
// else if (command instanceof AllianceCommand)
// bug = AnkamaBug.ALLY_NOT_FOUND;
// else if (command instanceof ItemCommand)
// if (message.getContent().contains("'"))
// bug = AnkamaBug.ITEM_NOT_FOUND_APOSTROPHE;
// else if (message.getContent().toLowerCase()
// .contains(Translator.getLabel(lg, "equip.muldo").toLowerCase())
// || message.getContent().toLowerCase()
// .contains(Translator.getLabel(lg, "equip.volkorne").toLowerCase()))
// bug = AnkamaBug.ITEM_PAGE_MULDO_VOLKORNE_NOT_FOUND;
//
// String gender = Translator.getLabel(lg, "exception.object." + objectKey + ".gender");
// String text = Translator.getLabel(lg, "exception.notfound.not." + gender)
// + " " + Translator.getLabel(lg, "exception.object." + objectKey + ".singular")
// + " " + Translator.getLabel(lg, "exception.notfound.found." + gender) + ".";
//
// if (bug != null){
// final AnkamaBug BUG = bug;
// message.getChannel().flatMap(channel -> channel
// .createEmbed(BUG.decorateEmbed(text, lg)))
// .subscribe();
// }
// else
// message.getChannel().flatMap(channel -> channel
// .createMessage(text))
// .subscribe();
// }
// }
//
// Path: src/main/java/exceptions/TooMuchDiscordException.java
// public class TooMuchDiscordException implements DiscordException {
// private final static int ITEM_LIMIT = 25;
// private String objectKey;
// private boolean isTranslatable;
//
// public TooMuchDiscordException(String objectKey){
// this.objectKey = objectKey;
// this.isTranslatable = false;
// }
//
// public TooMuchDiscordException(String objectKey, boolean isTranslatable){
// this.objectKey = objectKey;
// this.isTranslatable = isTranslatable;
// }
//
// @Override
// public void throwException(Message message, Command command, Language lg, Object... arguments) {
// AnkamaBug bug = null;
//
// String gender = Translator.getLabel(lg, "exception.object." + objectKey + ".gender");
// StringBuilder st = new StringBuilder(Translator.getLabel(lg, "exception.toomuch.toomuch." + gender))
// .append(" ").append(Translator.getLabel(lg, "exception.object." + objectKey + ".plural"))
// .append(" ").append(Translator.getLabel(lg, "exception.toomuch.found." + gender));
//
// if (arguments.length > 0) {
// List<Object> objects = (List<Object>) arguments[0];
//
// long similarOcc = objects.stream()
// .collect(Collectors.groupingBy(e -> e, Collectors.counting()))
// .values().stream()
// .max(Long::compareTo)
// .orElse(0L);
//
// if (similarOcc > 1){
// if (command instanceof WhoisCommand)
// bug = AnkamaBug.GHOST_CHARACTER;
// else if (command instanceof GuildCommand)
// bug = AnkamaBug.GHOST_GUILD;
// else if (command instanceof AllianceCommand)
// bug = AnkamaBug.GHOST_ALLY;
// }
//
// if (objects.size() <= ITEM_LIMIT){
// st.append(": ");
//
// for (Object object : objects)
// if (isTranslatable)
// st.append(Translator.getLabel(lg, object.toString())).append(", ");
// else
// st.append(object.toString()).append(", ");
// st.delete(st.length() - 2, st.length()).append(".");
// }
// else
// st.append(". ").append(Translator.getLabel(lg, "exception.toomuch.items"));
// }
// else {
// if (st.substring(st.length() - 1, st.length()).matches("\\s+"))
// st.delete(st.length() - 1, st.length());
// st.append(".");
// }
//
// if (bug != null){
// final AnkamaBug BUG = bug;
// message.getChannel().flatMap(channel -> channel
// .createEmbed(BUG.decorateEmbed(st.toString(), lg)))
// .subscribe();
// }
// else
// message.getChannel().flatMap(channel -> channel
// .createMessage(st.toString()))
// .subscribe();
// }
// }
| import discord4j.core.object.entity.Message;
import enums.Language;
import exceptions.DiscordException;
import exceptions.NotFoundDiscordException;
import exceptions.TooMuchDiscordException;
import java.util.List; | package commands.model;
public abstract class FetchCommand extends AbstractCommand {
protected DiscordException tooMuchServers;
protected DiscordException notFoundServer;
protected FetchCommand(String name, String pattern) {
super(name, pattern); | // Path: src/main/java/enums/Language.java
// public enum Language {
//
// FR("Français", "FR"), EN("English", "EN"), ES("Español", "ES");
//
// private String name;
// private String abrev;
//
// Language(String name, String abrev){
// this.name = name;
// this.abrev = abrev;
// }
//
// public String getName() {
// return name;
// }
//
// public String getAbrev() {
// return abrev;
// }
//
// @Override
// public String toString(){
// return name;
// }
// }
//
// Path: src/main/java/exceptions/DiscordException.java
// public interface DiscordException {
//
// void throwException(Message message, Command command, Language lg, Object... arguments);
// }
//
// Path: src/main/java/exceptions/NotFoundDiscordException.java
// public class NotFoundDiscordException implements DiscordException {
//
// private String objectKey;
//
// public NotFoundDiscordException(String objectKey){
// this.objectKey = objectKey;
// }
//
// @Override
// public void throwException(Message message, Command command, Language lg, Object... arguments) {
// AnkamaBug bug = null;
// if (command instanceof WhoisCommand)
// bug = AnkamaBug.CHARACTER_NOT_FOUND;
// else if (command instanceof GuildCommand)
// bug = AnkamaBug.GUILD_NOT_FOUND;
// else if (command instanceof AllianceCommand)
// bug = AnkamaBug.ALLY_NOT_FOUND;
// else if (command instanceof ItemCommand)
// if (message.getContent().contains("'"))
// bug = AnkamaBug.ITEM_NOT_FOUND_APOSTROPHE;
// else if (message.getContent().toLowerCase()
// .contains(Translator.getLabel(lg, "equip.muldo").toLowerCase())
// || message.getContent().toLowerCase()
// .contains(Translator.getLabel(lg, "equip.volkorne").toLowerCase()))
// bug = AnkamaBug.ITEM_PAGE_MULDO_VOLKORNE_NOT_FOUND;
//
// String gender = Translator.getLabel(lg, "exception.object." + objectKey + ".gender");
// String text = Translator.getLabel(lg, "exception.notfound.not." + gender)
// + " " + Translator.getLabel(lg, "exception.object." + objectKey + ".singular")
// + " " + Translator.getLabel(lg, "exception.notfound.found." + gender) + ".";
//
// if (bug != null){
// final AnkamaBug BUG = bug;
// message.getChannel().flatMap(channel -> channel
// .createEmbed(BUG.decorateEmbed(text, lg)))
// .subscribe();
// }
// else
// message.getChannel().flatMap(channel -> channel
// .createMessage(text))
// .subscribe();
// }
// }
//
// Path: src/main/java/exceptions/TooMuchDiscordException.java
// public class TooMuchDiscordException implements DiscordException {
// private final static int ITEM_LIMIT = 25;
// private String objectKey;
// private boolean isTranslatable;
//
// public TooMuchDiscordException(String objectKey){
// this.objectKey = objectKey;
// this.isTranslatable = false;
// }
//
// public TooMuchDiscordException(String objectKey, boolean isTranslatable){
// this.objectKey = objectKey;
// this.isTranslatable = isTranslatable;
// }
//
// @Override
// public void throwException(Message message, Command command, Language lg, Object... arguments) {
// AnkamaBug bug = null;
//
// String gender = Translator.getLabel(lg, "exception.object." + objectKey + ".gender");
// StringBuilder st = new StringBuilder(Translator.getLabel(lg, "exception.toomuch.toomuch." + gender))
// .append(" ").append(Translator.getLabel(lg, "exception.object." + objectKey + ".plural"))
// .append(" ").append(Translator.getLabel(lg, "exception.toomuch.found." + gender));
//
// if (arguments.length > 0) {
// List<Object> objects = (List<Object>) arguments[0];
//
// long similarOcc = objects.stream()
// .collect(Collectors.groupingBy(e -> e, Collectors.counting()))
// .values().stream()
// .max(Long::compareTo)
// .orElse(0L);
//
// if (similarOcc > 1){
// if (command instanceof WhoisCommand)
// bug = AnkamaBug.GHOST_CHARACTER;
// else if (command instanceof GuildCommand)
// bug = AnkamaBug.GHOST_GUILD;
// else if (command instanceof AllianceCommand)
// bug = AnkamaBug.GHOST_ALLY;
// }
//
// if (objects.size() <= ITEM_LIMIT){
// st.append(": ");
//
// for (Object object : objects)
// if (isTranslatable)
// st.append(Translator.getLabel(lg, object.toString())).append(", ");
// else
// st.append(object.toString()).append(", ");
// st.delete(st.length() - 2, st.length()).append(".");
// }
// else
// st.append(". ").append(Translator.getLabel(lg, "exception.toomuch.items"));
// }
// else {
// if (st.substring(st.length() - 1, st.length()).matches("\\s+"))
// st.delete(st.length() - 1, st.length());
// st.append(".");
// }
//
// if (bug != null){
// final AnkamaBug BUG = bug;
// message.getChannel().flatMap(channel -> channel
// .createEmbed(BUG.decorateEmbed(st.toString(), lg)))
// .subscribe();
// }
// else
// message.getChannel().flatMap(channel -> channel
// .createMessage(st.toString()))
// .subscribe();
// }
// }
// Path: src/main/java/commands/model/FetchCommand.java
import discord4j.core.object.entity.Message;
import enums.Language;
import exceptions.DiscordException;
import exceptions.NotFoundDiscordException;
import exceptions.TooMuchDiscordException;
import java.util.List;
package commands.model;
public abstract class FetchCommand extends AbstractCommand {
protected DiscordException tooMuchServers;
protected DiscordException notFoundServer;
protected FetchCommand(String name, String pattern) {
super(name, pattern); | tooMuchServers = new TooMuchDiscordException("server", true); |
Kaysoro/KaellyBot | src/main/java/commands/model/FetchCommand.java | // Path: src/main/java/enums/Language.java
// public enum Language {
//
// FR("Français", "FR"), EN("English", "EN"), ES("Español", "ES");
//
// private String name;
// private String abrev;
//
// Language(String name, String abrev){
// this.name = name;
// this.abrev = abrev;
// }
//
// public String getName() {
// return name;
// }
//
// public String getAbrev() {
// return abrev;
// }
//
// @Override
// public String toString(){
// return name;
// }
// }
//
// Path: src/main/java/exceptions/DiscordException.java
// public interface DiscordException {
//
// void throwException(Message message, Command command, Language lg, Object... arguments);
// }
//
// Path: src/main/java/exceptions/NotFoundDiscordException.java
// public class NotFoundDiscordException implements DiscordException {
//
// private String objectKey;
//
// public NotFoundDiscordException(String objectKey){
// this.objectKey = objectKey;
// }
//
// @Override
// public void throwException(Message message, Command command, Language lg, Object... arguments) {
// AnkamaBug bug = null;
// if (command instanceof WhoisCommand)
// bug = AnkamaBug.CHARACTER_NOT_FOUND;
// else if (command instanceof GuildCommand)
// bug = AnkamaBug.GUILD_NOT_FOUND;
// else if (command instanceof AllianceCommand)
// bug = AnkamaBug.ALLY_NOT_FOUND;
// else if (command instanceof ItemCommand)
// if (message.getContent().contains("'"))
// bug = AnkamaBug.ITEM_NOT_FOUND_APOSTROPHE;
// else if (message.getContent().toLowerCase()
// .contains(Translator.getLabel(lg, "equip.muldo").toLowerCase())
// || message.getContent().toLowerCase()
// .contains(Translator.getLabel(lg, "equip.volkorne").toLowerCase()))
// bug = AnkamaBug.ITEM_PAGE_MULDO_VOLKORNE_NOT_FOUND;
//
// String gender = Translator.getLabel(lg, "exception.object." + objectKey + ".gender");
// String text = Translator.getLabel(lg, "exception.notfound.not." + gender)
// + " " + Translator.getLabel(lg, "exception.object." + objectKey + ".singular")
// + " " + Translator.getLabel(lg, "exception.notfound.found." + gender) + ".";
//
// if (bug != null){
// final AnkamaBug BUG = bug;
// message.getChannel().flatMap(channel -> channel
// .createEmbed(BUG.decorateEmbed(text, lg)))
// .subscribe();
// }
// else
// message.getChannel().flatMap(channel -> channel
// .createMessage(text))
// .subscribe();
// }
// }
//
// Path: src/main/java/exceptions/TooMuchDiscordException.java
// public class TooMuchDiscordException implements DiscordException {
// private final static int ITEM_LIMIT = 25;
// private String objectKey;
// private boolean isTranslatable;
//
// public TooMuchDiscordException(String objectKey){
// this.objectKey = objectKey;
// this.isTranslatable = false;
// }
//
// public TooMuchDiscordException(String objectKey, boolean isTranslatable){
// this.objectKey = objectKey;
// this.isTranslatable = isTranslatable;
// }
//
// @Override
// public void throwException(Message message, Command command, Language lg, Object... arguments) {
// AnkamaBug bug = null;
//
// String gender = Translator.getLabel(lg, "exception.object." + objectKey + ".gender");
// StringBuilder st = new StringBuilder(Translator.getLabel(lg, "exception.toomuch.toomuch." + gender))
// .append(" ").append(Translator.getLabel(lg, "exception.object." + objectKey + ".plural"))
// .append(" ").append(Translator.getLabel(lg, "exception.toomuch.found." + gender));
//
// if (arguments.length > 0) {
// List<Object> objects = (List<Object>) arguments[0];
//
// long similarOcc = objects.stream()
// .collect(Collectors.groupingBy(e -> e, Collectors.counting()))
// .values().stream()
// .max(Long::compareTo)
// .orElse(0L);
//
// if (similarOcc > 1){
// if (command instanceof WhoisCommand)
// bug = AnkamaBug.GHOST_CHARACTER;
// else if (command instanceof GuildCommand)
// bug = AnkamaBug.GHOST_GUILD;
// else if (command instanceof AllianceCommand)
// bug = AnkamaBug.GHOST_ALLY;
// }
//
// if (objects.size() <= ITEM_LIMIT){
// st.append(": ");
//
// for (Object object : objects)
// if (isTranslatable)
// st.append(Translator.getLabel(lg, object.toString())).append(", ");
// else
// st.append(object.toString()).append(", ");
// st.delete(st.length() - 2, st.length()).append(".");
// }
// else
// st.append(". ").append(Translator.getLabel(lg, "exception.toomuch.items"));
// }
// else {
// if (st.substring(st.length() - 1, st.length()).matches("\\s+"))
// st.delete(st.length() - 1, st.length());
// st.append(".");
// }
//
// if (bug != null){
// final AnkamaBug BUG = bug;
// message.getChannel().flatMap(channel -> channel
// .createEmbed(BUG.decorateEmbed(st.toString(), lg)))
// .subscribe();
// }
// else
// message.getChannel().flatMap(channel -> channel
// .createMessage(st.toString()))
// .subscribe();
// }
// }
| import discord4j.core.object.entity.Message;
import enums.Language;
import exceptions.DiscordException;
import exceptions.NotFoundDiscordException;
import exceptions.TooMuchDiscordException;
import java.util.List; | package commands.model;
public abstract class FetchCommand extends AbstractCommand {
protected DiscordException tooMuchServers;
protected DiscordException notFoundServer;
protected FetchCommand(String name, String pattern) {
super(name, pattern);
tooMuchServers = new TooMuchDiscordException("server", true); | // Path: src/main/java/enums/Language.java
// public enum Language {
//
// FR("Français", "FR"), EN("English", "EN"), ES("Español", "ES");
//
// private String name;
// private String abrev;
//
// Language(String name, String abrev){
// this.name = name;
// this.abrev = abrev;
// }
//
// public String getName() {
// return name;
// }
//
// public String getAbrev() {
// return abrev;
// }
//
// @Override
// public String toString(){
// return name;
// }
// }
//
// Path: src/main/java/exceptions/DiscordException.java
// public interface DiscordException {
//
// void throwException(Message message, Command command, Language lg, Object... arguments);
// }
//
// Path: src/main/java/exceptions/NotFoundDiscordException.java
// public class NotFoundDiscordException implements DiscordException {
//
// private String objectKey;
//
// public NotFoundDiscordException(String objectKey){
// this.objectKey = objectKey;
// }
//
// @Override
// public void throwException(Message message, Command command, Language lg, Object... arguments) {
// AnkamaBug bug = null;
// if (command instanceof WhoisCommand)
// bug = AnkamaBug.CHARACTER_NOT_FOUND;
// else if (command instanceof GuildCommand)
// bug = AnkamaBug.GUILD_NOT_FOUND;
// else if (command instanceof AllianceCommand)
// bug = AnkamaBug.ALLY_NOT_FOUND;
// else if (command instanceof ItemCommand)
// if (message.getContent().contains("'"))
// bug = AnkamaBug.ITEM_NOT_FOUND_APOSTROPHE;
// else if (message.getContent().toLowerCase()
// .contains(Translator.getLabel(lg, "equip.muldo").toLowerCase())
// || message.getContent().toLowerCase()
// .contains(Translator.getLabel(lg, "equip.volkorne").toLowerCase()))
// bug = AnkamaBug.ITEM_PAGE_MULDO_VOLKORNE_NOT_FOUND;
//
// String gender = Translator.getLabel(lg, "exception.object." + objectKey + ".gender");
// String text = Translator.getLabel(lg, "exception.notfound.not." + gender)
// + " " + Translator.getLabel(lg, "exception.object." + objectKey + ".singular")
// + " " + Translator.getLabel(lg, "exception.notfound.found." + gender) + ".";
//
// if (bug != null){
// final AnkamaBug BUG = bug;
// message.getChannel().flatMap(channel -> channel
// .createEmbed(BUG.decorateEmbed(text, lg)))
// .subscribe();
// }
// else
// message.getChannel().flatMap(channel -> channel
// .createMessage(text))
// .subscribe();
// }
// }
//
// Path: src/main/java/exceptions/TooMuchDiscordException.java
// public class TooMuchDiscordException implements DiscordException {
// private final static int ITEM_LIMIT = 25;
// private String objectKey;
// private boolean isTranslatable;
//
// public TooMuchDiscordException(String objectKey){
// this.objectKey = objectKey;
// this.isTranslatable = false;
// }
//
// public TooMuchDiscordException(String objectKey, boolean isTranslatable){
// this.objectKey = objectKey;
// this.isTranslatable = isTranslatable;
// }
//
// @Override
// public void throwException(Message message, Command command, Language lg, Object... arguments) {
// AnkamaBug bug = null;
//
// String gender = Translator.getLabel(lg, "exception.object." + objectKey + ".gender");
// StringBuilder st = new StringBuilder(Translator.getLabel(lg, "exception.toomuch.toomuch." + gender))
// .append(" ").append(Translator.getLabel(lg, "exception.object." + objectKey + ".plural"))
// .append(" ").append(Translator.getLabel(lg, "exception.toomuch.found." + gender));
//
// if (arguments.length > 0) {
// List<Object> objects = (List<Object>) arguments[0];
//
// long similarOcc = objects.stream()
// .collect(Collectors.groupingBy(e -> e, Collectors.counting()))
// .values().stream()
// .max(Long::compareTo)
// .orElse(0L);
//
// if (similarOcc > 1){
// if (command instanceof WhoisCommand)
// bug = AnkamaBug.GHOST_CHARACTER;
// else if (command instanceof GuildCommand)
// bug = AnkamaBug.GHOST_GUILD;
// else if (command instanceof AllianceCommand)
// bug = AnkamaBug.GHOST_ALLY;
// }
//
// if (objects.size() <= ITEM_LIMIT){
// st.append(": ");
//
// for (Object object : objects)
// if (isTranslatable)
// st.append(Translator.getLabel(lg, object.toString())).append(", ");
// else
// st.append(object.toString()).append(", ");
// st.delete(st.length() - 2, st.length()).append(".");
// }
// else
// st.append(". ").append(Translator.getLabel(lg, "exception.toomuch.items"));
// }
// else {
// if (st.substring(st.length() - 1, st.length()).matches("\\s+"))
// st.delete(st.length() - 1, st.length());
// st.append(".");
// }
//
// if (bug != null){
// final AnkamaBug BUG = bug;
// message.getChannel().flatMap(channel -> channel
// .createEmbed(BUG.decorateEmbed(st.toString(), lg)))
// .subscribe();
// }
// else
// message.getChannel().flatMap(channel -> channel
// .createMessage(st.toString()))
// .subscribe();
// }
// }
// Path: src/main/java/commands/model/FetchCommand.java
import discord4j.core.object.entity.Message;
import enums.Language;
import exceptions.DiscordException;
import exceptions.NotFoundDiscordException;
import exceptions.TooMuchDiscordException;
import java.util.List;
package commands.model;
public abstract class FetchCommand extends AbstractCommand {
protected DiscordException tooMuchServers;
protected DiscordException notFoundServer;
protected FetchCommand(String name, String pattern) {
super(name, pattern);
tooMuchServers = new TooMuchDiscordException("server", true); | notFoundServer = new NotFoundDiscordException("server"); |
Kaysoro/KaellyBot | src/main/java/commands/classic/SetCommand.java | // Path: src/main/java/commands/model/DofusRequestCommand.java
// public abstract class DofusRequestCommand extends AbstractCommand {
//
// protected DofusRequestCommand(String name, String pattern) {
// super(name, pattern);
// }
//
// protected List<Requestable> getListRequestableFrom(String url, Message message, DiscordException notFound){
// List<Requestable> result = new ArrayList<>();
// Language lg = Translator.getLanguageFrom(message.getChannel().block());
// try {
// Document doc = JSoupManager.getDocument(url);
// Elements elems = doc.getElementsByClass("ak-bg-odd");
// elems.addAll(doc.getElementsByClass("ak-bg-even"));
//
// for (Element element : elems)
// result.add(new Requestable(element.child(1).text(),
// element.child(1).select("a").attr("href")));
//
// } catch(IOException e){
// ExceptionManager.manageIOException(e, message, this, lg, notFound);
// return new ArrayList<>();
// } catch (Exception e) {
// ExceptionManager.manageException(e, message, this, lg);
// return new ArrayList<>();
// }
//
// return result;
// }
// }
//
// Path: src/main/java/enums/Language.java
// public enum Language {
//
// FR("Français", "FR"), EN("English", "EN"), ES("Español", "ES");
//
// private String name;
// private String abrev;
//
// Language(String name, String abrev){
// this.name = name;
// this.abrev = abrev;
// }
//
// public String getName() {
// return name;
// }
//
// public String getAbrev() {
// return abrev;
// }
//
// @Override
// public String toString(){
// return name;
// }
// }
| import commands.model.DofusRequestCommand;
import discord4j.core.event.domain.message.MessageCreateEvent;
import discord4j.core.object.entity.Message;
import enums.Language;
import exceptions.*;
import util.*;
import data.*;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.Normalizer;
import java.util.regex.Matcher; | package commands.classic;
/**
* Created by steve on 12/10/2016.
*/
public class SetCommand extends DofusRequestCommand {
private final static String forName = "text=";
private DiscordException tooMuchSets;
private DiscordException notFoundSet;
public SetCommand(){
super("set", "\\s+(-more)?(.*)");
tooMuchSets = new TooMuchDiscordException("set");
notFoundSet = new NotFoundDiscordException("set");
}
@Override | // Path: src/main/java/commands/model/DofusRequestCommand.java
// public abstract class DofusRequestCommand extends AbstractCommand {
//
// protected DofusRequestCommand(String name, String pattern) {
// super(name, pattern);
// }
//
// protected List<Requestable> getListRequestableFrom(String url, Message message, DiscordException notFound){
// List<Requestable> result = new ArrayList<>();
// Language lg = Translator.getLanguageFrom(message.getChannel().block());
// try {
// Document doc = JSoupManager.getDocument(url);
// Elements elems = doc.getElementsByClass("ak-bg-odd");
// elems.addAll(doc.getElementsByClass("ak-bg-even"));
//
// for (Element element : elems)
// result.add(new Requestable(element.child(1).text(),
// element.child(1).select("a").attr("href")));
//
// } catch(IOException e){
// ExceptionManager.manageIOException(e, message, this, lg, notFound);
// return new ArrayList<>();
// } catch (Exception e) {
// ExceptionManager.manageException(e, message, this, lg);
// return new ArrayList<>();
// }
//
// return result;
// }
// }
//
// Path: src/main/java/enums/Language.java
// public enum Language {
//
// FR("Français", "FR"), EN("English", "EN"), ES("Español", "ES");
//
// private String name;
// private String abrev;
//
// Language(String name, String abrev){
// this.name = name;
// this.abrev = abrev;
// }
//
// public String getName() {
// return name;
// }
//
// public String getAbrev() {
// return abrev;
// }
//
// @Override
// public String toString(){
// return name;
// }
// }
// Path: src/main/java/commands/classic/SetCommand.java
import commands.model.DofusRequestCommand;
import discord4j.core.event.domain.message.MessageCreateEvent;
import discord4j.core.object.entity.Message;
import enums.Language;
import exceptions.*;
import util.*;
import data.*;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.Normalizer;
import java.util.regex.Matcher;
package commands.classic;
/**
* Created by steve on 12/10/2016.
*/
public class SetCommand extends DofusRequestCommand {
private final static String forName = "text=";
private DiscordException tooMuchSets;
private DiscordException notFoundSet;
public SetCommand(){
super("set", "\\s+(-more)?(.*)");
tooMuchSets = new TooMuchDiscordException("set");
notFoundSet = new NotFoundDiscordException("set");
}
@Override | public void request(MessageCreateEvent event, Message message, Matcher m, Language lg) { |
Kaysoro/KaellyBot | src/main/java/commands/CommandManager.java | // Path: src/main/java/commands/hidden/SendNudeCommand.java
// public class SendNudeCommand extends AbstractCommand {
//
// private static final Random RANDOM = new Random();
//
// public SendNudeCommand() {
// super("sendnude", "");
// setHidden(true);
// }
//
// @Override
// public void request(MessageCreateEvent event, Message message, Matcher m, Language lg) {
// if (message.getChannel().blockOptional().map(chan -> chan instanceof PrivateChannel).orElse(false)
// || message.getChannel().blockOptional().map(chan -> ((TextChannel) chan).isNsfw()).orElse(false)){
// int position = RANDOM.nextInt(Nude.values().length);
// Nude nude = Nude.values()[position];
//
// message.getChannel().flatMap(chan -> chan.createEmbed(spec -> spec.setTitle(Translator.getLabel(lg, "sendnude.title"))
// .setDescription(Translator.getLabel(lg, "sendnude.author")
// .replace("{author}", nude.getAuthor())
// .replace("{url}", nude.getUrl()))
// .setColor(discord4j.rest.util.Color.PINK)
// .setFooter(Translator.getLabel(lg, "sendnude.footer")
// .replace("{position}", String.valueOf(position + 1))
// .replace("{number}", String.valueOf(Nude.values().length)), null)
// .setImage(nude.getImage()))).subscribe();
// }
// else // Exception NSFW
// BasicDiscordException.NO_NSFW_CHANNEL.throwException(message, this, lg);
// }
//
// @Override
// public String help(Language lg, String prefixe) {
// return "**" + prefixe + name + "** " + Translator.getLabel(lg, "sendnude.help");
// }
//
// @Override
// public String helpDetailed(Language lg, String prefixe) {
// return help(lg, prefixe);
// }
// }
//
// Path: src/main/java/commands/model/Command.java
// public interface Command {
// String getName();
// String getPattern();
// Matcher getMatcher(Message message);
// void request(MessageCreateEvent event, Message message);
//
// /**
// * Is the command usable in MP?
// * @return True if it can be used in MP, else false.
// */
// boolean isUsableInMP();
//
// /**
// * Is the command only usable by admins ?
// * @return True if it only can be used by admin, else false.
// */
// boolean isAdmin();
//
// /**
// * Is the command available by the admin ?
// * @return true is the command is available, else false.
// */
// boolean isPublic();
//
// /**
// * is the command is hidden ?
// * @return True if the command is hidden
// */
// boolean isHidden();
//
// /**
// * Change the command scope
// * @param isPublic is command available or not
// */
// void setPublic(boolean isPublic);
//
// /**
// * Is the command available by the guild admin ?
// * @param g Guild concerned
// * @return true is the command is forbidden, else false.
// */
// boolean isForbidden(Guild g);
//
// /**
// * Change the command scope in MP
// * @param isUsableInMP is command available in MP or not
// */
// void setUsableInMP(boolean isUsableInMP);
//
// /**
// * Change the command scope for admin user
// * @param isAdmin is command only available for admins or not
// */
// void setAdmin(boolean isAdmin);
//
// /**
// * Hide or not the command
// * @param isHidden is command hidden or not
// */
// void setHidden(boolean isHidden);
//
// /**
// * @param prefixe Prefixe for command
// * @return Short description of the command
// */
// String help(Language lg, String prefixe);
//
// /**
// * @param prefixe Prefixe for command
// * @return Detailed description of the command
// */
// String helpDetailed(Language lg, String prefixe);
// }
| import commands.admin.*;
import commands.classic.*;
import commands.config.*;
import commands.hidden.SendNudeCommand;
import commands.model.Command;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList; | package commands;
/**
* Created by steve on 20/05/2017.
*/
public class CommandManager {
private static CommandManager instance;
| // Path: src/main/java/commands/hidden/SendNudeCommand.java
// public class SendNudeCommand extends AbstractCommand {
//
// private static final Random RANDOM = new Random();
//
// public SendNudeCommand() {
// super("sendnude", "");
// setHidden(true);
// }
//
// @Override
// public void request(MessageCreateEvent event, Message message, Matcher m, Language lg) {
// if (message.getChannel().blockOptional().map(chan -> chan instanceof PrivateChannel).orElse(false)
// || message.getChannel().blockOptional().map(chan -> ((TextChannel) chan).isNsfw()).orElse(false)){
// int position = RANDOM.nextInt(Nude.values().length);
// Nude nude = Nude.values()[position];
//
// message.getChannel().flatMap(chan -> chan.createEmbed(spec -> spec.setTitle(Translator.getLabel(lg, "sendnude.title"))
// .setDescription(Translator.getLabel(lg, "sendnude.author")
// .replace("{author}", nude.getAuthor())
// .replace("{url}", nude.getUrl()))
// .setColor(discord4j.rest.util.Color.PINK)
// .setFooter(Translator.getLabel(lg, "sendnude.footer")
// .replace("{position}", String.valueOf(position + 1))
// .replace("{number}", String.valueOf(Nude.values().length)), null)
// .setImage(nude.getImage()))).subscribe();
// }
// else // Exception NSFW
// BasicDiscordException.NO_NSFW_CHANNEL.throwException(message, this, lg);
// }
//
// @Override
// public String help(Language lg, String prefixe) {
// return "**" + prefixe + name + "** " + Translator.getLabel(lg, "sendnude.help");
// }
//
// @Override
// public String helpDetailed(Language lg, String prefixe) {
// return help(lg, prefixe);
// }
// }
//
// Path: src/main/java/commands/model/Command.java
// public interface Command {
// String getName();
// String getPattern();
// Matcher getMatcher(Message message);
// void request(MessageCreateEvent event, Message message);
//
// /**
// * Is the command usable in MP?
// * @return True if it can be used in MP, else false.
// */
// boolean isUsableInMP();
//
// /**
// * Is the command only usable by admins ?
// * @return True if it only can be used by admin, else false.
// */
// boolean isAdmin();
//
// /**
// * Is the command available by the admin ?
// * @return true is the command is available, else false.
// */
// boolean isPublic();
//
// /**
// * is the command is hidden ?
// * @return True if the command is hidden
// */
// boolean isHidden();
//
// /**
// * Change the command scope
// * @param isPublic is command available or not
// */
// void setPublic(boolean isPublic);
//
// /**
// * Is the command available by the guild admin ?
// * @param g Guild concerned
// * @return true is the command is forbidden, else false.
// */
// boolean isForbidden(Guild g);
//
// /**
// * Change the command scope in MP
// * @param isUsableInMP is command available in MP or not
// */
// void setUsableInMP(boolean isUsableInMP);
//
// /**
// * Change the command scope for admin user
// * @param isAdmin is command only available for admins or not
// */
// void setAdmin(boolean isAdmin);
//
// /**
// * Hide or not the command
// * @param isHidden is command hidden or not
// */
// void setHidden(boolean isHidden);
//
// /**
// * @param prefixe Prefixe for command
// * @return Short description of the command
// */
// String help(Language lg, String prefixe);
//
// /**
// * @param prefixe Prefixe for command
// * @return Detailed description of the command
// */
// String helpDetailed(Language lg, String prefixe);
// }
// Path: src/main/java/commands/CommandManager.java
import commands.admin.*;
import commands.classic.*;
import commands.config.*;
import commands.hidden.SendNudeCommand;
import commands.model.Command;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
package commands;
/**
* Created by steve on 20/05/2017.
*/
public class CommandManager {
private static CommandManager instance;
| private List<Command> commands; |
Kaysoro/KaellyBot | src/main/java/commands/CommandManager.java | // Path: src/main/java/commands/hidden/SendNudeCommand.java
// public class SendNudeCommand extends AbstractCommand {
//
// private static final Random RANDOM = new Random();
//
// public SendNudeCommand() {
// super("sendnude", "");
// setHidden(true);
// }
//
// @Override
// public void request(MessageCreateEvent event, Message message, Matcher m, Language lg) {
// if (message.getChannel().blockOptional().map(chan -> chan instanceof PrivateChannel).orElse(false)
// || message.getChannel().blockOptional().map(chan -> ((TextChannel) chan).isNsfw()).orElse(false)){
// int position = RANDOM.nextInt(Nude.values().length);
// Nude nude = Nude.values()[position];
//
// message.getChannel().flatMap(chan -> chan.createEmbed(spec -> spec.setTitle(Translator.getLabel(lg, "sendnude.title"))
// .setDescription(Translator.getLabel(lg, "sendnude.author")
// .replace("{author}", nude.getAuthor())
// .replace("{url}", nude.getUrl()))
// .setColor(discord4j.rest.util.Color.PINK)
// .setFooter(Translator.getLabel(lg, "sendnude.footer")
// .replace("{position}", String.valueOf(position + 1))
// .replace("{number}", String.valueOf(Nude.values().length)), null)
// .setImage(nude.getImage()))).subscribe();
// }
// else // Exception NSFW
// BasicDiscordException.NO_NSFW_CHANNEL.throwException(message, this, lg);
// }
//
// @Override
// public String help(Language lg, String prefixe) {
// return "**" + prefixe + name + "** " + Translator.getLabel(lg, "sendnude.help");
// }
//
// @Override
// public String helpDetailed(Language lg, String prefixe) {
// return help(lg, prefixe);
// }
// }
//
// Path: src/main/java/commands/model/Command.java
// public interface Command {
// String getName();
// String getPattern();
// Matcher getMatcher(Message message);
// void request(MessageCreateEvent event, Message message);
//
// /**
// * Is the command usable in MP?
// * @return True if it can be used in MP, else false.
// */
// boolean isUsableInMP();
//
// /**
// * Is the command only usable by admins ?
// * @return True if it only can be used by admin, else false.
// */
// boolean isAdmin();
//
// /**
// * Is the command available by the admin ?
// * @return true is the command is available, else false.
// */
// boolean isPublic();
//
// /**
// * is the command is hidden ?
// * @return True if the command is hidden
// */
// boolean isHidden();
//
// /**
// * Change the command scope
// * @param isPublic is command available or not
// */
// void setPublic(boolean isPublic);
//
// /**
// * Is the command available by the guild admin ?
// * @param g Guild concerned
// * @return true is the command is forbidden, else false.
// */
// boolean isForbidden(Guild g);
//
// /**
// * Change the command scope in MP
// * @param isUsableInMP is command available in MP or not
// */
// void setUsableInMP(boolean isUsableInMP);
//
// /**
// * Change the command scope for admin user
// * @param isAdmin is command only available for admins or not
// */
// void setAdmin(boolean isAdmin);
//
// /**
// * Hide or not the command
// * @param isHidden is command hidden or not
// */
// void setHidden(boolean isHidden);
//
// /**
// * @param prefixe Prefixe for command
// * @return Short description of the command
// */
// String help(Language lg, String prefixe);
//
// /**
// * @param prefixe Prefixe for command
// * @return Detailed description of the command
// */
// String helpDetailed(Language lg, String prefixe);
// }
| import commands.admin.*;
import commands.classic.*;
import commands.config.*;
import commands.hidden.SendNudeCommand;
import commands.model.Command;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList; | // Basics commands
addCommand(new AboutCommand());
addCommand(new AlignmentCommand());
addCommand(new AllianceCommand());
addCommand(new AlmanaxCommand());
addCommand(new AlmanaxAutoCommand());
addCommand(new CommandCommand());
addCommand(new DistanceCommand());
addCommand(new DonateCommand());
addCommand(new GuildCommand());
addCommand(new HelpCommand());
addCommand(new InviteCommand());
addCommand(new ItemCommand());
addCommand(new JobCommand());
addCommand(new LanguageCommand());
addCommand(new MapCommand());
addCommand(new MonsterCommand());
addCommand(new PingCommand());
addCommand(new PortalCommand());
addCommand(new PrefixCommand());
addCommand(new RandomCommand());
addCommand(new ResourceCommand());
addCommand(new RSSCommand());
addCommand(new ServerCommand());
addCommand(new SetCommand());
addCommand(new TutorialCommand());
addCommand(new TwitterCommand());
addCommand(new WhoisCommand());
// Hidden commands | // Path: src/main/java/commands/hidden/SendNudeCommand.java
// public class SendNudeCommand extends AbstractCommand {
//
// private static final Random RANDOM = new Random();
//
// public SendNudeCommand() {
// super("sendnude", "");
// setHidden(true);
// }
//
// @Override
// public void request(MessageCreateEvent event, Message message, Matcher m, Language lg) {
// if (message.getChannel().blockOptional().map(chan -> chan instanceof PrivateChannel).orElse(false)
// || message.getChannel().blockOptional().map(chan -> ((TextChannel) chan).isNsfw()).orElse(false)){
// int position = RANDOM.nextInt(Nude.values().length);
// Nude nude = Nude.values()[position];
//
// message.getChannel().flatMap(chan -> chan.createEmbed(spec -> spec.setTitle(Translator.getLabel(lg, "sendnude.title"))
// .setDescription(Translator.getLabel(lg, "sendnude.author")
// .replace("{author}", nude.getAuthor())
// .replace("{url}", nude.getUrl()))
// .setColor(discord4j.rest.util.Color.PINK)
// .setFooter(Translator.getLabel(lg, "sendnude.footer")
// .replace("{position}", String.valueOf(position + 1))
// .replace("{number}", String.valueOf(Nude.values().length)), null)
// .setImage(nude.getImage()))).subscribe();
// }
// else // Exception NSFW
// BasicDiscordException.NO_NSFW_CHANNEL.throwException(message, this, lg);
// }
//
// @Override
// public String help(Language lg, String prefixe) {
// return "**" + prefixe + name + "** " + Translator.getLabel(lg, "sendnude.help");
// }
//
// @Override
// public String helpDetailed(Language lg, String prefixe) {
// return help(lg, prefixe);
// }
// }
//
// Path: src/main/java/commands/model/Command.java
// public interface Command {
// String getName();
// String getPattern();
// Matcher getMatcher(Message message);
// void request(MessageCreateEvent event, Message message);
//
// /**
// * Is the command usable in MP?
// * @return True if it can be used in MP, else false.
// */
// boolean isUsableInMP();
//
// /**
// * Is the command only usable by admins ?
// * @return True if it only can be used by admin, else false.
// */
// boolean isAdmin();
//
// /**
// * Is the command available by the admin ?
// * @return true is the command is available, else false.
// */
// boolean isPublic();
//
// /**
// * is the command is hidden ?
// * @return True if the command is hidden
// */
// boolean isHidden();
//
// /**
// * Change the command scope
// * @param isPublic is command available or not
// */
// void setPublic(boolean isPublic);
//
// /**
// * Is the command available by the guild admin ?
// * @param g Guild concerned
// * @return true is the command is forbidden, else false.
// */
// boolean isForbidden(Guild g);
//
// /**
// * Change the command scope in MP
// * @param isUsableInMP is command available in MP or not
// */
// void setUsableInMP(boolean isUsableInMP);
//
// /**
// * Change the command scope for admin user
// * @param isAdmin is command only available for admins or not
// */
// void setAdmin(boolean isAdmin);
//
// /**
// * Hide or not the command
// * @param isHidden is command hidden or not
// */
// void setHidden(boolean isHidden);
//
// /**
// * @param prefixe Prefixe for command
// * @return Short description of the command
// */
// String help(Language lg, String prefixe);
//
// /**
// * @param prefixe Prefixe for command
// * @return Detailed description of the command
// */
// String helpDetailed(Language lg, String prefixe);
// }
// Path: src/main/java/commands/CommandManager.java
import commands.admin.*;
import commands.classic.*;
import commands.config.*;
import commands.hidden.SendNudeCommand;
import commands.model.Command;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
// Basics commands
addCommand(new AboutCommand());
addCommand(new AlignmentCommand());
addCommand(new AllianceCommand());
addCommand(new AlmanaxCommand());
addCommand(new AlmanaxAutoCommand());
addCommand(new CommandCommand());
addCommand(new DistanceCommand());
addCommand(new DonateCommand());
addCommand(new GuildCommand());
addCommand(new HelpCommand());
addCommand(new InviteCommand());
addCommand(new ItemCommand());
addCommand(new JobCommand());
addCommand(new LanguageCommand());
addCommand(new MapCommand());
addCommand(new MonsterCommand());
addCommand(new PingCommand());
addCommand(new PortalCommand());
addCommand(new PrefixCommand());
addCommand(new RandomCommand());
addCommand(new ResourceCommand());
addCommand(new RSSCommand());
addCommand(new ServerCommand());
addCommand(new SetCommand());
addCommand(new TutorialCommand());
addCommand(new TwitterCommand());
addCommand(new WhoisCommand());
// Hidden commands | addCommand(new SendNudeCommand()); |
Kaysoro/KaellyBot | src/test/java/BestMatcherTest.java | // Path: src/main/java/util/BestMatcher.java
// public class BestMatcher {
//
// private String base;
// private String[] pattern;
// private List<Requestable> bestMatches;
// private int bestPoint;
//
// public BestMatcher(String base){
// this.base = Normalizer.normalize(base.trim(), Normalizer.Form.NFD)
// .replaceAll("\\p{InCombiningDiacriticalMarks}+", "")
// .toLowerCase();
// this.pattern = this.base.split("\\s+");
// bestMatches = new ArrayList<>();
// bestPoint = 0;
// }
//
// public void evaluate(Requestable proposal){
// int points = 0;
// String key = Normalizer.normalize(proposal.getName().trim(), Normalizer.Form.NFD)
// .replaceAll("\\p{InCombiningDiacriticalMarks}+", "").toLowerCase();
//
// if (! key.equals(base)) {
// for (String base : pattern)
// if (key.contains(base))
// points++;
//
// if (points > bestPoint) {
// bestMatches.clear();
// bestMatches.add(proposal);
// bestPoint = points;
// } else if (points == bestPoint)
// bestMatches.add(proposal);
// }
// else {
// bestMatches.clear();
// bestMatches.add(proposal);
// bestPoint = Integer.MAX_VALUE;
// }
// }
//
// public void evaluateAll(List<Requestable> proposals){
// for(Requestable proposal : proposals)
// evaluate(proposal);
// }
//
// public void evaluateAll(Requestable... proposals){
// for(Requestable proposal : proposals)
// evaluate(proposal);
// }
//
// public boolean isUnique(){
// return bestMatches.size() == 1;
// }
//
// public boolean isEmpty(){
// return bestMatches.isEmpty();
// }
//
// public List<Requestable> getBests(){
// return bestMatches;
// }
//
//
// public Requestable getBest(){
// if (isUnique())
// return bestMatches.get(0);
// else
// return null;
// }
// }
//
// Path: src/main/java/util/Requestable.java
// public class Requestable {
//
// private String name;
// private String url;
//
// public Requestable(String name, String url){
// this.name = name;
// this.url = url;
// }
//
// @Override
// public String toString(){
// return name;
// }
//
// public String getName(){
// return name;
// }
//
// public String getUrl(){
// return url;
// }
// }
| import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import util.BestMatcher;
import util.Requestable;
import java.util.ArrayList;
import static org.junit.jupiter.api.Assertions.*; |
/**
* Created by steve on 08/11/2016.
*/
class BestMatcherTest {
private BestMatcher collection;
@BeforeEach
void init(){
collection = new BestMatcher("test");
}
@AfterEach
void end(){
collection = null;
}
@Test
void testEmptySize(){
assertTrue(collection.isEmpty());
assertTrue(collection.getBests().isEmpty());
assertNull(collection.getBest());
assertFalse(collection.isUnique());
}
@Test
void testOneElement(){ | // Path: src/main/java/util/BestMatcher.java
// public class BestMatcher {
//
// private String base;
// private String[] pattern;
// private List<Requestable> bestMatches;
// private int bestPoint;
//
// public BestMatcher(String base){
// this.base = Normalizer.normalize(base.trim(), Normalizer.Form.NFD)
// .replaceAll("\\p{InCombiningDiacriticalMarks}+", "")
// .toLowerCase();
// this.pattern = this.base.split("\\s+");
// bestMatches = new ArrayList<>();
// bestPoint = 0;
// }
//
// public void evaluate(Requestable proposal){
// int points = 0;
// String key = Normalizer.normalize(proposal.getName().trim(), Normalizer.Form.NFD)
// .replaceAll("\\p{InCombiningDiacriticalMarks}+", "").toLowerCase();
//
// if (! key.equals(base)) {
// for (String base : pattern)
// if (key.contains(base))
// points++;
//
// if (points > bestPoint) {
// bestMatches.clear();
// bestMatches.add(proposal);
// bestPoint = points;
// } else if (points == bestPoint)
// bestMatches.add(proposal);
// }
// else {
// bestMatches.clear();
// bestMatches.add(proposal);
// bestPoint = Integer.MAX_VALUE;
// }
// }
//
// public void evaluateAll(List<Requestable> proposals){
// for(Requestable proposal : proposals)
// evaluate(proposal);
// }
//
// public void evaluateAll(Requestable... proposals){
// for(Requestable proposal : proposals)
// evaluate(proposal);
// }
//
// public boolean isUnique(){
// return bestMatches.size() == 1;
// }
//
// public boolean isEmpty(){
// return bestMatches.isEmpty();
// }
//
// public List<Requestable> getBests(){
// return bestMatches;
// }
//
//
// public Requestable getBest(){
// if (isUnique())
// return bestMatches.get(0);
// else
// return null;
// }
// }
//
// Path: src/main/java/util/Requestable.java
// public class Requestable {
//
// private String name;
// private String url;
//
// public Requestable(String name, String url){
// this.name = name;
// this.url = url;
// }
//
// @Override
// public String toString(){
// return name;
// }
//
// public String getName(){
// return name;
// }
//
// public String getUrl(){
// return url;
// }
// }
// Path: src/test/java/BestMatcherTest.java
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import util.BestMatcher;
import util.Requestable;
import java.util.ArrayList;
import static org.junit.jupiter.api.Assertions.*;
/**
* Created by steve on 08/11/2016.
*/
class BestMatcherTest {
private BestMatcher collection;
@BeforeEach
void init(){
collection = new BestMatcher("test");
}
@AfterEach
void end(){
collection = null;
}
@Test
void testEmptySize(){
assertTrue(collection.isEmpty());
assertTrue(collection.getBests().isEmpty());
assertNull(collection.getBest());
assertFalse(collection.isUnique());
}
@Test
void testOneElement(){ | Requestable requestable = new Requestable("test", "http://test.tst"); |
Kaysoro/KaellyBot | src/main/java/commands/classic/MonsterCommand.java | // Path: src/main/java/commands/model/DofusRequestCommand.java
// public abstract class DofusRequestCommand extends AbstractCommand {
//
// protected DofusRequestCommand(String name, String pattern) {
// super(name, pattern);
// }
//
// protected List<Requestable> getListRequestableFrom(String url, Message message, DiscordException notFound){
// List<Requestable> result = new ArrayList<>();
// Language lg = Translator.getLanguageFrom(message.getChannel().block());
// try {
// Document doc = JSoupManager.getDocument(url);
// Elements elems = doc.getElementsByClass("ak-bg-odd");
// elems.addAll(doc.getElementsByClass("ak-bg-even"));
//
// for (Element element : elems)
// result.add(new Requestable(element.child(1).text(),
// element.child(1).select("a").attr("href")));
//
// } catch(IOException e){
// ExceptionManager.manageIOException(e, message, this, lg, notFound);
// return new ArrayList<>();
// } catch (Exception e) {
// ExceptionManager.manageException(e, message, this, lg);
// return new ArrayList<>();
// }
//
// return result;
// }
// }
//
// Path: src/main/java/enums/Language.java
// public enum Language {
//
// FR("Français", "FR"), EN("English", "EN"), ES("Español", "ES");
//
// private String name;
// private String abrev;
//
// Language(String name, String abrev){
// this.name = name;
// this.abrev = abrev;
// }
//
// public String getName() {
// return name;
// }
//
// public String getAbrev() {
// return abrev;
// }
//
// @Override
// public String toString(){
// return name;
// }
// }
| import commands.model.DofusRequestCommand;
import discord4j.core.event.domain.message.MessageCreateEvent;
import discord4j.core.object.entity.Message;
import enums.Language;
import exceptions.*;
import util.*;
import data.*;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.Normalizer;
import java.util.regex.Matcher; | package commands.classic;
/**
* Created by steve on 14/07/2016.
*/
public class MonsterCommand extends DofusRequestCommand {
private final static String forName = "text=";
private DiscordException tooMuchMonsters;
private DiscordException notFoundMonster;
public MonsterCommand(){
super("monster", "\\s+(-more)?(.*)");
tooMuchMonsters = new TooMuchDiscordException("monster");
notFoundMonster = new NotFoundDiscordException("monster");
}
@Override | // Path: src/main/java/commands/model/DofusRequestCommand.java
// public abstract class DofusRequestCommand extends AbstractCommand {
//
// protected DofusRequestCommand(String name, String pattern) {
// super(name, pattern);
// }
//
// protected List<Requestable> getListRequestableFrom(String url, Message message, DiscordException notFound){
// List<Requestable> result = new ArrayList<>();
// Language lg = Translator.getLanguageFrom(message.getChannel().block());
// try {
// Document doc = JSoupManager.getDocument(url);
// Elements elems = doc.getElementsByClass("ak-bg-odd");
// elems.addAll(doc.getElementsByClass("ak-bg-even"));
//
// for (Element element : elems)
// result.add(new Requestable(element.child(1).text(),
// element.child(1).select("a").attr("href")));
//
// } catch(IOException e){
// ExceptionManager.manageIOException(e, message, this, lg, notFound);
// return new ArrayList<>();
// } catch (Exception e) {
// ExceptionManager.manageException(e, message, this, lg);
// return new ArrayList<>();
// }
//
// return result;
// }
// }
//
// Path: src/main/java/enums/Language.java
// public enum Language {
//
// FR("Français", "FR"), EN("English", "EN"), ES("Español", "ES");
//
// private String name;
// private String abrev;
//
// Language(String name, String abrev){
// this.name = name;
// this.abrev = abrev;
// }
//
// public String getName() {
// return name;
// }
//
// public String getAbrev() {
// return abrev;
// }
//
// @Override
// public String toString(){
// return name;
// }
// }
// Path: src/main/java/commands/classic/MonsterCommand.java
import commands.model.DofusRequestCommand;
import discord4j.core.event.domain.message.MessageCreateEvent;
import discord4j.core.object.entity.Message;
import enums.Language;
import exceptions.*;
import util.*;
import data.*;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.Normalizer;
import java.util.regex.Matcher;
package commands.classic;
/**
* Created by steve on 14/07/2016.
*/
public class MonsterCommand extends DofusRequestCommand {
private final static String forName = "text=";
private DiscordException tooMuchMonsters;
private DiscordException notFoundMonster;
public MonsterCommand(){
super("monster", "\\s+(-more)?(.*)");
tooMuchMonsters = new TooMuchDiscordException("monster");
notFoundMonster = new NotFoundDiscordException("monster");
}
@Override | public void request(MessageCreateEvent event, Message message, Matcher m, Language lg) { |
Kaysoro/KaellyBot | src/main/java/data/Constants.java | // Path: src/main/java/enums/Game.java
// public enum Game {
//
// DOFUS("Dofus", Constants.invite),
// DOFUS_TOUCH("Dofus Touch", "https://discordapp.com/oauth2/authorize?&client_id=393925392618094612&scope=bot");
//
// private String name;
// private String botInvite;
//
// Game(String name, String botInvite){
// this.name = name;
// this.botInvite = botInvite;
// }
//
// public String getName() {
// return name;
// }
//
// public String getBotInvite(){
// return botInvite;
// }
// }
//
// Path: src/main/java/enums/Language.java
// public enum Language {
//
// FR("Français", "FR"), EN("English", "EN"), ES("Español", "ES");
//
// private String name;
// private String abrev;
//
// Language(String name, String abrev){
// this.name = name;
// this.abrev = abrev;
// }
//
// public String getName() {
// return name;
// }
//
// public String getAbrev() {
// return abrev;
// }
//
// @Override
// public String toString(){
// return name;
// }
// }
| import enums.Game;
import enums.Language; | package data;
/**
* Created by steve on 28/07/2016.
*/
public class Constants {
/**
* Application name
*/
public final static String name = "Kaelly";
/**
* Application version
*/
public final static String version = "1.6.4";
/**
* Changelog
*/
public final static String changelog = "https://raw.githubusercontent.com/KaellyBot/Kaelly-dashboard/master/public/img/kaellyFull.png";
/**
* Author id
*/
public final static long authorId = 162842827183751169L;
/**
* Author name
*/
public final static String authorName = "Kaysoro#8327";
/**
* Author avatar
*/
public final static String authorAvatar = "https://avatars0.githubusercontent.com/u/5544670?s=460&v=4";
/**
* URL for Kaelly twitter account
*/
public final static String twitterAccount = "https://twitter.com/KaellyBot";
/**
* URL for github KaellyBot repository
*/
public final static String git = "https://github.com/Kaysoro/KaellyBot";
/**
* Official link invite
*/
public final static String invite = "https://discordapp.com/oauth2/authorize?&client_id=202916641414184960&scope=bot";
/**
* Official paypal link
*/
public final static String paypal = "https://paypal.me/kaysoro";
/**
* Database name
*/
public final static String database = "bdd.sqlite";
/**
* Path to the database (can be left empty)
*/
public final static String database_path = "";
/**
* Path to the folder containing sounds (can be left empty)
*/
public final static String sound_path = "";
/**
* prefix used for command call.
* WARN : it is injected into regex expression.
* If you use special characters as '$', don't forget to prefix it with '\\' like this : "\\$"
*/
public final static String prefixCommand = "!";
| // Path: src/main/java/enums/Game.java
// public enum Game {
//
// DOFUS("Dofus", Constants.invite),
// DOFUS_TOUCH("Dofus Touch", "https://discordapp.com/oauth2/authorize?&client_id=393925392618094612&scope=bot");
//
// private String name;
// private String botInvite;
//
// Game(String name, String botInvite){
// this.name = name;
// this.botInvite = botInvite;
// }
//
// public String getName() {
// return name;
// }
//
// public String getBotInvite(){
// return botInvite;
// }
// }
//
// Path: src/main/java/enums/Language.java
// public enum Language {
//
// FR("Français", "FR"), EN("English", "EN"), ES("Español", "ES");
//
// private String name;
// private String abrev;
//
// Language(String name, String abrev){
// this.name = name;
// this.abrev = abrev;
// }
//
// public String getName() {
// return name;
// }
//
// public String getAbrev() {
// return abrev;
// }
//
// @Override
// public String toString(){
// return name;
// }
// }
// Path: src/main/java/data/Constants.java
import enums.Game;
import enums.Language;
package data;
/**
* Created by steve on 28/07/2016.
*/
public class Constants {
/**
* Application name
*/
public final static String name = "Kaelly";
/**
* Application version
*/
public final static String version = "1.6.4";
/**
* Changelog
*/
public final static String changelog = "https://raw.githubusercontent.com/KaellyBot/Kaelly-dashboard/master/public/img/kaellyFull.png";
/**
* Author id
*/
public final static long authorId = 162842827183751169L;
/**
* Author name
*/
public final static String authorName = "Kaysoro#8327";
/**
* Author avatar
*/
public final static String authorAvatar = "https://avatars0.githubusercontent.com/u/5544670?s=460&v=4";
/**
* URL for Kaelly twitter account
*/
public final static String twitterAccount = "https://twitter.com/KaellyBot";
/**
* URL for github KaellyBot repository
*/
public final static String git = "https://github.com/Kaysoro/KaellyBot";
/**
* Official link invite
*/
public final static String invite = "https://discordapp.com/oauth2/authorize?&client_id=202916641414184960&scope=bot";
/**
* Official paypal link
*/
public final static String paypal = "https://paypal.me/kaysoro";
/**
* Database name
*/
public final static String database = "bdd.sqlite";
/**
* Path to the database (can be left empty)
*/
public final static String database_path = "";
/**
* Path to the folder containing sounds (can be left empty)
*/
public final static String sound_path = "";
/**
* prefix used for command call.
* WARN : it is injected into regex expression.
* If you use special characters as '$', don't forget to prefix it with '\\' like this : "\\$"
*/
public final static String prefixCommand = "!";
| public final static Language defaultLanguage = Language.FR; |
Kaysoro/KaellyBot | src/main/java/data/Constants.java | // Path: src/main/java/enums/Game.java
// public enum Game {
//
// DOFUS("Dofus", Constants.invite),
// DOFUS_TOUCH("Dofus Touch", "https://discordapp.com/oauth2/authorize?&client_id=393925392618094612&scope=bot");
//
// private String name;
// private String botInvite;
//
// Game(String name, String botInvite){
// this.name = name;
// this.botInvite = botInvite;
// }
//
// public String getName() {
// return name;
// }
//
// public String getBotInvite(){
// return botInvite;
// }
// }
//
// Path: src/main/java/enums/Language.java
// public enum Language {
//
// FR("Français", "FR"), EN("English", "EN"), ES("Español", "ES");
//
// private String name;
// private String abrev;
//
// Language(String name, String abrev){
// this.name = name;
// this.abrev = abrev;
// }
//
// public String getName() {
// return name;
// }
//
// public String getAbrev() {
// return abrev;
// }
//
// @Override
// public String toString(){
// return name;
// }
// }
| import enums.Game;
import enums.Language; | package data;
/**
* Created by steve on 28/07/2016.
*/
public class Constants {
/**
* Application name
*/
public final static String name = "Kaelly";
/**
* Application version
*/
public final static String version = "1.6.4";
/**
* Changelog
*/
public final static String changelog = "https://raw.githubusercontent.com/KaellyBot/Kaelly-dashboard/master/public/img/kaellyFull.png";
/**
* Author id
*/
public final static long authorId = 162842827183751169L;
/**
* Author name
*/
public final static String authorName = "Kaysoro#8327";
/**
* Author avatar
*/
public final static String authorAvatar = "https://avatars0.githubusercontent.com/u/5544670?s=460&v=4";
/**
* URL for Kaelly twitter account
*/
public final static String twitterAccount = "https://twitter.com/KaellyBot";
/**
* URL for github KaellyBot repository
*/
public final static String git = "https://github.com/Kaysoro/KaellyBot";
/**
* Official link invite
*/
public final static String invite = "https://discordapp.com/oauth2/authorize?&client_id=202916641414184960&scope=bot";
/**
* Official paypal link
*/
public final static String paypal = "https://paypal.me/kaysoro";
/**
* Database name
*/
public final static String database = "bdd.sqlite";
/**
* Path to the database (can be left empty)
*/
public final static String database_path = "";
/**
* Path to the folder containing sounds (can be left empty)
*/
public final static String sound_path = "";
/**
* prefix used for command call.
* WARN : it is injected into regex expression.
* If you use special characters as '$', don't forget to prefix it with '\\' like this : "\\$"
*/
public final static String prefixCommand = "!";
public final static Language defaultLanguage = Language.FR;
/**
* Game desserved
*/ | // Path: src/main/java/enums/Game.java
// public enum Game {
//
// DOFUS("Dofus", Constants.invite),
// DOFUS_TOUCH("Dofus Touch", "https://discordapp.com/oauth2/authorize?&client_id=393925392618094612&scope=bot");
//
// private String name;
// private String botInvite;
//
// Game(String name, String botInvite){
// this.name = name;
// this.botInvite = botInvite;
// }
//
// public String getName() {
// return name;
// }
//
// public String getBotInvite(){
// return botInvite;
// }
// }
//
// Path: src/main/java/enums/Language.java
// public enum Language {
//
// FR("Français", "FR"), EN("English", "EN"), ES("Español", "ES");
//
// private String name;
// private String abrev;
//
// Language(String name, String abrev){
// this.name = name;
// this.abrev = abrev;
// }
//
// public String getName() {
// return name;
// }
//
// public String getAbrev() {
// return abrev;
// }
//
// @Override
// public String toString(){
// return name;
// }
// }
// Path: src/main/java/data/Constants.java
import enums.Game;
import enums.Language;
package data;
/**
* Created by steve on 28/07/2016.
*/
public class Constants {
/**
* Application name
*/
public final static String name = "Kaelly";
/**
* Application version
*/
public final static String version = "1.6.4";
/**
* Changelog
*/
public final static String changelog = "https://raw.githubusercontent.com/KaellyBot/Kaelly-dashboard/master/public/img/kaellyFull.png";
/**
* Author id
*/
public final static long authorId = 162842827183751169L;
/**
* Author name
*/
public final static String authorName = "Kaysoro#8327";
/**
* Author avatar
*/
public final static String authorAvatar = "https://avatars0.githubusercontent.com/u/5544670?s=460&v=4";
/**
* URL for Kaelly twitter account
*/
public final static String twitterAccount = "https://twitter.com/KaellyBot";
/**
* URL for github KaellyBot repository
*/
public final static String git = "https://github.com/Kaysoro/KaellyBot";
/**
* Official link invite
*/
public final static String invite = "https://discordapp.com/oauth2/authorize?&client_id=202916641414184960&scope=bot";
/**
* Official paypal link
*/
public final static String paypal = "https://paypal.me/kaysoro";
/**
* Database name
*/
public final static String database = "bdd.sqlite";
/**
* Path to the database (can be left empty)
*/
public final static String database_path = "";
/**
* Path to the folder containing sounds (can be left empty)
*/
public final static String sound_path = "";
/**
* prefix used for command call.
* WARN : it is injected into regex expression.
* If you use special characters as '$', don't forget to prefix it with '\\' like this : "\\$"
*/
public final static String prefixCommand = "!";
public final static Language defaultLanguage = Language.FR;
/**
* Game desserved
*/ | public final static Game game = Game.DOFUS; |
Kaysoro/KaellyBot | src/main/java/finders/RSSFinder.java | // Path: src/main/java/data/RSS.java
// public class RSS implements Comparable<RSS>, Embedded {
//
// private final static Logger LOG = LoggerFactory.getLogger(RSS.class);
// private final static DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy à HH:mm", Locale.FRANCE);
//
// private String title;
// private String url;
// private String imageUrl;
// private long date;
//
// private RSS(String title, String url, String imageUrl, long date) {
// this.title = title;
// this.url = url;
// if (imageUrl != null && !imageUrl.isEmpty())
// this.imageUrl = imageUrl;
// else
// this.imageUrl = Constants.officialLogo;
// this.date = date;
// }
//
// public static List<RSS> getRSSFeeds(Language lg){
// List<RSS> rss = new ArrayList<>();
//
// try {
// SyndFeedInput input = new SyndFeedInput();
// SyndFeed feed = input.build(new XmlReader(new URL(Translator.getLabel(lg, "game.url")
// + Translator.getLabel(lg, "feed.url"))));
//
// for(SyndEntry entry : feed.getEntries()) {
// Matcher m = Pattern.compile("<img.+src=\"(.*\\.jpg)\".+>").matcher(entry.getDescription().getValue());
// rss.add(new RSS(entry.getTitle(), entry.getLink(), (m.find()? m.group(1) : null),
// entry.getPublishedDate().getTime()));
// }
// } catch (FeedException e){
// Reporter.report(e);
// LOG.error("getRSSFeeds", e);
// } catch(IOException e){
// ExceptionManager.manageSilentlyIOException(e);
// } catch(Exception e){
// ExceptionManager.manageSilentlyException(e);
// }
// Collections.sort(rss);
// return rss;
// }
//
// public String getTitle() {
// return title;
// }
//
// public String getUrl() {
// return url;
// }
//
// public long getDate() {
// return date;
// }
//
// public String toStringDiscord(){
// return getTitle() + " (" + dateFormat.format(new Date(getDate())) + ")\n" + getUrl();
// }
//
// @Override
// public String toString(){
// return getTitle() + " (" + dateFormat.format(new Date(getDate())) + ")\n";
// }
//
// @Override
// public int compareTo(RSS o) {
// return (int) (getDate() - o.getDate());
// }
//
// @Override
// public EmbedCreateSpec decorateEmbedObject(Language lg) {
// return EmbedCreateSpec.builder()
// .author("Dofus.com", getUrl(), null)
// .title(getTitle())
// .image(imageUrl)
// .thumbnail(Constants.rssIcon)
// .footer(dateFormat.format(new Date(getDate())), null)
// .build();
// }
//
// public EmbedData decorateRestEmbedObject(Language lg) {
// return EmbedData.builder()
// .author(EmbedAuthorData.builder().name("Dofus.com").url(getUrl()).build())
// .title(getTitle())
// .image(EmbedImageData.builder().url(imageUrl).build())
// .thumbnail(EmbedThumbnailData.builder().url(Constants.rssIcon).build())
// .footer(EmbedFooterData.builder().text(dateFormat.format(new Date(getDate()))).build())
// .build();
// }
//
// @Override
// public EmbedCreateSpec decorateMoreEmbedObject(Language lg) {
// return decorateEmbedObject(lg);
// }
// }
//
// Path: src/main/java/enums/Language.java
// public enum Language {
//
// FR("Français", "FR"), EN("English", "EN"), ES("Español", "ES");
//
// private String name;
// private String abrev;
//
// Language(String name, String abrev){
// this.name = name;
// this.abrev = abrev;
// }
//
// public String getName() {
// return name;
// }
//
// public String getAbrev() {
// return abrev;
// }
//
// @Override
// public String toString(){
// return name;
// }
// }
| import data.RSS;
import discord4j.common.util.Snowflake;
import discord4j.rest.entity.RestChannel;
import discord4j.rest.http.client.ClientException;
import enums.Language;
import util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit; | if (rssFinders == null){
rssFinders = new ConcurrentHashMap<>();
Connexion connexion = Connexion.getInstance();
Connection connection = connexion.getConnection();
try {
PreparedStatement query = connection.prepareStatement("SELECT id_guild, id_chan, last_update FROM RSS_Finder");
ResultSet resultSet = query.executeQuery();
while (resultSet.next()){
String idChan = resultSet.getString("id_chan");
String idGuild = resultSet.getString("id_guild");
long lastUpdate = resultSet.getLong("last_update");
rssFinders.put(idChan, new RSSFinder(idGuild, idChan, lastUpdate));
}
} catch (SQLException e) {
Reporter.report(e);
LOG.error("getRSSFinders", e);
}
}
return rssFinders;
}
public static void start(){
if (!isStarted) {
isStarted = true;
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
scheduler.scheduleAtFixedRate(() -> { | // Path: src/main/java/data/RSS.java
// public class RSS implements Comparable<RSS>, Embedded {
//
// private final static Logger LOG = LoggerFactory.getLogger(RSS.class);
// private final static DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy à HH:mm", Locale.FRANCE);
//
// private String title;
// private String url;
// private String imageUrl;
// private long date;
//
// private RSS(String title, String url, String imageUrl, long date) {
// this.title = title;
// this.url = url;
// if (imageUrl != null && !imageUrl.isEmpty())
// this.imageUrl = imageUrl;
// else
// this.imageUrl = Constants.officialLogo;
// this.date = date;
// }
//
// public static List<RSS> getRSSFeeds(Language lg){
// List<RSS> rss = new ArrayList<>();
//
// try {
// SyndFeedInput input = new SyndFeedInput();
// SyndFeed feed = input.build(new XmlReader(new URL(Translator.getLabel(lg, "game.url")
// + Translator.getLabel(lg, "feed.url"))));
//
// for(SyndEntry entry : feed.getEntries()) {
// Matcher m = Pattern.compile("<img.+src=\"(.*\\.jpg)\".+>").matcher(entry.getDescription().getValue());
// rss.add(new RSS(entry.getTitle(), entry.getLink(), (m.find()? m.group(1) : null),
// entry.getPublishedDate().getTime()));
// }
// } catch (FeedException e){
// Reporter.report(e);
// LOG.error("getRSSFeeds", e);
// } catch(IOException e){
// ExceptionManager.manageSilentlyIOException(e);
// } catch(Exception e){
// ExceptionManager.manageSilentlyException(e);
// }
// Collections.sort(rss);
// return rss;
// }
//
// public String getTitle() {
// return title;
// }
//
// public String getUrl() {
// return url;
// }
//
// public long getDate() {
// return date;
// }
//
// public String toStringDiscord(){
// return getTitle() + " (" + dateFormat.format(new Date(getDate())) + ")\n" + getUrl();
// }
//
// @Override
// public String toString(){
// return getTitle() + " (" + dateFormat.format(new Date(getDate())) + ")\n";
// }
//
// @Override
// public int compareTo(RSS o) {
// return (int) (getDate() - o.getDate());
// }
//
// @Override
// public EmbedCreateSpec decorateEmbedObject(Language lg) {
// return EmbedCreateSpec.builder()
// .author("Dofus.com", getUrl(), null)
// .title(getTitle())
// .image(imageUrl)
// .thumbnail(Constants.rssIcon)
// .footer(dateFormat.format(new Date(getDate())), null)
// .build();
// }
//
// public EmbedData decorateRestEmbedObject(Language lg) {
// return EmbedData.builder()
// .author(EmbedAuthorData.builder().name("Dofus.com").url(getUrl()).build())
// .title(getTitle())
// .image(EmbedImageData.builder().url(imageUrl).build())
// .thumbnail(EmbedThumbnailData.builder().url(Constants.rssIcon).build())
// .footer(EmbedFooterData.builder().text(dateFormat.format(new Date(getDate()))).build())
// .build();
// }
//
// @Override
// public EmbedCreateSpec decorateMoreEmbedObject(Language lg) {
// return decorateEmbedObject(lg);
// }
// }
//
// Path: src/main/java/enums/Language.java
// public enum Language {
//
// FR("Français", "FR"), EN("English", "EN"), ES("Español", "ES");
//
// private String name;
// private String abrev;
//
// Language(String name, String abrev){
// this.name = name;
// this.abrev = abrev;
// }
//
// public String getName() {
// return name;
// }
//
// public String getAbrev() {
// return abrev;
// }
//
// @Override
// public String toString(){
// return name;
// }
// }
// Path: src/main/java/finders/RSSFinder.java
import data.RSS;
import discord4j.common.util.Snowflake;
import discord4j.rest.entity.RestChannel;
import discord4j.rest.http.client.ClientException;
import enums.Language;
import util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
if (rssFinders == null){
rssFinders = new ConcurrentHashMap<>();
Connexion connexion = Connexion.getInstance();
Connection connection = connexion.getConnection();
try {
PreparedStatement query = connection.prepareStatement("SELECT id_guild, id_chan, last_update FROM RSS_Finder");
ResultSet resultSet = query.executeQuery();
while (resultSet.next()){
String idChan = resultSet.getString("id_chan");
String idGuild = resultSet.getString("id_guild");
long lastUpdate = resultSet.getLong("last_update");
rssFinders.put(idChan, new RSSFinder(idGuild, idChan, lastUpdate));
}
} catch (SQLException e) {
Reporter.report(e);
LOG.error("getRSSFinders", e);
}
}
return rssFinders;
}
public static void start(){
if (!isStarted) {
isStarted = true;
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
scheduler.scheduleAtFixedRate(() -> { | Map<Language, List<RSS>> allFeeds = new HashMap<>(); |
Kaysoro/KaellyBot | src/main/java/finders/RSSFinder.java | // Path: src/main/java/data/RSS.java
// public class RSS implements Comparable<RSS>, Embedded {
//
// private final static Logger LOG = LoggerFactory.getLogger(RSS.class);
// private final static DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy à HH:mm", Locale.FRANCE);
//
// private String title;
// private String url;
// private String imageUrl;
// private long date;
//
// private RSS(String title, String url, String imageUrl, long date) {
// this.title = title;
// this.url = url;
// if (imageUrl != null && !imageUrl.isEmpty())
// this.imageUrl = imageUrl;
// else
// this.imageUrl = Constants.officialLogo;
// this.date = date;
// }
//
// public static List<RSS> getRSSFeeds(Language lg){
// List<RSS> rss = new ArrayList<>();
//
// try {
// SyndFeedInput input = new SyndFeedInput();
// SyndFeed feed = input.build(new XmlReader(new URL(Translator.getLabel(lg, "game.url")
// + Translator.getLabel(lg, "feed.url"))));
//
// for(SyndEntry entry : feed.getEntries()) {
// Matcher m = Pattern.compile("<img.+src=\"(.*\\.jpg)\".+>").matcher(entry.getDescription().getValue());
// rss.add(new RSS(entry.getTitle(), entry.getLink(), (m.find()? m.group(1) : null),
// entry.getPublishedDate().getTime()));
// }
// } catch (FeedException e){
// Reporter.report(e);
// LOG.error("getRSSFeeds", e);
// } catch(IOException e){
// ExceptionManager.manageSilentlyIOException(e);
// } catch(Exception e){
// ExceptionManager.manageSilentlyException(e);
// }
// Collections.sort(rss);
// return rss;
// }
//
// public String getTitle() {
// return title;
// }
//
// public String getUrl() {
// return url;
// }
//
// public long getDate() {
// return date;
// }
//
// public String toStringDiscord(){
// return getTitle() + " (" + dateFormat.format(new Date(getDate())) + ")\n" + getUrl();
// }
//
// @Override
// public String toString(){
// return getTitle() + " (" + dateFormat.format(new Date(getDate())) + ")\n";
// }
//
// @Override
// public int compareTo(RSS o) {
// return (int) (getDate() - o.getDate());
// }
//
// @Override
// public EmbedCreateSpec decorateEmbedObject(Language lg) {
// return EmbedCreateSpec.builder()
// .author("Dofus.com", getUrl(), null)
// .title(getTitle())
// .image(imageUrl)
// .thumbnail(Constants.rssIcon)
// .footer(dateFormat.format(new Date(getDate())), null)
// .build();
// }
//
// public EmbedData decorateRestEmbedObject(Language lg) {
// return EmbedData.builder()
// .author(EmbedAuthorData.builder().name("Dofus.com").url(getUrl()).build())
// .title(getTitle())
// .image(EmbedImageData.builder().url(imageUrl).build())
// .thumbnail(EmbedThumbnailData.builder().url(Constants.rssIcon).build())
// .footer(EmbedFooterData.builder().text(dateFormat.format(new Date(getDate()))).build())
// .build();
// }
//
// @Override
// public EmbedCreateSpec decorateMoreEmbedObject(Language lg) {
// return decorateEmbedObject(lg);
// }
// }
//
// Path: src/main/java/enums/Language.java
// public enum Language {
//
// FR("Français", "FR"), EN("English", "EN"), ES("Español", "ES");
//
// private String name;
// private String abrev;
//
// Language(String name, String abrev){
// this.name = name;
// this.abrev = abrev;
// }
//
// public String getName() {
// return name;
// }
//
// public String getAbrev() {
// return abrev;
// }
//
// @Override
// public String toString(){
// return name;
// }
// }
| import data.RSS;
import discord4j.common.util.Snowflake;
import discord4j.rest.entity.RestChannel;
import discord4j.rest.http.client.ClientException;
import enums.Language;
import util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit; | if (rssFinders == null){
rssFinders = new ConcurrentHashMap<>();
Connexion connexion = Connexion.getInstance();
Connection connection = connexion.getConnection();
try {
PreparedStatement query = connection.prepareStatement("SELECT id_guild, id_chan, last_update FROM RSS_Finder");
ResultSet resultSet = query.executeQuery();
while (resultSet.next()){
String idChan = resultSet.getString("id_chan");
String idGuild = resultSet.getString("id_guild");
long lastUpdate = resultSet.getLong("last_update");
rssFinders.put(idChan, new RSSFinder(idGuild, idChan, lastUpdate));
}
} catch (SQLException e) {
Reporter.report(e);
LOG.error("getRSSFinders", e);
}
}
return rssFinders;
}
public static void start(){
if (!isStarted) {
isStarted = true;
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
scheduler.scheduleAtFixedRate(() -> { | // Path: src/main/java/data/RSS.java
// public class RSS implements Comparable<RSS>, Embedded {
//
// private final static Logger LOG = LoggerFactory.getLogger(RSS.class);
// private final static DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy à HH:mm", Locale.FRANCE);
//
// private String title;
// private String url;
// private String imageUrl;
// private long date;
//
// private RSS(String title, String url, String imageUrl, long date) {
// this.title = title;
// this.url = url;
// if (imageUrl != null && !imageUrl.isEmpty())
// this.imageUrl = imageUrl;
// else
// this.imageUrl = Constants.officialLogo;
// this.date = date;
// }
//
// public static List<RSS> getRSSFeeds(Language lg){
// List<RSS> rss = new ArrayList<>();
//
// try {
// SyndFeedInput input = new SyndFeedInput();
// SyndFeed feed = input.build(new XmlReader(new URL(Translator.getLabel(lg, "game.url")
// + Translator.getLabel(lg, "feed.url"))));
//
// for(SyndEntry entry : feed.getEntries()) {
// Matcher m = Pattern.compile("<img.+src=\"(.*\\.jpg)\".+>").matcher(entry.getDescription().getValue());
// rss.add(new RSS(entry.getTitle(), entry.getLink(), (m.find()? m.group(1) : null),
// entry.getPublishedDate().getTime()));
// }
// } catch (FeedException e){
// Reporter.report(e);
// LOG.error("getRSSFeeds", e);
// } catch(IOException e){
// ExceptionManager.manageSilentlyIOException(e);
// } catch(Exception e){
// ExceptionManager.manageSilentlyException(e);
// }
// Collections.sort(rss);
// return rss;
// }
//
// public String getTitle() {
// return title;
// }
//
// public String getUrl() {
// return url;
// }
//
// public long getDate() {
// return date;
// }
//
// public String toStringDiscord(){
// return getTitle() + " (" + dateFormat.format(new Date(getDate())) + ")\n" + getUrl();
// }
//
// @Override
// public String toString(){
// return getTitle() + " (" + dateFormat.format(new Date(getDate())) + ")\n";
// }
//
// @Override
// public int compareTo(RSS o) {
// return (int) (getDate() - o.getDate());
// }
//
// @Override
// public EmbedCreateSpec decorateEmbedObject(Language lg) {
// return EmbedCreateSpec.builder()
// .author("Dofus.com", getUrl(), null)
// .title(getTitle())
// .image(imageUrl)
// .thumbnail(Constants.rssIcon)
// .footer(dateFormat.format(new Date(getDate())), null)
// .build();
// }
//
// public EmbedData decorateRestEmbedObject(Language lg) {
// return EmbedData.builder()
// .author(EmbedAuthorData.builder().name("Dofus.com").url(getUrl()).build())
// .title(getTitle())
// .image(EmbedImageData.builder().url(imageUrl).build())
// .thumbnail(EmbedThumbnailData.builder().url(Constants.rssIcon).build())
// .footer(EmbedFooterData.builder().text(dateFormat.format(new Date(getDate()))).build())
// .build();
// }
//
// @Override
// public EmbedCreateSpec decorateMoreEmbedObject(Language lg) {
// return decorateEmbedObject(lg);
// }
// }
//
// Path: src/main/java/enums/Language.java
// public enum Language {
//
// FR("Français", "FR"), EN("English", "EN"), ES("Español", "ES");
//
// private String name;
// private String abrev;
//
// Language(String name, String abrev){
// this.name = name;
// this.abrev = abrev;
// }
//
// public String getName() {
// return name;
// }
//
// public String getAbrev() {
// return abrev;
// }
//
// @Override
// public String toString(){
// return name;
// }
// }
// Path: src/main/java/finders/RSSFinder.java
import data.RSS;
import discord4j.common.util.Snowflake;
import discord4j.rest.entity.RestChannel;
import discord4j.rest.http.client.ClientException;
import enums.Language;
import util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
if (rssFinders == null){
rssFinders = new ConcurrentHashMap<>();
Connexion connexion = Connexion.getInstance();
Connection connection = connexion.getConnection();
try {
PreparedStatement query = connection.prepareStatement("SELECT id_guild, id_chan, last_update FROM RSS_Finder");
ResultSet resultSet = query.executeQuery();
while (resultSet.next()){
String idChan = resultSet.getString("id_chan");
String idGuild = resultSet.getString("id_guild");
long lastUpdate = resultSet.getLong("last_update");
rssFinders.put(idChan, new RSSFinder(idGuild, idChan, lastUpdate));
}
} catch (SQLException e) {
Reporter.report(e);
LOG.error("getRSSFinders", e);
}
}
return rssFinders;
}
public static void start(){
if (!isStarted) {
isStarted = true;
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
scheduler.scheduleAtFixedRate(() -> { | Map<Language, List<RSS>> allFeeds = new HashMap<>(); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.