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
|
|---|---|---|---|---|---|---|
Steppschuh/Java-Markdown-Generator
|
Source/MarkdownGenerator/src/test/java/net/steppschuh/markdowngenerator/text/emphasis/StrikeThroughTextTest.java
|
// Path: Source/MarkdownGenerator/src/test/java/net/steppschuh/markdowngenerator/DummyObject.java
// public class DummyObject implements MarkdownSerializable {
//
// private Object foo;
// private String bar;
// private int baz;
//
// public DummyObject() {
// this.foo = true;
// this.bar = "qux";
// this.baz = 1337;
// }
//
// public DummyObject(Object foo, String bar, int baz) {
// this.foo = foo;
// this.bar = bar;
// this.baz = baz;
// }
//
// public TableRow toMarkdownTableRow() {
// return new TableRow<>(Arrays.asList(
// foo, bar, baz
// ));
// }
//
// @Override
// public MarkdownElement toMarkdownElement() throws MarkdownSerializationException {
// return toMarkdownTableRow();
// }
//
// @Override
// public String toString() {
// try {
// return toMarkdownElement().toString();
// } catch (MarkdownSerializationException e) {
// return this.getClass().getSimpleName();
// }
// }
//
// public Object getFoo() {
// return foo;
// }
//
// public String getBar() {
// return bar;
// }
//
// public int getBaz() {
// return baz;
// }
// }
//
// Path: Source/MarkdownGenerator/src/main/java/net/steppschuh/markdowngenerator/text/Text.java
// public class Text extends MarkdownElement implements MarkdownCascadable {
//
// protected Object value;
//
// public Text(Object value) {
// this.value = value;
// }
//
// @Override
// public String serialize() throws MarkdownSerializationException {
// if (value == null) {
// throw new MarkdownSerializationException("Value is null");
// }
// return getPredecessor() + value.toString() + getSuccessor();
// }
//
// @Override
// public String getPredecessor() {
// return "";
// }
//
// @Override
// public String getSuccessor() {
// return getPredecessor();
// }
//
// public Object getValue() {
// return value;
// }
//
// public void setValue(Object value) {
// this.value = value;
// invalidateSerialized();
// }
//
// }
//
// Path: Source/MarkdownGenerator/src/main/java/net/steppschuh/markdowngenerator/text/emphasis/StrikeThroughText.java
// public class StrikeThroughText extends Text {
//
// public StrikeThroughText(Object value) {
// super(value);
// }
//
// @Override
// public String getPredecessor() {
// return "~~";
// }
//
// }
|
import net.steppschuh.markdowngenerator.DummyObject;
import net.steppschuh.markdowngenerator.text.Text;
import net.steppschuh.markdowngenerator.text.emphasis.StrikeThroughText;
import org.junit.Test;
|
package net.steppschuh.markdowngenerator.text.emphasis;
/**
* Created by steppschuh on 15/12/2016.
*/
public class StrikeThroughTextTest {
@Test
public void example1() throws Exception {
|
// Path: Source/MarkdownGenerator/src/test/java/net/steppschuh/markdowngenerator/DummyObject.java
// public class DummyObject implements MarkdownSerializable {
//
// private Object foo;
// private String bar;
// private int baz;
//
// public DummyObject() {
// this.foo = true;
// this.bar = "qux";
// this.baz = 1337;
// }
//
// public DummyObject(Object foo, String bar, int baz) {
// this.foo = foo;
// this.bar = bar;
// this.baz = baz;
// }
//
// public TableRow toMarkdownTableRow() {
// return new TableRow<>(Arrays.asList(
// foo, bar, baz
// ));
// }
//
// @Override
// public MarkdownElement toMarkdownElement() throws MarkdownSerializationException {
// return toMarkdownTableRow();
// }
//
// @Override
// public String toString() {
// try {
// return toMarkdownElement().toString();
// } catch (MarkdownSerializationException e) {
// return this.getClass().getSimpleName();
// }
// }
//
// public Object getFoo() {
// return foo;
// }
//
// public String getBar() {
// return bar;
// }
//
// public int getBaz() {
// return baz;
// }
// }
//
// Path: Source/MarkdownGenerator/src/main/java/net/steppschuh/markdowngenerator/text/Text.java
// public class Text extends MarkdownElement implements MarkdownCascadable {
//
// protected Object value;
//
// public Text(Object value) {
// this.value = value;
// }
//
// @Override
// public String serialize() throws MarkdownSerializationException {
// if (value == null) {
// throw new MarkdownSerializationException("Value is null");
// }
// return getPredecessor() + value.toString() + getSuccessor();
// }
//
// @Override
// public String getPredecessor() {
// return "";
// }
//
// @Override
// public String getSuccessor() {
// return getPredecessor();
// }
//
// public Object getValue() {
// return value;
// }
//
// public void setValue(Object value) {
// this.value = value;
// invalidateSerialized();
// }
//
// }
//
// Path: Source/MarkdownGenerator/src/main/java/net/steppschuh/markdowngenerator/text/emphasis/StrikeThroughText.java
// public class StrikeThroughText extends Text {
//
// public StrikeThroughText(Object value) {
// super(value);
// }
//
// @Override
// public String getPredecessor() {
// return "~~";
// }
//
// }
// Path: Source/MarkdownGenerator/src/test/java/net/steppschuh/markdowngenerator/text/emphasis/StrikeThroughTextTest.java
import net.steppschuh.markdowngenerator.DummyObject;
import net.steppschuh.markdowngenerator.text.Text;
import net.steppschuh.markdowngenerator.text.emphasis.StrikeThroughText;
import org.junit.Test;
package net.steppschuh.markdowngenerator.text.emphasis;
/**
* Created by steppschuh on 15/12/2016.
*/
public class StrikeThroughTextTest {
@Test
public void example1() throws Exception {
|
Text text = new StrikeThroughText("I am strike-through text");
|
Steppschuh/Java-Markdown-Generator
|
Source/MarkdownGenerator/src/test/java/net/steppschuh/markdowngenerator/text/emphasis/StrikeThroughTextTest.java
|
// Path: Source/MarkdownGenerator/src/test/java/net/steppschuh/markdowngenerator/DummyObject.java
// public class DummyObject implements MarkdownSerializable {
//
// private Object foo;
// private String bar;
// private int baz;
//
// public DummyObject() {
// this.foo = true;
// this.bar = "qux";
// this.baz = 1337;
// }
//
// public DummyObject(Object foo, String bar, int baz) {
// this.foo = foo;
// this.bar = bar;
// this.baz = baz;
// }
//
// public TableRow toMarkdownTableRow() {
// return new TableRow<>(Arrays.asList(
// foo, bar, baz
// ));
// }
//
// @Override
// public MarkdownElement toMarkdownElement() throws MarkdownSerializationException {
// return toMarkdownTableRow();
// }
//
// @Override
// public String toString() {
// try {
// return toMarkdownElement().toString();
// } catch (MarkdownSerializationException e) {
// return this.getClass().getSimpleName();
// }
// }
//
// public Object getFoo() {
// return foo;
// }
//
// public String getBar() {
// return bar;
// }
//
// public int getBaz() {
// return baz;
// }
// }
//
// Path: Source/MarkdownGenerator/src/main/java/net/steppschuh/markdowngenerator/text/Text.java
// public class Text extends MarkdownElement implements MarkdownCascadable {
//
// protected Object value;
//
// public Text(Object value) {
// this.value = value;
// }
//
// @Override
// public String serialize() throws MarkdownSerializationException {
// if (value == null) {
// throw new MarkdownSerializationException("Value is null");
// }
// return getPredecessor() + value.toString() + getSuccessor();
// }
//
// @Override
// public String getPredecessor() {
// return "";
// }
//
// @Override
// public String getSuccessor() {
// return getPredecessor();
// }
//
// public Object getValue() {
// return value;
// }
//
// public void setValue(Object value) {
// this.value = value;
// invalidateSerialized();
// }
//
// }
//
// Path: Source/MarkdownGenerator/src/main/java/net/steppschuh/markdowngenerator/text/emphasis/StrikeThroughText.java
// public class StrikeThroughText extends Text {
//
// public StrikeThroughText(Object value) {
// super(value);
// }
//
// @Override
// public String getPredecessor() {
// return "~~";
// }
//
// }
|
import net.steppschuh.markdowngenerator.DummyObject;
import net.steppschuh.markdowngenerator.text.Text;
import net.steppschuh.markdowngenerator.text.emphasis.StrikeThroughText;
import org.junit.Test;
|
package net.steppschuh.markdowngenerator.text.emphasis;
/**
* Created by steppschuh on 15/12/2016.
*/
public class StrikeThroughTextTest {
@Test
public void example1() throws Exception {
|
// Path: Source/MarkdownGenerator/src/test/java/net/steppschuh/markdowngenerator/DummyObject.java
// public class DummyObject implements MarkdownSerializable {
//
// private Object foo;
// private String bar;
// private int baz;
//
// public DummyObject() {
// this.foo = true;
// this.bar = "qux";
// this.baz = 1337;
// }
//
// public DummyObject(Object foo, String bar, int baz) {
// this.foo = foo;
// this.bar = bar;
// this.baz = baz;
// }
//
// public TableRow toMarkdownTableRow() {
// return new TableRow<>(Arrays.asList(
// foo, bar, baz
// ));
// }
//
// @Override
// public MarkdownElement toMarkdownElement() throws MarkdownSerializationException {
// return toMarkdownTableRow();
// }
//
// @Override
// public String toString() {
// try {
// return toMarkdownElement().toString();
// } catch (MarkdownSerializationException e) {
// return this.getClass().getSimpleName();
// }
// }
//
// public Object getFoo() {
// return foo;
// }
//
// public String getBar() {
// return bar;
// }
//
// public int getBaz() {
// return baz;
// }
// }
//
// Path: Source/MarkdownGenerator/src/main/java/net/steppschuh/markdowngenerator/text/Text.java
// public class Text extends MarkdownElement implements MarkdownCascadable {
//
// protected Object value;
//
// public Text(Object value) {
// this.value = value;
// }
//
// @Override
// public String serialize() throws MarkdownSerializationException {
// if (value == null) {
// throw new MarkdownSerializationException("Value is null");
// }
// return getPredecessor() + value.toString() + getSuccessor();
// }
//
// @Override
// public String getPredecessor() {
// return "";
// }
//
// @Override
// public String getSuccessor() {
// return getPredecessor();
// }
//
// public Object getValue() {
// return value;
// }
//
// public void setValue(Object value) {
// this.value = value;
// invalidateSerialized();
// }
//
// }
//
// Path: Source/MarkdownGenerator/src/main/java/net/steppschuh/markdowngenerator/text/emphasis/StrikeThroughText.java
// public class StrikeThroughText extends Text {
//
// public StrikeThroughText(Object value) {
// super(value);
// }
//
// @Override
// public String getPredecessor() {
// return "~~";
// }
//
// }
// Path: Source/MarkdownGenerator/src/test/java/net/steppschuh/markdowngenerator/text/emphasis/StrikeThroughTextTest.java
import net.steppschuh.markdowngenerator.DummyObject;
import net.steppschuh.markdowngenerator.text.Text;
import net.steppschuh.markdowngenerator.text.emphasis.StrikeThroughText;
import org.junit.Test;
package net.steppschuh.markdowngenerator.text.emphasis;
/**
* Created by steppschuh on 15/12/2016.
*/
public class StrikeThroughTextTest {
@Test
public void example1() throws Exception {
|
Text text = new StrikeThroughText("I am strike-through text");
|
Steppschuh/Java-Markdown-Generator
|
Source/MarkdownGenerator/src/test/java/net/steppschuh/markdowngenerator/text/emphasis/StrikeThroughTextTest.java
|
// Path: Source/MarkdownGenerator/src/test/java/net/steppschuh/markdowngenerator/DummyObject.java
// public class DummyObject implements MarkdownSerializable {
//
// private Object foo;
// private String bar;
// private int baz;
//
// public DummyObject() {
// this.foo = true;
// this.bar = "qux";
// this.baz = 1337;
// }
//
// public DummyObject(Object foo, String bar, int baz) {
// this.foo = foo;
// this.bar = bar;
// this.baz = baz;
// }
//
// public TableRow toMarkdownTableRow() {
// return new TableRow<>(Arrays.asList(
// foo, bar, baz
// ));
// }
//
// @Override
// public MarkdownElement toMarkdownElement() throws MarkdownSerializationException {
// return toMarkdownTableRow();
// }
//
// @Override
// public String toString() {
// try {
// return toMarkdownElement().toString();
// } catch (MarkdownSerializationException e) {
// return this.getClass().getSimpleName();
// }
// }
//
// public Object getFoo() {
// return foo;
// }
//
// public String getBar() {
// return bar;
// }
//
// public int getBaz() {
// return baz;
// }
// }
//
// Path: Source/MarkdownGenerator/src/main/java/net/steppschuh/markdowngenerator/text/Text.java
// public class Text extends MarkdownElement implements MarkdownCascadable {
//
// protected Object value;
//
// public Text(Object value) {
// this.value = value;
// }
//
// @Override
// public String serialize() throws MarkdownSerializationException {
// if (value == null) {
// throw new MarkdownSerializationException("Value is null");
// }
// return getPredecessor() + value.toString() + getSuccessor();
// }
//
// @Override
// public String getPredecessor() {
// return "";
// }
//
// @Override
// public String getSuccessor() {
// return getPredecessor();
// }
//
// public Object getValue() {
// return value;
// }
//
// public void setValue(Object value) {
// this.value = value;
// invalidateSerialized();
// }
//
// }
//
// Path: Source/MarkdownGenerator/src/main/java/net/steppschuh/markdowngenerator/text/emphasis/StrikeThroughText.java
// public class StrikeThroughText extends Text {
//
// public StrikeThroughText(Object value) {
// super(value);
// }
//
// @Override
// public String getPredecessor() {
// return "~~";
// }
//
// }
|
import net.steppschuh.markdowngenerator.DummyObject;
import net.steppschuh.markdowngenerator.text.Text;
import net.steppschuh.markdowngenerator.text.emphasis.StrikeThroughText;
import org.junit.Test;
|
package net.steppschuh.markdowngenerator.text.emphasis;
/**
* Created by steppschuh on 15/12/2016.
*/
public class StrikeThroughTextTest {
@Test
public void example1() throws Exception {
Text text = new StrikeThroughText("I am strike-through text");
System.out.println(text);
}
@Test
public void example2() throws Exception {
|
// Path: Source/MarkdownGenerator/src/test/java/net/steppschuh/markdowngenerator/DummyObject.java
// public class DummyObject implements MarkdownSerializable {
//
// private Object foo;
// private String bar;
// private int baz;
//
// public DummyObject() {
// this.foo = true;
// this.bar = "qux";
// this.baz = 1337;
// }
//
// public DummyObject(Object foo, String bar, int baz) {
// this.foo = foo;
// this.bar = bar;
// this.baz = baz;
// }
//
// public TableRow toMarkdownTableRow() {
// return new TableRow<>(Arrays.asList(
// foo, bar, baz
// ));
// }
//
// @Override
// public MarkdownElement toMarkdownElement() throws MarkdownSerializationException {
// return toMarkdownTableRow();
// }
//
// @Override
// public String toString() {
// try {
// return toMarkdownElement().toString();
// } catch (MarkdownSerializationException e) {
// return this.getClass().getSimpleName();
// }
// }
//
// public Object getFoo() {
// return foo;
// }
//
// public String getBar() {
// return bar;
// }
//
// public int getBaz() {
// return baz;
// }
// }
//
// Path: Source/MarkdownGenerator/src/main/java/net/steppschuh/markdowngenerator/text/Text.java
// public class Text extends MarkdownElement implements MarkdownCascadable {
//
// protected Object value;
//
// public Text(Object value) {
// this.value = value;
// }
//
// @Override
// public String serialize() throws MarkdownSerializationException {
// if (value == null) {
// throw new MarkdownSerializationException("Value is null");
// }
// return getPredecessor() + value.toString() + getSuccessor();
// }
//
// @Override
// public String getPredecessor() {
// return "";
// }
//
// @Override
// public String getSuccessor() {
// return getPredecessor();
// }
//
// public Object getValue() {
// return value;
// }
//
// public void setValue(Object value) {
// this.value = value;
// invalidateSerialized();
// }
//
// }
//
// Path: Source/MarkdownGenerator/src/main/java/net/steppschuh/markdowngenerator/text/emphasis/StrikeThroughText.java
// public class StrikeThroughText extends Text {
//
// public StrikeThroughText(Object value) {
// super(value);
// }
//
// @Override
// public String getPredecessor() {
// return "~~";
// }
//
// }
// Path: Source/MarkdownGenerator/src/test/java/net/steppschuh/markdowngenerator/text/emphasis/StrikeThroughTextTest.java
import net.steppschuh.markdowngenerator.DummyObject;
import net.steppschuh.markdowngenerator.text.Text;
import net.steppschuh.markdowngenerator.text.emphasis.StrikeThroughText;
import org.junit.Test;
package net.steppschuh.markdowngenerator.text.emphasis;
/**
* Created by steppschuh on 15/12/2016.
*/
public class StrikeThroughTextTest {
@Test
public void example1() throws Exception {
Text text = new StrikeThroughText("I am strike-through text");
System.out.println(text);
}
@Test
public void example2() throws Exception {
|
Text text = new StrikeThroughText(new DummyObject());
|
Steppschuh/Java-Markdown-Generator
|
Source/MarkdownGenerator/src/main/java/net/steppschuh/markdowngenerator/text/quote/Quote.java
|
// Path: Source/MarkdownGenerator/src/main/java/net/steppschuh/markdowngenerator/MarkdownSerializationException.java
// public class MarkdownSerializationException extends Exception {
//
// public MarkdownSerializationException() {
// super();
// }
//
// public MarkdownSerializationException(String s) {
// super(s);
// }
//
// public MarkdownSerializationException(String s, Throwable throwable) {
// super(s, throwable);
// }
//
// public MarkdownSerializationException(Throwable throwable) {
// super(throwable);
// }
//
// }
//
// Path: Source/MarkdownGenerator/src/main/java/net/steppschuh/markdowngenerator/text/Text.java
// public class Text extends MarkdownElement implements MarkdownCascadable {
//
// protected Object value;
//
// public Text(Object value) {
// this.value = value;
// }
//
// @Override
// public String serialize() throws MarkdownSerializationException {
// if (value == null) {
// throw new MarkdownSerializationException("Value is null");
// }
// return getPredecessor() + value.toString() + getSuccessor();
// }
//
// @Override
// public String getPredecessor() {
// return "";
// }
//
// @Override
// public String getSuccessor() {
// return getPredecessor();
// }
//
// public Object getValue() {
// return value;
// }
//
// public void setValue(Object value) {
// this.value = value;
// invalidateSerialized();
// }
//
// }
|
import net.steppschuh.markdowngenerator.MarkdownSerializationException;
import net.steppschuh.markdowngenerator.text.Text;
|
package net.steppschuh.markdowngenerator.text.quote;
/**
* Created by steppschuh on 15/12/2016.
*/
public class Quote extends Text {
public Quote(Object value) {
super(value);
}
@Override
|
// Path: Source/MarkdownGenerator/src/main/java/net/steppschuh/markdowngenerator/MarkdownSerializationException.java
// public class MarkdownSerializationException extends Exception {
//
// public MarkdownSerializationException() {
// super();
// }
//
// public MarkdownSerializationException(String s) {
// super(s);
// }
//
// public MarkdownSerializationException(String s, Throwable throwable) {
// super(s, throwable);
// }
//
// public MarkdownSerializationException(Throwable throwable) {
// super(throwable);
// }
//
// }
//
// Path: Source/MarkdownGenerator/src/main/java/net/steppschuh/markdowngenerator/text/Text.java
// public class Text extends MarkdownElement implements MarkdownCascadable {
//
// protected Object value;
//
// public Text(Object value) {
// this.value = value;
// }
//
// @Override
// public String serialize() throws MarkdownSerializationException {
// if (value == null) {
// throw new MarkdownSerializationException("Value is null");
// }
// return getPredecessor() + value.toString() + getSuccessor();
// }
//
// @Override
// public String getPredecessor() {
// return "";
// }
//
// @Override
// public String getSuccessor() {
// return getPredecessor();
// }
//
// public Object getValue() {
// return value;
// }
//
// public void setValue(Object value) {
// this.value = value;
// invalidateSerialized();
// }
//
// }
// Path: Source/MarkdownGenerator/src/main/java/net/steppschuh/markdowngenerator/text/quote/Quote.java
import net.steppschuh.markdowngenerator.MarkdownSerializationException;
import net.steppschuh.markdowngenerator.text.Text;
package net.steppschuh.markdowngenerator.text.quote;
/**
* Created by steppschuh on 15/12/2016.
*/
public class Quote extends Text {
public Quote(Object value) {
super(value);
}
@Override
|
public String serialize() throws MarkdownSerializationException {
|
DylanVann/react-native-fast-image
|
android/src/main/java/com/dylanvann/fastimage/FastImageViewManager.java
|
// Path: android/src/main/java/com/dylanvann/fastimage/FastImageRequestListener.java
// static final String REACT_ON_ERROR_EVENT = "onFastImageError";
//
// Path: android/src/main/java/com/dylanvann/fastimage/FastImageRequestListener.java
// static final String REACT_ON_LOAD_END_EVENT = "onFastImageLoadEnd";
//
// Path: android/src/main/java/com/dylanvann/fastimage/FastImageRequestListener.java
// static final String REACT_ON_LOAD_EVENT = "onFastImageLoad";
|
import android.app.Activity;
import android.content.Context;
import android.content.ContextWrapper;
import android.graphics.PorterDuff;
import android.os.Build;
import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestManager;
import com.bumptech.glide.load.model.GlideUrl;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.bridge.WritableNativeMap;
import com.facebook.react.common.MapBuilder;
import com.facebook.react.uimanager.SimpleViewManager;
import com.facebook.react.uimanager.ThemedReactContext;
import com.facebook.react.uimanager.annotations.ReactProp;
import com.facebook.react.uimanager.events.RCTEventEmitter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.WeakHashMap;
import javax.annotation.Nullable;
import static com.dylanvann.fastimage.FastImageRequestListener.REACT_ON_ERROR_EVENT;
import static com.dylanvann.fastimage.FastImageRequestListener.REACT_ON_LOAD_END_EVENT;
import static com.dylanvann.fastimage.FastImageRequestListener.REACT_ON_LOAD_EVENT;
|
requestManager = Glide.with(reactContext);
}
return new FastImageViewWithUrl(reactContext);
}
@ReactProp(name = "source")
public void setSrc(FastImageViewWithUrl view, @Nullable ReadableMap source) {
if (source == null || !source.hasKey("uri") || isNullOrEmpty(source.getString("uri"))) {
// Cancel existing requests.
if (requestManager != null) {
requestManager.clear(view);
}
if (view.glideUrl != null) {
FastImageOkHttpProgressGlideModule.forget(view.glideUrl.toStringUrl());
}
// Clear the image.
view.setImageDrawable(null);
return;
}
//final GlideUrl glideUrl = FastImageViewConverter.getGlideUrl(view.getContext(), source);
final FastImageSource imageSource = FastImageViewConverter.getImageSource(view.getContext(), source);
if (imageSource.getUri().toString().length() == 0) {
ThemedReactContext context = (ThemedReactContext) view.getContext();
RCTEventEmitter eventEmitter = context.getJSModule(RCTEventEmitter.class);
int viewId = view.getId();
WritableMap event = new WritableNativeMap();
event.putString("message", "Invalid source prop:" + source);
|
// Path: android/src/main/java/com/dylanvann/fastimage/FastImageRequestListener.java
// static final String REACT_ON_ERROR_EVENT = "onFastImageError";
//
// Path: android/src/main/java/com/dylanvann/fastimage/FastImageRequestListener.java
// static final String REACT_ON_LOAD_END_EVENT = "onFastImageLoadEnd";
//
// Path: android/src/main/java/com/dylanvann/fastimage/FastImageRequestListener.java
// static final String REACT_ON_LOAD_EVENT = "onFastImageLoad";
// Path: android/src/main/java/com/dylanvann/fastimage/FastImageViewManager.java
import android.app.Activity;
import android.content.Context;
import android.content.ContextWrapper;
import android.graphics.PorterDuff;
import android.os.Build;
import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestManager;
import com.bumptech.glide.load.model.GlideUrl;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.bridge.WritableNativeMap;
import com.facebook.react.common.MapBuilder;
import com.facebook.react.uimanager.SimpleViewManager;
import com.facebook.react.uimanager.ThemedReactContext;
import com.facebook.react.uimanager.annotations.ReactProp;
import com.facebook.react.uimanager.events.RCTEventEmitter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.WeakHashMap;
import javax.annotation.Nullable;
import static com.dylanvann.fastimage.FastImageRequestListener.REACT_ON_ERROR_EVENT;
import static com.dylanvann.fastimage.FastImageRequestListener.REACT_ON_LOAD_END_EVENT;
import static com.dylanvann.fastimage.FastImageRequestListener.REACT_ON_LOAD_EVENT;
requestManager = Glide.with(reactContext);
}
return new FastImageViewWithUrl(reactContext);
}
@ReactProp(name = "source")
public void setSrc(FastImageViewWithUrl view, @Nullable ReadableMap source) {
if (source == null || !source.hasKey("uri") || isNullOrEmpty(source.getString("uri"))) {
// Cancel existing requests.
if (requestManager != null) {
requestManager.clear(view);
}
if (view.glideUrl != null) {
FastImageOkHttpProgressGlideModule.forget(view.glideUrl.toStringUrl());
}
// Clear the image.
view.setImageDrawable(null);
return;
}
//final GlideUrl glideUrl = FastImageViewConverter.getGlideUrl(view.getContext(), source);
final FastImageSource imageSource = FastImageViewConverter.getImageSource(view.getContext(), source);
if (imageSource.getUri().toString().length() == 0) {
ThemedReactContext context = (ThemedReactContext) view.getContext();
RCTEventEmitter eventEmitter = context.getJSModule(RCTEventEmitter.class);
int viewId = view.getId();
WritableMap event = new WritableNativeMap();
event.putString("message", "Invalid source prop:" + source);
|
eventEmitter.receiveEvent(viewId, REACT_ON_ERROR_EVENT, event);
|
DylanVann/react-native-fast-image
|
android/src/main/java/com/dylanvann/fastimage/FastImageViewManager.java
|
// Path: android/src/main/java/com/dylanvann/fastimage/FastImageRequestListener.java
// static final String REACT_ON_ERROR_EVENT = "onFastImageError";
//
// Path: android/src/main/java/com/dylanvann/fastimage/FastImageRequestListener.java
// static final String REACT_ON_LOAD_END_EVENT = "onFastImageLoadEnd";
//
// Path: android/src/main/java/com/dylanvann/fastimage/FastImageRequestListener.java
// static final String REACT_ON_LOAD_EVENT = "onFastImageLoad";
|
import android.app.Activity;
import android.content.Context;
import android.content.ContextWrapper;
import android.graphics.PorterDuff;
import android.os.Build;
import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestManager;
import com.bumptech.glide.load.model.GlideUrl;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.bridge.WritableNativeMap;
import com.facebook.react.common.MapBuilder;
import com.facebook.react.uimanager.SimpleViewManager;
import com.facebook.react.uimanager.ThemedReactContext;
import com.facebook.react.uimanager.annotations.ReactProp;
import com.facebook.react.uimanager.events.RCTEventEmitter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.WeakHashMap;
import javax.annotation.Nullable;
import static com.dylanvann.fastimage.FastImageRequestListener.REACT_ON_ERROR_EVENT;
import static com.dylanvann.fastimage.FastImageRequestListener.REACT_ON_LOAD_END_EVENT;
import static com.dylanvann.fastimage.FastImageRequestListener.REACT_ON_LOAD_EVENT;
|
public void setResizeMode(FastImageViewWithUrl view, String resizeMode) {
final FastImageViewWithUrl.ScaleType scaleType = FastImageViewConverter.getScaleType(resizeMode);
view.setScaleType(scaleType);
}
@Override
public void onDropViewInstance(FastImageViewWithUrl view) {
// This will cancel existing requests.
if (requestManager != null) {
requestManager.clear(view);
}
if (view.glideUrl != null) {
final String key = view.glideUrl.toString();
FastImageOkHttpProgressGlideModule.forget(key);
List<FastImageViewWithUrl> viewsForKey = VIEWS_FOR_URLS.get(key);
if (viewsForKey != null) {
viewsForKey.remove(view);
if (viewsForKey.size() == 0) VIEWS_FOR_URLS.remove(key);
}
}
super.onDropViewInstance(view);
}
@Override
public Map<String, Object> getExportedCustomDirectEventTypeConstants() {
return MapBuilder.<String, Object>builder()
.put(REACT_ON_LOAD_START_EVENT, MapBuilder.of("registrationName", REACT_ON_LOAD_START_EVENT))
.put(REACT_ON_PROGRESS_EVENT, MapBuilder.of("registrationName", REACT_ON_PROGRESS_EVENT))
|
// Path: android/src/main/java/com/dylanvann/fastimage/FastImageRequestListener.java
// static final String REACT_ON_ERROR_EVENT = "onFastImageError";
//
// Path: android/src/main/java/com/dylanvann/fastimage/FastImageRequestListener.java
// static final String REACT_ON_LOAD_END_EVENT = "onFastImageLoadEnd";
//
// Path: android/src/main/java/com/dylanvann/fastimage/FastImageRequestListener.java
// static final String REACT_ON_LOAD_EVENT = "onFastImageLoad";
// Path: android/src/main/java/com/dylanvann/fastimage/FastImageViewManager.java
import android.app.Activity;
import android.content.Context;
import android.content.ContextWrapper;
import android.graphics.PorterDuff;
import android.os.Build;
import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestManager;
import com.bumptech.glide.load.model.GlideUrl;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.bridge.WritableNativeMap;
import com.facebook.react.common.MapBuilder;
import com.facebook.react.uimanager.SimpleViewManager;
import com.facebook.react.uimanager.ThemedReactContext;
import com.facebook.react.uimanager.annotations.ReactProp;
import com.facebook.react.uimanager.events.RCTEventEmitter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.WeakHashMap;
import javax.annotation.Nullable;
import static com.dylanvann.fastimage.FastImageRequestListener.REACT_ON_ERROR_EVENT;
import static com.dylanvann.fastimage.FastImageRequestListener.REACT_ON_LOAD_END_EVENT;
import static com.dylanvann.fastimage.FastImageRequestListener.REACT_ON_LOAD_EVENT;
public void setResizeMode(FastImageViewWithUrl view, String resizeMode) {
final FastImageViewWithUrl.ScaleType scaleType = FastImageViewConverter.getScaleType(resizeMode);
view.setScaleType(scaleType);
}
@Override
public void onDropViewInstance(FastImageViewWithUrl view) {
// This will cancel existing requests.
if (requestManager != null) {
requestManager.clear(view);
}
if (view.glideUrl != null) {
final String key = view.glideUrl.toString();
FastImageOkHttpProgressGlideModule.forget(key);
List<FastImageViewWithUrl> viewsForKey = VIEWS_FOR_URLS.get(key);
if (viewsForKey != null) {
viewsForKey.remove(view);
if (viewsForKey.size() == 0) VIEWS_FOR_URLS.remove(key);
}
}
super.onDropViewInstance(view);
}
@Override
public Map<String, Object> getExportedCustomDirectEventTypeConstants() {
return MapBuilder.<String, Object>builder()
.put(REACT_ON_LOAD_START_EVENT, MapBuilder.of("registrationName", REACT_ON_LOAD_START_EVENT))
.put(REACT_ON_PROGRESS_EVENT, MapBuilder.of("registrationName", REACT_ON_PROGRESS_EVENT))
|
.put(REACT_ON_LOAD_EVENT, MapBuilder.of("registrationName", REACT_ON_LOAD_EVENT))
|
DylanVann/react-native-fast-image
|
android/src/main/java/com/dylanvann/fastimage/FastImageViewManager.java
|
// Path: android/src/main/java/com/dylanvann/fastimage/FastImageRequestListener.java
// static final String REACT_ON_ERROR_EVENT = "onFastImageError";
//
// Path: android/src/main/java/com/dylanvann/fastimage/FastImageRequestListener.java
// static final String REACT_ON_LOAD_END_EVENT = "onFastImageLoadEnd";
//
// Path: android/src/main/java/com/dylanvann/fastimage/FastImageRequestListener.java
// static final String REACT_ON_LOAD_EVENT = "onFastImageLoad";
|
import android.app.Activity;
import android.content.Context;
import android.content.ContextWrapper;
import android.graphics.PorterDuff;
import android.os.Build;
import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestManager;
import com.bumptech.glide.load.model.GlideUrl;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.bridge.WritableNativeMap;
import com.facebook.react.common.MapBuilder;
import com.facebook.react.uimanager.SimpleViewManager;
import com.facebook.react.uimanager.ThemedReactContext;
import com.facebook.react.uimanager.annotations.ReactProp;
import com.facebook.react.uimanager.events.RCTEventEmitter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.WeakHashMap;
import javax.annotation.Nullable;
import static com.dylanvann.fastimage.FastImageRequestListener.REACT_ON_ERROR_EVENT;
import static com.dylanvann.fastimage.FastImageRequestListener.REACT_ON_LOAD_END_EVENT;
import static com.dylanvann.fastimage.FastImageRequestListener.REACT_ON_LOAD_EVENT;
|
view.setScaleType(scaleType);
}
@Override
public void onDropViewInstance(FastImageViewWithUrl view) {
// This will cancel existing requests.
if (requestManager != null) {
requestManager.clear(view);
}
if (view.glideUrl != null) {
final String key = view.glideUrl.toString();
FastImageOkHttpProgressGlideModule.forget(key);
List<FastImageViewWithUrl> viewsForKey = VIEWS_FOR_URLS.get(key);
if (viewsForKey != null) {
viewsForKey.remove(view);
if (viewsForKey.size() == 0) VIEWS_FOR_URLS.remove(key);
}
}
super.onDropViewInstance(view);
}
@Override
public Map<String, Object> getExportedCustomDirectEventTypeConstants() {
return MapBuilder.<String, Object>builder()
.put(REACT_ON_LOAD_START_EVENT, MapBuilder.of("registrationName", REACT_ON_LOAD_START_EVENT))
.put(REACT_ON_PROGRESS_EVENT, MapBuilder.of("registrationName", REACT_ON_PROGRESS_EVENT))
.put(REACT_ON_LOAD_EVENT, MapBuilder.of("registrationName", REACT_ON_LOAD_EVENT))
.put(REACT_ON_ERROR_EVENT, MapBuilder.of("registrationName", REACT_ON_ERROR_EVENT))
|
// Path: android/src/main/java/com/dylanvann/fastimage/FastImageRequestListener.java
// static final String REACT_ON_ERROR_EVENT = "onFastImageError";
//
// Path: android/src/main/java/com/dylanvann/fastimage/FastImageRequestListener.java
// static final String REACT_ON_LOAD_END_EVENT = "onFastImageLoadEnd";
//
// Path: android/src/main/java/com/dylanvann/fastimage/FastImageRequestListener.java
// static final String REACT_ON_LOAD_EVENT = "onFastImageLoad";
// Path: android/src/main/java/com/dylanvann/fastimage/FastImageViewManager.java
import android.app.Activity;
import android.content.Context;
import android.content.ContextWrapper;
import android.graphics.PorterDuff;
import android.os.Build;
import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestManager;
import com.bumptech.glide.load.model.GlideUrl;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.bridge.WritableNativeMap;
import com.facebook.react.common.MapBuilder;
import com.facebook.react.uimanager.SimpleViewManager;
import com.facebook.react.uimanager.ThemedReactContext;
import com.facebook.react.uimanager.annotations.ReactProp;
import com.facebook.react.uimanager.events.RCTEventEmitter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.WeakHashMap;
import javax.annotation.Nullable;
import static com.dylanvann.fastimage.FastImageRequestListener.REACT_ON_ERROR_EVENT;
import static com.dylanvann.fastimage.FastImageRequestListener.REACT_ON_LOAD_END_EVENT;
import static com.dylanvann.fastimage.FastImageRequestListener.REACT_ON_LOAD_EVENT;
view.setScaleType(scaleType);
}
@Override
public void onDropViewInstance(FastImageViewWithUrl view) {
// This will cancel existing requests.
if (requestManager != null) {
requestManager.clear(view);
}
if (view.glideUrl != null) {
final String key = view.glideUrl.toString();
FastImageOkHttpProgressGlideModule.forget(key);
List<FastImageViewWithUrl> viewsForKey = VIEWS_FOR_URLS.get(key);
if (viewsForKey != null) {
viewsForKey.remove(view);
if (viewsForKey.size() == 0) VIEWS_FOR_URLS.remove(key);
}
}
super.onDropViewInstance(view);
}
@Override
public Map<String, Object> getExportedCustomDirectEventTypeConstants() {
return MapBuilder.<String, Object>builder()
.put(REACT_ON_LOAD_START_EVENT, MapBuilder.of("registrationName", REACT_ON_LOAD_START_EVENT))
.put(REACT_ON_PROGRESS_EVENT, MapBuilder.of("registrationName", REACT_ON_PROGRESS_EVENT))
.put(REACT_ON_LOAD_EVENT, MapBuilder.of("registrationName", REACT_ON_LOAD_EVENT))
.put(REACT_ON_ERROR_EVENT, MapBuilder.of("registrationName", REACT_ON_ERROR_EVENT))
|
.put(REACT_ON_LOAD_END_EVENT, MapBuilder.of("registrationName", REACT_ON_LOAD_END_EVENT))
|
zhaozepeng/Android_framework
|
libcore-ui/src/main/java/com/android/libcore_ui/dialog/DialogCreator.java
|
// Path: libcore-ui/src/main/java/com/android/libcore_ui/application/BaseApplication.java
// public class BaseApplication extends RootApplication{
// }
|
import android.view.View;
import com.android.libcore_ui.application.BaseApplication;
import java.util.ArrayList;
|
package com.android.libcore_ui.dialog;
/**
* Description: dialog的生成类,用来获取所需要基本常用的dialog
*
* @author zzp(zhao_zepeng@hotmail.com)
* @since 2015-07-16
*/
public class DialogCreator {
/**
* 创建dialog函数
* @param title 只能为string和view
* @param message 只能为string和view
* @param positive 只能为string和view
*/
public static AppDialog createDialog(Object title, Object message, Object positive){
return createDialog(title, message, positive, null);
}
/**
* 创建dialog函数
* @param title 只能为string和view
* @param message 只能为string和view
* @param positive 只能为string和view
* @param negative 只能为string和view
*/
public static AppDialog createDialog(Object title, Object message, Object positive, Object negative){
return createDialog(title, message, positive, negative, null);
}
/**
* 创建dialog函数
* @param title 只能为string和view
* @param message 只能为string和view
* @param positive 只能为string和view
* @param negative 只能为string和view
* @param neutral 只能为string和view
*/
public static AppDialog createDialog(Object title, Object message, Object positive, Object negative, Object neutral){
return createDialog(title, message, positive, negative, neutral, null);
}
/**
* 创建dialog函数
* @param title 只能为string和view
* @param message 只能为string和view
* @param positive 只能为string和view
* @param negative 只能为string和view
* @param neutral 只能为string和view
* @param others 需要另外加上按钮的数据集合
*/
public static AppDialog createDialog(Object title, Object message, Object positive, Object negative, Object neutral,
ArrayList<OtherButton> others){
|
// Path: libcore-ui/src/main/java/com/android/libcore_ui/application/BaseApplication.java
// public class BaseApplication extends RootApplication{
// }
// Path: libcore-ui/src/main/java/com/android/libcore_ui/dialog/DialogCreator.java
import android.view.View;
import com.android.libcore_ui.application.BaseApplication;
import java.util.ArrayList;
package com.android.libcore_ui.dialog;
/**
* Description: dialog的生成类,用来获取所需要基本常用的dialog
*
* @author zzp(zhao_zepeng@hotmail.com)
* @since 2015-07-16
*/
public class DialogCreator {
/**
* 创建dialog函数
* @param title 只能为string和view
* @param message 只能为string和view
* @param positive 只能为string和view
*/
public static AppDialog createDialog(Object title, Object message, Object positive){
return createDialog(title, message, positive, null);
}
/**
* 创建dialog函数
* @param title 只能为string和view
* @param message 只能为string和view
* @param positive 只能为string和view
* @param negative 只能为string和view
*/
public static AppDialog createDialog(Object title, Object message, Object positive, Object negative){
return createDialog(title, message, positive, negative, null);
}
/**
* 创建dialog函数
* @param title 只能为string和view
* @param message 只能为string和view
* @param positive 只能为string和view
* @param negative 只能为string和view
* @param neutral 只能为string和view
*/
public static AppDialog createDialog(Object title, Object message, Object positive, Object negative, Object neutral){
return createDialog(title, message, positive, negative, neutral, null);
}
/**
* 创建dialog函数
* @param title 只能为string和view
* @param message 只能为string和view
* @param positive 只能为string和view
* @param negative 只能为string和view
* @param neutral 只能为string和view
* @param others 需要另外加上按钮的数据集合
*/
public static AppDialog createDialog(Object title, Object message, Object positive, Object negative, Object neutral,
ArrayList<OtherButton> others){
|
AppDialog dialog = new AppDialog(BaseApplication.getInstance());
|
thinkaurelius/titan
|
titan-hadoop-parent/titan-hadoop-core/src/main/java/com/thinkaurelius/titan/hadoop/formats/util/TitanVertexDeserializer.java
|
// Path: titan-core/src/main/java/com/thinkaurelius/titan/graphdb/relations/RelationCache.java
// public class RelationCache implements Iterable<LongObjectCursor<Object>> {
//
// private static final LongObjectHashMap<Object> EMPTY = new LongObjectHashMap<>(0);
//
// public final Direction direction;
// public final long typeId;
// public final long relationId;
// private final Object other;
// private final LongObjectHashMap<Object> properties;
//
// public RelationCache(final Direction direction, final long typeId, final long relationId,
// final Object other, final LongObjectHashMap<Object> properties) {
// this.direction = direction;
// this.typeId = typeId;
// this.relationId = relationId;
// this.other = other;
// this.properties = (properties == null || properties.size() > 0) ? properties : EMPTY;
// }
//
// public RelationCache(final Direction direction, final long typeId, final long relationId,
// final Object other) {
// this(direction,typeId,relationId,other,null);
// }
//
// @SuppressWarnings("unchecked")
// public <O> O get(long key) {
// return (O) properties.get(key);
// }
//
// public boolean hasProperties() {
// return properties != null && !properties.isEmpty();
// }
//
// public int numProperties() {
// return properties.size();
// }
//
// public Object getValue() {
// return other;
// }
//
// public Long getOtherVertexId() {
// return (Long) other;
// }
//
// public Iterator<LongObjectCursor<Object>> propertyIterator() {
// return properties.iterator();
// }
//
// @Override
// public Iterator<LongObjectCursor<Object>> iterator() {
// return propertyIterator();
// }
//
// @Override
// public String toString() {
// return typeId + "-" + direction + "->" + other + ":" + relationId;
// }
//
// }
|
import com.carrotsearch.hppc.cursors.LongObjectCursor;
import com.google.common.base.Preconditions;
import com.thinkaurelius.titan.core.*;
import com.thinkaurelius.titan.diskstorage.Entry;
import com.thinkaurelius.titan.diskstorage.StaticBuffer;
import com.thinkaurelius.titan.graphdb.database.RelationReader;
import com.thinkaurelius.titan.graphdb.idmanagement.IDManager;
import com.thinkaurelius.titan.graphdb.internal.InternalRelationType;
import com.thinkaurelius.titan.graphdb.relations.RelationCache;
import com.thinkaurelius.titan.graphdb.types.TypeInspector;
import com.thinkaurelius.titan.hadoop.formats.util.input.SystemTypeInspector;
import com.thinkaurelius.titan.hadoop.formats.util.input.TitanHadoopSetup;
import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.structure.Direction;
import org.apache.tinkerpop.gremlin.structure.VertexProperty;
import org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerEdge;
import org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerGraph;
import org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerVertex;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.NoSuchElementException;
|
package com.thinkaurelius.titan.hadoop.formats.util;
public class TitanVertexDeserializer implements AutoCloseable {
private final TitanHadoopSetup setup;
private final TypeInspector typeManager;
private final SystemTypeInspector systemTypes;
private final IDManager idManager;
private final boolean verifyVertexExistence = false;
private static final Logger log =
LoggerFactory.getLogger(TitanVertexDeserializer.class);
public TitanVertexDeserializer(final TitanHadoopSetup setup) {
this.setup = setup;
this.typeManager = setup.getTypeInspector();
this.systemTypes = setup.getSystemTypeInspector();
this.idManager = setup.getIDManager();
}
// Read a single row from the edgestore and create a TinkerVertex corresponding to the row
// The neighboring vertices are represented by DetachedVertex instances
public TinkerVertex readHadoopVertex(final StaticBuffer key, Iterable<Entry> entries) {
// Convert key to a vertex ID
final long vertexId = idManager.getKeyID(key);
Preconditions.checkArgument(vertexId > 0);
// Partitioned vertex handling
if (idManager.isPartitionedVertex(vertexId)) {
Preconditions.checkState(setup.getFilterPartitionedVertices(),
"Read partitioned vertex (ID=%s), but partitioned vertex filtering is disabled.", vertexId);
log.debug("Skipping partitioned vertex with ID {}", vertexId);
return null;
}
// Create TinkerVertex
TinkerGraph tg = TinkerGraph.open();
boolean foundVertexState = !verifyVertexExistence;
TinkerVertex tv = null;
// Iterate over edgestore columns to find the vertex's label relation
for (final Entry data : entries) {
RelationReader relationReader = setup.getRelationReader(vertexId);
|
// Path: titan-core/src/main/java/com/thinkaurelius/titan/graphdb/relations/RelationCache.java
// public class RelationCache implements Iterable<LongObjectCursor<Object>> {
//
// private static final LongObjectHashMap<Object> EMPTY = new LongObjectHashMap<>(0);
//
// public final Direction direction;
// public final long typeId;
// public final long relationId;
// private final Object other;
// private final LongObjectHashMap<Object> properties;
//
// public RelationCache(final Direction direction, final long typeId, final long relationId,
// final Object other, final LongObjectHashMap<Object> properties) {
// this.direction = direction;
// this.typeId = typeId;
// this.relationId = relationId;
// this.other = other;
// this.properties = (properties == null || properties.size() > 0) ? properties : EMPTY;
// }
//
// public RelationCache(final Direction direction, final long typeId, final long relationId,
// final Object other) {
// this(direction,typeId,relationId,other,null);
// }
//
// @SuppressWarnings("unchecked")
// public <O> O get(long key) {
// return (O) properties.get(key);
// }
//
// public boolean hasProperties() {
// return properties != null && !properties.isEmpty();
// }
//
// public int numProperties() {
// return properties.size();
// }
//
// public Object getValue() {
// return other;
// }
//
// public Long getOtherVertexId() {
// return (Long) other;
// }
//
// public Iterator<LongObjectCursor<Object>> propertyIterator() {
// return properties.iterator();
// }
//
// @Override
// public Iterator<LongObjectCursor<Object>> iterator() {
// return propertyIterator();
// }
//
// @Override
// public String toString() {
// return typeId + "-" + direction + "->" + other + ":" + relationId;
// }
//
// }
// Path: titan-hadoop-parent/titan-hadoop-core/src/main/java/com/thinkaurelius/titan/hadoop/formats/util/TitanVertexDeserializer.java
import com.carrotsearch.hppc.cursors.LongObjectCursor;
import com.google.common.base.Preconditions;
import com.thinkaurelius.titan.core.*;
import com.thinkaurelius.titan.diskstorage.Entry;
import com.thinkaurelius.titan.diskstorage.StaticBuffer;
import com.thinkaurelius.titan.graphdb.database.RelationReader;
import com.thinkaurelius.titan.graphdb.idmanagement.IDManager;
import com.thinkaurelius.titan.graphdb.internal.InternalRelationType;
import com.thinkaurelius.titan.graphdb.relations.RelationCache;
import com.thinkaurelius.titan.graphdb.types.TypeInspector;
import com.thinkaurelius.titan.hadoop.formats.util.input.SystemTypeInspector;
import com.thinkaurelius.titan.hadoop.formats.util.input.TitanHadoopSetup;
import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.structure.Direction;
import org.apache.tinkerpop.gremlin.structure.VertexProperty;
import org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerEdge;
import org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerGraph;
import org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerVertex;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.NoSuchElementException;
package com.thinkaurelius.titan.hadoop.formats.util;
public class TitanVertexDeserializer implements AutoCloseable {
private final TitanHadoopSetup setup;
private final TypeInspector typeManager;
private final SystemTypeInspector systemTypes;
private final IDManager idManager;
private final boolean verifyVertexExistence = false;
private static final Logger log =
LoggerFactory.getLogger(TitanVertexDeserializer.class);
public TitanVertexDeserializer(final TitanHadoopSetup setup) {
this.setup = setup;
this.typeManager = setup.getTypeInspector();
this.systemTypes = setup.getSystemTypeInspector();
this.idManager = setup.getIDManager();
}
// Read a single row from the edgestore and create a TinkerVertex corresponding to the row
// The neighboring vertices are represented by DetachedVertex instances
public TinkerVertex readHadoopVertex(final StaticBuffer key, Iterable<Entry> entries) {
// Convert key to a vertex ID
final long vertexId = idManager.getKeyID(key);
Preconditions.checkArgument(vertexId > 0);
// Partitioned vertex handling
if (idManager.isPartitionedVertex(vertexId)) {
Preconditions.checkState(setup.getFilterPartitionedVertices(),
"Read partitioned vertex (ID=%s), but partitioned vertex filtering is disabled.", vertexId);
log.debug("Skipping partitioned vertex with ID {}", vertexId);
return null;
}
// Create TinkerVertex
TinkerGraph tg = TinkerGraph.open();
boolean foundVertexState = !verifyVertexExistence;
TinkerVertex tv = null;
// Iterate over edgestore columns to find the vertex's label relation
for (final Entry data : entries) {
RelationReader relationReader = setup.getRelationReader(vertexId);
|
final RelationCache relation = relationReader.parseRelation(data, false, typeManager);
|
simplify20/PowerfulRecyclerViewAdapter
|
holder-compiler/src/main/java/com/steve/creact/processor/core/view/BaseViewGenerator.java
|
// Path: holder-compiler/src/main/java/com/steve/creact/processor/core/Constants.java
// public final class Constants {
// private Constants(){}
//
// public static final String TEMPLATE_PATH = "templates/databean-source.tm";
// public static final String PACKAGE_NAME = "${PACKAGE_NAME}";
// public static final String DATA_ENTITY_FULL_QUALIFIED_CLASS_NAME = "${DATA_ENTITY_FULL_QUALIFIED_CLASS_NAME}";
// public static final String VIEW_HOLDER_FULL_QUALIFIED_CLASS_NAME = "${VIEW_HOLDER_FULL_QUALIFIED_CLASS_NAME}";
// public static final String VIEW_HOLDER_SIMPLE_CLASS_NAME = "${VIEW_HOLDER_SIMPLE_CLASS_NAME}";
// public static final String DATA_BEAN_SIMPLE_CLASS_NAME = "${DATA_BEAN_SIMPLE_CLASS_NAME}";
// public static final String DATA_ENTITY_SIMPLE_CLASS_NAME = "${DATA_ENTITY_SIMPLE_CLASS_NAME}";
// }
//
// Path: holder-compiler/src/main/java/com/steve/creact/processor/core/Logger.java
// public class Logger {
// public static boolean logOn = false;
// public static Logger getInstance(Messager messager) {
// if (instance == null) {
// synchronized (Logger.class) {
// if (instance != null)
// return instance;
// instance = new Logger(messager);
// }
// }
// return instance;
// }
//
// private static Messager actual;
// private static volatile Logger instance;
// private Logger(Messager actual) {
// this.actual = actual;
// }
//
// public void log(Diagnostic.Kind kind, String message) {
// if (logOn && actual != null) {
// actual.printMessage(kind, message);
// }
// }
// }
//
// Path: holder-compiler/src/main/java/com/steve/creact/processor/core/model/AbstractModel.java
// public abstract class AbstractModel<R> {
//
// protected Element element;
// protected ElementVisitorAdapter elementVisitor;
// /**
// * real model
// */
// private R model;
//
// public AbstractModel(Element element) {
// this.element = element;
// }
//
// public boolean isClass() {
// return element.getKind().isClass();
// }
//
// public boolean isInterface() {
// return element.getKind().isInterface();
// }
//
// public boolean isField() {
//
// return element.getKind().isField();
// }
//
// public String getSimpleName() {
// return element.getSimpleName().toString();
// }
//
// public <P> void visit(P p) {
// model = (R) element.accept(this.elementVisitor, p);
// }
//
// public <P> void setElementVisitor(ElementVisitorAdapter<R, P> visitor) {
// this.elementVisitor = visitor;
// }
//
// public R getRealModel() {
// return model;
// }
//
// }
|
import com.steve.creact.processor.core.Constants;
import com.steve.creact.processor.core.Logger;
import com.steve.creact.processor.core.model.AbstractModel;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Writer;
import java.util.HashMap;
import javax.annotation.processing.Filer;
import javax.annotation.processing.ProcessingEnvironment;
import javax.tools.Diagnostic;
import javax.tools.JavaFileObject;
|
package com.steve.creact.processor.core.view;
/**
* Base Template Engine
* Created by Administrator on 2016/4/17.
*/
public abstract class BaseViewGenerator<T> implements ViewGenerator<T>, Replacer {
/**
* when template file has updated,call this method to flush cache
*
* @param templateFilePath
*/
public static void flushCache(String templateFilePath) {
if (templateFilePath != null)
templateCache.remove(templateFilePath);
}
/**
* flush all
*/
public static void flushCache() {
templateCache.clear();
}
protected ProcessingEnvironment processingEnvironment;
|
// Path: holder-compiler/src/main/java/com/steve/creact/processor/core/Constants.java
// public final class Constants {
// private Constants(){}
//
// public static final String TEMPLATE_PATH = "templates/databean-source.tm";
// public static final String PACKAGE_NAME = "${PACKAGE_NAME}";
// public static final String DATA_ENTITY_FULL_QUALIFIED_CLASS_NAME = "${DATA_ENTITY_FULL_QUALIFIED_CLASS_NAME}";
// public static final String VIEW_HOLDER_FULL_QUALIFIED_CLASS_NAME = "${VIEW_HOLDER_FULL_QUALIFIED_CLASS_NAME}";
// public static final String VIEW_HOLDER_SIMPLE_CLASS_NAME = "${VIEW_HOLDER_SIMPLE_CLASS_NAME}";
// public static final String DATA_BEAN_SIMPLE_CLASS_NAME = "${DATA_BEAN_SIMPLE_CLASS_NAME}";
// public static final String DATA_ENTITY_SIMPLE_CLASS_NAME = "${DATA_ENTITY_SIMPLE_CLASS_NAME}";
// }
//
// Path: holder-compiler/src/main/java/com/steve/creact/processor/core/Logger.java
// public class Logger {
// public static boolean logOn = false;
// public static Logger getInstance(Messager messager) {
// if (instance == null) {
// synchronized (Logger.class) {
// if (instance != null)
// return instance;
// instance = new Logger(messager);
// }
// }
// return instance;
// }
//
// private static Messager actual;
// private static volatile Logger instance;
// private Logger(Messager actual) {
// this.actual = actual;
// }
//
// public void log(Diagnostic.Kind kind, String message) {
// if (logOn && actual != null) {
// actual.printMessage(kind, message);
// }
// }
// }
//
// Path: holder-compiler/src/main/java/com/steve/creact/processor/core/model/AbstractModel.java
// public abstract class AbstractModel<R> {
//
// protected Element element;
// protected ElementVisitorAdapter elementVisitor;
// /**
// * real model
// */
// private R model;
//
// public AbstractModel(Element element) {
// this.element = element;
// }
//
// public boolean isClass() {
// return element.getKind().isClass();
// }
//
// public boolean isInterface() {
// return element.getKind().isInterface();
// }
//
// public boolean isField() {
//
// return element.getKind().isField();
// }
//
// public String getSimpleName() {
// return element.getSimpleName().toString();
// }
//
// public <P> void visit(P p) {
// model = (R) element.accept(this.elementVisitor, p);
// }
//
// public <P> void setElementVisitor(ElementVisitorAdapter<R, P> visitor) {
// this.elementVisitor = visitor;
// }
//
// public R getRealModel() {
// return model;
// }
//
// }
// Path: holder-compiler/src/main/java/com/steve/creact/processor/core/view/BaseViewGenerator.java
import com.steve.creact.processor.core.Constants;
import com.steve.creact.processor.core.Logger;
import com.steve.creact.processor.core.model.AbstractModel;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Writer;
import java.util.HashMap;
import javax.annotation.processing.Filer;
import javax.annotation.processing.ProcessingEnvironment;
import javax.tools.Diagnostic;
import javax.tools.JavaFileObject;
package com.steve.creact.processor.core.view;
/**
* Base Template Engine
* Created by Administrator on 2016/4/17.
*/
public abstract class BaseViewGenerator<T> implements ViewGenerator<T>, Replacer {
/**
* when template file has updated,call this method to flush cache
*
* @param templateFilePath
*/
public static void flushCache(String templateFilePath) {
if (templateFilePath != null)
templateCache.remove(templateFilePath);
}
/**
* flush all
*/
public static void flushCache() {
templateCache.clear();
}
protected ProcessingEnvironment processingEnvironment;
|
protected Logger logger;
|
simplify20/PowerfulRecyclerViewAdapter
|
holder-compiler/src/main/java/com/steve/creact/processor/core/view/BaseViewGenerator.java
|
// Path: holder-compiler/src/main/java/com/steve/creact/processor/core/Constants.java
// public final class Constants {
// private Constants(){}
//
// public static final String TEMPLATE_PATH = "templates/databean-source.tm";
// public static final String PACKAGE_NAME = "${PACKAGE_NAME}";
// public static final String DATA_ENTITY_FULL_QUALIFIED_CLASS_NAME = "${DATA_ENTITY_FULL_QUALIFIED_CLASS_NAME}";
// public static final String VIEW_HOLDER_FULL_QUALIFIED_CLASS_NAME = "${VIEW_HOLDER_FULL_QUALIFIED_CLASS_NAME}";
// public static final String VIEW_HOLDER_SIMPLE_CLASS_NAME = "${VIEW_HOLDER_SIMPLE_CLASS_NAME}";
// public static final String DATA_BEAN_SIMPLE_CLASS_NAME = "${DATA_BEAN_SIMPLE_CLASS_NAME}";
// public static final String DATA_ENTITY_SIMPLE_CLASS_NAME = "${DATA_ENTITY_SIMPLE_CLASS_NAME}";
// }
//
// Path: holder-compiler/src/main/java/com/steve/creact/processor/core/Logger.java
// public class Logger {
// public static boolean logOn = false;
// public static Logger getInstance(Messager messager) {
// if (instance == null) {
// synchronized (Logger.class) {
// if (instance != null)
// return instance;
// instance = new Logger(messager);
// }
// }
// return instance;
// }
//
// private static Messager actual;
// private static volatile Logger instance;
// private Logger(Messager actual) {
// this.actual = actual;
// }
//
// public void log(Diagnostic.Kind kind, String message) {
// if (logOn && actual != null) {
// actual.printMessage(kind, message);
// }
// }
// }
//
// Path: holder-compiler/src/main/java/com/steve/creact/processor/core/model/AbstractModel.java
// public abstract class AbstractModel<R> {
//
// protected Element element;
// protected ElementVisitorAdapter elementVisitor;
// /**
// * real model
// */
// private R model;
//
// public AbstractModel(Element element) {
// this.element = element;
// }
//
// public boolean isClass() {
// return element.getKind().isClass();
// }
//
// public boolean isInterface() {
// return element.getKind().isInterface();
// }
//
// public boolean isField() {
//
// return element.getKind().isField();
// }
//
// public String getSimpleName() {
// return element.getSimpleName().toString();
// }
//
// public <P> void visit(P p) {
// model = (R) element.accept(this.elementVisitor, p);
// }
//
// public <P> void setElementVisitor(ElementVisitorAdapter<R, P> visitor) {
// this.elementVisitor = visitor;
// }
//
// public R getRealModel() {
// return model;
// }
//
// }
|
import com.steve.creact.processor.core.Constants;
import com.steve.creact.processor.core.Logger;
import com.steve.creact.processor.core.model.AbstractModel;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Writer;
import java.util.HashMap;
import javax.annotation.processing.Filer;
import javax.annotation.processing.ProcessingEnvironment;
import javax.tools.Diagnostic;
import javax.tools.JavaFileObject;
|
package com.steve.creact.processor.core.view;
/**
* Base Template Engine
* Created by Administrator on 2016/4/17.
*/
public abstract class BaseViewGenerator<T> implements ViewGenerator<T>, Replacer {
/**
* when template file has updated,call this method to flush cache
*
* @param templateFilePath
*/
public static void flushCache(String templateFilePath) {
if (templateFilePath != null)
templateCache.remove(templateFilePath);
}
/**
* flush all
*/
public static void flushCache() {
templateCache.clear();
}
protected ProcessingEnvironment processingEnvironment;
protected Logger logger;
protected T realModel;
//use to cache template read in last time,and reduce cost of I/O operations
private static final HashMap<String, String> templateCache = new HashMap<>(2);
@Override
|
// Path: holder-compiler/src/main/java/com/steve/creact/processor/core/Constants.java
// public final class Constants {
// private Constants(){}
//
// public static final String TEMPLATE_PATH = "templates/databean-source.tm";
// public static final String PACKAGE_NAME = "${PACKAGE_NAME}";
// public static final String DATA_ENTITY_FULL_QUALIFIED_CLASS_NAME = "${DATA_ENTITY_FULL_QUALIFIED_CLASS_NAME}";
// public static final String VIEW_HOLDER_FULL_QUALIFIED_CLASS_NAME = "${VIEW_HOLDER_FULL_QUALIFIED_CLASS_NAME}";
// public static final String VIEW_HOLDER_SIMPLE_CLASS_NAME = "${VIEW_HOLDER_SIMPLE_CLASS_NAME}";
// public static final String DATA_BEAN_SIMPLE_CLASS_NAME = "${DATA_BEAN_SIMPLE_CLASS_NAME}";
// public static final String DATA_ENTITY_SIMPLE_CLASS_NAME = "${DATA_ENTITY_SIMPLE_CLASS_NAME}";
// }
//
// Path: holder-compiler/src/main/java/com/steve/creact/processor/core/Logger.java
// public class Logger {
// public static boolean logOn = false;
// public static Logger getInstance(Messager messager) {
// if (instance == null) {
// synchronized (Logger.class) {
// if (instance != null)
// return instance;
// instance = new Logger(messager);
// }
// }
// return instance;
// }
//
// private static Messager actual;
// private static volatile Logger instance;
// private Logger(Messager actual) {
// this.actual = actual;
// }
//
// public void log(Diagnostic.Kind kind, String message) {
// if (logOn && actual != null) {
// actual.printMessage(kind, message);
// }
// }
// }
//
// Path: holder-compiler/src/main/java/com/steve/creact/processor/core/model/AbstractModel.java
// public abstract class AbstractModel<R> {
//
// protected Element element;
// protected ElementVisitorAdapter elementVisitor;
// /**
// * real model
// */
// private R model;
//
// public AbstractModel(Element element) {
// this.element = element;
// }
//
// public boolean isClass() {
// return element.getKind().isClass();
// }
//
// public boolean isInterface() {
// return element.getKind().isInterface();
// }
//
// public boolean isField() {
//
// return element.getKind().isField();
// }
//
// public String getSimpleName() {
// return element.getSimpleName().toString();
// }
//
// public <P> void visit(P p) {
// model = (R) element.accept(this.elementVisitor, p);
// }
//
// public <P> void setElementVisitor(ElementVisitorAdapter<R, P> visitor) {
// this.elementVisitor = visitor;
// }
//
// public R getRealModel() {
// return model;
// }
//
// }
// Path: holder-compiler/src/main/java/com/steve/creact/processor/core/view/BaseViewGenerator.java
import com.steve.creact.processor.core.Constants;
import com.steve.creact.processor.core.Logger;
import com.steve.creact.processor.core.model.AbstractModel;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Writer;
import java.util.HashMap;
import javax.annotation.processing.Filer;
import javax.annotation.processing.ProcessingEnvironment;
import javax.tools.Diagnostic;
import javax.tools.JavaFileObject;
package com.steve.creact.processor.core.view;
/**
* Base Template Engine
* Created by Administrator on 2016/4/17.
*/
public abstract class BaseViewGenerator<T> implements ViewGenerator<T>, Replacer {
/**
* when template file has updated,call this method to flush cache
*
* @param templateFilePath
*/
public static void flushCache(String templateFilePath) {
if (templateFilePath != null)
templateCache.remove(templateFilePath);
}
/**
* flush all
*/
public static void flushCache() {
templateCache.clear();
}
protected ProcessingEnvironment processingEnvironment;
protected Logger logger;
protected T realModel;
//use to cache template read in last time,and reduce cost of I/O operations
private static final HashMap<String, String> templateCache = new HashMap<>(2);
@Override
|
public void generate(AbstractModel<T> model, ProcessingEnvironment processingEnv) {
|
simplify20/PowerfulRecyclerViewAdapter
|
holder-compiler/src/main/java/com/steve/creact/processor/core/view/BaseViewGenerator.java
|
// Path: holder-compiler/src/main/java/com/steve/creact/processor/core/Constants.java
// public final class Constants {
// private Constants(){}
//
// public static final String TEMPLATE_PATH = "templates/databean-source.tm";
// public static final String PACKAGE_NAME = "${PACKAGE_NAME}";
// public static final String DATA_ENTITY_FULL_QUALIFIED_CLASS_NAME = "${DATA_ENTITY_FULL_QUALIFIED_CLASS_NAME}";
// public static final String VIEW_HOLDER_FULL_QUALIFIED_CLASS_NAME = "${VIEW_HOLDER_FULL_QUALIFIED_CLASS_NAME}";
// public static final String VIEW_HOLDER_SIMPLE_CLASS_NAME = "${VIEW_HOLDER_SIMPLE_CLASS_NAME}";
// public static final String DATA_BEAN_SIMPLE_CLASS_NAME = "${DATA_BEAN_SIMPLE_CLASS_NAME}";
// public static final String DATA_ENTITY_SIMPLE_CLASS_NAME = "${DATA_ENTITY_SIMPLE_CLASS_NAME}";
// }
//
// Path: holder-compiler/src/main/java/com/steve/creact/processor/core/Logger.java
// public class Logger {
// public static boolean logOn = false;
// public static Logger getInstance(Messager messager) {
// if (instance == null) {
// synchronized (Logger.class) {
// if (instance != null)
// return instance;
// instance = new Logger(messager);
// }
// }
// return instance;
// }
//
// private static Messager actual;
// private static volatile Logger instance;
// private Logger(Messager actual) {
// this.actual = actual;
// }
//
// public void log(Diagnostic.Kind kind, String message) {
// if (logOn && actual != null) {
// actual.printMessage(kind, message);
// }
// }
// }
//
// Path: holder-compiler/src/main/java/com/steve/creact/processor/core/model/AbstractModel.java
// public abstract class AbstractModel<R> {
//
// protected Element element;
// protected ElementVisitorAdapter elementVisitor;
// /**
// * real model
// */
// private R model;
//
// public AbstractModel(Element element) {
// this.element = element;
// }
//
// public boolean isClass() {
// return element.getKind().isClass();
// }
//
// public boolean isInterface() {
// return element.getKind().isInterface();
// }
//
// public boolean isField() {
//
// return element.getKind().isField();
// }
//
// public String getSimpleName() {
// return element.getSimpleName().toString();
// }
//
// public <P> void visit(P p) {
// model = (R) element.accept(this.elementVisitor, p);
// }
//
// public <P> void setElementVisitor(ElementVisitorAdapter<R, P> visitor) {
// this.elementVisitor = visitor;
// }
//
// public R getRealModel() {
// return model;
// }
//
// }
|
import com.steve.creact.processor.core.Constants;
import com.steve.creact.processor.core.Logger;
import com.steve.creact.processor.core.model.AbstractModel;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Writer;
import java.util.HashMap;
import javax.annotation.processing.Filer;
import javax.annotation.processing.ProcessingEnvironment;
import javax.tools.Diagnostic;
import javax.tools.JavaFileObject;
|
logger.log(Diagnostic.Kind.NOTE, "create source file...");
JavaFileObject jfo = createFile();
if (jfo == null) {
logger.log(Diagnostic.Kind.NOTE, "create java file failed,aborted");
return;
}
//write file
logger.log(Diagnostic.Kind.NOTE, "write source file...");
try {
writeFile(template, jfo.openWriter());
String sourceFileName = getModelClassName();
logger.log(Diagnostic.Kind.NOTE, "generate source file successful:" + sourceFileName);
} catch (IOException e) {
logger.log(Diagnostic.Kind.ERROR, "create file failed");
e.printStackTrace();
}
}
/**
* Firstly,check whether template cache contains the target template,if not,
* load template file into memory from resource directory.
*
* @return template content
*/
protected String loadTemplate() {
String result = "";
String templateFilePath = getTemplateFilePath();
//check cache first
if (templateFilePath != null && (result = templateCache.get(templateFilePath)) != null)
return result;
|
// Path: holder-compiler/src/main/java/com/steve/creact/processor/core/Constants.java
// public final class Constants {
// private Constants(){}
//
// public static final String TEMPLATE_PATH = "templates/databean-source.tm";
// public static final String PACKAGE_NAME = "${PACKAGE_NAME}";
// public static final String DATA_ENTITY_FULL_QUALIFIED_CLASS_NAME = "${DATA_ENTITY_FULL_QUALIFIED_CLASS_NAME}";
// public static final String VIEW_HOLDER_FULL_QUALIFIED_CLASS_NAME = "${VIEW_HOLDER_FULL_QUALIFIED_CLASS_NAME}";
// public static final String VIEW_HOLDER_SIMPLE_CLASS_NAME = "${VIEW_HOLDER_SIMPLE_CLASS_NAME}";
// public static final String DATA_BEAN_SIMPLE_CLASS_NAME = "${DATA_BEAN_SIMPLE_CLASS_NAME}";
// public static final String DATA_ENTITY_SIMPLE_CLASS_NAME = "${DATA_ENTITY_SIMPLE_CLASS_NAME}";
// }
//
// Path: holder-compiler/src/main/java/com/steve/creact/processor/core/Logger.java
// public class Logger {
// public static boolean logOn = false;
// public static Logger getInstance(Messager messager) {
// if (instance == null) {
// synchronized (Logger.class) {
// if (instance != null)
// return instance;
// instance = new Logger(messager);
// }
// }
// return instance;
// }
//
// private static Messager actual;
// private static volatile Logger instance;
// private Logger(Messager actual) {
// this.actual = actual;
// }
//
// public void log(Diagnostic.Kind kind, String message) {
// if (logOn && actual != null) {
// actual.printMessage(kind, message);
// }
// }
// }
//
// Path: holder-compiler/src/main/java/com/steve/creact/processor/core/model/AbstractModel.java
// public abstract class AbstractModel<R> {
//
// protected Element element;
// protected ElementVisitorAdapter elementVisitor;
// /**
// * real model
// */
// private R model;
//
// public AbstractModel(Element element) {
// this.element = element;
// }
//
// public boolean isClass() {
// return element.getKind().isClass();
// }
//
// public boolean isInterface() {
// return element.getKind().isInterface();
// }
//
// public boolean isField() {
//
// return element.getKind().isField();
// }
//
// public String getSimpleName() {
// return element.getSimpleName().toString();
// }
//
// public <P> void visit(P p) {
// model = (R) element.accept(this.elementVisitor, p);
// }
//
// public <P> void setElementVisitor(ElementVisitorAdapter<R, P> visitor) {
// this.elementVisitor = visitor;
// }
//
// public R getRealModel() {
// return model;
// }
//
// }
// Path: holder-compiler/src/main/java/com/steve/creact/processor/core/view/BaseViewGenerator.java
import com.steve.creact.processor.core.Constants;
import com.steve.creact.processor.core.Logger;
import com.steve.creact.processor.core.model.AbstractModel;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Writer;
import java.util.HashMap;
import javax.annotation.processing.Filer;
import javax.annotation.processing.ProcessingEnvironment;
import javax.tools.Diagnostic;
import javax.tools.JavaFileObject;
logger.log(Diagnostic.Kind.NOTE, "create source file...");
JavaFileObject jfo = createFile();
if (jfo == null) {
logger.log(Diagnostic.Kind.NOTE, "create java file failed,aborted");
return;
}
//write file
logger.log(Diagnostic.Kind.NOTE, "write source file...");
try {
writeFile(template, jfo.openWriter());
String sourceFileName = getModelClassName();
logger.log(Diagnostic.Kind.NOTE, "generate source file successful:" + sourceFileName);
} catch (IOException e) {
logger.log(Diagnostic.Kind.ERROR, "create file failed");
e.printStackTrace();
}
}
/**
* Firstly,check whether template cache contains the target template,if not,
* load template file into memory from resource directory.
*
* @return template content
*/
protected String loadTemplate() {
String result = "";
String templateFilePath = getTemplateFilePath();
//check cache first
if (templateFilePath != null && (result = templateCache.get(templateFilePath)) != null)
return result;
|
InputStream is = this.getClass().getClassLoader().getResourceAsStream(Constants.TEMPLATE_PATH);
|
simplify20/PowerfulRecyclerViewAdapter
|
holder-compiler/src/main/java/com/steve/creact/processor/app/model/DataBeanModelCreator.java
|
// Path: holder-compiler/src/main/java/com/steve/creact/processor/core/model/AbstractModel.java
// public abstract class AbstractModel<R> {
//
// protected Element element;
// protected ElementVisitorAdapter elementVisitor;
// /**
// * real model
// */
// private R model;
//
// public AbstractModel(Element element) {
// this.element = element;
// }
//
// public boolean isClass() {
// return element.getKind().isClass();
// }
//
// public boolean isInterface() {
// return element.getKind().isInterface();
// }
//
// public boolean isField() {
//
// return element.getKind().isField();
// }
//
// public String getSimpleName() {
// return element.getSimpleName().toString();
// }
//
// public <P> void visit(P p) {
// model = (R) element.accept(this.elementVisitor, p);
// }
//
// public <P> void setElementVisitor(ElementVisitorAdapter<R, P> visitor) {
// this.elementVisitor = visitor;
// }
//
// public R getRealModel() {
// return model;
// }
//
// }
//
// Path: holder-compiler/src/main/java/com/steve/creact/processor/core/model/ModelCreator.java
// public interface ModelCreator {
//
// /**
// * create a model
// * @param element
// * @param processingEnv
// * @return
// */
// AbstractModel createModel(Element element, ProcessingEnvironment processingEnv);
// }
|
import com.steve.creact.processor.core.model.AbstractModel;
import com.steve.creact.processor.core.model.ModelCreator;
import javax.annotation.processing.ProcessingEnvironment;
import javax.lang.model.element.Element;
|
package com.steve.creact.processor.app.model;
/**
* Created by Administrator on 2016/4/10.
*/
public class DataBeanModelCreator implements ModelCreator {
@Override
|
// Path: holder-compiler/src/main/java/com/steve/creact/processor/core/model/AbstractModel.java
// public abstract class AbstractModel<R> {
//
// protected Element element;
// protected ElementVisitorAdapter elementVisitor;
// /**
// * real model
// */
// private R model;
//
// public AbstractModel(Element element) {
// this.element = element;
// }
//
// public boolean isClass() {
// return element.getKind().isClass();
// }
//
// public boolean isInterface() {
// return element.getKind().isInterface();
// }
//
// public boolean isField() {
//
// return element.getKind().isField();
// }
//
// public String getSimpleName() {
// return element.getSimpleName().toString();
// }
//
// public <P> void visit(P p) {
// model = (R) element.accept(this.elementVisitor, p);
// }
//
// public <P> void setElementVisitor(ElementVisitorAdapter<R, P> visitor) {
// this.elementVisitor = visitor;
// }
//
// public R getRealModel() {
// return model;
// }
//
// }
//
// Path: holder-compiler/src/main/java/com/steve/creact/processor/core/model/ModelCreator.java
// public interface ModelCreator {
//
// /**
// * create a model
// * @param element
// * @param processingEnv
// * @return
// */
// AbstractModel createModel(Element element, ProcessingEnvironment processingEnv);
// }
// Path: holder-compiler/src/main/java/com/steve/creact/processor/app/model/DataBeanModelCreator.java
import com.steve.creact.processor.core.model.AbstractModel;
import com.steve.creact.processor.core.model.ModelCreator;
import javax.annotation.processing.ProcessingEnvironment;
import javax.lang.model.element.Element;
package com.steve.creact.processor.app.model;
/**
* Created by Administrator on 2016/4/10.
*/
public class DataBeanModelCreator implements ModelCreator {
@Override
|
public AbstractModel createModel(Element element, ProcessingEnvironment processingEnv) {
|
simplify20/PowerfulRecyclerViewAdapter
|
library/src/main/java/com/steve/creact/library/HolderAPI.java
|
// Path: library/src/main/java/com/steve/creact/library/listener/TextWatcherAdapter.java
// public class TextWatcherAdapter implements TextWatcher {
//
// @Override
// public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//
// }
//
// @Override
// public void onTextChanged(CharSequence s, int start, int before, int count) {
//
// }
//
// @Override
// public void afterTextChanged(Editable s) {
//
// }
// }
|
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.support.annotation.DrawableRes;
import android.support.annotation.IdRes;
import android.view.View;
import com.steve.creact.library.listener.TextWatcherAdapter;
|
package com.steve.creact.library;
/**
* An interface provides useful APIs for all kinds of ViewHolder,and can be reused.
* Created by jiyang on 16/4/25.
*/
public interface HolderAPI {
Context getContext();
void removeFromCache(@IdRes int id);
void removeAll();
void initView();
<T extends View> T getView(@IdRes int id);
void setText(@IdRes int id, CharSequence text);
CharSequence getText(@IdRes int id);
void setOnItemClickListener(View.OnClickListener listener);
|
// Path: library/src/main/java/com/steve/creact/library/listener/TextWatcherAdapter.java
// public class TextWatcherAdapter implements TextWatcher {
//
// @Override
// public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//
// }
//
// @Override
// public void onTextChanged(CharSequence s, int start, int before, int count) {
//
// }
//
// @Override
// public void afterTextChanged(Editable s) {
//
// }
// }
// Path: library/src/main/java/com/steve/creact/library/HolderAPI.java
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.support.annotation.DrawableRes;
import android.support.annotation.IdRes;
import android.view.View;
import com.steve.creact.library.listener.TextWatcherAdapter;
package com.steve.creact.library;
/**
* An interface provides useful APIs for all kinds of ViewHolder,and can be reused.
* Created by jiyang on 16/4/25.
*/
public interface HolderAPI {
Context getContext();
void removeFromCache(@IdRes int id);
void removeAll();
void initView();
<T extends View> T getView(@IdRes int id);
void setText(@IdRes int id, CharSequence text);
CharSequence getText(@IdRes int id);
void setOnItemClickListener(View.OnClickListener listener);
|
void setTextWatcher(@IdRes int id, TextWatcherAdapter watcherAdapter);
|
simplify20/PowerfulRecyclerViewAdapter
|
library/src/main/java/com/steve/creact/library/viewholder/BaseRecyclerViewHolder.java
|
// Path: library/src/main/java/com/steve/creact/library/HolderAPI.java
// public interface HolderAPI {
//
// Context getContext();
// void removeFromCache(@IdRes int id);
// void removeAll();
// void initView();
// <T extends View> T getView(@IdRes int id);
//
// void setText(@IdRes int id, CharSequence text);
// CharSequence getText(@IdRes int id);
//
// void setOnItemClickListener(View.OnClickListener listener);
// void setTextWatcher(@IdRes int id, TextWatcherAdapter watcherAdapter);
// void setOnClickListener(@IdRes int id, View.OnClickListener onClickListener);
// void setOnLongClickListener(@IdRes int id, View.OnLongClickListener onLongClickListener);
//
// void setVisibility(@IdRes int id, int visibility);
//
// void setImageSrc(@IdRes int id, @DrawableRes int res);
// void setImageBitmap(@IdRes int id, Bitmap bitmap);
// void setImageDrawable(@IdRes int id, Drawable drawable);
// }
//
// Path: library/src/main/java/com/steve/creact/library/listener/TextWatcherAdapter.java
// public class TextWatcherAdapter implements TextWatcher {
//
// @Override
// public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//
// }
//
// @Override
// public void onTextChanged(CharSequence s, int start, int before, int count) {
//
// }
//
// @Override
// public void afterTextChanged(Editable s) {
//
// }
// }
|
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.support.annotation.DrawableRes;
import android.support.annotation.IdRes;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import com.steve.creact.library.HolderAPI;
import com.steve.creact.library.listener.TextWatcherAdapter;
|
holderAPI.removeFromCache( id );
}
/**
* remove all views in cache
*/
@Override
public void removeAll() {
holderAPI.removeAll();
}
/**
* subclass can overwrite this method
*/
@Override
public void initView() {
holderAPI.initView();
}
@Override
public <T extends View> T getView( @IdRes int id ) {
return holderAPI.getView( id );
}
@Override
public void setText( @IdRes int id, CharSequence text ) {
holderAPI.setText( id, text );
}
@Override
|
// Path: library/src/main/java/com/steve/creact/library/HolderAPI.java
// public interface HolderAPI {
//
// Context getContext();
// void removeFromCache(@IdRes int id);
// void removeAll();
// void initView();
// <T extends View> T getView(@IdRes int id);
//
// void setText(@IdRes int id, CharSequence text);
// CharSequence getText(@IdRes int id);
//
// void setOnItemClickListener(View.OnClickListener listener);
// void setTextWatcher(@IdRes int id, TextWatcherAdapter watcherAdapter);
// void setOnClickListener(@IdRes int id, View.OnClickListener onClickListener);
// void setOnLongClickListener(@IdRes int id, View.OnLongClickListener onLongClickListener);
//
// void setVisibility(@IdRes int id, int visibility);
//
// void setImageSrc(@IdRes int id, @DrawableRes int res);
// void setImageBitmap(@IdRes int id, Bitmap bitmap);
// void setImageDrawable(@IdRes int id, Drawable drawable);
// }
//
// Path: library/src/main/java/com/steve/creact/library/listener/TextWatcherAdapter.java
// public class TextWatcherAdapter implements TextWatcher {
//
// @Override
// public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//
// }
//
// @Override
// public void onTextChanged(CharSequence s, int start, int before, int count) {
//
// }
//
// @Override
// public void afterTextChanged(Editable s) {
//
// }
// }
// Path: library/src/main/java/com/steve/creact/library/viewholder/BaseRecyclerViewHolder.java
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.support.annotation.DrawableRes;
import android.support.annotation.IdRes;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import com.steve.creact.library.HolderAPI;
import com.steve.creact.library.listener.TextWatcherAdapter;
holderAPI.removeFromCache( id );
}
/**
* remove all views in cache
*/
@Override
public void removeAll() {
holderAPI.removeAll();
}
/**
* subclass can overwrite this method
*/
@Override
public void initView() {
holderAPI.initView();
}
@Override
public <T extends View> T getView( @IdRes int id ) {
return holderAPI.getView( id );
}
@Override
public void setText( @IdRes int id, CharSequence text ) {
holderAPI.setText( id, text );
}
@Override
|
public void setTextWatcher( @IdRes int id, TextWatcherAdapter watcherAdapter ) {
|
simplify20/PowerfulRecyclerViewAdapter
|
holder-compiler/src/main/java/com/steve/creact/processor/core/model/ElementVisitorAdapter.java
|
// Path: holder-compiler/src/main/java/com/steve/creact/processor/core/Logger.java
// public class Logger {
// public static boolean logOn = false;
// public static Logger getInstance(Messager messager) {
// if (instance == null) {
// synchronized (Logger.class) {
// if (instance != null)
// return instance;
// instance = new Logger(messager);
// }
// }
// return instance;
// }
//
// private static Messager actual;
// private static volatile Logger instance;
// private Logger(Messager actual) {
// this.actual = actual;
// }
//
// public void log(Diagnostic.Kind kind, String message) {
// if (logOn && actual != null) {
// actual.printMessage(kind, message);
// }
// }
// }
|
import com.steve.creact.processor.core.Logger;
import javax.annotation.processing.ProcessingEnvironment;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementVisitor;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.PackageElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.TypeParameterElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.util.Elements;
import javax.lang.model.util.Types;
|
package com.steve.creact.processor.core.model;
/**
* @see ElementVisitor
* Created by Administrator on 2016/4/10.
*/
public abstract class ElementVisitorAdapter<R, P> implements ElementVisitor<R, P> {
protected ProcessingEnvironment processingEnv;
protected Types typeUtils;
|
// Path: holder-compiler/src/main/java/com/steve/creact/processor/core/Logger.java
// public class Logger {
// public static boolean logOn = false;
// public static Logger getInstance(Messager messager) {
// if (instance == null) {
// synchronized (Logger.class) {
// if (instance != null)
// return instance;
// instance = new Logger(messager);
// }
// }
// return instance;
// }
//
// private static Messager actual;
// private static volatile Logger instance;
// private Logger(Messager actual) {
// this.actual = actual;
// }
//
// public void log(Diagnostic.Kind kind, String message) {
// if (logOn && actual != null) {
// actual.printMessage(kind, message);
// }
// }
// }
// Path: holder-compiler/src/main/java/com/steve/creact/processor/core/model/ElementVisitorAdapter.java
import com.steve.creact.processor.core.Logger;
import javax.annotation.processing.ProcessingEnvironment;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementVisitor;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.PackageElement;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.TypeParameterElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.util.Elements;
import javax.lang.model.util.Types;
package com.steve.creact.processor.core.model;
/**
* @see ElementVisitor
* Created by Administrator on 2016/4/10.
*/
public abstract class ElementVisitorAdapter<R, P> implements ElementVisitor<R, P> {
protected ProcessingEnvironment processingEnv;
protected Types typeUtils;
|
protected Logger logger;
|
simplify20/PowerfulRecyclerViewAdapter
|
holder-compiler/src/main/java/com/steve/creact/processor/app/model/DataBeanModel.java
|
// Path: holder-compiler/src/main/java/com/steve/creact/processor/core/model/AbstractModel.java
// public abstract class AbstractModel<R> {
//
// protected Element element;
// protected ElementVisitorAdapter elementVisitor;
// /**
// * real model
// */
// private R model;
//
// public AbstractModel(Element element) {
// this.element = element;
// }
//
// public boolean isClass() {
// return element.getKind().isClass();
// }
//
// public boolean isInterface() {
// return element.getKind().isInterface();
// }
//
// public boolean isField() {
//
// return element.getKind().isField();
// }
//
// public String getSimpleName() {
// return element.getSimpleName().toString();
// }
//
// public <P> void visit(P p) {
// model = (R) element.accept(this.elementVisitor, p);
// }
//
// public <P> void setElementVisitor(ElementVisitorAdapter<R, P> visitor) {
// this.elementVisitor = visitor;
// }
//
// public R getRealModel() {
// return model;
// }
//
// }
//
// Path: holder-compiler/src/main/java/com/steve/creact/processor/core/model/ElementVisitorAdapter.java
// public abstract class ElementVisitorAdapter<R, P> implements ElementVisitor<R, P> {
// protected ProcessingEnvironment processingEnv;
// protected Types typeUtils;
// protected Logger logger;
// protected Elements elements;
//
// public ElementVisitorAdapter(ProcessingEnvironment processingEnv) {
// this.processingEnv = processingEnv;
// this.typeUtils = processingEnv.getTypeUtils();
// this.logger = Logger.getInstance(processingEnv.getMessager());
// this.elements = processingEnv.getElementUtils();
// }
//
// @Override
// public R visit(Element e, P p) {
// return null;
// }
//
// @Override
// public R visit(Element e) {
// return null;
// }
//
// @Override
// public R visitPackage(PackageElement e, P p) {
// return null;
// }
//
// @Override
// public R visitType(TypeElement e, P p) {
// return null;
// }
//
// @Override
// public R visitVariable(VariableElement e, P p) {
// return null;
// }
//
// @Override
// public R visitExecutable(ExecutableElement e, P p) {
// return null;
// }
//
// @Override
// public R visitTypeParameter(TypeParameterElement e, P p) {
// return null;
// }
//
// @Override
// public R visitUnknown(Element e, P p) {
// return null;
// }
//
// protected String getSimpleName(Element e){
// return e.getSimpleName().toString();
// }
//
// protected String getQualifiedName(TypeElement te){
// return te.getQualifiedName().toString();
// }
//
// protected String getPackageName(TypeElement te){
// return getQualifiedName(te).replace("."+getSimpleName(te),"");
// }
// }
|
import com.steve.creact.annotation.DataBean;
import com.steve.creact.processor.core.model.AbstractModel;
import com.steve.creact.processor.core.model.ElementVisitorAdapter;
import javax.annotation.processing.ProcessingEnvironment;
import javax.lang.model.element.Element;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.MirroredTypeException;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
import javax.tools.Diagnostic;
|
package com.steve.creact.processor.app.model;
/**
* Created by Administrator on 2016/4/10.
*/
public class DataBeanModel extends AbstractModel<BeanInfo> {
public DataBeanModel(Element element, ProcessingEnvironment processingEnv) {
super(element);
setElementVisitor(DataBeanVisitor.getInstance(processingEnv));
visit(null);
}
/**
* Element Visitor
*/
|
// Path: holder-compiler/src/main/java/com/steve/creact/processor/core/model/AbstractModel.java
// public abstract class AbstractModel<R> {
//
// protected Element element;
// protected ElementVisitorAdapter elementVisitor;
// /**
// * real model
// */
// private R model;
//
// public AbstractModel(Element element) {
// this.element = element;
// }
//
// public boolean isClass() {
// return element.getKind().isClass();
// }
//
// public boolean isInterface() {
// return element.getKind().isInterface();
// }
//
// public boolean isField() {
//
// return element.getKind().isField();
// }
//
// public String getSimpleName() {
// return element.getSimpleName().toString();
// }
//
// public <P> void visit(P p) {
// model = (R) element.accept(this.elementVisitor, p);
// }
//
// public <P> void setElementVisitor(ElementVisitorAdapter<R, P> visitor) {
// this.elementVisitor = visitor;
// }
//
// public R getRealModel() {
// return model;
// }
//
// }
//
// Path: holder-compiler/src/main/java/com/steve/creact/processor/core/model/ElementVisitorAdapter.java
// public abstract class ElementVisitorAdapter<R, P> implements ElementVisitor<R, P> {
// protected ProcessingEnvironment processingEnv;
// protected Types typeUtils;
// protected Logger logger;
// protected Elements elements;
//
// public ElementVisitorAdapter(ProcessingEnvironment processingEnv) {
// this.processingEnv = processingEnv;
// this.typeUtils = processingEnv.getTypeUtils();
// this.logger = Logger.getInstance(processingEnv.getMessager());
// this.elements = processingEnv.getElementUtils();
// }
//
// @Override
// public R visit(Element e, P p) {
// return null;
// }
//
// @Override
// public R visit(Element e) {
// return null;
// }
//
// @Override
// public R visitPackage(PackageElement e, P p) {
// return null;
// }
//
// @Override
// public R visitType(TypeElement e, P p) {
// return null;
// }
//
// @Override
// public R visitVariable(VariableElement e, P p) {
// return null;
// }
//
// @Override
// public R visitExecutable(ExecutableElement e, P p) {
// return null;
// }
//
// @Override
// public R visitTypeParameter(TypeParameterElement e, P p) {
// return null;
// }
//
// @Override
// public R visitUnknown(Element e, P p) {
// return null;
// }
//
// protected String getSimpleName(Element e){
// return e.getSimpleName().toString();
// }
//
// protected String getQualifiedName(TypeElement te){
// return te.getQualifiedName().toString();
// }
//
// protected String getPackageName(TypeElement te){
// return getQualifiedName(te).replace("."+getSimpleName(te),"");
// }
// }
// Path: holder-compiler/src/main/java/com/steve/creact/processor/app/model/DataBeanModel.java
import com.steve.creact.annotation.DataBean;
import com.steve.creact.processor.core.model.AbstractModel;
import com.steve.creact.processor.core.model.ElementVisitorAdapter;
import javax.annotation.processing.ProcessingEnvironment;
import javax.lang.model.element.Element;
import javax.lang.model.element.TypeElement;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.MirroredTypeException;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
import javax.tools.Diagnostic;
package com.steve.creact.processor.app.model;
/**
* Created by Administrator on 2016/4/10.
*/
public class DataBeanModel extends AbstractModel<BeanInfo> {
public DataBeanModel(Element element, ProcessingEnvironment processingEnv) {
super(element);
setElementVisitor(DataBeanVisitor.getInstance(processingEnv));
visit(null);
}
/**
* Element Visitor
*/
|
public static class DataBeanVisitor extends ElementVisitorAdapter<BeanInfo, Void> {
|
simplify20/PowerfulRecyclerViewAdapter
|
library/src/main/java/com/steve/creact/library/viewholder/HolderHelper.java
|
// Path: library/src/main/java/com/steve/creact/library/HolderAPI.java
// public interface HolderAPI {
//
// Context getContext();
// void removeFromCache(@IdRes int id);
// void removeAll();
// void initView();
// <T extends View> T getView(@IdRes int id);
//
// void setText(@IdRes int id, CharSequence text);
// CharSequence getText(@IdRes int id);
//
// void setOnItemClickListener(View.OnClickListener listener);
// void setTextWatcher(@IdRes int id, TextWatcherAdapter watcherAdapter);
// void setOnClickListener(@IdRes int id, View.OnClickListener onClickListener);
// void setOnLongClickListener(@IdRes int id, View.OnLongClickListener onLongClickListener);
//
// void setVisibility(@IdRes int id, int visibility);
//
// void setImageSrc(@IdRes int id, @DrawableRes int res);
// void setImageBitmap(@IdRes int id, Bitmap bitmap);
// void setImageDrawable(@IdRes int id, Drawable drawable);
// }
//
// Path: library/src/main/java/com/steve/creact/library/listener/TextWatcherAdapter.java
// public class TextWatcherAdapter implements TextWatcher {
//
// @Override
// public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//
// }
//
// @Override
// public void onTextChanged(CharSequence s, int start, int before, int count) {
//
// }
//
// @Override
// public void afterTextChanged(Editable s) {
//
// }
// }
|
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.support.annotation.DrawableRes;
import android.support.annotation.IdRes;
import android.util.SparseArray;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.steve.creact.library.HolderAPI;
import com.steve.creact.library.listener.TextWatcherAdapter;
|
} catch (ClassCastException e) {
e.printStackTrace();
return result;
}
//add to cache
views.put(id, View.class.cast(result));
return result;
}
@Override
public void setText( @IdRes int id, CharSequence text ) {
TextView targetTxt = getView(id);
if (targetTxt != null)
targetTxt.setText(text);
}
@Override
public CharSequence getText( @IdRes int id ) {
TextView targetTxt = getView(id);
if (targetTxt != null)
return targetTxt.getText();
return "";
}
@Override
public void setOnItemClickListener( View.OnClickListener listener ) {
itemView.setOnClickListener(listener);
}
@Override
|
// Path: library/src/main/java/com/steve/creact/library/HolderAPI.java
// public interface HolderAPI {
//
// Context getContext();
// void removeFromCache(@IdRes int id);
// void removeAll();
// void initView();
// <T extends View> T getView(@IdRes int id);
//
// void setText(@IdRes int id, CharSequence text);
// CharSequence getText(@IdRes int id);
//
// void setOnItemClickListener(View.OnClickListener listener);
// void setTextWatcher(@IdRes int id, TextWatcherAdapter watcherAdapter);
// void setOnClickListener(@IdRes int id, View.OnClickListener onClickListener);
// void setOnLongClickListener(@IdRes int id, View.OnLongClickListener onLongClickListener);
//
// void setVisibility(@IdRes int id, int visibility);
//
// void setImageSrc(@IdRes int id, @DrawableRes int res);
// void setImageBitmap(@IdRes int id, Bitmap bitmap);
// void setImageDrawable(@IdRes int id, Drawable drawable);
// }
//
// Path: library/src/main/java/com/steve/creact/library/listener/TextWatcherAdapter.java
// public class TextWatcherAdapter implements TextWatcher {
//
// @Override
// public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//
// }
//
// @Override
// public void onTextChanged(CharSequence s, int start, int before, int count) {
//
// }
//
// @Override
// public void afterTextChanged(Editable s) {
//
// }
// }
// Path: library/src/main/java/com/steve/creact/library/viewholder/HolderHelper.java
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.support.annotation.DrawableRes;
import android.support.annotation.IdRes;
import android.util.SparseArray;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.steve.creact.library.HolderAPI;
import com.steve.creact.library.listener.TextWatcherAdapter;
} catch (ClassCastException e) {
e.printStackTrace();
return result;
}
//add to cache
views.put(id, View.class.cast(result));
return result;
}
@Override
public void setText( @IdRes int id, CharSequence text ) {
TextView targetTxt = getView(id);
if (targetTxt != null)
targetTxt.setText(text);
}
@Override
public CharSequence getText( @IdRes int id ) {
TextView targetTxt = getView(id);
if (targetTxt != null)
return targetTxt.getText();
return "";
}
@Override
public void setOnItemClickListener( View.OnClickListener listener ) {
itemView.setOnClickListener(listener);
}
@Override
|
public void setTextWatcher( @IdRes int id, TextWatcherAdapter watcherAdapter ) {
|
simplify20/PowerfulRecyclerViewAdapter
|
holder-compiler/src/main/java/com/steve/creact/processor/core/factory/ViewGeneratorFactory.java
|
// Path: holder-compiler/src/main/java/com/steve/creact/processor/core/view/ViewGenerator.java
// public interface ViewGenerator<T> {
//
// /**
// * Generate View according to the model
// * @param abstractModel
// * @param processingEnv
// */
// void generate(AbstractModel<T> abstractModel,ProcessingEnvironment processingEnv);
// }
|
import com.steve.creact.processor.core.view.ViewGenerator;
|
package com.steve.creact.processor.core.factory;
/**
* Created by Administrator on 2016/4/10.
*/
public class ViewGeneratorFactory {
private ViewGeneratorFactory() {
}
|
// Path: holder-compiler/src/main/java/com/steve/creact/processor/core/view/ViewGenerator.java
// public interface ViewGenerator<T> {
//
// /**
// * Generate View according to the model
// * @param abstractModel
// * @param processingEnv
// */
// void generate(AbstractModel<T> abstractModel,ProcessingEnvironment processingEnv);
// }
// Path: holder-compiler/src/main/java/com/steve/creact/processor/core/factory/ViewGeneratorFactory.java
import com.steve.creact.processor.core.view.ViewGenerator;
package com.steve.creact.processor.core.factory;
/**
* Created by Administrator on 2016/4/10.
*/
public class ViewGeneratorFactory {
private ViewGeneratorFactory() {
}
|
public static ViewGenerator getGenerator(Class<? extends ViewGenerator> clz) {
|
simplify20/PowerfulRecyclerViewAdapter
|
library/src/main/java/com/steve/creact/library/adapter/CommonRecyclerAdapter.java
|
// Path: library/src/main/java/com/steve/creact/library/display/CommonDisplayBean.java
// public class CommonDisplayBean extends BaseDisplayBean<BaseRecyclerViewHolder> {
// private int layoutId;
//
// public CommonDisplayBean(int layoutId) {
// this.layoutId = layoutId;
// }
//
// @Override
// public BaseRecyclerViewHolder createHolder(ViewGroup parent) {
// return new BaseRecyclerViewHolder(getView(parent, layoutId)){
//
// @Override
// public void setData(Object data) {
// //do nothing
// }
// };
// }
// }
//
// Path: library/src/main/java/com/steve/creact/library/display/DataBean.java
// public interface DataBean<T,VH extends BaseRecyclerViewHolder> extends DisplayBean<VH> {
// void bindData(VH holder);
// T getData();
// }
//
// Path: library/src/main/java/com/steve/creact/library/display/DisplayBean.java
// public interface DisplayBean<VH extends BaseRecyclerViewHolder> {
//
// VH createHolder(ViewGroup parent);
// }
//
// Path: library/src/main/java/com/steve/creact/library/viewholder/BaseRecyclerViewHolder.java
// public abstract class BaseRecyclerViewHolder<D> extends RecyclerView.ViewHolder implements HolderAPI {
//
// protected final HolderAPI holderAPI;
//
// public BaseRecyclerViewHolder( View itemView ) {
// super( itemView );
// holderAPI = new HolderHelper( itemView );
// initView();
// }
//
// @Override
// public Context getContext() {
// return holderAPI.getContext();
// }
//
// @Override
// public void setOnItemClickListener( View.OnClickListener listener ) {
// holderAPI.setOnItemClickListener( listener );
// }
//
// /**
// * Notes:when you remove a view,you must remove it from cache
// *
// * @param id
// */
// @Override
// public void removeFromCache( @IdRes int id ) {
// holderAPI.removeFromCache( id );
// }
//
// /**
// * remove all views in cache
// */
// @Override
// public void removeAll() {
// holderAPI.removeAll();
// }
//
// /**
// * subclass can overwrite this method
// */
// @Override
// public void initView() {
// holderAPI.initView();
// }
//
// @Override
// public <T extends View> T getView( @IdRes int id ) {
// return holderAPI.getView( id );
// }
//
// @Override
// public void setText( @IdRes int id, CharSequence text ) {
// holderAPI.setText( id, text );
// }
//
// @Override
// public void setTextWatcher( @IdRes int id, TextWatcherAdapter watcherAdapter ) {
// holderAPI.setTextWatcher( id, watcherAdapter );
// }
//
// @Override
// public CharSequence getText( @IdRes int id ) {
// return holderAPI.getText( id );
// }
//
// @Override
// public void setOnClickListener( @IdRes int id, View.OnClickListener onClickListener ) {
// holderAPI.setOnClickListener( id, onClickListener );
// }
//
// @Override
// public void setOnLongClickListener( @IdRes int id, View.OnLongClickListener onLongClickListener ) {
// holderAPI.setOnLongClickListener( id, onLongClickListener );
// }
//
// @Override
// public void setVisibility( @IdRes int id, int visibility ) {
// holderAPI.setVisibility( id, visibility );
// }
//
// @Override
// public void setImageSrc( @IdRes int id, @DrawableRes int res ) {
// holderAPI.setImageSrc( id, res );
// }
//
// @Override
// public void setImageDrawable( @IdRes int id, Drawable drawable ) {
// holderAPI.setImageDrawable( id, drawable );
// }
//
// @Override
// public void setImageBitmap( @IdRes int id, Bitmap bitmap ) {
// holderAPI.setImageBitmap( id, bitmap );
// }
//
// public abstract void setData( D data );
// }
|
import android.view.ViewGroup;
import com.steve.creact.library.display.CommonDisplayBean;
import com.steve.creact.library.display.DataBean;
import com.steve.creact.library.display.DisplayBean;
import com.steve.creact.library.viewholder.BaseRecyclerViewHolder;
import java.util.ArrayList;
import java.util.List;
|
package com.steve.creact.library.adapter;
/**
* A common adapter which extends from BaseRecyclerAdapter,can handle ViewHolder's creation
* and bind data to ViewHolder.
* <p/>
* Use this class as your RecyclerView's adapter,it will do all tasks for you,
* what you need to do is extending BaseRecyclerViewHolder,writing your custom ViewHolder class,
* and extending BaseDataBean ,writing your DataBean,or just using CommonDisplayBean.
* <p/>
* Alternatively,you can use @DataBean annotation(which can generate DataBean class at compiler time for you)
* on your custom ViewHolder class
*
* @see DisplayBean
* @see DataBean
* @see CommonDisplayBean
* @see BaseRecyclerViewHolder
*/
public class CommonRecyclerAdapter extends BaseRecyclerAdapter<DisplayBean, BaseRecyclerViewHolder> {
private boolean userAnimation = false;
//those bean instance will use to create concrete ViewHolders
private List<DisplayBean> createBeans = new ArrayList<>();
//those bean class will use to get correct item type
private List<Class<DisplayBean>> createBeanClass = new ArrayList<>();
//load data
@Override
public void loadData(List<? extends DisplayBean> dataSet) {
if (dataSet == null || dataSet.size() == 0)
return;
for (int i = 0; i < dataSet.size(); i++) {
DisplayBean bean = dataSet.get(i);
if (!createBeanClass.contains(bean.getClass())) {
addCreateBean(bean);
}
}
super.loadData(dataSet);
}
@Override
public BaseRecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
DisplayBean createBean = createBeans.get(viewType);
return createBean.createHolder(parent);
}
@Override
public void onBindViewHolder(BaseRecyclerViewHolder holder, int position) {
DisplayBean bindBean = data.get(position);
|
// Path: library/src/main/java/com/steve/creact/library/display/CommonDisplayBean.java
// public class CommonDisplayBean extends BaseDisplayBean<BaseRecyclerViewHolder> {
// private int layoutId;
//
// public CommonDisplayBean(int layoutId) {
// this.layoutId = layoutId;
// }
//
// @Override
// public BaseRecyclerViewHolder createHolder(ViewGroup parent) {
// return new BaseRecyclerViewHolder(getView(parent, layoutId)){
//
// @Override
// public void setData(Object data) {
// //do nothing
// }
// };
// }
// }
//
// Path: library/src/main/java/com/steve/creact/library/display/DataBean.java
// public interface DataBean<T,VH extends BaseRecyclerViewHolder> extends DisplayBean<VH> {
// void bindData(VH holder);
// T getData();
// }
//
// Path: library/src/main/java/com/steve/creact/library/display/DisplayBean.java
// public interface DisplayBean<VH extends BaseRecyclerViewHolder> {
//
// VH createHolder(ViewGroup parent);
// }
//
// Path: library/src/main/java/com/steve/creact/library/viewholder/BaseRecyclerViewHolder.java
// public abstract class BaseRecyclerViewHolder<D> extends RecyclerView.ViewHolder implements HolderAPI {
//
// protected final HolderAPI holderAPI;
//
// public BaseRecyclerViewHolder( View itemView ) {
// super( itemView );
// holderAPI = new HolderHelper( itemView );
// initView();
// }
//
// @Override
// public Context getContext() {
// return holderAPI.getContext();
// }
//
// @Override
// public void setOnItemClickListener( View.OnClickListener listener ) {
// holderAPI.setOnItemClickListener( listener );
// }
//
// /**
// * Notes:when you remove a view,you must remove it from cache
// *
// * @param id
// */
// @Override
// public void removeFromCache( @IdRes int id ) {
// holderAPI.removeFromCache( id );
// }
//
// /**
// * remove all views in cache
// */
// @Override
// public void removeAll() {
// holderAPI.removeAll();
// }
//
// /**
// * subclass can overwrite this method
// */
// @Override
// public void initView() {
// holderAPI.initView();
// }
//
// @Override
// public <T extends View> T getView( @IdRes int id ) {
// return holderAPI.getView( id );
// }
//
// @Override
// public void setText( @IdRes int id, CharSequence text ) {
// holderAPI.setText( id, text );
// }
//
// @Override
// public void setTextWatcher( @IdRes int id, TextWatcherAdapter watcherAdapter ) {
// holderAPI.setTextWatcher( id, watcherAdapter );
// }
//
// @Override
// public CharSequence getText( @IdRes int id ) {
// return holderAPI.getText( id );
// }
//
// @Override
// public void setOnClickListener( @IdRes int id, View.OnClickListener onClickListener ) {
// holderAPI.setOnClickListener( id, onClickListener );
// }
//
// @Override
// public void setOnLongClickListener( @IdRes int id, View.OnLongClickListener onLongClickListener ) {
// holderAPI.setOnLongClickListener( id, onLongClickListener );
// }
//
// @Override
// public void setVisibility( @IdRes int id, int visibility ) {
// holderAPI.setVisibility( id, visibility );
// }
//
// @Override
// public void setImageSrc( @IdRes int id, @DrawableRes int res ) {
// holderAPI.setImageSrc( id, res );
// }
//
// @Override
// public void setImageDrawable( @IdRes int id, Drawable drawable ) {
// holderAPI.setImageDrawable( id, drawable );
// }
//
// @Override
// public void setImageBitmap( @IdRes int id, Bitmap bitmap ) {
// holderAPI.setImageBitmap( id, bitmap );
// }
//
// public abstract void setData( D data );
// }
// Path: library/src/main/java/com/steve/creact/library/adapter/CommonRecyclerAdapter.java
import android.view.ViewGroup;
import com.steve.creact.library.display.CommonDisplayBean;
import com.steve.creact.library.display.DataBean;
import com.steve.creact.library.display.DisplayBean;
import com.steve.creact.library.viewholder.BaseRecyclerViewHolder;
import java.util.ArrayList;
import java.util.List;
package com.steve.creact.library.adapter;
/**
* A common adapter which extends from BaseRecyclerAdapter,can handle ViewHolder's creation
* and bind data to ViewHolder.
* <p/>
* Use this class as your RecyclerView's adapter,it will do all tasks for you,
* what you need to do is extending BaseRecyclerViewHolder,writing your custom ViewHolder class,
* and extending BaseDataBean ,writing your DataBean,or just using CommonDisplayBean.
* <p/>
* Alternatively,you can use @DataBean annotation(which can generate DataBean class at compiler time for you)
* on your custom ViewHolder class
*
* @see DisplayBean
* @see DataBean
* @see CommonDisplayBean
* @see BaseRecyclerViewHolder
*/
public class CommonRecyclerAdapter extends BaseRecyclerAdapter<DisplayBean, BaseRecyclerViewHolder> {
private boolean userAnimation = false;
//those bean instance will use to create concrete ViewHolders
private List<DisplayBean> createBeans = new ArrayList<>();
//those bean class will use to get correct item type
private List<Class<DisplayBean>> createBeanClass = new ArrayList<>();
//load data
@Override
public void loadData(List<? extends DisplayBean> dataSet) {
if (dataSet == null || dataSet.size() == 0)
return;
for (int i = 0; i < dataSet.size(); i++) {
DisplayBean bean = dataSet.get(i);
if (!createBeanClass.contains(bean.getClass())) {
addCreateBean(bean);
}
}
super.loadData(dataSet);
}
@Override
public BaseRecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
DisplayBean createBean = createBeans.get(viewType);
return createBean.createHolder(parent);
}
@Override
public void onBindViewHolder(BaseRecyclerViewHolder holder, int position) {
DisplayBean bindBean = data.get(position);
|
if (bindBean instanceof DataBean) {
|
simplify20/PowerfulRecyclerViewAdapter
|
holder-compiler/src/main/java/com/steve/creact/processor/core/view/CommonReplacer.java
|
// Path: holder-compiler/src/main/java/com/steve/creact/processor/core/Constants.java
// public final class Constants {
// private Constants(){}
//
// public static final String TEMPLATE_PATH = "templates/databean-source.tm";
// public static final String PACKAGE_NAME = "${PACKAGE_NAME}";
// public static final String DATA_ENTITY_FULL_QUALIFIED_CLASS_NAME = "${DATA_ENTITY_FULL_QUALIFIED_CLASS_NAME}";
// public static final String VIEW_HOLDER_FULL_QUALIFIED_CLASS_NAME = "${VIEW_HOLDER_FULL_QUALIFIED_CLASS_NAME}";
// public static final String VIEW_HOLDER_SIMPLE_CLASS_NAME = "${VIEW_HOLDER_SIMPLE_CLASS_NAME}";
// public static final String DATA_BEAN_SIMPLE_CLASS_NAME = "${DATA_BEAN_SIMPLE_CLASS_NAME}";
// public static final String DATA_ENTITY_SIMPLE_CLASS_NAME = "${DATA_ENTITY_SIMPLE_CLASS_NAME}";
// }
|
import com.steve.creact.processor.core.Constants;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
|
package com.steve.creact.processor.core.view;
/**
* Created by Administrator on 2016/4/10.
*/
public class CommonReplacer implements Replacer {
public static CommonReplacer getInstance() {
if (instance == null) {
synchronized (CommonReplacer.class) {
if (instance != null)
return instance;
instance = new CommonReplacer();
}
}
return instance;
}
private static HashSet<String> placeHolders = new HashSet<>();
private volatile static CommonReplacer instance;
private CommonReplacer() {
}
static {
|
// Path: holder-compiler/src/main/java/com/steve/creact/processor/core/Constants.java
// public final class Constants {
// private Constants(){}
//
// public static final String TEMPLATE_PATH = "templates/databean-source.tm";
// public static final String PACKAGE_NAME = "${PACKAGE_NAME}";
// public static final String DATA_ENTITY_FULL_QUALIFIED_CLASS_NAME = "${DATA_ENTITY_FULL_QUALIFIED_CLASS_NAME}";
// public static final String VIEW_HOLDER_FULL_QUALIFIED_CLASS_NAME = "${VIEW_HOLDER_FULL_QUALIFIED_CLASS_NAME}";
// public static final String VIEW_HOLDER_SIMPLE_CLASS_NAME = "${VIEW_HOLDER_SIMPLE_CLASS_NAME}";
// public static final String DATA_BEAN_SIMPLE_CLASS_NAME = "${DATA_BEAN_SIMPLE_CLASS_NAME}";
// public static final String DATA_ENTITY_SIMPLE_CLASS_NAME = "${DATA_ENTITY_SIMPLE_CLASS_NAME}";
// }
// Path: holder-compiler/src/main/java/com/steve/creact/processor/core/view/CommonReplacer.java
import com.steve.creact.processor.core.Constants;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
package com.steve.creact.processor.core.view;
/**
* Created by Administrator on 2016/4/10.
*/
public class CommonReplacer implements Replacer {
public static CommonReplacer getInstance() {
if (instance == null) {
synchronized (CommonReplacer.class) {
if (instance != null)
return instance;
instance = new CommonReplacer();
}
}
return instance;
}
private static HashSet<String> placeHolders = new HashSet<>();
private volatile static CommonReplacer instance;
private CommonReplacer() {
}
static {
|
placeHolders.add(Constants.PACKAGE_NAME);
|
simplify20/PowerfulRecyclerViewAdapter
|
holder-compiler/src/main/java/com/steve/creact/processor/core/BaseProcessor.java
|
// Path: holder-compiler/src/main/java/com/steve/creact/processor/core/model/AbstractModel.java
// public abstract class AbstractModel<R> {
//
// protected Element element;
// protected ElementVisitorAdapter elementVisitor;
// /**
// * real model
// */
// private R model;
//
// public AbstractModel(Element element) {
// this.element = element;
// }
//
// public boolean isClass() {
// return element.getKind().isClass();
// }
//
// public boolean isInterface() {
// return element.getKind().isInterface();
// }
//
// public boolean isField() {
//
// return element.getKind().isField();
// }
//
// public String getSimpleName() {
// return element.getSimpleName().toString();
// }
//
// public <P> void visit(P p) {
// model = (R) element.accept(this.elementVisitor, p);
// }
//
// public <P> void setElementVisitor(ElementVisitorAdapter<R, P> visitor) {
// this.elementVisitor = visitor;
// }
//
// public R getRealModel() {
// return model;
// }
//
// }
//
// Path: holder-compiler/src/main/java/com/steve/creact/processor/core/model/ModelCreator.java
// public interface ModelCreator {
//
// /**
// * create a model
// * @param element
// * @param processingEnv
// * @return
// */
// AbstractModel createModel(Element element, ProcessingEnvironment processingEnv);
// }
//
// Path: holder-compiler/src/main/java/com/steve/creact/processor/core/view/ViewGenerator.java
// public interface ViewGenerator<T> {
//
// /**
// * Generate View according to the model
// * @param abstractModel
// * @param processingEnv
// */
// void generate(AbstractModel<T> abstractModel,ProcessingEnvironment processingEnv);
// }
|
import com.steve.creact.processor.core.model.AbstractModel;
import com.steve.creact.processor.core.model.ModelCreator;
import com.steve.creact.processor.core.view.ViewGenerator;
import java.lang.annotation.Annotation;
import java.util.Set;
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.RoundEnvironment;
import javax.lang.model.element.Element;
import javax.lang.model.element.TypeElement;
import javax.tools.Diagnostic;
|
package com.steve.creact.processor.core;
/**
* Created by Administrator on 2016/4/17.
*/
public abstract class BaseProcessor extends AbstractProcessor {
public enum ProcessType {
PROCESS_ANNOTATION_OF_TYPE_ELEMENT,
PROCESS_ANNOTATION_OF_ELEMENT
}
protected Set<? extends Element> elements;
protected Set<? extends TypeElement> typeElements;
protected Logger logger;
|
// Path: holder-compiler/src/main/java/com/steve/creact/processor/core/model/AbstractModel.java
// public abstract class AbstractModel<R> {
//
// protected Element element;
// protected ElementVisitorAdapter elementVisitor;
// /**
// * real model
// */
// private R model;
//
// public AbstractModel(Element element) {
// this.element = element;
// }
//
// public boolean isClass() {
// return element.getKind().isClass();
// }
//
// public boolean isInterface() {
// return element.getKind().isInterface();
// }
//
// public boolean isField() {
//
// return element.getKind().isField();
// }
//
// public String getSimpleName() {
// return element.getSimpleName().toString();
// }
//
// public <P> void visit(P p) {
// model = (R) element.accept(this.elementVisitor, p);
// }
//
// public <P> void setElementVisitor(ElementVisitorAdapter<R, P> visitor) {
// this.elementVisitor = visitor;
// }
//
// public R getRealModel() {
// return model;
// }
//
// }
//
// Path: holder-compiler/src/main/java/com/steve/creact/processor/core/model/ModelCreator.java
// public interface ModelCreator {
//
// /**
// * create a model
// * @param element
// * @param processingEnv
// * @return
// */
// AbstractModel createModel(Element element, ProcessingEnvironment processingEnv);
// }
//
// Path: holder-compiler/src/main/java/com/steve/creact/processor/core/view/ViewGenerator.java
// public interface ViewGenerator<T> {
//
// /**
// * Generate View according to the model
// * @param abstractModel
// * @param processingEnv
// */
// void generate(AbstractModel<T> abstractModel,ProcessingEnvironment processingEnv);
// }
// Path: holder-compiler/src/main/java/com/steve/creact/processor/core/BaseProcessor.java
import com.steve.creact.processor.core.model.AbstractModel;
import com.steve.creact.processor.core.model.ModelCreator;
import com.steve.creact.processor.core.view.ViewGenerator;
import java.lang.annotation.Annotation;
import java.util.Set;
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.RoundEnvironment;
import javax.lang.model.element.Element;
import javax.lang.model.element.TypeElement;
import javax.tools.Diagnostic;
package com.steve.creact.processor.core;
/**
* Created by Administrator on 2016/4/17.
*/
public abstract class BaseProcessor extends AbstractProcessor {
public enum ProcessType {
PROCESS_ANNOTATION_OF_TYPE_ELEMENT,
PROCESS_ANNOTATION_OF_ELEMENT
}
protected Set<? extends Element> elements;
protected Set<? extends TypeElement> typeElements;
protected Logger logger;
|
protected ModelCreator modelCreator;
|
simplify20/PowerfulRecyclerViewAdapter
|
holder-compiler/src/main/java/com/steve/creact/processor/core/BaseProcessor.java
|
// Path: holder-compiler/src/main/java/com/steve/creact/processor/core/model/AbstractModel.java
// public abstract class AbstractModel<R> {
//
// protected Element element;
// protected ElementVisitorAdapter elementVisitor;
// /**
// * real model
// */
// private R model;
//
// public AbstractModel(Element element) {
// this.element = element;
// }
//
// public boolean isClass() {
// return element.getKind().isClass();
// }
//
// public boolean isInterface() {
// return element.getKind().isInterface();
// }
//
// public boolean isField() {
//
// return element.getKind().isField();
// }
//
// public String getSimpleName() {
// return element.getSimpleName().toString();
// }
//
// public <P> void visit(P p) {
// model = (R) element.accept(this.elementVisitor, p);
// }
//
// public <P> void setElementVisitor(ElementVisitorAdapter<R, P> visitor) {
// this.elementVisitor = visitor;
// }
//
// public R getRealModel() {
// return model;
// }
//
// }
//
// Path: holder-compiler/src/main/java/com/steve/creact/processor/core/model/ModelCreator.java
// public interface ModelCreator {
//
// /**
// * create a model
// * @param element
// * @param processingEnv
// * @return
// */
// AbstractModel createModel(Element element, ProcessingEnvironment processingEnv);
// }
//
// Path: holder-compiler/src/main/java/com/steve/creact/processor/core/view/ViewGenerator.java
// public interface ViewGenerator<T> {
//
// /**
// * Generate View according to the model
// * @param abstractModel
// * @param processingEnv
// */
// void generate(AbstractModel<T> abstractModel,ProcessingEnvironment processingEnv);
// }
|
import com.steve.creact.processor.core.model.AbstractModel;
import com.steve.creact.processor.core.model.ModelCreator;
import com.steve.creact.processor.core.view.ViewGenerator;
import java.lang.annotation.Annotation;
import java.util.Set;
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.RoundEnvironment;
import javax.lang.model.element.Element;
import javax.lang.model.element.TypeElement;
import javax.tools.Diagnostic;
|
package com.steve.creact.processor.core;
/**
* Created by Administrator on 2016/4/17.
*/
public abstract class BaseProcessor extends AbstractProcessor {
public enum ProcessType {
PROCESS_ANNOTATION_OF_TYPE_ELEMENT,
PROCESS_ANNOTATION_OF_ELEMENT
}
protected Set<? extends Element> elements;
protected Set<? extends TypeElement> typeElements;
protected Logger logger;
protected ModelCreator modelCreator;
|
// Path: holder-compiler/src/main/java/com/steve/creact/processor/core/model/AbstractModel.java
// public abstract class AbstractModel<R> {
//
// protected Element element;
// protected ElementVisitorAdapter elementVisitor;
// /**
// * real model
// */
// private R model;
//
// public AbstractModel(Element element) {
// this.element = element;
// }
//
// public boolean isClass() {
// return element.getKind().isClass();
// }
//
// public boolean isInterface() {
// return element.getKind().isInterface();
// }
//
// public boolean isField() {
//
// return element.getKind().isField();
// }
//
// public String getSimpleName() {
// return element.getSimpleName().toString();
// }
//
// public <P> void visit(P p) {
// model = (R) element.accept(this.elementVisitor, p);
// }
//
// public <P> void setElementVisitor(ElementVisitorAdapter<R, P> visitor) {
// this.elementVisitor = visitor;
// }
//
// public R getRealModel() {
// return model;
// }
//
// }
//
// Path: holder-compiler/src/main/java/com/steve/creact/processor/core/model/ModelCreator.java
// public interface ModelCreator {
//
// /**
// * create a model
// * @param element
// * @param processingEnv
// * @return
// */
// AbstractModel createModel(Element element, ProcessingEnvironment processingEnv);
// }
//
// Path: holder-compiler/src/main/java/com/steve/creact/processor/core/view/ViewGenerator.java
// public interface ViewGenerator<T> {
//
// /**
// * Generate View according to the model
// * @param abstractModel
// * @param processingEnv
// */
// void generate(AbstractModel<T> abstractModel,ProcessingEnvironment processingEnv);
// }
// Path: holder-compiler/src/main/java/com/steve/creact/processor/core/BaseProcessor.java
import com.steve.creact.processor.core.model.AbstractModel;
import com.steve.creact.processor.core.model.ModelCreator;
import com.steve.creact.processor.core.view.ViewGenerator;
import java.lang.annotation.Annotation;
import java.util.Set;
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.RoundEnvironment;
import javax.lang.model.element.Element;
import javax.lang.model.element.TypeElement;
import javax.tools.Diagnostic;
package com.steve.creact.processor.core;
/**
* Created by Administrator on 2016/4/17.
*/
public abstract class BaseProcessor extends AbstractProcessor {
public enum ProcessType {
PROCESS_ANNOTATION_OF_TYPE_ELEMENT,
PROCESS_ANNOTATION_OF_ELEMENT
}
protected Set<? extends Element> elements;
protected Set<? extends TypeElement> typeElements;
protected Logger logger;
protected ModelCreator modelCreator;
|
protected ViewGenerator viewGenerator;
|
simplify20/PowerfulRecyclerViewAdapter
|
holder-compiler/src/main/java/com/steve/creact/processor/core/BaseProcessor.java
|
// Path: holder-compiler/src/main/java/com/steve/creact/processor/core/model/AbstractModel.java
// public abstract class AbstractModel<R> {
//
// protected Element element;
// protected ElementVisitorAdapter elementVisitor;
// /**
// * real model
// */
// private R model;
//
// public AbstractModel(Element element) {
// this.element = element;
// }
//
// public boolean isClass() {
// return element.getKind().isClass();
// }
//
// public boolean isInterface() {
// return element.getKind().isInterface();
// }
//
// public boolean isField() {
//
// return element.getKind().isField();
// }
//
// public String getSimpleName() {
// return element.getSimpleName().toString();
// }
//
// public <P> void visit(P p) {
// model = (R) element.accept(this.elementVisitor, p);
// }
//
// public <P> void setElementVisitor(ElementVisitorAdapter<R, P> visitor) {
// this.elementVisitor = visitor;
// }
//
// public R getRealModel() {
// return model;
// }
//
// }
//
// Path: holder-compiler/src/main/java/com/steve/creact/processor/core/model/ModelCreator.java
// public interface ModelCreator {
//
// /**
// * create a model
// * @param element
// * @param processingEnv
// * @return
// */
// AbstractModel createModel(Element element, ProcessingEnvironment processingEnv);
// }
//
// Path: holder-compiler/src/main/java/com/steve/creact/processor/core/view/ViewGenerator.java
// public interface ViewGenerator<T> {
//
// /**
// * Generate View according to the model
// * @param abstractModel
// * @param processingEnv
// */
// void generate(AbstractModel<T> abstractModel,ProcessingEnvironment processingEnv);
// }
|
import com.steve.creact.processor.core.model.AbstractModel;
import com.steve.creact.processor.core.model.ModelCreator;
import com.steve.creact.processor.core.view.ViewGenerator;
import java.lang.annotation.Annotation;
import java.util.Set;
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.RoundEnvironment;
import javax.lang.model.element.Element;
import javax.lang.model.element.TypeElement;
import javax.tools.Diagnostic;
|
this.viewGenerator = viewGenerator;
}
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
logger = Logger.getInstance(processingEnv.getMessager());
typeElements = annotations;
elements = roundEnv.getElementsAnnotatedWith(getTargetAnnotationClass());
long startR = System.currentTimeMillis();
switch (getProcessType()) {
case PROCESS_ANNOTATION_OF_ELEMENT:
processEachElement();
break;
case PROCESS_ANNOTATION_OF_TYPE_ELEMENT:
processEachTypeElement();
break;
default:
throw new IllegalStateException("not a supported type");
}
logger.log(Diagnostic.Kind.NOTE,
"\nFinished a round,time:" + (System.currentTimeMillis() - startR) + "ms");
return true;
}
private void processEachTypeElement() {
for (Element element : typeElements) {
logger.log(Diagnostic.Kind.NOTE,
"\nCollect Model Info:");
long start = System.currentTimeMillis();
//collect Model info
|
// Path: holder-compiler/src/main/java/com/steve/creact/processor/core/model/AbstractModel.java
// public abstract class AbstractModel<R> {
//
// protected Element element;
// protected ElementVisitorAdapter elementVisitor;
// /**
// * real model
// */
// private R model;
//
// public AbstractModel(Element element) {
// this.element = element;
// }
//
// public boolean isClass() {
// return element.getKind().isClass();
// }
//
// public boolean isInterface() {
// return element.getKind().isInterface();
// }
//
// public boolean isField() {
//
// return element.getKind().isField();
// }
//
// public String getSimpleName() {
// return element.getSimpleName().toString();
// }
//
// public <P> void visit(P p) {
// model = (R) element.accept(this.elementVisitor, p);
// }
//
// public <P> void setElementVisitor(ElementVisitorAdapter<R, P> visitor) {
// this.elementVisitor = visitor;
// }
//
// public R getRealModel() {
// return model;
// }
//
// }
//
// Path: holder-compiler/src/main/java/com/steve/creact/processor/core/model/ModelCreator.java
// public interface ModelCreator {
//
// /**
// * create a model
// * @param element
// * @param processingEnv
// * @return
// */
// AbstractModel createModel(Element element, ProcessingEnvironment processingEnv);
// }
//
// Path: holder-compiler/src/main/java/com/steve/creact/processor/core/view/ViewGenerator.java
// public interface ViewGenerator<T> {
//
// /**
// * Generate View according to the model
// * @param abstractModel
// * @param processingEnv
// */
// void generate(AbstractModel<T> abstractModel,ProcessingEnvironment processingEnv);
// }
// Path: holder-compiler/src/main/java/com/steve/creact/processor/core/BaseProcessor.java
import com.steve.creact.processor.core.model.AbstractModel;
import com.steve.creact.processor.core.model.ModelCreator;
import com.steve.creact.processor.core.view.ViewGenerator;
import java.lang.annotation.Annotation;
import java.util.Set;
import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.RoundEnvironment;
import javax.lang.model.element.Element;
import javax.lang.model.element.TypeElement;
import javax.tools.Diagnostic;
this.viewGenerator = viewGenerator;
}
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
logger = Logger.getInstance(processingEnv.getMessager());
typeElements = annotations;
elements = roundEnv.getElementsAnnotatedWith(getTargetAnnotationClass());
long startR = System.currentTimeMillis();
switch (getProcessType()) {
case PROCESS_ANNOTATION_OF_ELEMENT:
processEachElement();
break;
case PROCESS_ANNOTATION_OF_TYPE_ELEMENT:
processEachTypeElement();
break;
default:
throw new IllegalStateException("not a supported type");
}
logger.log(Diagnostic.Kind.NOTE,
"\nFinished a round,time:" + (System.currentTimeMillis() - startR) + "ms");
return true;
}
private void processEachTypeElement() {
for (Element element : typeElements) {
logger.log(Diagnostic.Kind.NOTE,
"\nCollect Model Info:");
long start = System.currentTimeMillis();
//collect Model info
|
AbstractModel abstractModel = collectModeInfo(element);
|
simplify20/PowerfulRecyclerViewAdapter
|
holder-compiler/src/main/java/com/steve/creact/processor/core/factory/ModelCreatorFactory.java
|
// Path: holder-compiler/src/main/java/com/steve/creact/processor/core/model/ModelCreator.java
// public interface ModelCreator {
//
// /**
// * create a model
// * @param element
// * @param processingEnv
// * @return
// */
// AbstractModel createModel(Element element, ProcessingEnvironment processingEnv);
// }
|
import com.steve.creact.processor.core.model.ModelCreator;
|
package com.steve.creact.processor.core.factory;
/**
* Created by Administrator on 2016/4/10.
*/
public class ModelCreatorFactory {
private ModelCreatorFactory() {
}
|
// Path: holder-compiler/src/main/java/com/steve/creact/processor/core/model/ModelCreator.java
// public interface ModelCreator {
//
// /**
// * create a model
// * @param element
// * @param processingEnv
// * @return
// */
// AbstractModel createModel(Element element, ProcessingEnvironment processingEnv);
// }
// Path: holder-compiler/src/main/java/com/steve/creact/processor/core/factory/ModelCreatorFactory.java
import com.steve.creact.processor.core.model.ModelCreator;
package com.steve.creact.processor.core.factory;
/**
* Created by Administrator on 2016/4/10.
*/
public class ModelCreatorFactory {
private ModelCreatorFactory() {
}
|
public static ModelCreator getCreator(Class<? extends ModelCreator> clz) {
|
MPieter/Notification-Analyser
|
NotificationAnalyser/app/src/main/java/com/tierep/notificationanalyser/ui/HistoryWeeklyFragment.java
|
// Path: NotificationAnalyser/app/src/main/java/com/tierep/notificationanalyser/NotificationAppView.java
// public class NotificationAppView {
// public String AppName;
// public Integer Notifications;
// public Integer MaxNotifications;
//
// public NotificationAppView() {
// this.AppName = "";
// this.Notifications = 0;
// this.MaxNotifications = 0;
// }
//
// /**
// *
// * @param appName The name of the app.
// * @param notifications The number of notifications from the app.
// * @param maxNotifications The maximum number of notifications from any app.
// */
// public NotificationAppView(String appName, Integer notifications, Integer maxNotifications) {
// this.AppName = appName;
// this.Notifications = notifications;
// this.MaxNotifications = maxNotifications;
// }
// }
//
// Path: NotificationAnalyser/app/src/main/java/com/tierep/notificationanalyser/NotificationDateView.java
// public class NotificationDateView {
// public Date Date;
// public Integer Notifications;
//
// public NotificationDateView() {
// this.Date = null;
// this.Notifications = 0;
// }
//
// public NotificationDateView(Date date, Integer notifications) {
// this.Date = date;
// this.Notifications = notifications;
// }
// }
|
import android.content.Intent;
import android.util.Log;
import com.tierep.notificationanalyser.NotificationAppView;
import com.tierep.notificationanalyser.NotificationDateView;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
|
package com.tierep.notificationanalyser.ui;
/**
* Created by pieter on 25/10/14.
*/
public class HistoryWeeklyFragment extends HistoryFragment {
protected SimpleDateFormat dateFormat = new SimpleDateFormat("w");
@Override
protected void startAppDetailActivity(String appName, Date date) {
Intent intent = new Intent(getActivity(), AppDetail.class);
intent.putExtra(AppDetail.EXTRA_PACKAGENAME, appName);
intent.putExtra(AppDetail.EXTRA_INTERVALTYPE, AppDetail.FLAG_VIEW_WEEKLY);
intent.putExtra(AppDetail.EXTRA_DATESTRING, new SimpleDateFormat("yyyy-MM-dd").format(date));
startActivity(intent);
}
@Override
|
// Path: NotificationAnalyser/app/src/main/java/com/tierep/notificationanalyser/NotificationAppView.java
// public class NotificationAppView {
// public String AppName;
// public Integer Notifications;
// public Integer MaxNotifications;
//
// public NotificationAppView() {
// this.AppName = "";
// this.Notifications = 0;
// this.MaxNotifications = 0;
// }
//
// /**
// *
// * @param appName The name of the app.
// * @param notifications The number of notifications from the app.
// * @param maxNotifications The maximum number of notifications from any app.
// */
// public NotificationAppView(String appName, Integer notifications, Integer maxNotifications) {
// this.AppName = appName;
// this.Notifications = notifications;
// this.MaxNotifications = maxNotifications;
// }
// }
//
// Path: NotificationAnalyser/app/src/main/java/com/tierep/notificationanalyser/NotificationDateView.java
// public class NotificationDateView {
// public Date Date;
// public Integer Notifications;
//
// public NotificationDateView() {
// this.Date = null;
// this.Notifications = 0;
// }
//
// public NotificationDateView(Date date, Integer notifications) {
// this.Date = date;
// this.Notifications = notifications;
// }
// }
// Path: NotificationAnalyser/app/src/main/java/com/tierep/notificationanalyser/ui/HistoryWeeklyFragment.java
import android.content.Intent;
import android.util.Log;
import com.tierep.notificationanalyser.NotificationAppView;
import com.tierep.notificationanalyser.NotificationDateView;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
package com.tierep.notificationanalyser.ui;
/**
* Created by pieter on 25/10/14.
*/
public class HistoryWeeklyFragment extends HistoryFragment {
protected SimpleDateFormat dateFormat = new SimpleDateFormat("w");
@Override
protected void startAppDetailActivity(String appName, Date date) {
Intent intent = new Intent(getActivity(), AppDetail.class);
intent.putExtra(AppDetail.EXTRA_PACKAGENAME, appName);
intent.putExtra(AppDetail.EXTRA_INTERVALTYPE, AppDetail.FLAG_VIEW_WEEKLY);
intent.putExtra(AppDetail.EXTRA_DATESTRING, new SimpleDateFormat("yyyy-MM-dd").format(date));
startActivity(intent);
}
@Override
|
protected List<NotificationDateView> getChartData(int items) throws SQLException {
|
MPieter/Notification-Analyser
|
NotificationAnalyser/app/src/main/java/com/tierep/notificationanalyser/ui/HistoryWeeklyFragment.java
|
// Path: NotificationAnalyser/app/src/main/java/com/tierep/notificationanalyser/NotificationAppView.java
// public class NotificationAppView {
// public String AppName;
// public Integer Notifications;
// public Integer MaxNotifications;
//
// public NotificationAppView() {
// this.AppName = "";
// this.Notifications = 0;
// this.MaxNotifications = 0;
// }
//
// /**
// *
// * @param appName The name of the app.
// * @param notifications The number of notifications from the app.
// * @param maxNotifications The maximum number of notifications from any app.
// */
// public NotificationAppView(String appName, Integer notifications, Integer maxNotifications) {
// this.AppName = appName;
// this.Notifications = notifications;
// this.MaxNotifications = maxNotifications;
// }
// }
//
// Path: NotificationAnalyser/app/src/main/java/com/tierep/notificationanalyser/NotificationDateView.java
// public class NotificationDateView {
// public Date Date;
// public Integer Notifications;
//
// public NotificationDateView() {
// this.Date = null;
// this.Notifications = 0;
// }
//
// public NotificationDateView(Date date, Integer notifications) {
// this.Date = date;
// this.Notifications = notifications;
// }
// }
|
import android.content.Intent;
import android.util.Log;
import com.tierep.notificationanalyser.NotificationAppView;
import com.tierep.notificationanalyser.NotificationDateView;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
|
if (i < notificationDateViews.size() - 1) {
Calendar nextNotificationDate = Calendar.getInstance();
nextNotificationDate.setTime(notificationDateViews.get(i + 1).Date);
nextNotificationDate.set(Calendar.HOUR_OF_DAY, 0);
nextNotificationDate.set(Calendar.MINUTE, 0);
nextNotificationDate.set(Calendar.SECOND, 0);
nextNotificationDate.set(Calendar.MILLISECOND, 0);
Calendar nextCalendarDate = Calendar.getInstance();
nextCalendarDate.setTime(notificationDateViews.get(i).Date);
nextCalendarDate.add(Calendar.WEEK_OF_YEAR, 1);
nextCalendarDate.set(Calendar.HOUR_OF_DAY, 0);
nextCalendarDate.set(Calendar.MINUTE, 0);
nextCalendarDate.set(Calendar.SECOND, 0);
nextCalendarDate.set(Calendar.MILLISECOND, 0);
while (nextCalendarDate.get(Calendar.WEEK_OF_YEAR) != nextNotificationDate.get(Calendar.WEEK_OF_YEAR)){
NotificationDateView emptyEntry = new NotificationDateView();
emptyEntry.Date = nextCalendarDate.getTime();
completeNotificationDateViews.add(completeNotificationDateViews.size(), emptyEntry);
nextCalendarDate.add(Calendar.WEEK_OF_YEAR, 1);
}
}
}
return completeNotificationDateViews;
}
@Override
|
// Path: NotificationAnalyser/app/src/main/java/com/tierep/notificationanalyser/NotificationAppView.java
// public class NotificationAppView {
// public String AppName;
// public Integer Notifications;
// public Integer MaxNotifications;
//
// public NotificationAppView() {
// this.AppName = "";
// this.Notifications = 0;
// this.MaxNotifications = 0;
// }
//
// /**
// *
// * @param appName The name of the app.
// * @param notifications The number of notifications from the app.
// * @param maxNotifications The maximum number of notifications from any app.
// */
// public NotificationAppView(String appName, Integer notifications, Integer maxNotifications) {
// this.AppName = appName;
// this.Notifications = notifications;
// this.MaxNotifications = maxNotifications;
// }
// }
//
// Path: NotificationAnalyser/app/src/main/java/com/tierep/notificationanalyser/NotificationDateView.java
// public class NotificationDateView {
// public Date Date;
// public Integer Notifications;
//
// public NotificationDateView() {
// this.Date = null;
// this.Notifications = 0;
// }
//
// public NotificationDateView(Date date, Integer notifications) {
// this.Date = date;
// this.Notifications = notifications;
// }
// }
// Path: NotificationAnalyser/app/src/main/java/com/tierep/notificationanalyser/ui/HistoryWeeklyFragment.java
import android.content.Intent;
import android.util.Log;
import com.tierep.notificationanalyser.NotificationAppView;
import com.tierep.notificationanalyser.NotificationDateView;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
if (i < notificationDateViews.size() - 1) {
Calendar nextNotificationDate = Calendar.getInstance();
nextNotificationDate.setTime(notificationDateViews.get(i + 1).Date);
nextNotificationDate.set(Calendar.HOUR_OF_DAY, 0);
nextNotificationDate.set(Calendar.MINUTE, 0);
nextNotificationDate.set(Calendar.SECOND, 0);
nextNotificationDate.set(Calendar.MILLISECOND, 0);
Calendar nextCalendarDate = Calendar.getInstance();
nextCalendarDate.setTime(notificationDateViews.get(i).Date);
nextCalendarDate.add(Calendar.WEEK_OF_YEAR, 1);
nextCalendarDate.set(Calendar.HOUR_OF_DAY, 0);
nextCalendarDate.set(Calendar.MINUTE, 0);
nextCalendarDate.set(Calendar.SECOND, 0);
nextCalendarDate.set(Calendar.MILLISECOND, 0);
while (nextCalendarDate.get(Calendar.WEEK_OF_YEAR) != nextNotificationDate.get(Calendar.WEEK_OF_YEAR)){
NotificationDateView emptyEntry = new NotificationDateView();
emptyEntry.Date = nextCalendarDate.getTime();
completeNotificationDateViews.add(completeNotificationDateViews.size(), emptyEntry);
nextCalendarDate.add(Calendar.WEEK_OF_YEAR, 1);
}
}
}
return completeNotificationDateViews;
}
@Override
|
protected List<NotificationAppView> getListViewDate(Date date) throws SQLException {
|
MPieter/Notification-Analyser
|
NotificationAnalyser/app/src/main/java/com/tierep/notificationanalyser/models/NotificationItemDao.java
|
// Path: NotificationAnalyser/app/src/main/java/com/tierep/notificationanalyser/NotificationAppView.java
// public class NotificationAppView {
// public String AppName;
// public Integer Notifications;
// public Integer MaxNotifications;
//
// public NotificationAppView() {
// this.AppName = "";
// this.Notifications = 0;
// this.MaxNotifications = 0;
// }
//
// /**
// *
// * @param appName The name of the app.
// * @param notifications The number of notifications from the app.
// * @param maxNotifications The maximum number of notifications from any app.
// */
// public NotificationAppView(String appName, Integer notifications, Integer maxNotifications) {
// this.AppName = appName;
// this.Notifications = notifications;
// this.MaxNotifications = maxNotifications;
// }
// }
//
// Path: NotificationAnalyser/app/src/main/java/com/tierep/notificationanalyser/NotificationDateView.java
// public class NotificationDateView {
// public Date Date;
// public Integer Notifications;
//
// public NotificationDateView() {
// this.Date = null;
// this.Notifications = 0;
// }
//
// public NotificationDateView(Date date, Integer notifications) {
// this.Date = date;
// this.Notifications = notifications;
// }
// }
|
import com.j256.ormlite.dao.Dao;
import com.tierep.notificationanalyser.NotificationAppView;
import com.tierep.notificationanalyser.NotificationDateView;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;
|
package com.tierep.notificationanalyser.models;
/**
* NotificationItem DAO.
*
* Created by pieter on 24/09/14.
*/
public interface NotificationItemDao extends Dao<NotificationItem, Integer> {
public List<NotificationAppView> getOverviewToday() throws SQLException;
public List<NotificationAppView> getOverviewDay(Date date) throws SQLException;
public List<NotificationAppView> getOverviewWeek(Date date) throws SQLException;
public List<NotificationAppView> getOverviewMonth(Date date) throws SQLException;
public List<NotificationItem> getOverviewAppDay(Date date, String appName) throws SQLException;
public List<NotificationItem> getOverviewAppWeek(Date date, String appName) throws SQLException;
public List<NotificationItem> getOverviewAppMonth(Date date, String appName) throws SQLException;
/**
* @param days The number of previous days to fetch (counting backwards, starting from today).
* @return An ordered ascending list on the Date.
* @throws SQLException
*/
|
// Path: NotificationAnalyser/app/src/main/java/com/tierep/notificationanalyser/NotificationAppView.java
// public class NotificationAppView {
// public String AppName;
// public Integer Notifications;
// public Integer MaxNotifications;
//
// public NotificationAppView() {
// this.AppName = "";
// this.Notifications = 0;
// this.MaxNotifications = 0;
// }
//
// /**
// *
// * @param appName The name of the app.
// * @param notifications The number of notifications from the app.
// * @param maxNotifications The maximum number of notifications from any app.
// */
// public NotificationAppView(String appName, Integer notifications, Integer maxNotifications) {
// this.AppName = appName;
// this.Notifications = notifications;
// this.MaxNotifications = maxNotifications;
// }
// }
//
// Path: NotificationAnalyser/app/src/main/java/com/tierep/notificationanalyser/NotificationDateView.java
// public class NotificationDateView {
// public Date Date;
// public Integer Notifications;
//
// public NotificationDateView() {
// this.Date = null;
// this.Notifications = 0;
// }
//
// public NotificationDateView(Date date, Integer notifications) {
// this.Date = date;
// this.Notifications = notifications;
// }
// }
// Path: NotificationAnalyser/app/src/main/java/com/tierep/notificationanalyser/models/NotificationItemDao.java
import com.j256.ormlite.dao.Dao;
import com.tierep.notificationanalyser.NotificationAppView;
import com.tierep.notificationanalyser.NotificationDateView;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;
package com.tierep.notificationanalyser.models;
/**
* NotificationItem DAO.
*
* Created by pieter on 24/09/14.
*/
public interface NotificationItemDao extends Dao<NotificationItem, Integer> {
public List<NotificationAppView> getOverviewToday() throws SQLException;
public List<NotificationAppView> getOverviewDay(Date date) throws SQLException;
public List<NotificationAppView> getOverviewWeek(Date date) throws SQLException;
public List<NotificationAppView> getOverviewMonth(Date date) throws SQLException;
public List<NotificationItem> getOverviewAppDay(Date date, String appName) throws SQLException;
public List<NotificationItem> getOverviewAppWeek(Date date, String appName) throws SQLException;
public List<NotificationItem> getOverviewAppMonth(Date date, String appName) throws SQLException;
/**
* @param days The number of previous days to fetch (counting backwards, starting from today).
* @return An ordered ascending list on the Date.
* @throws SQLException
*/
|
public List<NotificationDateView> getSummaryLastDays(int days) throws SQLException;
|
MPieter/Notification-Analyser
|
NotificationAnalyser/app/src/main/java/com/tierep/notificationanalyser/ui/DrawerActivity.java
|
// Path: NotificationAnalyser/app/src/main/java/com/tierep/notificationanalyser/NotificationListener.java
// public class NotificationListener extends NotificationListenerService {
// public static boolean isNotificationAccessEnabled = false;
//
// private DatabaseHelper databaseHelper = null;
//
// public NotificationListener() {
// }
//
// public DatabaseHelper getDatabaseHelper() {
// if (databaseHelper == null) {
// databaseHelper = OpenHelperManager.getHelper(this, DatabaseHelper.class);
// }
// return databaseHelper;
// }
//
// @Override
// public void onDestroy() {
// super.onDestroy();
// if (databaseHelper != null) {
// OpenHelperManager.releaseHelper();
// databaseHelper = null;
// }
// }
//
// @Override
// public void onNotificationPosted(StatusBarNotification sbn) {
// if (!sbn.isOngoing()) {
// storeNotification(sbn);
// }
// }
//
// @Override
// public void onNotificationRemoved(StatusBarNotification sbn) {
// if (sbn.isOngoing()) {
// storeNotification(sbn);
// }
// }
//
// private void storeNotification(StatusBarNotification sbn) {
// try {
// String packageName = sbn.getPackageName();
// ApplicationDao applicationDao = getDatabaseHelper().getApplicationDao();
// if (!applicationDao.idExists(packageName)) {
// Application application = new Application(packageName, false);
// applicationDao.create(application);
// }
//
// String appName = packageName;
// try {
// ApplicationInfo info = getPackageManager().getApplicationInfo(packageName, 0);
// appName = getPackageManager().getApplicationLabel(info).toString();
// } catch (PackageManager.NameNotFoundException e) {
// e.printStackTrace();
// }
// String message = null;
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
// if (sbn.getNotification().extras != null) {
// message = sbn.getNotification().extras.getString(
// Notification.EXTRA_TITLE);
// if (message == null || "".equals(message)) {
// message = sbn.getNotification().extras.getString(
// Notification.EXTRA_TEXT);
// } else if (message.equals(appName)) {
// String otherMsg = sbn.getNotification().extras.getString(
// Notification.EXTRA_TEXT);
// if (otherMsg != null && !"".equals(otherMsg)) {
// message = otherMsg;
// }
// }
// }
// }
//
// if (message == null || "".equals(message)) {
// message = sbn.getNotification().tickerText.toString();
// } else if (message.equals(appName)) {
// String otherMsg = sbn.getNotification().tickerText.toString();
// if (otherMsg != null && !"".equals(otherMsg)) {
// message = otherMsg;
// }
// }
//
// Dao<NotificationItem, Integer> dao = getDatabaseHelper().getNotificationDao();
// NotificationItem newItem = new NotificationItem(packageName, new Date(sbn.getPostTime()), message);
// dao.create(newItem);
// } catch (SQLException e) {
// e.printStackTrace();
// }
// }
//
// @Override
// public IBinder onBind(Intent intent) {
// IBinder binder = super.onBind(intent);
// isNotificationAccessEnabled = true;
// return binder;
// }
//
// @Override
// public boolean onUnbind(Intent intent) {
// boolean onUnbind = super.onUnbind(intent);
// isNotificationAccessEnabled = false;
// return onUnbind;
// }
// }
|
import android.app.Activity;
import android.app.DialogFragment;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import com.tierep.notificationanalyser.NotificationListener;
import com.tierep.notificationanalyser.R;
|
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
drawerList = (ListView) findViewById(R.id.drawer_list);
drawerItems = getResources().getStringArray(R.array.navigation_drawer_list);
drawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.navigation_drawer_list_item, drawerItems));
drawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
selectItem(i);
}
});
drawerToggle = new ActionBarDrawerToggle(
this,
drawerLayout,
R.string.drawer_open,
R.string.drawer_close) {
@Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getActionBar().setTitle(R.string.app_name);
}
@Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
getActionBar().setTitle(currentTitle);
}
};
drawerLayout.setDrawerListener(drawerToggle);
|
// Path: NotificationAnalyser/app/src/main/java/com/tierep/notificationanalyser/NotificationListener.java
// public class NotificationListener extends NotificationListenerService {
// public static boolean isNotificationAccessEnabled = false;
//
// private DatabaseHelper databaseHelper = null;
//
// public NotificationListener() {
// }
//
// public DatabaseHelper getDatabaseHelper() {
// if (databaseHelper == null) {
// databaseHelper = OpenHelperManager.getHelper(this, DatabaseHelper.class);
// }
// return databaseHelper;
// }
//
// @Override
// public void onDestroy() {
// super.onDestroy();
// if (databaseHelper != null) {
// OpenHelperManager.releaseHelper();
// databaseHelper = null;
// }
// }
//
// @Override
// public void onNotificationPosted(StatusBarNotification sbn) {
// if (!sbn.isOngoing()) {
// storeNotification(sbn);
// }
// }
//
// @Override
// public void onNotificationRemoved(StatusBarNotification sbn) {
// if (sbn.isOngoing()) {
// storeNotification(sbn);
// }
// }
//
// private void storeNotification(StatusBarNotification sbn) {
// try {
// String packageName = sbn.getPackageName();
// ApplicationDao applicationDao = getDatabaseHelper().getApplicationDao();
// if (!applicationDao.idExists(packageName)) {
// Application application = new Application(packageName, false);
// applicationDao.create(application);
// }
//
// String appName = packageName;
// try {
// ApplicationInfo info = getPackageManager().getApplicationInfo(packageName, 0);
// appName = getPackageManager().getApplicationLabel(info).toString();
// } catch (PackageManager.NameNotFoundException e) {
// e.printStackTrace();
// }
// String message = null;
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
// if (sbn.getNotification().extras != null) {
// message = sbn.getNotification().extras.getString(
// Notification.EXTRA_TITLE);
// if (message == null || "".equals(message)) {
// message = sbn.getNotification().extras.getString(
// Notification.EXTRA_TEXT);
// } else if (message.equals(appName)) {
// String otherMsg = sbn.getNotification().extras.getString(
// Notification.EXTRA_TEXT);
// if (otherMsg != null && !"".equals(otherMsg)) {
// message = otherMsg;
// }
// }
// }
// }
//
// if (message == null || "".equals(message)) {
// message = sbn.getNotification().tickerText.toString();
// } else if (message.equals(appName)) {
// String otherMsg = sbn.getNotification().tickerText.toString();
// if (otherMsg != null && !"".equals(otherMsg)) {
// message = otherMsg;
// }
// }
//
// Dao<NotificationItem, Integer> dao = getDatabaseHelper().getNotificationDao();
// NotificationItem newItem = new NotificationItem(packageName, new Date(sbn.getPostTime()), message);
// dao.create(newItem);
// } catch (SQLException e) {
// e.printStackTrace();
// }
// }
//
// @Override
// public IBinder onBind(Intent intent) {
// IBinder binder = super.onBind(intent);
// isNotificationAccessEnabled = true;
// return binder;
// }
//
// @Override
// public boolean onUnbind(Intent intent) {
// boolean onUnbind = super.onUnbind(intent);
// isNotificationAccessEnabled = false;
// return onUnbind;
// }
// }
// Path: NotificationAnalyser/app/src/main/java/com/tierep/notificationanalyser/ui/DrawerActivity.java
import android.app.Activity;
import android.app.DialogFragment;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import com.tierep.notificationanalyser.NotificationListener;
import com.tierep.notificationanalyser.R;
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
drawerList = (ListView) findViewById(R.id.drawer_list);
drawerItems = getResources().getStringArray(R.array.navigation_drawer_list);
drawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.navigation_drawer_list_item, drawerItems));
drawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
selectItem(i);
}
});
drawerToggle = new ActionBarDrawerToggle(
this,
drawerLayout,
R.string.drawer_open,
R.string.drawer_close) {
@Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getActionBar().setTitle(R.string.app_name);
}
@Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
getActionBar().setTitle(currentTitle);
}
};
drawerLayout.setDrawerListener(drawerToggle);
|
if (!NotificationListener.isNotificationAccessEnabled) {
|
MPieter/Notification-Analyser
|
NotificationAnalyser/app/src/main/java/com/tierep/notificationanalyser/models/NotificationItemDaoImpl.java
|
// Path: NotificationAnalyser/app/src/main/java/com/tierep/notificationanalyser/NotificationAppView.java
// public class NotificationAppView {
// public String AppName;
// public Integer Notifications;
// public Integer MaxNotifications;
//
// public NotificationAppView() {
// this.AppName = "";
// this.Notifications = 0;
// this.MaxNotifications = 0;
// }
//
// /**
// *
// * @param appName The name of the app.
// * @param notifications The number of notifications from the app.
// * @param maxNotifications The maximum number of notifications from any app.
// */
// public NotificationAppView(String appName, Integer notifications, Integer maxNotifications) {
// this.AppName = appName;
// this.Notifications = notifications;
// this.MaxNotifications = maxNotifications;
// }
// }
//
// Path: NotificationAnalyser/app/src/main/java/com/tierep/notificationanalyser/NotificationDateView.java
// public class NotificationDateView {
// public Date Date;
// public Integer Notifications;
//
// public NotificationDateView() {
// this.Date = null;
// this.Notifications = 0;
// }
//
// public NotificationDateView(Date date, Integer notifications) {
// this.Date = date;
// this.Notifications = notifications;
// }
// }
|
import com.j256.ormlite.dao.BaseDaoImpl;
import com.j256.ormlite.dao.GenericRawResults;
import com.j256.ormlite.support.ConnectionSource;
import com.tierep.notificationanalyser.NotificationAppView;
import com.tierep.notificationanalyser.NotificationDateView;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
|
package com.tierep.notificationanalyser.models;
/**
* NotificationItem DAO implementation.
*
* Created by pieter on 24/09/14.
*/
public class NotificationItemDaoImpl extends BaseDaoImpl<NotificationItem, Integer> implements NotificationItemDao {
public NotificationItemDaoImpl(ConnectionSource connectionSource) throws SQLException {
super(connectionSource, NotificationItem.class);
}
@Override
|
// Path: NotificationAnalyser/app/src/main/java/com/tierep/notificationanalyser/NotificationAppView.java
// public class NotificationAppView {
// public String AppName;
// public Integer Notifications;
// public Integer MaxNotifications;
//
// public NotificationAppView() {
// this.AppName = "";
// this.Notifications = 0;
// this.MaxNotifications = 0;
// }
//
// /**
// *
// * @param appName The name of the app.
// * @param notifications The number of notifications from the app.
// * @param maxNotifications The maximum number of notifications from any app.
// */
// public NotificationAppView(String appName, Integer notifications, Integer maxNotifications) {
// this.AppName = appName;
// this.Notifications = notifications;
// this.MaxNotifications = maxNotifications;
// }
// }
//
// Path: NotificationAnalyser/app/src/main/java/com/tierep/notificationanalyser/NotificationDateView.java
// public class NotificationDateView {
// public Date Date;
// public Integer Notifications;
//
// public NotificationDateView() {
// this.Date = null;
// this.Notifications = 0;
// }
//
// public NotificationDateView(Date date, Integer notifications) {
// this.Date = date;
// this.Notifications = notifications;
// }
// }
// Path: NotificationAnalyser/app/src/main/java/com/tierep/notificationanalyser/models/NotificationItemDaoImpl.java
import com.j256.ormlite.dao.BaseDaoImpl;
import com.j256.ormlite.dao.GenericRawResults;
import com.j256.ormlite.support.ConnectionSource;
import com.tierep.notificationanalyser.NotificationAppView;
import com.tierep.notificationanalyser.NotificationDateView;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
package com.tierep.notificationanalyser.models;
/**
* NotificationItem DAO implementation.
*
* Created by pieter on 24/09/14.
*/
public class NotificationItemDaoImpl extends BaseDaoImpl<NotificationItem, Integer> implements NotificationItemDao {
public NotificationItemDaoImpl(ConnectionSource connectionSource) throws SQLException {
super(connectionSource, NotificationItem.class);
}
@Override
|
public List<NotificationAppView> getOverviewToday() throws SQLException {
|
MPieter/Notification-Analyser
|
NotificationAnalyser/app/src/main/java/com/tierep/notificationanalyser/models/NotificationItemDaoImpl.java
|
// Path: NotificationAnalyser/app/src/main/java/com/tierep/notificationanalyser/NotificationAppView.java
// public class NotificationAppView {
// public String AppName;
// public Integer Notifications;
// public Integer MaxNotifications;
//
// public NotificationAppView() {
// this.AppName = "";
// this.Notifications = 0;
// this.MaxNotifications = 0;
// }
//
// /**
// *
// * @param appName The name of the app.
// * @param notifications The number of notifications from the app.
// * @param maxNotifications The maximum number of notifications from any app.
// */
// public NotificationAppView(String appName, Integer notifications, Integer maxNotifications) {
// this.AppName = appName;
// this.Notifications = notifications;
// this.MaxNotifications = maxNotifications;
// }
// }
//
// Path: NotificationAnalyser/app/src/main/java/com/tierep/notificationanalyser/NotificationDateView.java
// public class NotificationDateView {
// public Date Date;
// public Integer Notifications;
//
// public NotificationDateView() {
// this.Date = null;
// this.Notifications = 0;
// }
//
// public NotificationDateView(Date date, Integer notifications) {
// this.Date = date;
// this.Notifications = notifications;
// }
// }
|
import com.j256.ormlite.dao.BaseDaoImpl;
import com.j256.ormlite.dao.GenericRawResults;
import com.j256.ormlite.support.ConnectionSource;
import com.tierep.notificationanalyser.NotificationAppView;
import com.tierep.notificationanalyser.NotificationDateView;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
|
Date firstDayOfMonth = cal.getTime();
cal.add(Calendar.MONTH, 1);
Date lastDayOfMonth = cal.getTime();
return this.queryBuilder().where()
.eq(NotificationItem.FIELD_PACKAGE_NAME, appName).and()
.ge(NotificationItem.FIELD_DATE, firstDayOfMonth).and()
.le(NotificationItem.FIELD_DATE, lastDayOfMonth).query();
}
private List<NotificationAppView> getOverviewGeneric(String rawQuery) throws SQLException {
List<NotificationAppView> list = new LinkedList<NotificationAppView>();
int maxCount = 0;
GenericRawResults<String[]> rawResults = this.queryRaw(rawQuery);
List<String[]> results = rawResults.getResults();
for (String[] result : results) {
int ntfCount = Integer.parseInt(result[1]);
maxCount = ntfCount > maxCount ? ntfCount : maxCount;
}
for (String[] result : results) {
list.add(new NotificationAppView(result[0], Integer.parseInt(result[1]), maxCount));
}
return list;
}
@Override
|
// Path: NotificationAnalyser/app/src/main/java/com/tierep/notificationanalyser/NotificationAppView.java
// public class NotificationAppView {
// public String AppName;
// public Integer Notifications;
// public Integer MaxNotifications;
//
// public NotificationAppView() {
// this.AppName = "";
// this.Notifications = 0;
// this.MaxNotifications = 0;
// }
//
// /**
// *
// * @param appName The name of the app.
// * @param notifications The number of notifications from the app.
// * @param maxNotifications The maximum number of notifications from any app.
// */
// public NotificationAppView(String appName, Integer notifications, Integer maxNotifications) {
// this.AppName = appName;
// this.Notifications = notifications;
// this.MaxNotifications = maxNotifications;
// }
// }
//
// Path: NotificationAnalyser/app/src/main/java/com/tierep/notificationanalyser/NotificationDateView.java
// public class NotificationDateView {
// public Date Date;
// public Integer Notifications;
//
// public NotificationDateView() {
// this.Date = null;
// this.Notifications = 0;
// }
//
// public NotificationDateView(Date date, Integer notifications) {
// this.Date = date;
// this.Notifications = notifications;
// }
// }
// Path: NotificationAnalyser/app/src/main/java/com/tierep/notificationanalyser/models/NotificationItemDaoImpl.java
import com.j256.ormlite.dao.BaseDaoImpl;
import com.j256.ormlite.dao.GenericRawResults;
import com.j256.ormlite.support.ConnectionSource;
import com.tierep.notificationanalyser.NotificationAppView;
import com.tierep.notificationanalyser.NotificationDateView;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
Date firstDayOfMonth = cal.getTime();
cal.add(Calendar.MONTH, 1);
Date lastDayOfMonth = cal.getTime();
return this.queryBuilder().where()
.eq(NotificationItem.FIELD_PACKAGE_NAME, appName).and()
.ge(NotificationItem.FIELD_DATE, firstDayOfMonth).and()
.le(NotificationItem.FIELD_DATE, lastDayOfMonth).query();
}
private List<NotificationAppView> getOverviewGeneric(String rawQuery) throws SQLException {
List<NotificationAppView> list = new LinkedList<NotificationAppView>();
int maxCount = 0;
GenericRawResults<String[]> rawResults = this.queryRaw(rawQuery);
List<String[]> results = rawResults.getResults();
for (String[] result : results) {
int ntfCount = Integer.parseInt(result[1]);
maxCount = ntfCount > maxCount ? ntfCount : maxCount;
}
for (String[] result : results) {
list.add(new NotificationAppView(result[0], Integer.parseInt(result[1]), maxCount));
}
return list;
}
@Override
|
public List<NotificationDateView> getSummaryLastDays(int days) throws SQLException {
|
MPieter/Notification-Analyser
|
NotificationAnalyser/app/src/main/java/com/tierep/notificationanalyser/ui/HistoryMonthlyFragment.java
|
// Path: NotificationAnalyser/app/src/main/java/com/tierep/notificationanalyser/NotificationAppView.java
// public class NotificationAppView {
// public String AppName;
// public Integer Notifications;
// public Integer MaxNotifications;
//
// public NotificationAppView() {
// this.AppName = "";
// this.Notifications = 0;
// this.MaxNotifications = 0;
// }
//
// /**
// *
// * @param appName The name of the app.
// * @param notifications The number of notifications from the app.
// * @param maxNotifications The maximum number of notifications from any app.
// */
// public NotificationAppView(String appName, Integer notifications, Integer maxNotifications) {
// this.AppName = appName;
// this.Notifications = notifications;
// this.MaxNotifications = maxNotifications;
// }
// }
//
// Path: NotificationAnalyser/app/src/main/java/com/tierep/notificationanalyser/NotificationDateView.java
// public class NotificationDateView {
// public Date Date;
// public Integer Notifications;
//
// public NotificationDateView() {
// this.Date = null;
// this.Notifications = 0;
// }
//
// public NotificationDateView(Date date, Integer notifications) {
// this.Date = date;
// this.Notifications = notifications;
// }
// }
|
import android.content.Intent;
import com.tierep.notificationanalyser.NotificationAppView;
import com.tierep.notificationanalyser.NotificationDateView;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
|
package com.tierep.notificationanalyser.ui;
/**
* Created by pieter on 25/10/14.
*/
public class HistoryMonthlyFragment extends HistoryFragment {
protected SimpleDateFormat dateFormat = new SimpleDateFormat("MMM");
@Override
protected void startAppDetailActivity(String appName, Date date) {
Intent intent = new Intent(getActivity(), AppDetail.class);
intent.putExtra(AppDetail.EXTRA_PACKAGENAME, appName);
intent.putExtra(AppDetail.EXTRA_INTERVALTYPE, AppDetail.FLAG_VIEW_MONTHLY);
intent.putExtra(AppDetail.EXTRA_DATESTRING, new SimpleDateFormat("yyyy-MM-dd").format(date));
startActivity(intent);
}
@Override
|
// Path: NotificationAnalyser/app/src/main/java/com/tierep/notificationanalyser/NotificationAppView.java
// public class NotificationAppView {
// public String AppName;
// public Integer Notifications;
// public Integer MaxNotifications;
//
// public NotificationAppView() {
// this.AppName = "";
// this.Notifications = 0;
// this.MaxNotifications = 0;
// }
//
// /**
// *
// * @param appName The name of the app.
// * @param notifications The number of notifications from the app.
// * @param maxNotifications The maximum number of notifications from any app.
// */
// public NotificationAppView(String appName, Integer notifications, Integer maxNotifications) {
// this.AppName = appName;
// this.Notifications = notifications;
// this.MaxNotifications = maxNotifications;
// }
// }
//
// Path: NotificationAnalyser/app/src/main/java/com/tierep/notificationanalyser/NotificationDateView.java
// public class NotificationDateView {
// public Date Date;
// public Integer Notifications;
//
// public NotificationDateView() {
// this.Date = null;
// this.Notifications = 0;
// }
//
// public NotificationDateView(Date date, Integer notifications) {
// this.Date = date;
// this.Notifications = notifications;
// }
// }
// Path: NotificationAnalyser/app/src/main/java/com/tierep/notificationanalyser/ui/HistoryMonthlyFragment.java
import android.content.Intent;
import com.tierep.notificationanalyser.NotificationAppView;
import com.tierep.notificationanalyser.NotificationDateView;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
package com.tierep.notificationanalyser.ui;
/**
* Created by pieter on 25/10/14.
*/
public class HistoryMonthlyFragment extends HistoryFragment {
protected SimpleDateFormat dateFormat = new SimpleDateFormat("MMM");
@Override
protected void startAppDetailActivity(String appName, Date date) {
Intent intent = new Intent(getActivity(), AppDetail.class);
intent.putExtra(AppDetail.EXTRA_PACKAGENAME, appName);
intent.putExtra(AppDetail.EXTRA_INTERVALTYPE, AppDetail.FLAG_VIEW_MONTHLY);
intent.putExtra(AppDetail.EXTRA_DATESTRING, new SimpleDateFormat("yyyy-MM-dd").format(date));
startActivity(intent);
}
@Override
|
protected List<NotificationDateView> getChartData(int items) throws SQLException {
|
MPieter/Notification-Analyser
|
NotificationAnalyser/app/src/main/java/com/tierep/notificationanalyser/ui/HistoryMonthlyFragment.java
|
// Path: NotificationAnalyser/app/src/main/java/com/tierep/notificationanalyser/NotificationAppView.java
// public class NotificationAppView {
// public String AppName;
// public Integer Notifications;
// public Integer MaxNotifications;
//
// public NotificationAppView() {
// this.AppName = "";
// this.Notifications = 0;
// this.MaxNotifications = 0;
// }
//
// /**
// *
// * @param appName The name of the app.
// * @param notifications The number of notifications from the app.
// * @param maxNotifications The maximum number of notifications from any app.
// */
// public NotificationAppView(String appName, Integer notifications, Integer maxNotifications) {
// this.AppName = appName;
// this.Notifications = notifications;
// this.MaxNotifications = maxNotifications;
// }
// }
//
// Path: NotificationAnalyser/app/src/main/java/com/tierep/notificationanalyser/NotificationDateView.java
// public class NotificationDateView {
// public Date Date;
// public Integer Notifications;
//
// public NotificationDateView() {
// this.Date = null;
// this.Notifications = 0;
// }
//
// public NotificationDateView(Date date, Integer notifications) {
// this.Date = date;
// this.Notifications = notifications;
// }
// }
|
import android.content.Intent;
import com.tierep.notificationanalyser.NotificationAppView;
import com.tierep.notificationanalyser.NotificationDateView;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
|
completeNotificationDateViews.add(completeNotificationDateViews.size(), notificationDateViews.get(i));
if (i < notificationDateViews.size() - 1) {
Calendar nextNotificationDate = Calendar.getInstance();
nextNotificationDate.setTime(notificationDateViews.get(i + 1).Date);
nextNotificationDate.set(Calendar.HOUR_OF_DAY, 0);
nextNotificationDate.set(Calendar.MINUTE, 0);
nextNotificationDate.set(Calendar.SECOND, 0);
nextNotificationDate.set(Calendar.MILLISECOND, 0);
Calendar nextCalendarDate = Calendar.getInstance();
nextCalendarDate.setTime(notificationDateViews.get(i).Date);
nextCalendarDate.add(Calendar.MONTH, 1);
nextCalendarDate.set(Calendar.HOUR_OF_DAY, 0);
nextCalendarDate.set(Calendar.MINUTE, 0);
nextCalendarDate.set(Calendar.SECOND, 0);
nextCalendarDate.set(Calendar.MILLISECOND, 0);
while (nextCalendarDate.get(Calendar.MONTH) != nextNotificationDate.get(Calendar.MONTH)){
NotificationDateView emptyEntry = new NotificationDateView();
emptyEntry.Date = nextCalendarDate.getTime();
completeNotificationDateViews.add(completeNotificationDateViews.size(), emptyEntry);
nextCalendarDate.add(Calendar.MONTH, 1);
}
}
}
return completeNotificationDateViews;
}
@Override
|
// Path: NotificationAnalyser/app/src/main/java/com/tierep/notificationanalyser/NotificationAppView.java
// public class NotificationAppView {
// public String AppName;
// public Integer Notifications;
// public Integer MaxNotifications;
//
// public NotificationAppView() {
// this.AppName = "";
// this.Notifications = 0;
// this.MaxNotifications = 0;
// }
//
// /**
// *
// * @param appName The name of the app.
// * @param notifications The number of notifications from the app.
// * @param maxNotifications The maximum number of notifications from any app.
// */
// public NotificationAppView(String appName, Integer notifications, Integer maxNotifications) {
// this.AppName = appName;
// this.Notifications = notifications;
// this.MaxNotifications = maxNotifications;
// }
// }
//
// Path: NotificationAnalyser/app/src/main/java/com/tierep/notificationanalyser/NotificationDateView.java
// public class NotificationDateView {
// public Date Date;
// public Integer Notifications;
//
// public NotificationDateView() {
// this.Date = null;
// this.Notifications = 0;
// }
//
// public NotificationDateView(Date date, Integer notifications) {
// this.Date = date;
// this.Notifications = notifications;
// }
// }
// Path: NotificationAnalyser/app/src/main/java/com/tierep/notificationanalyser/ui/HistoryMonthlyFragment.java
import android.content.Intent;
import com.tierep.notificationanalyser.NotificationAppView;
import com.tierep.notificationanalyser.NotificationDateView;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
completeNotificationDateViews.add(completeNotificationDateViews.size(), notificationDateViews.get(i));
if (i < notificationDateViews.size() - 1) {
Calendar nextNotificationDate = Calendar.getInstance();
nextNotificationDate.setTime(notificationDateViews.get(i + 1).Date);
nextNotificationDate.set(Calendar.HOUR_OF_DAY, 0);
nextNotificationDate.set(Calendar.MINUTE, 0);
nextNotificationDate.set(Calendar.SECOND, 0);
nextNotificationDate.set(Calendar.MILLISECOND, 0);
Calendar nextCalendarDate = Calendar.getInstance();
nextCalendarDate.setTime(notificationDateViews.get(i).Date);
nextCalendarDate.add(Calendar.MONTH, 1);
nextCalendarDate.set(Calendar.HOUR_OF_DAY, 0);
nextCalendarDate.set(Calendar.MINUTE, 0);
nextCalendarDate.set(Calendar.SECOND, 0);
nextCalendarDate.set(Calendar.MILLISECOND, 0);
while (nextCalendarDate.get(Calendar.MONTH) != nextNotificationDate.get(Calendar.MONTH)){
NotificationDateView emptyEntry = new NotificationDateView();
emptyEntry.Date = nextCalendarDate.getTime();
completeNotificationDateViews.add(completeNotificationDateViews.size(), emptyEntry);
nextCalendarDate.add(Calendar.MONTH, 1);
}
}
}
return completeNotificationDateViews;
}
@Override
|
protected List<NotificationAppView> getListViewDate(Date date) throws SQLException {
|
MPieter/Notification-Analyser
|
NotificationAnalyser/app/src/main/java/com/tierep/notificationanalyser/ui/HistoryDailyFragment.java
|
// Path: NotificationAnalyser/app/src/main/java/com/tierep/notificationanalyser/NotificationAppView.java
// public class NotificationAppView {
// public String AppName;
// public Integer Notifications;
// public Integer MaxNotifications;
//
// public NotificationAppView() {
// this.AppName = "";
// this.Notifications = 0;
// this.MaxNotifications = 0;
// }
//
// /**
// *
// * @param appName The name of the app.
// * @param notifications The number of notifications from the app.
// * @param maxNotifications The maximum number of notifications from any app.
// */
// public NotificationAppView(String appName, Integer notifications, Integer maxNotifications) {
// this.AppName = appName;
// this.Notifications = notifications;
// this.MaxNotifications = maxNotifications;
// }
// }
//
// Path: NotificationAnalyser/app/src/main/java/com/tierep/notificationanalyser/NotificationDateView.java
// public class NotificationDateView {
// public Date Date;
// public Integer Notifications;
//
// public NotificationDateView() {
// this.Date = null;
// this.Notifications = 0;
// }
//
// public NotificationDateView(Date date, Integer notifications) {
// this.Date = date;
// this.Notifications = notifications;
// }
// }
|
import android.content.Intent;
import com.tierep.notificationanalyser.NotificationAppView;
import com.tierep.notificationanalyser.NotificationDateView;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
|
package com.tierep.notificationanalyser.ui;
/**
* Created by pieter on 25/10/14.
*/
public class HistoryDailyFragment extends HistoryFragment {
protected SimpleDateFormat dateFormat = new SimpleDateFormat("d MMM");
@Override
protected void startAppDetailActivity(String appName, Date date) {
Intent intent = new Intent(getActivity(), AppDetail.class);
intent.putExtra(AppDetail.EXTRA_PACKAGENAME, appName);
intent.putExtra(AppDetail.EXTRA_INTERVALTYPE, AppDetail.FLAG_VIEW_DAILY);
intent.putExtra(AppDetail.EXTRA_DATESTRING, new SimpleDateFormat("yyyy-MM-dd").format(date));
startActivity(intent);
}
@Override
|
// Path: NotificationAnalyser/app/src/main/java/com/tierep/notificationanalyser/NotificationAppView.java
// public class NotificationAppView {
// public String AppName;
// public Integer Notifications;
// public Integer MaxNotifications;
//
// public NotificationAppView() {
// this.AppName = "";
// this.Notifications = 0;
// this.MaxNotifications = 0;
// }
//
// /**
// *
// * @param appName The name of the app.
// * @param notifications The number of notifications from the app.
// * @param maxNotifications The maximum number of notifications from any app.
// */
// public NotificationAppView(String appName, Integer notifications, Integer maxNotifications) {
// this.AppName = appName;
// this.Notifications = notifications;
// this.MaxNotifications = maxNotifications;
// }
// }
//
// Path: NotificationAnalyser/app/src/main/java/com/tierep/notificationanalyser/NotificationDateView.java
// public class NotificationDateView {
// public Date Date;
// public Integer Notifications;
//
// public NotificationDateView() {
// this.Date = null;
// this.Notifications = 0;
// }
//
// public NotificationDateView(Date date, Integer notifications) {
// this.Date = date;
// this.Notifications = notifications;
// }
// }
// Path: NotificationAnalyser/app/src/main/java/com/tierep/notificationanalyser/ui/HistoryDailyFragment.java
import android.content.Intent;
import com.tierep.notificationanalyser.NotificationAppView;
import com.tierep.notificationanalyser.NotificationDateView;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
package com.tierep.notificationanalyser.ui;
/**
* Created by pieter on 25/10/14.
*/
public class HistoryDailyFragment extends HistoryFragment {
protected SimpleDateFormat dateFormat = new SimpleDateFormat("d MMM");
@Override
protected void startAppDetailActivity(String appName, Date date) {
Intent intent = new Intent(getActivity(), AppDetail.class);
intent.putExtra(AppDetail.EXTRA_PACKAGENAME, appName);
intent.putExtra(AppDetail.EXTRA_INTERVALTYPE, AppDetail.FLAG_VIEW_DAILY);
intent.putExtra(AppDetail.EXTRA_DATESTRING, new SimpleDateFormat("yyyy-MM-dd").format(date));
startActivity(intent);
}
@Override
|
protected List<NotificationDateView> getChartData(int items) throws SQLException {
|
MPieter/Notification-Analyser
|
NotificationAnalyser/app/src/main/java/com/tierep/notificationanalyser/ui/HistoryDailyFragment.java
|
// Path: NotificationAnalyser/app/src/main/java/com/tierep/notificationanalyser/NotificationAppView.java
// public class NotificationAppView {
// public String AppName;
// public Integer Notifications;
// public Integer MaxNotifications;
//
// public NotificationAppView() {
// this.AppName = "";
// this.Notifications = 0;
// this.MaxNotifications = 0;
// }
//
// /**
// *
// * @param appName The name of the app.
// * @param notifications The number of notifications from the app.
// * @param maxNotifications The maximum number of notifications from any app.
// */
// public NotificationAppView(String appName, Integer notifications, Integer maxNotifications) {
// this.AppName = appName;
// this.Notifications = notifications;
// this.MaxNotifications = maxNotifications;
// }
// }
//
// Path: NotificationAnalyser/app/src/main/java/com/tierep/notificationanalyser/NotificationDateView.java
// public class NotificationDateView {
// public Date Date;
// public Integer Notifications;
//
// public NotificationDateView() {
// this.Date = null;
// this.Notifications = 0;
// }
//
// public NotificationDateView(Date date, Integer notifications) {
// this.Date = date;
// this.Notifications = notifications;
// }
// }
|
import android.content.Intent;
import com.tierep.notificationanalyser.NotificationAppView;
import com.tierep.notificationanalyser.NotificationDateView;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
|
completeNotificationDateViews.add(completeNotificationDateViews.size(), notificationDateViews.get(i));
if (i < notificationDateViews.size() - 1) {
Calendar nextNotificationDate = Calendar.getInstance();
nextNotificationDate.setTime(notificationDateViews.get(i + 1).Date);
nextNotificationDate.set(Calendar.HOUR_OF_DAY, 0);
nextNotificationDate.set(Calendar.MINUTE, 0);
nextNotificationDate.set(Calendar.SECOND, 0);
nextNotificationDate.set(Calendar.MILLISECOND, 0);
Calendar nextCalendarDate = Calendar.getInstance();
nextCalendarDate.setTime(notificationDateViews.get(i).Date);
nextCalendarDate.add(Calendar.DAY_OF_YEAR, 1);
nextCalendarDate.set(Calendar.HOUR_OF_DAY, 0);
nextCalendarDate.set(Calendar.MINUTE, 0);
nextCalendarDate.set(Calendar.SECOND, 0);
nextCalendarDate.set(Calendar.MILLISECOND, 0);
while (!nextCalendarDate.equals(nextNotificationDate)){
NotificationDateView emptyEntry = new NotificationDateView();
emptyEntry.Date = nextCalendarDate.getTime();
completeNotificationDateViews.add(completeNotificationDateViews.size(), emptyEntry);
nextCalendarDate.add(Calendar.DAY_OF_YEAR, 1);
}
}
}
return completeNotificationDateViews;
}
@Override
|
// Path: NotificationAnalyser/app/src/main/java/com/tierep/notificationanalyser/NotificationAppView.java
// public class NotificationAppView {
// public String AppName;
// public Integer Notifications;
// public Integer MaxNotifications;
//
// public NotificationAppView() {
// this.AppName = "";
// this.Notifications = 0;
// this.MaxNotifications = 0;
// }
//
// /**
// *
// * @param appName The name of the app.
// * @param notifications The number of notifications from the app.
// * @param maxNotifications The maximum number of notifications from any app.
// */
// public NotificationAppView(String appName, Integer notifications, Integer maxNotifications) {
// this.AppName = appName;
// this.Notifications = notifications;
// this.MaxNotifications = maxNotifications;
// }
// }
//
// Path: NotificationAnalyser/app/src/main/java/com/tierep/notificationanalyser/NotificationDateView.java
// public class NotificationDateView {
// public Date Date;
// public Integer Notifications;
//
// public NotificationDateView() {
// this.Date = null;
// this.Notifications = 0;
// }
//
// public NotificationDateView(Date date, Integer notifications) {
// this.Date = date;
// this.Notifications = notifications;
// }
// }
// Path: NotificationAnalyser/app/src/main/java/com/tierep/notificationanalyser/ui/HistoryDailyFragment.java
import android.content.Intent;
import com.tierep.notificationanalyser.NotificationAppView;
import com.tierep.notificationanalyser.NotificationDateView;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
completeNotificationDateViews.add(completeNotificationDateViews.size(), notificationDateViews.get(i));
if (i < notificationDateViews.size() - 1) {
Calendar nextNotificationDate = Calendar.getInstance();
nextNotificationDate.setTime(notificationDateViews.get(i + 1).Date);
nextNotificationDate.set(Calendar.HOUR_OF_DAY, 0);
nextNotificationDate.set(Calendar.MINUTE, 0);
nextNotificationDate.set(Calendar.SECOND, 0);
nextNotificationDate.set(Calendar.MILLISECOND, 0);
Calendar nextCalendarDate = Calendar.getInstance();
nextCalendarDate.setTime(notificationDateViews.get(i).Date);
nextCalendarDate.add(Calendar.DAY_OF_YEAR, 1);
nextCalendarDate.set(Calendar.HOUR_OF_DAY, 0);
nextCalendarDate.set(Calendar.MINUTE, 0);
nextCalendarDate.set(Calendar.SECOND, 0);
nextCalendarDate.set(Calendar.MILLISECOND, 0);
while (!nextCalendarDate.equals(nextNotificationDate)){
NotificationDateView emptyEntry = new NotificationDateView();
emptyEntry.Date = nextCalendarDate.getTime();
completeNotificationDateViews.add(completeNotificationDateViews.size(), emptyEntry);
nextCalendarDate.add(Calendar.DAY_OF_YEAR, 1);
}
}
}
return completeNotificationDateViews;
}
@Override
|
protected List<NotificationAppView> getListViewDate(Date date) throws SQLException {
|
MPieter/Notification-Analyser
|
NotificationAnalyser/app/src/main/java/com/tierep/notificationanalyser/ui/IgnoredApps.java
|
// Path: NotificationAnalyser/app/src/main/java/com/tierep/notificationanalyser/models/Application.java
// @DatabaseTable(tableName = "Applications", daoClass = ApplicationDaoImpl.class)
// public class Application {
// public static final String FIELD_TABLE_NAME = "Applications";
// public static final String FIELD_PACKAGE_NAME = "PackageName";
// public static final String FIELD_IGNORE = "Ignore";
//
// @DatabaseField(columnName = FIELD_PACKAGE_NAME, id = true, generatedId = false)
// private String PackageName;
// @DatabaseField(columnName = FIELD_IGNORE, canBeNull = false)
// private Boolean Ignore;
//
// public Application() {
// //ORMLite needs a no-arg constructor.
// }
//
// public Application(String packageName, Boolean ignore) {
// this.PackageName = packageName;
// this.Ignore = ignore;
// }
//
// public String getPackageName() {
// return PackageName;
// }
//
// public void setPackageName(String packageName) {
// PackageName = packageName;
// }
//
// public Boolean getIgnore() {
// return Ignore;
// }
//
// public void setIgnore(Boolean ignore) {
// Ignore = ignore;
// }
// }
//
// Path: NotificationAnalyser/app/src/main/java/com/tierep/notificationanalyser/models/ApplicationDao.java
// public interface ApplicationDao extends Dao<Application, String> {
// public List<Application> getIgnoredApps() throws SQLException;
//
// }
//
// Path: NotificationAnalyser/app/src/main/java/com/tierep/notificationanalyser/models/DatabaseHelper.java
// public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
// private static final String DATABASE_NAME = "notifications.db";
//
// private static final int DATABASE_VERSION = 2;
//
// private ApplicationDao applicationDao = null;
// private NotificationItemDao notificationDao = null;
//
// public DatabaseHelper(Context context) {
// super(context, DATABASE_NAME, null, DATABASE_VERSION);
// }
//
// /**
// * This is called when the database is first created. This call createTable statements here to
// * create the tables that will store your data.
// */
// @Override
// public void onCreate(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource) {
// try {
// TableUtils.createTable(connectionSource, NotificationItem.class);
// TableUtils.createTable(connectionSource, Application.class);
// } catch (SQLException e) {
// e.printStackTrace();
// }
// }
//
// @Override
// public void onUpgrade(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource, int oldVersion, int newVersion) {
// if (oldVersion < 2) {
// // Do changes from version 1 to 2
// try {
// NotificationItemDao dao = getNotificationDao();
// dao.executeRawNoArgs("ALTER TABLE " + NotificationItem.FIELD_TABLE_NAME + " ADD COLUMN " + NotificationItem.FIELD_MESSAGE + " TEXT");
// } catch (SQLException e) {
// e.printStackTrace();
// }
//
// }
//
// if (oldVersion < 3) {
// // Do changes from version 2 to 3
// }
// }
//
// /**
// * Returns the Database Access Object (DAO) for Application class. It will create it or
// * just give the cached value.
// */
// public ApplicationDao getApplicationDao() throws SQLException {
// if (applicationDao == null) {
// applicationDao = getDao(Application.class);
// }
// return applicationDao;
// }
//
// /**
// * Returns the Database Access Object (DAO) for NotificationItem class. It will create it or
// * just give the cached value.
// */
// public NotificationItemDao getNotificationDao() throws SQLException {
// if (notificationDao == null) {
// notificationDao = getDao(NotificationItem.class);
// }
// return notificationDao;
// }
//
// /**
// * Close the database connections and clear any cached DAOs.
// */
// @Override
// public void close() {
// super.close();
// applicationDao = null;
// notificationDao = null;
// }
// }
|
import android.app.Activity;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.j256.ormlite.android.apptools.OpenHelperManager;
import com.tierep.notificationanalyser.R;
import com.tierep.notificationanalyser.models.Application;
import com.tierep.notificationanalyser.models.ApplicationDao;
import com.tierep.notificationanalyser.models.DatabaseHelper;
import java.sql.SQLException;
import java.util.List;
import de.timroes.android.listview.EnhancedListView;
|
package com.tierep.notificationanalyser.ui;
/**
* An activity that will display all the ignored applications in the statistics.
*/
public class IgnoredApps extends Activity {
private DatabaseHelper databaseHelper = null;
private ApplicationIgnoreAdapter ignoredAppsAdapter = null;
private EnhancedListView listView = null;
public DatabaseHelper getDatabaseHelper() {
if (databaseHelper == null) {
databaseHelper = OpenHelperManager.getHelper(this, DatabaseHelper.class);
}
return databaseHelper;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ignored_apps);
getActionBar().setDisplayHomeAsUpEnabled(true);
listView = (EnhancedListView) findViewById(R.id.list_ignored_apps);
try {
|
// Path: NotificationAnalyser/app/src/main/java/com/tierep/notificationanalyser/models/Application.java
// @DatabaseTable(tableName = "Applications", daoClass = ApplicationDaoImpl.class)
// public class Application {
// public static final String FIELD_TABLE_NAME = "Applications";
// public static final String FIELD_PACKAGE_NAME = "PackageName";
// public static final String FIELD_IGNORE = "Ignore";
//
// @DatabaseField(columnName = FIELD_PACKAGE_NAME, id = true, generatedId = false)
// private String PackageName;
// @DatabaseField(columnName = FIELD_IGNORE, canBeNull = false)
// private Boolean Ignore;
//
// public Application() {
// //ORMLite needs a no-arg constructor.
// }
//
// public Application(String packageName, Boolean ignore) {
// this.PackageName = packageName;
// this.Ignore = ignore;
// }
//
// public String getPackageName() {
// return PackageName;
// }
//
// public void setPackageName(String packageName) {
// PackageName = packageName;
// }
//
// public Boolean getIgnore() {
// return Ignore;
// }
//
// public void setIgnore(Boolean ignore) {
// Ignore = ignore;
// }
// }
//
// Path: NotificationAnalyser/app/src/main/java/com/tierep/notificationanalyser/models/ApplicationDao.java
// public interface ApplicationDao extends Dao<Application, String> {
// public List<Application> getIgnoredApps() throws SQLException;
//
// }
//
// Path: NotificationAnalyser/app/src/main/java/com/tierep/notificationanalyser/models/DatabaseHelper.java
// public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
// private static final String DATABASE_NAME = "notifications.db";
//
// private static final int DATABASE_VERSION = 2;
//
// private ApplicationDao applicationDao = null;
// private NotificationItemDao notificationDao = null;
//
// public DatabaseHelper(Context context) {
// super(context, DATABASE_NAME, null, DATABASE_VERSION);
// }
//
// /**
// * This is called when the database is first created. This call createTable statements here to
// * create the tables that will store your data.
// */
// @Override
// public void onCreate(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource) {
// try {
// TableUtils.createTable(connectionSource, NotificationItem.class);
// TableUtils.createTable(connectionSource, Application.class);
// } catch (SQLException e) {
// e.printStackTrace();
// }
// }
//
// @Override
// public void onUpgrade(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource, int oldVersion, int newVersion) {
// if (oldVersion < 2) {
// // Do changes from version 1 to 2
// try {
// NotificationItemDao dao = getNotificationDao();
// dao.executeRawNoArgs("ALTER TABLE " + NotificationItem.FIELD_TABLE_NAME + " ADD COLUMN " + NotificationItem.FIELD_MESSAGE + " TEXT");
// } catch (SQLException e) {
// e.printStackTrace();
// }
//
// }
//
// if (oldVersion < 3) {
// // Do changes from version 2 to 3
// }
// }
//
// /**
// * Returns the Database Access Object (DAO) for Application class. It will create it or
// * just give the cached value.
// */
// public ApplicationDao getApplicationDao() throws SQLException {
// if (applicationDao == null) {
// applicationDao = getDao(Application.class);
// }
// return applicationDao;
// }
//
// /**
// * Returns the Database Access Object (DAO) for NotificationItem class. It will create it or
// * just give the cached value.
// */
// public NotificationItemDao getNotificationDao() throws SQLException {
// if (notificationDao == null) {
// notificationDao = getDao(NotificationItem.class);
// }
// return notificationDao;
// }
//
// /**
// * Close the database connections and clear any cached DAOs.
// */
// @Override
// public void close() {
// super.close();
// applicationDao = null;
// notificationDao = null;
// }
// }
// Path: NotificationAnalyser/app/src/main/java/com/tierep/notificationanalyser/ui/IgnoredApps.java
import android.app.Activity;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.j256.ormlite.android.apptools.OpenHelperManager;
import com.tierep.notificationanalyser.R;
import com.tierep.notificationanalyser.models.Application;
import com.tierep.notificationanalyser.models.ApplicationDao;
import com.tierep.notificationanalyser.models.DatabaseHelper;
import java.sql.SQLException;
import java.util.List;
import de.timroes.android.listview.EnhancedListView;
package com.tierep.notificationanalyser.ui;
/**
* An activity that will display all the ignored applications in the statistics.
*/
public class IgnoredApps extends Activity {
private DatabaseHelper databaseHelper = null;
private ApplicationIgnoreAdapter ignoredAppsAdapter = null;
private EnhancedListView listView = null;
public DatabaseHelper getDatabaseHelper() {
if (databaseHelper == null) {
databaseHelper = OpenHelperManager.getHelper(this, DatabaseHelper.class);
}
return databaseHelper;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ignored_apps);
getActionBar().setDisplayHomeAsUpEnabled(true);
listView = (EnhancedListView) findViewById(R.id.list_ignored_apps);
try {
|
List<Application> applicationList = getDatabaseHelper().getApplicationDao().getIgnoredApps();
|
MPieter/Notification-Analyser
|
NotificationAnalyser/app/src/main/java/com/tierep/notificationanalyser/ui/IgnoredApps.java
|
// Path: NotificationAnalyser/app/src/main/java/com/tierep/notificationanalyser/models/Application.java
// @DatabaseTable(tableName = "Applications", daoClass = ApplicationDaoImpl.class)
// public class Application {
// public static final String FIELD_TABLE_NAME = "Applications";
// public static final String FIELD_PACKAGE_NAME = "PackageName";
// public static final String FIELD_IGNORE = "Ignore";
//
// @DatabaseField(columnName = FIELD_PACKAGE_NAME, id = true, generatedId = false)
// private String PackageName;
// @DatabaseField(columnName = FIELD_IGNORE, canBeNull = false)
// private Boolean Ignore;
//
// public Application() {
// //ORMLite needs a no-arg constructor.
// }
//
// public Application(String packageName, Boolean ignore) {
// this.PackageName = packageName;
// this.Ignore = ignore;
// }
//
// public String getPackageName() {
// return PackageName;
// }
//
// public void setPackageName(String packageName) {
// PackageName = packageName;
// }
//
// public Boolean getIgnore() {
// return Ignore;
// }
//
// public void setIgnore(Boolean ignore) {
// Ignore = ignore;
// }
// }
//
// Path: NotificationAnalyser/app/src/main/java/com/tierep/notificationanalyser/models/ApplicationDao.java
// public interface ApplicationDao extends Dao<Application, String> {
// public List<Application> getIgnoredApps() throws SQLException;
//
// }
//
// Path: NotificationAnalyser/app/src/main/java/com/tierep/notificationanalyser/models/DatabaseHelper.java
// public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
// private static final String DATABASE_NAME = "notifications.db";
//
// private static final int DATABASE_VERSION = 2;
//
// private ApplicationDao applicationDao = null;
// private NotificationItemDao notificationDao = null;
//
// public DatabaseHelper(Context context) {
// super(context, DATABASE_NAME, null, DATABASE_VERSION);
// }
//
// /**
// * This is called when the database is first created. This call createTable statements here to
// * create the tables that will store your data.
// */
// @Override
// public void onCreate(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource) {
// try {
// TableUtils.createTable(connectionSource, NotificationItem.class);
// TableUtils.createTable(connectionSource, Application.class);
// } catch (SQLException e) {
// e.printStackTrace();
// }
// }
//
// @Override
// public void onUpgrade(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource, int oldVersion, int newVersion) {
// if (oldVersion < 2) {
// // Do changes from version 1 to 2
// try {
// NotificationItemDao dao = getNotificationDao();
// dao.executeRawNoArgs("ALTER TABLE " + NotificationItem.FIELD_TABLE_NAME + " ADD COLUMN " + NotificationItem.FIELD_MESSAGE + " TEXT");
// } catch (SQLException e) {
// e.printStackTrace();
// }
//
// }
//
// if (oldVersion < 3) {
// // Do changes from version 2 to 3
// }
// }
//
// /**
// * Returns the Database Access Object (DAO) for Application class. It will create it or
// * just give the cached value.
// */
// public ApplicationDao getApplicationDao() throws SQLException {
// if (applicationDao == null) {
// applicationDao = getDao(Application.class);
// }
// return applicationDao;
// }
//
// /**
// * Returns the Database Access Object (DAO) for NotificationItem class. It will create it or
// * just give the cached value.
// */
// public NotificationItemDao getNotificationDao() throws SQLException {
// if (notificationDao == null) {
// notificationDao = getDao(NotificationItem.class);
// }
// return notificationDao;
// }
//
// /**
// * Close the database connections and clear any cached DAOs.
// */
// @Override
// public void close() {
// super.close();
// applicationDao = null;
// notificationDao = null;
// }
// }
|
import android.app.Activity;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.j256.ormlite.android.apptools.OpenHelperManager;
import com.tierep.notificationanalyser.R;
import com.tierep.notificationanalyser.models.Application;
import com.tierep.notificationanalyser.models.ApplicationDao;
import com.tierep.notificationanalyser.models.DatabaseHelper;
import java.sql.SQLException;
import java.util.List;
import de.timroes.android.listview.EnhancedListView;
|
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ignored_apps);
getActionBar().setDisplayHomeAsUpEnabled(true);
listView = (EnhancedListView) findViewById(R.id.list_ignored_apps);
try {
List<Application> applicationList = getDatabaseHelper().getApplicationDao().getIgnoredApps();
applicationList.add(0, new Application()); // Insert empty element for header
ignoredAppsAdapter = new ApplicationIgnoreAdapter(this, applicationList);
listView.setAdapter(ignoredAppsAdapter);
} catch (SQLException e) {
e.printStackTrace();
}
listView.setDismissCallback(new EnhancedListView.OnDismissCallback() {
@Override
public EnhancedListView.Undoable onDismiss(EnhancedListView enhancedListView, final int i) {
final Application item = ignoredAppsAdapter.getItem(i);
ignoredAppsAdapter.remove(item);
return new EnhancedListView.Undoable() {
@Override
public void undo() {
ignoredAppsAdapter.insert(item, i);
}
@Override
public void discard() {
try {
|
// Path: NotificationAnalyser/app/src/main/java/com/tierep/notificationanalyser/models/Application.java
// @DatabaseTable(tableName = "Applications", daoClass = ApplicationDaoImpl.class)
// public class Application {
// public static final String FIELD_TABLE_NAME = "Applications";
// public static final String FIELD_PACKAGE_NAME = "PackageName";
// public static final String FIELD_IGNORE = "Ignore";
//
// @DatabaseField(columnName = FIELD_PACKAGE_NAME, id = true, generatedId = false)
// private String PackageName;
// @DatabaseField(columnName = FIELD_IGNORE, canBeNull = false)
// private Boolean Ignore;
//
// public Application() {
// //ORMLite needs a no-arg constructor.
// }
//
// public Application(String packageName, Boolean ignore) {
// this.PackageName = packageName;
// this.Ignore = ignore;
// }
//
// public String getPackageName() {
// return PackageName;
// }
//
// public void setPackageName(String packageName) {
// PackageName = packageName;
// }
//
// public Boolean getIgnore() {
// return Ignore;
// }
//
// public void setIgnore(Boolean ignore) {
// Ignore = ignore;
// }
// }
//
// Path: NotificationAnalyser/app/src/main/java/com/tierep/notificationanalyser/models/ApplicationDao.java
// public interface ApplicationDao extends Dao<Application, String> {
// public List<Application> getIgnoredApps() throws SQLException;
//
// }
//
// Path: NotificationAnalyser/app/src/main/java/com/tierep/notificationanalyser/models/DatabaseHelper.java
// public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
// private static final String DATABASE_NAME = "notifications.db";
//
// private static final int DATABASE_VERSION = 2;
//
// private ApplicationDao applicationDao = null;
// private NotificationItemDao notificationDao = null;
//
// public DatabaseHelper(Context context) {
// super(context, DATABASE_NAME, null, DATABASE_VERSION);
// }
//
// /**
// * This is called when the database is first created. This call createTable statements here to
// * create the tables that will store your data.
// */
// @Override
// public void onCreate(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource) {
// try {
// TableUtils.createTable(connectionSource, NotificationItem.class);
// TableUtils.createTable(connectionSource, Application.class);
// } catch (SQLException e) {
// e.printStackTrace();
// }
// }
//
// @Override
// public void onUpgrade(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource, int oldVersion, int newVersion) {
// if (oldVersion < 2) {
// // Do changes from version 1 to 2
// try {
// NotificationItemDao dao = getNotificationDao();
// dao.executeRawNoArgs("ALTER TABLE " + NotificationItem.FIELD_TABLE_NAME + " ADD COLUMN " + NotificationItem.FIELD_MESSAGE + " TEXT");
// } catch (SQLException e) {
// e.printStackTrace();
// }
//
// }
//
// if (oldVersion < 3) {
// // Do changes from version 2 to 3
// }
// }
//
// /**
// * Returns the Database Access Object (DAO) for Application class. It will create it or
// * just give the cached value.
// */
// public ApplicationDao getApplicationDao() throws SQLException {
// if (applicationDao == null) {
// applicationDao = getDao(Application.class);
// }
// return applicationDao;
// }
//
// /**
// * Returns the Database Access Object (DAO) for NotificationItem class. It will create it or
// * just give the cached value.
// */
// public NotificationItemDao getNotificationDao() throws SQLException {
// if (notificationDao == null) {
// notificationDao = getDao(NotificationItem.class);
// }
// return notificationDao;
// }
//
// /**
// * Close the database connections and clear any cached DAOs.
// */
// @Override
// public void close() {
// super.close();
// applicationDao = null;
// notificationDao = null;
// }
// }
// Path: NotificationAnalyser/app/src/main/java/com/tierep/notificationanalyser/ui/IgnoredApps.java
import android.app.Activity;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.j256.ormlite.android.apptools.OpenHelperManager;
import com.tierep.notificationanalyser.R;
import com.tierep.notificationanalyser.models.Application;
import com.tierep.notificationanalyser.models.ApplicationDao;
import com.tierep.notificationanalyser.models.DatabaseHelper;
import java.sql.SQLException;
import java.util.List;
import de.timroes.android.listview.EnhancedListView;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ignored_apps);
getActionBar().setDisplayHomeAsUpEnabled(true);
listView = (EnhancedListView) findViewById(R.id.list_ignored_apps);
try {
List<Application> applicationList = getDatabaseHelper().getApplicationDao().getIgnoredApps();
applicationList.add(0, new Application()); // Insert empty element for header
ignoredAppsAdapter = new ApplicationIgnoreAdapter(this, applicationList);
listView.setAdapter(ignoredAppsAdapter);
} catch (SQLException e) {
e.printStackTrace();
}
listView.setDismissCallback(new EnhancedListView.OnDismissCallback() {
@Override
public EnhancedListView.Undoable onDismiss(EnhancedListView enhancedListView, final int i) {
final Application item = ignoredAppsAdapter.getItem(i);
ignoredAppsAdapter.remove(item);
return new EnhancedListView.Undoable() {
@Override
public void undo() {
ignoredAppsAdapter.insert(item, i);
}
@Override
public void discard() {
try {
|
ApplicationDao dao = getDatabaseHelper().getApplicationDao();
|
treasure-data/td-jdbc
|
src/test/java/com/treasuredata/jdbc/TestTDResultSet.java
|
// Path: src/main/java/com/treasuredata/jdbc/command/ClientAPI.java
// public interface ClientAPI
// {
// public static class ExtUnpacker
// {
// private File file;
// private Unpacker unpacker;
//
// public ExtUnpacker(File file, Unpacker unpacker)
// {
// this.file = file;
// this.unpacker = unpacker;
// }
//
// public File getFile()
// {
// return file;
// }
//
// public Unpacker getUnpacker()
// {
// return unpacker;
// }
// }
//
// // show all databases statement
// List<DatabaseSummary> showDatabases()
// throws ClientException;
//
// // show current database statement
// DatabaseSummary showDatabase()
// throws ClientException;
//
// // show table statement
// List<TableSummary> showTables()
// throws ClientException;
//
// // select statement
// TDResultSetBase select(String sql)
// throws ClientException;
//
// TDResultSetBase select(String sql, int queryTimeout)
// throws ClientException;
//
// TDResultSetMetaData getMetaDataWithSelect1();
//
// boolean flush(); // for debugging
//
// JobSummary waitJobResult(Job job)
// throws ClientException;
//
// Unpacker getJobResult(Job job)
// throws ClientException;
//
// ExtUnpacker getJobResult2(Job job)
// throws ClientException;
//
// void close()
// throws ClientException;
// }
|
import com.treasure_data.client.ClientException;
import com.treasuredata.jdbc.command.ClientAPI;
import com.treasure_data.model.Database;
import com.treasure_data.model.DatabaseSummary;
import com.treasure_data.model.Job;
import com.treasure_data.model.JobSummary;
import com.treasure_data.model.JobSummary.Status;
import com.treasure_data.model.TableSummary;
import org.junit.Test;
import org.msgpack.MessagePack;
import org.msgpack.packer.BufferPacker;
import org.msgpack.type.ValueFactory;
import org.msgpack.unpacker.Unpacker;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeoutException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.treasuredata.jdbc;
public class TestTDResultSet
{
public static class MockClientAPI
|
// Path: src/main/java/com/treasuredata/jdbc/command/ClientAPI.java
// public interface ClientAPI
// {
// public static class ExtUnpacker
// {
// private File file;
// private Unpacker unpacker;
//
// public ExtUnpacker(File file, Unpacker unpacker)
// {
// this.file = file;
// this.unpacker = unpacker;
// }
//
// public File getFile()
// {
// return file;
// }
//
// public Unpacker getUnpacker()
// {
// return unpacker;
// }
// }
//
// // show all databases statement
// List<DatabaseSummary> showDatabases()
// throws ClientException;
//
// // show current database statement
// DatabaseSummary showDatabase()
// throws ClientException;
//
// // show table statement
// List<TableSummary> showTables()
// throws ClientException;
//
// // select statement
// TDResultSetBase select(String sql)
// throws ClientException;
//
// TDResultSetBase select(String sql, int queryTimeout)
// throws ClientException;
//
// TDResultSetMetaData getMetaDataWithSelect1();
//
// boolean flush(); // for debugging
//
// JobSummary waitJobResult(Job job)
// throws ClientException;
//
// Unpacker getJobResult(Job job)
// throws ClientException;
//
// ExtUnpacker getJobResult2(Job job)
// throws ClientException;
//
// void close()
// throws ClientException;
// }
// Path: src/test/java/com/treasuredata/jdbc/TestTDResultSet.java
import com.treasure_data.client.ClientException;
import com.treasuredata.jdbc.command.ClientAPI;
import com.treasure_data.model.Database;
import com.treasure_data.model.DatabaseSummary;
import com.treasure_data.model.Job;
import com.treasure_data.model.JobSummary;
import com.treasure_data.model.JobSummary.Status;
import com.treasure_data.model.TableSummary;
import org.junit.Test;
import org.msgpack.MessagePack;
import org.msgpack.packer.BufferPacker;
import org.msgpack.type.ValueFactory;
import org.msgpack.unpacker.Unpacker;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeoutException;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.treasuredata.jdbc;
public class TestTDResultSet
{
public static class MockClientAPI
|
implements ClientAPI
|
treasure-data/td-jdbc
|
src/main/java/com/treasuredata/jdbc/TDPreparedStatement.java
|
// Path: src/main/java/com/treasuredata/jdbc/command/CommandContext.java
// public class CommandContext
// {
//
// public int queryTimeout = 0; // seconds
//
// public String sql;
//
// public TDResultSetBase resultSet;
//
// public CommandContext()
// {
// }
// }
|
import com.treasuredata.jdbc.command.CommandContext;
import com.treasure_data.model.Job;
import java.io.InputStream;
import java.io.Reader;
import java.math.BigDecimal;
import java.net.URL;
import java.sql.Array;
import java.sql.Blob;
import java.sql.Clob;
import java.sql.Date;
import java.sql.NClob;
import java.sql.ParameterMetaData;
import java.sql.PreparedStatement;
import java.sql.Ref;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.RowId;
import java.sql.SQLException;
import java.sql.SQLXML;
import java.sql.Time;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.treasuredata.jdbc;
public class TDPreparedStatement
extends TDStatement
implements PreparedStatement
{
private static Logger LOG = Logger.getLogger(
TDPreparedStatement.class.getName());
|
// Path: src/main/java/com/treasuredata/jdbc/command/CommandContext.java
// public class CommandContext
// {
//
// public int queryTimeout = 0; // seconds
//
// public String sql;
//
// public TDResultSetBase resultSet;
//
// public CommandContext()
// {
// }
// }
// Path: src/main/java/com/treasuredata/jdbc/TDPreparedStatement.java
import com.treasuredata.jdbc.command.CommandContext;
import com.treasure_data.model.Job;
import java.io.InputStream;
import java.io.Reader;
import java.math.BigDecimal;
import java.net.URL;
import java.sql.Array;
import java.sql.Blob;
import java.sql.Clob;
import java.sql.Date;
import java.sql.NClob;
import java.sql.ParameterMetaData;
import java.sql.PreparedStatement;
import java.sql.Ref;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.RowId;
import java.sql.SQLException;
import java.sql.SQLXML;
import java.sql.Time;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.treasuredata.jdbc;
public class TDPreparedStatement
extends TDStatement
implements PreparedStatement
{
private static Logger LOG = Logger.getLogger(
TDPreparedStatement.class.getName());
|
private CommandContext context;
|
treasure-data/td-jdbc
|
src/main/java/com/treasuredata/jdbc/TDStatementBase.java
|
// Path: src/main/java/com/treasuredata/jdbc/command/CommandContext.java
// public class CommandContext
// {
//
// public int queryTimeout = 0; // seconds
//
// public String sql;
//
// public TDResultSetBase resultSet;
//
// public CommandContext()
// {
// }
// }
//
// Path: src/main/java/com/treasuredata/jdbc/command/CommandExecutor.java
// public class CommandExecutor
// implements Constants
// {
// private static final Logger LOG = Logger.getLogger(CommandExecutor.class.getName());
//
// private ClientAPI api;
//
// public CommandExecutor(ClientAPI api)
// {
// this.api = api;
// }
//
// public ClientAPI getAPI()
// {
// return api;
// }
//
// public synchronized void execute(CommandContext context)
// throws SQLException
// {
// String sql = context.sql;
// try {
// if (sql.toUpperCase().equals("SELECT 1")) {
// context.resultSet = new TDResultSetSelectOne(api);
// }
// else {
// context.resultSet = api.select(context.sql, context.queryTimeout);
// }
// }
// catch (ClientException e) {
// throw new SQLException(e);
// }
// }
//
// public static class TDResultSetSelectOne
// extends TDResultSetBase
// {
// private ClientAPI api;
//
// private int rowsFetched = 0;
//
// private Unpacker fetchedRows;
//
// private Iterator<Value> fetchedRowsItr;
//
// public TDResultSetSelectOne(ClientAPI api)
// {
// this.api = api;
// }
//
// @Override
// public boolean next()
// throws SQLException
// {
// try {
// if (fetchedRows == null) {
// fetchedRows = fetchRows();
// fetchedRowsItr = fetchedRows.iterator();
// }
//
// if (!fetchedRowsItr.hasNext()) {
// return false;
// }
//
// ArrayValue vs = (ArrayValue) fetchedRowsItr.next();
// row = new ArrayList<Object>(vs.size());
// for (int i = 0; i < vs.size(); i++) {
// row.add(i, vs.get(i));
// }
// rowsFetched++;
// }
// catch (Exception e) {
// throw new SQLException("Error retrieving next row", e);
// }
// // NOTE: fetchOne dosn't throw new SQLException("Method not supported").
// return true;
// }
//
// @Override
// public void close()
// throws SQLException
// {
// // do nothing
// }
//
// @Override
// public ResultSetMetaData getMetaData()
// throws SQLException
// {
// return api.getMetaDataWithSelect1();
// }
//
// private Unpacker fetchRows()
// throws SQLException
// {
// try {
// MessagePack msgpack = new MessagePack();
// ByteArrayOutputStream out = new ByteArrayOutputStream();
// Packer packer = msgpack.createPacker(out);
// List<Integer> src = new ArrayList<Integer>();
// src.add(1);
// packer.write(src);
// byte[] bytes = out.toByteArray();
// ByteArrayInputStream in = new ByteArrayInputStream(bytes);
// Unpacker unpacker = msgpack.createUnpacker(in);
// return unpacker;
// }
// catch (IOException e) {
// throw new SQLException(e);
// }
// }
// }
// }
|
import com.treasuredata.jdbc.command.CommandContext;
import com.treasuredata.jdbc.command.CommandExecutor;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.SQLWarning;
import java.sql.Statement;
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.treasuredata.jdbc;
public abstract class TDStatementBase
implements Statement
{
protected TDConnection conn;
|
// Path: src/main/java/com/treasuredata/jdbc/command/CommandContext.java
// public class CommandContext
// {
//
// public int queryTimeout = 0; // seconds
//
// public String sql;
//
// public TDResultSetBase resultSet;
//
// public CommandContext()
// {
// }
// }
//
// Path: src/main/java/com/treasuredata/jdbc/command/CommandExecutor.java
// public class CommandExecutor
// implements Constants
// {
// private static final Logger LOG = Logger.getLogger(CommandExecutor.class.getName());
//
// private ClientAPI api;
//
// public CommandExecutor(ClientAPI api)
// {
// this.api = api;
// }
//
// public ClientAPI getAPI()
// {
// return api;
// }
//
// public synchronized void execute(CommandContext context)
// throws SQLException
// {
// String sql = context.sql;
// try {
// if (sql.toUpperCase().equals("SELECT 1")) {
// context.resultSet = new TDResultSetSelectOne(api);
// }
// else {
// context.resultSet = api.select(context.sql, context.queryTimeout);
// }
// }
// catch (ClientException e) {
// throw new SQLException(e);
// }
// }
//
// public static class TDResultSetSelectOne
// extends TDResultSetBase
// {
// private ClientAPI api;
//
// private int rowsFetched = 0;
//
// private Unpacker fetchedRows;
//
// private Iterator<Value> fetchedRowsItr;
//
// public TDResultSetSelectOne(ClientAPI api)
// {
// this.api = api;
// }
//
// @Override
// public boolean next()
// throws SQLException
// {
// try {
// if (fetchedRows == null) {
// fetchedRows = fetchRows();
// fetchedRowsItr = fetchedRows.iterator();
// }
//
// if (!fetchedRowsItr.hasNext()) {
// return false;
// }
//
// ArrayValue vs = (ArrayValue) fetchedRowsItr.next();
// row = new ArrayList<Object>(vs.size());
// for (int i = 0; i < vs.size(); i++) {
// row.add(i, vs.get(i));
// }
// rowsFetched++;
// }
// catch (Exception e) {
// throw new SQLException("Error retrieving next row", e);
// }
// // NOTE: fetchOne dosn't throw new SQLException("Method not supported").
// return true;
// }
//
// @Override
// public void close()
// throws SQLException
// {
// // do nothing
// }
//
// @Override
// public ResultSetMetaData getMetaData()
// throws SQLException
// {
// return api.getMetaDataWithSelect1();
// }
//
// private Unpacker fetchRows()
// throws SQLException
// {
// try {
// MessagePack msgpack = new MessagePack();
// ByteArrayOutputStream out = new ByteArrayOutputStream();
// Packer packer = msgpack.createPacker(out);
// List<Integer> src = new ArrayList<Integer>();
// src.add(1);
// packer.write(src);
// byte[] bytes = out.toByteArray();
// ByteArrayInputStream in = new ByteArrayInputStream(bytes);
// Unpacker unpacker = msgpack.createUnpacker(in);
// return unpacker;
// }
// catch (IOException e) {
// throw new SQLException(e);
// }
// }
// }
// }
// Path: src/main/java/com/treasuredata/jdbc/TDStatementBase.java
import com.treasuredata.jdbc.command.CommandContext;
import com.treasuredata.jdbc.command.CommandExecutor;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.SQLWarning;
import java.sql.Statement;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.treasuredata.jdbc;
public abstract class TDStatementBase
implements Statement
{
protected TDConnection conn;
|
protected CommandExecutor exec;
|
treasure-data/td-jdbc
|
src/main/java/com/treasuredata/jdbc/TDStatementBase.java
|
// Path: src/main/java/com/treasuredata/jdbc/command/CommandContext.java
// public class CommandContext
// {
//
// public int queryTimeout = 0; // seconds
//
// public String sql;
//
// public TDResultSetBase resultSet;
//
// public CommandContext()
// {
// }
// }
//
// Path: src/main/java/com/treasuredata/jdbc/command/CommandExecutor.java
// public class CommandExecutor
// implements Constants
// {
// private static final Logger LOG = Logger.getLogger(CommandExecutor.class.getName());
//
// private ClientAPI api;
//
// public CommandExecutor(ClientAPI api)
// {
// this.api = api;
// }
//
// public ClientAPI getAPI()
// {
// return api;
// }
//
// public synchronized void execute(CommandContext context)
// throws SQLException
// {
// String sql = context.sql;
// try {
// if (sql.toUpperCase().equals("SELECT 1")) {
// context.resultSet = new TDResultSetSelectOne(api);
// }
// else {
// context.resultSet = api.select(context.sql, context.queryTimeout);
// }
// }
// catch (ClientException e) {
// throw new SQLException(e);
// }
// }
//
// public static class TDResultSetSelectOne
// extends TDResultSetBase
// {
// private ClientAPI api;
//
// private int rowsFetched = 0;
//
// private Unpacker fetchedRows;
//
// private Iterator<Value> fetchedRowsItr;
//
// public TDResultSetSelectOne(ClientAPI api)
// {
// this.api = api;
// }
//
// @Override
// public boolean next()
// throws SQLException
// {
// try {
// if (fetchedRows == null) {
// fetchedRows = fetchRows();
// fetchedRowsItr = fetchedRows.iterator();
// }
//
// if (!fetchedRowsItr.hasNext()) {
// return false;
// }
//
// ArrayValue vs = (ArrayValue) fetchedRowsItr.next();
// row = new ArrayList<Object>(vs.size());
// for (int i = 0; i < vs.size(); i++) {
// row.add(i, vs.get(i));
// }
// rowsFetched++;
// }
// catch (Exception e) {
// throw new SQLException("Error retrieving next row", e);
// }
// // NOTE: fetchOne dosn't throw new SQLException("Method not supported").
// return true;
// }
//
// @Override
// public void close()
// throws SQLException
// {
// // do nothing
// }
//
// @Override
// public ResultSetMetaData getMetaData()
// throws SQLException
// {
// return api.getMetaDataWithSelect1();
// }
//
// private Unpacker fetchRows()
// throws SQLException
// {
// try {
// MessagePack msgpack = new MessagePack();
// ByteArrayOutputStream out = new ByteArrayOutputStream();
// Packer packer = msgpack.createPacker(out);
// List<Integer> src = new ArrayList<Integer>();
// src.add(1);
// packer.write(src);
// byte[] bytes = out.toByteArray();
// ByteArrayInputStream in = new ByteArrayInputStream(bytes);
// Unpacker unpacker = msgpack.createUnpacker(in);
// return unpacker;
// }
// catch (IOException e) {
// throw new SQLException(e);
// }
// }
// }
// }
|
import com.treasuredata.jdbc.command.CommandContext;
import com.treasuredata.jdbc.command.CommandExecutor;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.SQLWarning;
import java.sql.Statement;
|
* @throws SQLException - if a database access error occurs, this method is
* called on a closed Statement or the condition seconds >= 0 is not
* satisfied
*
* @see java.sql.Statement#setQueryTimeout(int)
*/
public void setQueryTimeout(int seconds)
throws SQLException
{
if (seconds < 0) {
throw new SQLException("seconds must be >= 0");
}
this.queryTimeout = seconds;
}
public int getMaxRows()
throws SQLException
{
return maxRows;
}
public void setMaxRows(int max)
throws SQLException
{
if (max < 0) {
throw new SQLException("max must be >= 0");
}
maxRows = max;
}
|
// Path: src/main/java/com/treasuredata/jdbc/command/CommandContext.java
// public class CommandContext
// {
//
// public int queryTimeout = 0; // seconds
//
// public String sql;
//
// public TDResultSetBase resultSet;
//
// public CommandContext()
// {
// }
// }
//
// Path: src/main/java/com/treasuredata/jdbc/command/CommandExecutor.java
// public class CommandExecutor
// implements Constants
// {
// private static final Logger LOG = Logger.getLogger(CommandExecutor.class.getName());
//
// private ClientAPI api;
//
// public CommandExecutor(ClientAPI api)
// {
// this.api = api;
// }
//
// public ClientAPI getAPI()
// {
// return api;
// }
//
// public synchronized void execute(CommandContext context)
// throws SQLException
// {
// String sql = context.sql;
// try {
// if (sql.toUpperCase().equals("SELECT 1")) {
// context.resultSet = new TDResultSetSelectOne(api);
// }
// else {
// context.resultSet = api.select(context.sql, context.queryTimeout);
// }
// }
// catch (ClientException e) {
// throw new SQLException(e);
// }
// }
//
// public static class TDResultSetSelectOne
// extends TDResultSetBase
// {
// private ClientAPI api;
//
// private int rowsFetched = 0;
//
// private Unpacker fetchedRows;
//
// private Iterator<Value> fetchedRowsItr;
//
// public TDResultSetSelectOne(ClientAPI api)
// {
// this.api = api;
// }
//
// @Override
// public boolean next()
// throws SQLException
// {
// try {
// if (fetchedRows == null) {
// fetchedRows = fetchRows();
// fetchedRowsItr = fetchedRows.iterator();
// }
//
// if (!fetchedRowsItr.hasNext()) {
// return false;
// }
//
// ArrayValue vs = (ArrayValue) fetchedRowsItr.next();
// row = new ArrayList<Object>(vs.size());
// for (int i = 0; i < vs.size(); i++) {
// row.add(i, vs.get(i));
// }
// rowsFetched++;
// }
// catch (Exception e) {
// throw new SQLException("Error retrieving next row", e);
// }
// // NOTE: fetchOne dosn't throw new SQLException("Method not supported").
// return true;
// }
//
// @Override
// public void close()
// throws SQLException
// {
// // do nothing
// }
//
// @Override
// public ResultSetMetaData getMetaData()
// throws SQLException
// {
// return api.getMetaDataWithSelect1();
// }
//
// private Unpacker fetchRows()
// throws SQLException
// {
// try {
// MessagePack msgpack = new MessagePack();
// ByteArrayOutputStream out = new ByteArrayOutputStream();
// Packer packer = msgpack.createPacker(out);
// List<Integer> src = new ArrayList<Integer>();
// src.add(1);
// packer.write(src);
// byte[] bytes = out.toByteArray();
// ByteArrayInputStream in = new ByteArrayInputStream(bytes);
// Unpacker unpacker = msgpack.createUnpacker(in);
// return unpacker;
// }
// catch (IOException e) {
// throw new SQLException(e);
// }
// }
// }
// }
// Path: src/main/java/com/treasuredata/jdbc/TDStatementBase.java
import com.treasuredata.jdbc.command.CommandContext;
import com.treasuredata.jdbc.command.CommandExecutor;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.SQLWarning;
import java.sql.Statement;
* @throws SQLException - if a database access error occurs, this method is
* called on a closed Statement or the condition seconds >= 0 is not
* satisfied
*
* @see java.sql.Statement#setQueryTimeout(int)
*/
public void setQueryTimeout(int seconds)
throws SQLException
{
if (seconds < 0) {
throw new SQLException("seconds must be >= 0");
}
this.queryTimeout = seconds;
}
public int getMaxRows()
throws SQLException
{
return maxRows;
}
public void setMaxRows(int max)
throws SQLException
{
if (max < 0) {
throw new SQLException("max must be >= 0");
}
maxRows = max;
}
|
protected CommandContext fetchResult(String sql)
|
treasure-data/td-jdbc
|
src/main/java/com/treasuredata/jdbc/TDResultSet.java
|
// Path: src/main/java/com/treasuredata/jdbc/command/ClientAPI.java
// public interface ClientAPI
// {
// public static class ExtUnpacker
// {
// private File file;
// private Unpacker unpacker;
//
// public ExtUnpacker(File file, Unpacker unpacker)
// {
// this.file = file;
// this.unpacker = unpacker;
// }
//
// public File getFile()
// {
// return file;
// }
//
// public Unpacker getUnpacker()
// {
// return unpacker;
// }
// }
//
// // show all databases statement
// List<DatabaseSummary> showDatabases()
// throws ClientException;
//
// // show current database statement
// DatabaseSummary showDatabase()
// throws ClientException;
//
// // show table statement
// List<TableSummary> showTables()
// throws ClientException;
//
// // select statement
// TDResultSetBase select(String sql)
// throws ClientException;
//
// TDResultSetBase select(String sql, int queryTimeout)
// throws ClientException;
//
// TDResultSetMetaData getMetaDataWithSelect1();
//
// boolean flush(); // for debugging
//
// JobSummary waitJobResult(Job job)
// throws ClientException;
//
// Unpacker getJobResult(Job job)
// throws ClientException;
//
// ExtUnpacker getJobResult2(Job job)
// throws ClientException;
//
// void close()
// throws ClientException;
// }
|
import com.treasure_data.client.ClientException;
import com.treasuredata.jdbc.command.ClientAPI;
import com.treasure_data.model.Job;
import com.treasure_data.model.JobSummary;
import org.json.simple.JSONValue;
import org.msgpack.type.ArrayValue;
import org.msgpack.type.Value;
import java.io.File;
import java.io.IOException;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.logging.Level;
import java.util.logging.Logger;
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.treasuredata.jdbc;
public class TDResultSet
extends TDResultSetBase
{
private static Logger LOG = Logger.getLogger(TDResultSet.class.getName());
private ExecutorService executor = Executors.newSingleThreadExecutor();
|
// Path: src/main/java/com/treasuredata/jdbc/command/ClientAPI.java
// public interface ClientAPI
// {
// public static class ExtUnpacker
// {
// private File file;
// private Unpacker unpacker;
//
// public ExtUnpacker(File file, Unpacker unpacker)
// {
// this.file = file;
// this.unpacker = unpacker;
// }
//
// public File getFile()
// {
// return file;
// }
//
// public Unpacker getUnpacker()
// {
// return unpacker;
// }
// }
//
// // show all databases statement
// List<DatabaseSummary> showDatabases()
// throws ClientException;
//
// // show current database statement
// DatabaseSummary showDatabase()
// throws ClientException;
//
// // show table statement
// List<TableSummary> showTables()
// throws ClientException;
//
// // select statement
// TDResultSetBase select(String sql)
// throws ClientException;
//
// TDResultSetBase select(String sql, int queryTimeout)
// throws ClientException;
//
// TDResultSetMetaData getMetaDataWithSelect1();
//
// boolean flush(); // for debugging
//
// JobSummary waitJobResult(Job job)
// throws ClientException;
//
// Unpacker getJobResult(Job job)
// throws ClientException;
//
// ExtUnpacker getJobResult2(Job job)
// throws ClientException;
//
// void close()
// throws ClientException;
// }
// Path: src/main/java/com/treasuredata/jdbc/TDResultSet.java
import com.treasure_data.client.ClientException;
import com.treasuredata.jdbc.command.ClientAPI;
import com.treasure_data.model.Job;
import com.treasure_data.model.JobSummary;
import org.json.simple.JSONValue;
import org.msgpack.type.ArrayValue;
import org.msgpack.type.Value;
import java.io.File;
import java.io.IOException;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.logging.Level;
import java.util.logging.Logger;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.treasuredata.jdbc;
public class TDResultSet
extends TDResultSetBase
{
private static Logger LOG = Logger.getLogger(TDResultSet.class.getName());
private ExecutorService executor = Executors.newSingleThreadExecutor();
|
private ClientAPI clientApi;
|
treasure-data/td-jdbc
|
src/main/java/com/treasuredata/jdbc/model/TDColumn.java
|
// Path: src/main/java/com/treasuredata/jdbc/Utils.java
// public class Utils
// {
//
// /**
// * Convert hive types to sql types.
// *
// * @param t
// * @return Integer java.sql.Types values
// * @throws SQLException
// */
// public static int TDTypeToSqlType(String t)
// throws SQLException
// {
// String type = t.toLowerCase();
// if ("string".equals(type)) {
// return Types.VARCHAR;
// }
// else if ("varchar".equals(type) || type.startsWith("varchar(")) {
// return Types.VARCHAR;
// }
// else if ("float".equals(type)) {
// return Types.FLOAT;
// }
// else if ("double".equals(type)) {
// return Types.DOUBLE;
// }
// else if ("boolean".equals(type)) {
// return Types.BOOLEAN;
// }
// else if ("tinyint".equals(type)) {
// return Types.TINYINT;
// }
// else if ("smallint".equals(type)) {
// return Types.SMALLINT;
// }
// else if ("int".equals(type)) {
// return Types.INTEGER;
// }
// else if ("long".equals(type)) {
// return Types.BIGINT;
// }
// else if ("bigint".equals(type)) {
// return Types.BIGINT;
// }
// else if ("date".equals(type)) {
// return Types.DATE;
// }
// else if ("timestamp".equals(type)) {
// return Types.TIMESTAMP;
// }
// else if (type.startsWith("map<")) {
// return Types.VARCHAR;
// }
// else if (type.startsWith("array<")) {
// return Types.VARCHAR;
// }
// else if (type.startsWith("struct<")) {
// return Types.VARCHAR;
// }
// throw new SQLException("Unrecognized column type: " + type);
// }
// }
|
import com.treasuredata.jdbc.Utils;
import java.sql.SQLException;
import java.sql.Types;
|
this.tableName = tableName;
this.tableCatalog = tableCatalog;
this.type = type;
this.comment = comment;
this.ordinal = ordinal;
}
public String getColumnName()
{
return columnName;
}
public String getTableName()
{
return tableName;
}
public String getTableCatalog()
{
return tableCatalog;
}
public String getType()
{
return type;
}
public Integer getSqlType()
throws SQLException
{
|
// Path: src/main/java/com/treasuredata/jdbc/Utils.java
// public class Utils
// {
//
// /**
// * Convert hive types to sql types.
// *
// * @param t
// * @return Integer java.sql.Types values
// * @throws SQLException
// */
// public static int TDTypeToSqlType(String t)
// throws SQLException
// {
// String type = t.toLowerCase();
// if ("string".equals(type)) {
// return Types.VARCHAR;
// }
// else if ("varchar".equals(type) || type.startsWith("varchar(")) {
// return Types.VARCHAR;
// }
// else if ("float".equals(type)) {
// return Types.FLOAT;
// }
// else if ("double".equals(type)) {
// return Types.DOUBLE;
// }
// else if ("boolean".equals(type)) {
// return Types.BOOLEAN;
// }
// else if ("tinyint".equals(type)) {
// return Types.TINYINT;
// }
// else if ("smallint".equals(type)) {
// return Types.SMALLINT;
// }
// else if ("int".equals(type)) {
// return Types.INTEGER;
// }
// else if ("long".equals(type)) {
// return Types.BIGINT;
// }
// else if ("bigint".equals(type)) {
// return Types.BIGINT;
// }
// else if ("date".equals(type)) {
// return Types.DATE;
// }
// else if ("timestamp".equals(type)) {
// return Types.TIMESTAMP;
// }
// else if (type.startsWith("map<")) {
// return Types.VARCHAR;
// }
// else if (type.startsWith("array<")) {
// return Types.VARCHAR;
// }
// else if (type.startsWith("struct<")) {
// return Types.VARCHAR;
// }
// throw new SQLException("Unrecognized column type: " + type);
// }
// }
// Path: src/main/java/com/treasuredata/jdbc/model/TDColumn.java
import com.treasuredata.jdbc.Utils;
import java.sql.SQLException;
import java.sql.Types;
this.tableName = tableName;
this.tableCatalog = tableCatalog;
this.type = type;
this.comment = comment;
this.ordinal = ordinal;
}
public String getColumnName()
{
return columnName;
}
public String getTableName()
{
return tableName;
}
public String getTableCatalog()
{
return tableCatalog;
}
public String getType()
{
return type;
}
public Integer getSqlType()
throws SQLException
{
|
return Utils.TDTypeToSqlType(type);
|
treasure-data/td-jdbc
|
src/test/java/com/treasuredata/jdbc/TestTDResultSetBase.java
|
// Path: src/main/java/com/treasuredata/jdbc/command/ClientAPI.java
// public interface ClientAPI
// {
// public static class ExtUnpacker
// {
// private File file;
// private Unpacker unpacker;
//
// public ExtUnpacker(File file, Unpacker unpacker)
// {
// this.file = file;
// this.unpacker = unpacker;
// }
//
// public File getFile()
// {
// return file;
// }
//
// public Unpacker getUnpacker()
// {
// return unpacker;
// }
// }
//
// // show all databases statement
// List<DatabaseSummary> showDatabases()
// throws ClientException;
//
// // show current database statement
// DatabaseSummary showDatabase()
// throws ClientException;
//
// // show table statement
// List<TableSummary> showTables()
// throws ClientException;
//
// // select statement
// TDResultSetBase select(String sql)
// throws ClientException;
//
// TDResultSetBase select(String sql, int queryTimeout)
// throws ClientException;
//
// TDResultSetMetaData getMetaDataWithSelect1();
//
// boolean flush(); // for debugging
//
// JobSummary waitJobResult(Job job)
// throws ClientException;
//
// Unpacker getJobResult(Job job)
// throws ClientException;
//
// ExtUnpacker getJobResult2(Job job)
// throws ClientException;
//
// void close()
// throws ClientException;
// }
|
import com.treasure_data.client.ClientException;
import com.treasuredata.jdbc.command.ClientAPI;
import com.treasure_data.model.Database;
import com.treasure_data.model.DatabaseSummary;
import com.treasure_data.model.Job;
import com.treasure_data.model.JobSummary;
import com.treasure_data.model.JobSummary.Status;
import com.treasure_data.model.TableSummary;
import org.junit.Test;
import org.msgpack.MessagePack;
import org.msgpack.packer.BufferPacker;
import org.msgpack.unpacker.Unpacker;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.treasuredata.jdbc;
public class TestTDResultSetBase
{
public static class MockClientAPI
|
// Path: src/main/java/com/treasuredata/jdbc/command/ClientAPI.java
// public interface ClientAPI
// {
// public static class ExtUnpacker
// {
// private File file;
// private Unpacker unpacker;
//
// public ExtUnpacker(File file, Unpacker unpacker)
// {
// this.file = file;
// this.unpacker = unpacker;
// }
//
// public File getFile()
// {
// return file;
// }
//
// public Unpacker getUnpacker()
// {
// return unpacker;
// }
// }
//
// // show all databases statement
// List<DatabaseSummary> showDatabases()
// throws ClientException;
//
// // show current database statement
// DatabaseSummary showDatabase()
// throws ClientException;
//
// // show table statement
// List<TableSummary> showTables()
// throws ClientException;
//
// // select statement
// TDResultSetBase select(String sql)
// throws ClientException;
//
// TDResultSetBase select(String sql, int queryTimeout)
// throws ClientException;
//
// TDResultSetMetaData getMetaDataWithSelect1();
//
// boolean flush(); // for debugging
//
// JobSummary waitJobResult(Job job)
// throws ClientException;
//
// Unpacker getJobResult(Job job)
// throws ClientException;
//
// ExtUnpacker getJobResult2(Job job)
// throws ClientException;
//
// void close()
// throws ClientException;
// }
// Path: src/test/java/com/treasuredata/jdbc/TestTDResultSetBase.java
import com.treasure_data.client.ClientException;
import com.treasuredata.jdbc.command.ClientAPI;
import com.treasure_data.model.Database;
import com.treasure_data.model.DatabaseSummary;
import com.treasure_data.model.Job;
import com.treasure_data.model.JobSummary;
import com.treasure_data.model.JobSummary.Status;
import com.treasure_data.model.TableSummary;
import org.junit.Test;
import org.msgpack.MessagePack;
import org.msgpack.packer.BufferPacker;
import org.msgpack.unpacker.Unpacker;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.treasuredata.jdbc;
public class TestTDResultSetBase
{
public static class MockClientAPI
|
implements ClientAPI
|
treasure-data/td-jdbc
|
src/main/java/com/treasuredata/jdbc/TDResultSetMetaData.java
|
// Path: src/main/java/com/treasuredata/jdbc/model/TDColumn.java
// public class TDColumn
// {
// private final String columnName;
//
// private final String tableName;
//
// private final String tableCatalog;
//
// private final String type;
//
// private final String comment;
//
// private final int ordinal;
//
// public TDColumn(String columnName, String tableName, String tableCatalog,
// String type, String comment, int ordinal)
// {
// this.columnName = columnName;
// this.tableName = tableName;
// this.tableCatalog = tableCatalog;
// this.type = type;
// this.comment = comment;
// this.ordinal = ordinal;
// }
//
// public String getColumnName()
// {
// return columnName;
// }
//
// public String getTableName()
// {
// return tableName;
// }
//
// public String getTableCatalog()
// {
// return tableCatalog;
// }
//
// public String getType()
// {
// return type;
// }
//
// public Integer getSqlType()
// throws SQLException
// {
// return Utils.TDTypeToSqlType(type);
// }
//
// public static int columnDisplaySize(int columnType)
// throws SQLException
// {
// // according to hiveTypeToSqlType possible options are:
// switch (columnType) {
// case Types.BOOLEAN:
// return columnPrecision(columnType);
// case Types.VARCHAR:
// return Integer.MAX_VALUE; // hive has no max limit for strings
// case Types.TINYINT:
// case Types.SMALLINT:
// case Types.INTEGER:
// case Types.BIGINT:
// return columnPrecision(columnType) + 1; // allow +/-
//
// // see
// // http://download.oracle.com/javase/6/docs/api/constant-values.html#java.lang.Float.MAX_EXPONENT
// case Types.FLOAT:
// return 24; // e.g. -(17#).e-###
// // see
// // http://download.oracle.com/javase/6/docs/api/constant-values.html#java.lang.Double.MAX_EXPONENT
// case Types.DOUBLE:
// return 25; // e.g. -(17#).e-####
// default:
// throw new SQLException("Invalid column type: " + columnType);
// }
// }
//
// public static int columnPrecision(int columnType)
// throws SQLException
// {
// // according to hiveTypeToSqlType possible options are:
// switch (columnType) {
// case Types.BOOLEAN:
// return 1;
// case Types.VARCHAR:
// return Integer.MAX_VALUE; // hive has no max limit for strings
// case Types.TINYINT:
// return 3;
// case Types.SMALLINT:
// return 5;
// case Types.INTEGER:
// return 10;
// case Types.BIGINT:
// return 19;
// case Types.FLOAT:
// return 7;
// case Types.DOUBLE:
// return 15;
// default:
// throw new SQLException("Invalid column type: " + columnType);
// }
// }
//
// public static int columnScale(int columnType)
// throws SQLException
// {
// // according to hiveTypeToSqlType possible options are:
// switch (columnType) {
// case Types.BOOLEAN:
// case Types.VARCHAR:
// case Types.TINYINT:
// case Types.SMALLINT:
// case Types.INTEGER:
// case Types.BIGINT:
// return 0;
// case Types.FLOAT:
// return 7;
// case Types.DOUBLE:
// return 15;
// default:
// throw new SQLException("Invalid column type: " + columnType);
// }
// }
//
// public Integer getColumnSize()
// throws SQLException
// {
// int precision = columnPrecision(Utils.TDTypeToSqlType(type));
// return precision == 0 ? null : precision;
// }
//
// public Integer getDecimalDigits()
// throws SQLException
// {
// return columnScale(Utils.TDTypeToSqlType(type));
// }
//
// public Integer getNumPrecRadix()
// {
// if (type.equalsIgnoreCase("tinyint")) {
// return 10;
// }
// else if (type.equalsIgnoreCase("smallint")) {
// return 10;
// }
// else if (type.equalsIgnoreCase("int")) {
// return 10;
// }
// else if (type.equalsIgnoreCase("bigint")) {
// return 10;
// }
// else if (type.equalsIgnoreCase("float")) {
// return 2;
// }
// else if (type.equalsIgnoreCase("double")) {
// return 2;
// }
// else { // anything else including boolean and string is null
// return null;
// }
// }
//
// public String getComment()
// {
// return comment;
// }
//
// public int getOrdinal()
// {
// return ordinal;
// }
// }
|
import java.util.List;
import com.treasuredata.jdbc.model.TDColumn;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
|
this.columnTypes = columnTypes;
}
public String getJobId() {
return jobId;
}
public String getCatalogName(int column)
throws SQLException
{
throw new SQLException("Method not supported");
}
public String getColumnClassName(int column)
throws SQLException
{
throw new SQLException("Method not supported");
}
public int getColumnCount()
throws SQLException
{
return columnNames.size();
}
public int getColumnDisplaySize(int column)
throws SQLException
{
int columnType = getColumnType(column);
|
// Path: src/main/java/com/treasuredata/jdbc/model/TDColumn.java
// public class TDColumn
// {
// private final String columnName;
//
// private final String tableName;
//
// private final String tableCatalog;
//
// private final String type;
//
// private final String comment;
//
// private final int ordinal;
//
// public TDColumn(String columnName, String tableName, String tableCatalog,
// String type, String comment, int ordinal)
// {
// this.columnName = columnName;
// this.tableName = tableName;
// this.tableCatalog = tableCatalog;
// this.type = type;
// this.comment = comment;
// this.ordinal = ordinal;
// }
//
// public String getColumnName()
// {
// return columnName;
// }
//
// public String getTableName()
// {
// return tableName;
// }
//
// public String getTableCatalog()
// {
// return tableCatalog;
// }
//
// public String getType()
// {
// return type;
// }
//
// public Integer getSqlType()
// throws SQLException
// {
// return Utils.TDTypeToSqlType(type);
// }
//
// public static int columnDisplaySize(int columnType)
// throws SQLException
// {
// // according to hiveTypeToSqlType possible options are:
// switch (columnType) {
// case Types.BOOLEAN:
// return columnPrecision(columnType);
// case Types.VARCHAR:
// return Integer.MAX_VALUE; // hive has no max limit for strings
// case Types.TINYINT:
// case Types.SMALLINT:
// case Types.INTEGER:
// case Types.BIGINT:
// return columnPrecision(columnType) + 1; // allow +/-
//
// // see
// // http://download.oracle.com/javase/6/docs/api/constant-values.html#java.lang.Float.MAX_EXPONENT
// case Types.FLOAT:
// return 24; // e.g. -(17#).e-###
// // see
// // http://download.oracle.com/javase/6/docs/api/constant-values.html#java.lang.Double.MAX_EXPONENT
// case Types.DOUBLE:
// return 25; // e.g. -(17#).e-####
// default:
// throw new SQLException("Invalid column type: " + columnType);
// }
// }
//
// public static int columnPrecision(int columnType)
// throws SQLException
// {
// // according to hiveTypeToSqlType possible options are:
// switch (columnType) {
// case Types.BOOLEAN:
// return 1;
// case Types.VARCHAR:
// return Integer.MAX_VALUE; // hive has no max limit for strings
// case Types.TINYINT:
// return 3;
// case Types.SMALLINT:
// return 5;
// case Types.INTEGER:
// return 10;
// case Types.BIGINT:
// return 19;
// case Types.FLOAT:
// return 7;
// case Types.DOUBLE:
// return 15;
// default:
// throw new SQLException("Invalid column type: " + columnType);
// }
// }
//
// public static int columnScale(int columnType)
// throws SQLException
// {
// // according to hiveTypeToSqlType possible options are:
// switch (columnType) {
// case Types.BOOLEAN:
// case Types.VARCHAR:
// case Types.TINYINT:
// case Types.SMALLINT:
// case Types.INTEGER:
// case Types.BIGINT:
// return 0;
// case Types.FLOAT:
// return 7;
// case Types.DOUBLE:
// return 15;
// default:
// throw new SQLException("Invalid column type: " + columnType);
// }
// }
//
// public Integer getColumnSize()
// throws SQLException
// {
// int precision = columnPrecision(Utils.TDTypeToSqlType(type));
// return precision == 0 ? null : precision;
// }
//
// public Integer getDecimalDigits()
// throws SQLException
// {
// return columnScale(Utils.TDTypeToSqlType(type));
// }
//
// public Integer getNumPrecRadix()
// {
// if (type.equalsIgnoreCase("tinyint")) {
// return 10;
// }
// else if (type.equalsIgnoreCase("smallint")) {
// return 10;
// }
// else if (type.equalsIgnoreCase("int")) {
// return 10;
// }
// else if (type.equalsIgnoreCase("bigint")) {
// return 10;
// }
// else if (type.equalsIgnoreCase("float")) {
// return 2;
// }
// else if (type.equalsIgnoreCase("double")) {
// return 2;
// }
// else { // anything else including boolean and string is null
// return null;
// }
// }
//
// public String getComment()
// {
// return comment;
// }
//
// public int getOrdinal()
// {
// return ordinal;
// }
// }
// Path: src/main/java/com/treasuredata/jdbc/TDResultSetMetaData.java
import java.util.List;
import com.treasuredata.jdbc.model.TDColumn;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
this.columnTypes = columnTypes;
}
public String getJobId() {
return jobId;
}
public String getCatalogName(int column)
throws SQLException
{
throw new SQLException("Method not supported");
}
public String getColumnClassName(int column)
throws SQLException
{
throw new SQLException("Method not supported");
}
public int getColumnCount()
throws SQLException
{
return columnNames.size();
}
public int getColumnDisplaySize(int column)
throws SQLException
{
int columnType = getColumnType(column);
|
return TDColumn.columnDisplaySize(columnType);
|
treasure-data/td-jdbc
|
src/test/java/com/treasuredata/jdbc/TestTDDatabaseMetaData.java
|
// Path: src/main/java/com/treasuredata/jdbc/command/NullClientAPI.java
// public class NullClientAPI
// implements ClientAPI
// {
// public NullClientAPI()
// {
// }
//
// public List<DatabaseSummary> showDatabases()
// throws ClientException
// {
// return null;
// }
//
// public DatabaseSummary showDatabase()
// throws ClientException
// {
// return null;
// }
//
// public List<TableSummary> showTables()
// throws ClientException
// {
// return null;
// }
//
// public boolean flush()
// {
// return true;
// }
//
// public TDResultSetBase select(String sql)
// throws ClientException
// {
// return null;
// }
//
// public TDResultSetBase select(String sql, int queryTimeout)
// throws ClientException
// {
// return null;
// }
//
// public TDResultSetMetaData getMetaDataWithSelect1()
// {
// return null;
// }
//
// public JobSummary waitJobResult(Job job)
// throws ClientException
// {
// return null;
// }
//
// public Unpacker getJobResult(Job job)
// throws ClientException
// {
// return null;
// }
//
// public ExtUnpacker getJobResult2(Job job)
// throws ClientException
// {
// return new ExtUnpacker(null, getJobResult(job));
// }
//
// public void close()
// throws ClientException
// {
// }
// }
|
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import com.treasure_data.client.ClientException;
import com.treasuredata.jdbc.command.NullClientAPI;
import com.treasure_data.model.Database;
import com.treasure_data.model.DatabaseSummary;
import com.treasure_data.model.Table;
import com.treasure_data.model.TableSummary;
import org.junit.Test;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.treasuredata.jdbc;
public class TestTDDatabaseMetaData
{
@Test
public void getCatalogSeparator()
throws Exception
{
TDDatabaseMetaData metadata = new TDDatabaseMetaData(
|
// Path: src/main/java/com/treasuredata/jdbc/command/NullClientAPI.java
// public class NullClientAPI
// implements ClientAPI
// {
// public NullClientAPI()
// {
// }
//
// public List<DatabaseSummary> showDatabases()
// throws ClientException
// {
// return null;
// }
//
// public DatabaseSummary showDatabase()
// throws ClientException
// {
// return null;
// }
//
// public List<TableSummary> showTables()
// throws ClientException
// {
// return null;
// }
//
// public boolean flush()
// {
// return true;
// }
//
// public TDResultSetBase select(String sql)
// throws ClientException
// {
// return null;
// }
//
// public TDResultSetBase select(String sql, int queryTimeout)
// throws ClientException
// {
// return null;
// }
//
// public TDResultSetMetaData getMetaDataWithSelect1()
// {
// return null;
// }
//
// public JobSummary waitJobResult(Job job)
// throws ClientException
// {
// return null;
// }
//
// public Unpacker getJobResult(Job job)
// throws ClientException
// {
// return null;
// }
//
// public ExtUnpacker getJobResult2(Job job)
// throws ClientException
// {
// return new ExtUnpacker(null, getJobResult(job));
// }
//
// public void close()
// throws ClientException
// {
// }
// }
// Path: src/test/java/com/treasuredata/jdbc/TestTDDatabaseMetaData.java
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import com.treasure_data.client.ClientException;
import com.treasuredata.jdbc.command.NullClientAPI;
import com.treasure_data.model.Database;
import com.treasure_data.model.DatabaseSummary;
import com.treasure_data.model.Table;
import com.treasure_data.model.TableSummary;
import org.junit.Test;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.treasuredata.jdbc;
public class TestTDDatabaseMetaData
{
@Test
public void getCatalogSeparator()
throws Exception
{
TDDatabaseMetaData metadata = new TDDatabaseMetaData(
|
new NullClientAPI());
|
VelbazhdSoftwareLLC/Complica4
|
client/test/eu/veldsoft/complica4/model/ia/AbstractArtificialIntelligenceTest.java
|
// Path: client/src/eu/veldsoft/complica4/model/Util.java
// public class Util {
// /**
// * Pseudo-random number generator instance.
// */
// public static final Random PRNG = new Random();
//
// /**
// * ANN file name.
// */
// public static final String ANN_FILE_NAME = "ann.bin";
//
// /**
// * ANN file name.
// */
// public static final boolean VERBOSE_LOG = true;
//
// /**
// * Find better way for giving value of this constant.
// */
// public static final int ALARM_REQUEST_CODE = 0;
//
// /**
// * Fixed number of examples to be trained in a single training.
// */
// public static final int NUMBER_OF_SINGLE_TRAINING_EXAMPLES = 11;
//
// /**
// * Consultant ANN object JSON key value.
// */
// public static final String JSON_OBJECT_KEY = "object";
//
// /**
// * Consultant ANN rating JSON key value.
// */
// public static final String JSON_RATING_KEY = "rating";
//
// /**
// * Consultant found data JSON key value.
// */
// public static final String JSON_FOUND_KEY = "found";
//
// /**
// * Create new artificial neural network.
// *
// * @param inputSize
// * Size of the input layer.
// * @param hiddenSize
// * Size of the hidden layer.
// * @param outputSize
// * Size of the output layer.
// *
// * @return Neural network created object.
// */
// public static BasicNetwork newNetwork(int inputSize, int hiddenSize, int outputSize) {
// BasicNetwork net = new BasicNetwork();
//
// net.addLayer(new BasicLayer(null, true, inputSize));
// net.addLayer(new BasicLayer(new ActivationSigmoid(), true, hiddenSize));
// net.addLayer(new BasicLayer(new ActivationSigmoid(), false, outputSize));
// net.getStructure().finalizeStructure();
// net.reset();
//
// return net;
// }
//
// /**
// * Load ANN from a file.
// *
// * @param name
// * File name.
// *
// * @return True if the loading is successful, false otherwise.
// */
// public static BasicNetwork loadFromFile(String name) {
// BasicNetwork ann = null;
//
// try {
// ObjectInputStream in = new ObjectInputStream(new FileInputStream(name));
// ann = (BasicNetwork) in.readObject();
// in.close();
// } catch (Exception ex) {
// }
//
// return ann;
// }
//
// /**
// * Save ANN to a file.
// *
// * @param ann
// * Artificial Neural Network object.
// * @param name
// * File name.
// */
// public static void saveToFile(BasicNetwork ann, String name) {
// try {
// ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(name));
// out.writeObject(ann);
// out.close();
// } catch (Exception ex) {
// }
// }
//
// /**
// * Log activity.
// *
// * @param text
// * Text to log.
// */
// public static void log(String text) {
// if (VERBOSE_LOG == false) {
// return;
// }
//
// System.out.println(text);
// }
// }
|
import static org.junit.Assert.assertEquals;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import eu.veldsoft.complica4.model.Util;
|
package eu.veldsoft.complica4.model.ia;
/**
* Tests the methods in the AbstractArtificialIntelligence class.
*
* @author Georgi Gospodinov
* @see AbstractArtificialIntelligence
*/
public class AbstractArtificialIntelligenceTest {
/**
* This object is used to test that the correct exception is thrown.
*/
@Rule
public ExpectedException exception = ExpectedException.none();
/**
* Test to see that the move method returns the correct value when the input
* is valid.
*/
@Test
public void testMove() {
int[][] state = new int[ArtificialIntelligence.STATE_COLS][ArtificialIntelligence.STATE_ROWS];
|
// Path: client/src/eu/veldsoft/complica4/model/Util.java
// public class Util {
// /**
// * Pseudo-random number generator instance.
// */
// public static final Random PRNG = new Random();
//
// /**
// * ANN file name.
// */
// public static final String ANN_FILE_NAME = "ann.bin";
//
// /**
// * ANN file name.
// */
// public static final boolean VERBOSE_LOG = true;
//
// /**
// * Find better way for giving value of this constant.
// */
// public static final int ALARM_REQUEST_CODE = 0;
//
// /**
// * Fixed number of examples to be trained in a single training.
// */
// public static final int NUMBER_OF_SINGLE_TRAINING_EXAMPLES = 11;
//
// /**
// * Consultant ANN object JSON key value.
// */
// public static final String JSON_OBJECT_KEY = "object";
//
// /**
// * Consultant ANN rating JSON key value.
// */
// public static final String JSON_RATING_KEY = "rating";
//
// /**
// * Consultant found data JSON key value.
// */
// public static final String JSON_FOUND_KEY = "found";
//
// /**
// * Create new artificial neural network.
// *
// * @param inputSize
// * Size of the input layer.
// * @param hiddenSize
// * Size of the hidden layer.
// * @param outputSize
// * Size of the output layer.
// *
// * @return Neural network created object.
// */
// public static BasicNetwork newNetwork(int inputSize, int hiddenSize, int outputSize) {
// BasicNetwork net = new BasicNetwork();
//
// net.addLayer(new BasicLayer(null, true, inputSize));
// net.addLayer(new BasicLayer(new ActivationSigmoid(), true, hiddenSize));
// net.addLayer(new BasicLayer(new ActivationSigmoid(), false, outputSize));
// net.getStructure().finalizeStructure();
// net.reset();
//
// return net;
// }
//
// /**
// * Load ANN from a file.
// *
// * @param name
// * File name.
// *
// * @return True if the loading is successful, false otherwise.
// */
// public static BasicNetwork loadFromFile(String name) {
// BasicNetwork ann = null;
//
// try {
// ObjectInputStream in = new ObjectInputStream(new FileInputStream(name));
// ann = (BasicNetwork) in.readObject();
// in.close();
// } catch (Exception ex) {
// }
//
// return ann;
// }
//
// /**
// * Save ANN to a file.
// *
// * @param ann
// * Artificial Neural Network object.
// * @param name
// * File name.
// */
// public static void saveToFile(BasicNetwork ann, String name) {
// try {
// ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(name));
// out.writeObject(ann);
// out.close();
// } catch (Exception ex) {
// }
// }
//
// /**
// * Log activity.
// *
// * @param text
// * Text to log.
// */
// public static void log(String text) {
// if (VERBOSE_LOG == false) {
// return;
// }
//
// System.out.println(text);
// }
// }
// Path: client/test/eu/veldsoft/complica4/model/ia/AbstractArtificialIntelligenceTest.java
import static org.junit.Assert.assertEquals;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import eu.veldsoft.complica4.model.Util;
package eu.veldsoft.complica4.model.ia;
/**
* Tests the methods in the AbstractArtificialIntelligence class.
*
* @author Georgi Gospodinov
* @see AbstractArtificialIntelligence
*/
public class AbstractArtificialIntelligenceTest {
/**
* This object is used to test that the correct exception is thrown.
*/
@Rule
public ExpectedException exception = ExpectedException.none();
/**
* Test to see that the move method returns the correct value when the input
* is valid.
*/
@Test
public void testMove() {
int[][] state = new int[ArtificialIntelligence.STATE_COLS][ArtificialIntelligence.STATE_ROWS];
|
int player = Util.PRNG.nextInt(ArtificialIntelligence.NUMBER_OF_PLAYERS + 1);
|
bin-liu/TYComponent
|
TangyuComponentProject/Test/src/com/tangyu/component/TestJavaBean.java
|
// Path: TangyuComponentProject/Source/demo/com/tangyu/component/demo/util/JavaBeanV2.java
// public class JavaBeanV2 implements IJsonBeanV2 {
//
// private int paramA;
//
// private String paramB;
//
// public JavaBeanV2() {
// }
//
// public int getParamA() {
// return paramA;
// }
//
// public void setParamA(int paramA) {
// this.paramA = paramA;
// }
//
// public String getParamB() {
// return paramB;
// }
//
// public void setParamB(String paramB) {
// this.paramB = paramB;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// JavaBeanV2 that = (JavaBeanV2) o;
//
// if (paramA != that.paramA) return false;
// if (paramB != null ? !paramB.equals(that.paramB) : that.paramB != null) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = paramA;
// result = 31 * result + (paramB != null ? paramB.hashCode() : 0);
// return result;
// }
//
// @Override
// public String toString() {
// return "JavaBeanV2{" +
// "paramA=" + paramA +
// ", paramB='" + paramB + '\'' +
// '}';
// }
//
// public static final EncodeObject<JavaBeanV2> CODE = new EncodeObject<JavaBeanV2>() { };
// public static final EncodeString<JavaBeanV2> CODE_STRING = new EncodeString<JavaBeanV2>() { };
// }
|
import android.test.AndroidTestCase;
import com.alibaba.fastjson.JSON;
import com.tangyu.component.demo.util.JavaBeanV2;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
|
package com.tangyu.component;
/**
* @author binliu on 8/24/14.
*/
public class TestJavaBean extends AndroidTestCase {
@Override
protected void setUp() throws Exception {
super.setUp();
}
@Override
protected void tearDown() throws Exception {
super.tearDown();
}
public void testEnDecode() throws Exception {
|
// Path: TangyuComponentProject/Source/demo/com/tangyu/component/demo/util/JavaBeanV2.java
// public class JavaBeanV2 implements IJsonBeanV2 {
//
// private int paramA;
//
// private String paramB;
//
// public JavaBeanV2() {
// }
//
// public int getParamA() {
// return paramA;
// }
//
// public void setParamA(int paramA) {
// this.paramA = paramA;
// }
//
// public String getParamB() {
// return paramB;
// }
//
// public void setParamB(String paramB) {
// this.paramB = paramB;
// }
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// JavaBeanV2 that = (JavaBeanV2) o;
//
// if (paramA != that.paramA) return false;
// if (paramB != null ? !paramB.equals(that.paramB) : that.paramB != null) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result = paramA;
// result = 31 * result + (paramB != null ? paramB.hashCode() : 0);
// return result;
// }
//
// @Override
// public String toString() {
// return "JavaBeanV2{" +
// "paramA=" + paramA +
// ", paramB='" + paramB + '\'' +
// '}';
// }
//
// public static final EncodeObject<JavaBeanV2> CODE = new EncodeObject<JavaBeanV2>() { };
// public static final EncodeString<JavaBeanV2> CODE_STRING = new EncodeString<JavaBeanV2>() { };
// }
// Path: TangyuComponentProject/Test/src/com/tangyu/component/TestJavaBean.java
import android.test.AndroidTestCase;
import com.alibaba.fastjson.JSON;
import com.tangyu.component.demo.util.JavaBeanV2;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
package com.tangyu.component;
/**
* @author binliu on 8/24/14.
*/
public class TestJavaBean extends AndroidTestCase {
@Override
protected void setUp() throws Exception {
super.setUp();
}
@Override
protected void tearDown() throws Exception {
super.tearDown();
}
public void testEnDecode() throws Exception {
|
enDeCode(JavaBeanV2.class);
|
bin-liu/TYComponent
|
TangyuComponentProject/Source/src/com/tangyu/component/util/GPSHelper.java
|
// Path: TangyuComponentProject/Source/src/com/tangyu/component/ActionCfg.java
// public class ActionCfg {
//
// public static final String APP_NAME = "com.tangyu.app";
//
// public static final String ACT_GPS = ".gps";
//
// public final static String ACT_REMIND_NEWDAY = ".NEWDAY_REMIND";
// public final static String ACT_REMIND_WAKEUP = ".WAKEUP";
// }
|
import android.app.PendingIntent;
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import com.tangyu.component.ActionCfg;
|
/**
* The MIT License (MIT)
* Copyright (c) 2012-2014 唐虞科技(TangyuSoft) Corporation
*
* 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 com.tangyu.component.util;
/**
* Before use GPSHelper. u should add permission in AndroidManifest.xml</br>
* "android.permission.ACCESS_FINE_LOCATION"
*
* @author bin
*/
public class GPSHelper {
public static final int MIN_DISTANCE = 500;
public static final int MIN_TIME = 120 * 1000;
public static int minDistance = MIN_DISTANCE;
public static int minTime = MIN_TIME;
|
// Path: TangyuComponentProject/Source/src/com/tangyu/component/ActionCfg.java
// public class ActionCfg {
//
// public static final String APP_NAME = "com.tangyu.app";
//
// public static final String ACT_GPS = ".gps";
//
// public final static String ACT_REMIND_NEWDAY = ".NEWDAY_REMIND";
// public final static String ACT_REMIND_WAKEUP = ".WAKEUP";
// }
// Path: TangyuComponentProject/Source/src/com/tangyu/component/util/GPSHelper.java
import android.app.PendingIntent;
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import com.tangyu.component.ActionCfg;
/**
* The MIT License (MIT)
* Copyright (c) 2012-2014 唐虞科技(TangyuSoft) Corporation
*
* 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 com.tangyu.component.util;
/**
* Before use GPSHelper. u should add permission in AndroidManifest.xml</br>
* "android.permission.ACCESS_FINE_LOCATION"
*
* @author bin
*/
public class GPSHelper {
public static final int MIN_DISTANCE = 500;
public static final int MIN_TIME = 120 * 1000;
public static int minDistance = MIN_DISTANCE;
public static int minTime = MIN_TIME;
|
public static final String ACTION_GPS = ActionCfg.APP_NAME + ActionCfg.ACT_GPS;
|
Gwindow/WhatAndroid
|
WhatAndroid/src/main/java/what/whatandroid/search/UserSearchFragment.java
|
// Path: WhatAndroid/src/main/java/what/whatandroid/callbacks/OnLoggedInCallback.java
// public interface OnLoggedInCallback {
// /**
// * Function called when the user has logged in or has been confirmed to be logged in
// */
// public void onLoggedIn();
// }
//
// Path: WhatAndroid/src/main/java/what/whatandroid/callbacks/ViewUserCallbacks.java
// public interface ViewUserCallbacks {
// /**
// * Request the activity to launch a profile activity viewing the user with some id
// *
// * @param id user id to view
// */
// public void viewUser(int id);
// }
|
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.*;
import api.search.user.UserSearch;
import what.whatandroid.R;
import what.whatandroid.callbacks.OnLoggedInCallback;
import what.whatandroid.callbacks.SetTitleCallback;
import what.whatandroid.callbacks.ViewUserCallbacks;
|
package what.whatandroid.search;
/**
* Fragment for searching for users. If only one user is returned as a result we go to their profile,
* otherwise a list of found users is displayed
*/
public class UserSearchFragment extends Fragment implements View.OnClickListener, TextView.OnEditorActionListener,
OnLoggedInCallback, LoaderManager.LoaderCallbacks<UserSearch>, AbsListView.OnScrollListener {
/**
* So we can set the action bar title and viewing a user
*/
private SetTitleCallback setTitle;
|
// Path: WhatAndroid/src/main/java/what/whatandroid/callbacks/OnLoggedInCallback.java
// public interface OnLoggedInCallback {
// /**
// * Function called when the user has logged in or has been confirmed to be logged in
// */
// public void onLoggedIn();
// }
//
// Path: WhatAndroid/src/main/java/what/whatandroid/callbacks/ViewUserCallbacks.java
// public interface ViewUserCallbacks {
// /**
// * Request the activity to launch a profile activity viewing the user with some id
// *
// * @param id user id to view
// */
// public void viewUser(int id);
// }
// Path: WhatAndroid/src/main/java/what/whatandroid/search/UserSearchFragment.java
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.*;
import api.search.user.UserSearch;
import what.whatandroid.R;
import what.whatandroid.callbacks.OnLoggedInCallback;
import what.whatandroid.callbacks.SetTitleCallback;
import what.whatandroid.callbacks.ViewUserCallbacks;
package what.whatandroid.search;
/**
* Fragment for searching for users. If only one user is returned as a result we go to their profile,
* otherwise a list of found users is displayed
*/
public class UserSearchFragment extends Fragment implements View.OnClickListener, TextView.OnEditorActionListener,
OnLoggedInCallback, LoaderManager.LoaderCallbacks<UserSearch>, AbsListView.OnScrollListener {
/**
* So we can set the action bar title and viewing a user
*/
private SetTitleCallback setTitle;
|
private ViewUserCallbacks viewUser;
|
Gwindow/WhatAndroid
|
WhatAndroid/src/main/java/what/whatandroid/request/RequestAdapter.java
|
// Path: WhatAndroid/src/main/java/what/whatandroid/callbacks/ViewArtistCallbacks.java
// public interface ViewArtistCallbacks {
// /**
// * Launch an artists activity viewing the artist
// *
// * @param id artist id to view
// */
// public void viewArtist(int id);
// }
//
// Path: WhatAndroid/src/main/java/what/whatandroid/callbacks/ViewUserCallbacks.java
// public interface ViewUserCallbacks {
// /**
// * Request the activity to launch a profile activity viewing the user with some id
// *
// * @param id user id to view
// */
// public void viewUser(int id);
// }
|
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.TextView;
import api.cli.Utils;
import api.requests.TopContributor;
import api.torrents.torrents.Artist;
import api.torrents.torrents.MusicInfo;
import what.whatandroid.R;
import what.whatandroid.callbacks.ViewArtistCallbacks;
import what.whatandroid.callbacks.ViewUserCallbacks;
import java.util.List;
|
package what.whatandroid.request;
/**
* Adapter for the expandable list view in the Request fragment that shows
* the artists and top contributors
*/
public class RequestAdapter extends BaseExpandableListAdapter implements ExpandableListView.OnChildClickListener {
private final LayoutInflater inflater;
List<Artist> artists;
List<TopContributor> topContributors;
/**
* Callbacks to go view an artist or user in the list
*/
|
// Path: WhatAndroid/src/main/java/what/whatandroid/callbacks/ViewArtistCallbacks.java
// public interface ViewArtistCallbacks {
// /**
// * Launch an artists activity viewing the artist
// *
// * @param id artist id to view
// */
// public void viewArtist(int id);
// }
//
// Path: WhatAndroid/src/main/java/what/whatandroid/callbacks/ViewUserCallbacks.java
// public interface ViewUserCallbacks {
// /**
// * Request the activity to launch a profile activity viewing the user with some id
// *
// * @param id user id to view
// */
// public void viewUser(int id);
// }
// Path: WhatAndroid/src/main/java/what/whatandroid/request/RequestAdapter.java
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.TextView;
import api.cli.Utils;
import api.requests.TopContributor;
import api.torrents.torrents.Artist;
import api.torrents.torrents.MusicInfo;
import what.whatandroid.R;
import what.whatandroid.callbacks.ViewArtistCallbacks;
import what.whatandroid.callbacks.ViewUserCallbacks;
import java.util.List;
package what.whatandroid.request;
/**
* Adapter for the expandable list view in the Request fragment that shows
* the artists and top contributors
*/
public class RequestAdapter extends BaseExpandableListAdapter implements ExpandableListView.OnChildClickListener {
private final LayoutInflater inflater;
List<Artist> artists;
List<TopContributor> topContributors;
/**
* Callbacks to go view an artist or user in the list
*/
|
private ViewArtistCallbacks viewArtist;
|
Gwindow/WhatAndroid
|
WhatAndroid/src/main/java/what/whatandroid/request/RequestAdapter.java
|
// Path: WhatAndroid/src/main/java/what/whatandroid/callbacks/ViewArtistCallbacks.java
// public interface ViewArtistCallbacks {
// /**
// * Launch an artists activity viewing the artist
// *
// * @param id artist id to view
// */
// public void viewArtist(int id);
// }
//
// Path: WhatAndroid/src/main/java/what/whatandroid/callbacks/ViewUserCallbacks.java
// public interface ViewUserCallbacks {
// /**
// * Request the activity to launch a profile activity viewing the user with some id
// *
// * @param id user id to view
// */
// public void viewUser(int id);
// }
|
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.TextView;
import api.cli.Utils;
import api.requests.TopContributor;
import api.torrents.torrents.Artist;
import api.torrents.torrents.MusicInfo;
import what.whatandroid.R;
import what.whatandroid.callbacks.ViewArtistCallbacks;
import what.whatandroid.callbacks.ViewUserCallbacks;
import java.util.List;
|
package what.whatandroid.request;
/**
* Adapter for the expandable list view in the Request fragment that shows
* the artists and top contributors
*/
public class RequestAdapter extends BaseExpandableListAdapter implements ExpandableListView.OnChildClickListener {
private final LayoutInflater inflater;
List<Artist> artists;
List<TopContributor> topContributors;
/**
* Callbacks to go view an artist or user in the list
*/
private ViewArtistCallbacks viewArtist;
|
// Path: WhatAndroid/src/main/java/what/whatandroid/callbacks/ViewArtistCallbacks.java
// public interface ViewArtistCallbacks {
// /**
// * Launch an artists activity viewing the artist
// *
// * @param id artist id to view
// */
// public void viewArtist(int id);
// }
//
// Path: WhatAndroid/src/main/java/what/whatandroid/callbacks/ViewUserCallbacks.java
// public interface ViewUserCallbacks {
// /**
// * Request the activity to launch a profile activity viewing the user with some id
// *
// * @param id user id to view
// */
// public void viewUser(int id);
// }
// Path: WhatAndroid/src/main/java/what/whatandroid/request/RequestAdapter.java
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.TextView;
import api.cli.Utils;
import api.requests.TopContributor;
import api.torrents.torrents.Artist;
import api.torrents.torrents.MusicInfo;
import what.whatandroid.R;
import what.whatandroid.callbacks.ViewArtistCallbacks;
import what.whatandroid.callbacks.ViewUserCallbacks;
import java.util.List;
package what.whatandroid.request;
/**
* Adapter for the expandable list view in the Request fragment that shows
* the artists and top contributors
*/
public class RequestAdapter extends BaseExpandableListAdapter implements ExpandableListView.OnChildClickListener {
private final LayoutInflater inflater;
List<Artist> artists;
List<TopContributor> topContributors;
/**
* Callbacks to go view an artist or user in the list
*/
private ViewArtistCallbacks viewArtist;
|
private ViewUserCallbacks viewUser;
|
Gwindow/WhatAndroid
|
WhatAndroid/src/main/java/what/whatandroid/comments/spans/HiddenTextSpan.java
|
// Path: WhatAndroid/src/main/java/what/whatandroid/callbacks/ShowHiddenTagListener.java
// public interface ShowHiddenTagListener {
// /**
// * Request that the hidden text be shown in a popup view
// *
// * @param title the title of the hidden text
// * @param text the hidden text to show, markup will be parsed
// */
// public void showText(String title, String text);
//
// /**
// * Request that the hidden image be shown in a popup view
// *
// * @param url the url of the image to show
// */
// public void showImage(String url);
// }
|
import android.text.style.ClickableSpan;
import android.util.Log;
import android.view.View;
import what.whatandroid.callbacks.ShowHiddenTagListener;
|
package what.whatandroid.comments.spans;
/**
* Implements the behavior of the site's hidden/mature tags. When clicked we try to
* get a ShowHiddenTagListener from the context and if it implements it we request
* to display the hidden text
*/
public class HiddenTextSpan extends ClickableSpan {
private String title, text;
//TODO: maybe change these to be charsequences as well?
public HiddenTextSpan(String title, String text){
super();
this.title = title;
this.text = text;
}
@Override
public void onClick(View widget){
try {
|
// Path: WhatAndroid/src/main/java/what/whatandroid/callbacks/ShowHiddenTagListener.java
// public interface ShowHiddenTagListener {
// /**
// * Request that the hidden text be shown in a popup view
// *
// * @param title the title of the hidden text
// * @param text the hidden text to show, markup will be parsed
// */
// public void showText(String title, String text);
//
// /**
// * Request that the hidden image be shown in a popup view
// *
// * @param url the url of the image to show
// */
// public void showImage(String url);
// }
// Path: WhatAndroid/src/main/java/what/whatandroid/comments/spans/HiddenTextSpan.java
import android.text.style.ClickableSpan;
import android.util.Log;
import android.view.View;
import what.whatandroid.callbacks.ShowHiddenTagListener;
package what.whatandroid.comments.spans;
/**
* Implements the behavior of the site's hidden/mature tags. When clicked we try to
* get a ShowHiddenTagListener from the context and if it implements it we request
* to display the hidden text
*/
public class HiddenTextSpan extends ClickableSpan {
private String title, text;
//TODO: maybe change these to be charsequences as well?
public HiddenTextSpan(String title, String text){
super();
this.title = title;
this.text = text;
}
@Override
public void onClick(View widget){
try {
|
ShowHiddenTagListener listener = (ShowHiddenTagListener)widget.getContext();
|
Gwindow/WhatAndroid
|
WhatAndroid/src/main/java/what/whatandroid/torrentgroup/group/TorrentGroupOverviewFragment.java
|
// Path: WhatAndroid/src/main/java/what/whatandroid/WhatApplication.java
// public class WhatApplication extends Application {
//
// //TODO: Developers put your local Gazelle install IP here instead of testing on the live site
// //I recommend setting up with Vagrant: https://github.com/dr4g0nnn/VagrantGazelle
// public static final String DEFAULT_SITE = "";
//
// @Override
// public void onCreate() {
// super.onCreate();
//
// initSoup(DEFAULT_SITE);
// if (SettingsActivity.lightThemeEnabled(getApplicationContext())) {
// AppCompatDelegate.setDefaultNightMode(
// AppCompatDelegate.MODE_NIGHT_NO);
// } else {
// AppCompatDelegate.setDefaultNightMode(
// AppCompatDelegate.MODE_NIGHT_YES);
// }
// }
//
// /**
// * Initialize MySoup so that we can start making API requests
// */
// public void initSoup(String site) {
// MySoup.setSite(site, true);
// MySoup.setUserAgent("WhatAndroid Android");
// }
//
// /**
// * Main method for all image displaying operations
// * Fail tracking is done here instead of wherever this method is called from.
// */
//
// public static void loadImage(Context context, final String url, final ImageView imageView, final ProgressBar spinner, final ImageLoadFailTracker failTracker, final Integer failImage) {
//
// if (failTracker != null && failTracker.failed(url)) {
// if (spinner != null) spinner.setVisibility(View.GONE);
// if (failImage != null) {
// imageView.setImageResource(failImage);
// } else {
// imageView.setImageResource(R.drawable.no_artwork);
// }
// } else {
// if (spinner != null) spinner.setVisibility(View.VISIBLE);
// Glide.with(context)
// .load(url)
// .listener(new RequestListener<String, GlideDrawable>() {
// @Override
// public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
// if (spinner != null) {
// spinner.setVisibility(View.GONE);
// }
// if (failTracker != null) {
// failTracker.addFailed(url);
// }
// if (failImage != null) {
// imageView.setImageResource(failImage);
// } else {
// imageView.setImageResource(R.drawable.no_artwork);
// }
// return true;
// }
//
// @Override
// public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
// if (spinner != null) {
// spinner.setVisibility(View.GONE);
// }
// // imageView.setImageDrawable(resource);
// return false;
// }
// })
// .into(imageView);
// }
//
// }
//
// }
//
// Path: WhatAndroid/src/main/java/what/whatandroid/callbacks/ViewArtistCallbacks.java
// public interface ViewArtistCallbacks {
// /**
// * Launch an artists activity viewing the artist
// *
// * @param id artist id to view
// */
// public void viewArtist(int id);
// }
|
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import java.util.List;
import api.torrents.torrents.Artist;
import api.torrents.torrents.EditionTorrents;
import api.torrents.torrents.MusicInfo;
import api.torrents.torrents.TorrentGroup;
import what.whatandroid.R;
import what.whatandroid.WhatApplication;
import what.whatandroid.callbacks.LoadingListener;
import what.whatandroid.callbacks.SetTitleCallback;
import what.whatandroid.callbacks.ViewArtistCallbacks;
import what.whatandroid.settings.SettingsActivity;
import what.whatandroid.views.ImageDialog;
|
package what.whatandroid.torrentgroup.group;
/**
* Fragment for viewing a torrent group's information
*/
public class TorrentGroupOverviewFragment extends Fragment implements View.OnClickListener, LoadingListener<TorrentGroup> {
/**
* Torrent group being shown
*/
private TorrentGroup group;
/**
* Callbacks to the parent activity for setting the title and viewing artists
*/
private SetTitleCallback setTitle;
|
// Path: WhatAndroid/src/main/java/what/whatandroid/WhatApplication.java
// public class WhatApplication extends Application {
//
// //TODO: Developers put your local Gazelle install IP here instead of testing on the live site
// //I recommend setting up with Vagrant: https://github.com/dr4g0nnn/VagrantGazelle
// public static final String DEFAULT_SITE = "";
//
// @Override
// public void onCreate() {
// super.onCreate();
//
// initSoup(DEFAULT_SITE);
// if (SettingsActivity.lightThemeEnabled(getApplicationContext())) {
// AppCompatDelegate.setDefaultNightMode(
// AppCompatDelegate.MODE_NIGHT_NO);
// } else {
// AppCompatDelegate.setDefaultNightMode(
// AppCompatDelegate.MODE_NIGHT_YES);
// }
// }
//
// /**
// * Initialize MySoup so that we can start making API requests
// */
// public void initSoup(String site) {
// MySoup.setSite(site, true);
// MySoup.setUserAgent("WhatAndroid Android");
// }
//
// /**
// * Main method for all image displaying operations
// * Fail tracking is done here instead of wherever this method is called from.
// */
//
// public static void loadImage(Context context, final String url, final ImageView imageView, final ProgressBar spinner, final ImageLoadFailTracker failTracker, final Integer failImage) {
//
// if (failTracker != null && failTracker.failed(url)) {
// if (spinner != null) spinner.setVisibility(View.GONE);
// if (failImage != null) {
// imageView.setImageResource(failImage);
// } else {
// imageView.setImageResource(R.drawable.no_artwork);
// }
// } else {
// if (spinner != null) spinner.setVisibility(View.VISIBLE);
// Glide.with(context)
// .load(url)
// .listener(new RequestListener<String, GlideDrawable>() {
// @Override
// public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
// if (spinner != null) {
// spinner.setVisibility(View.GONE);
// }
// if (failTracker != null) {
// failTracker.addFailed(url);
// }
// if (failImage != null) {
// imageView.setImageResource(failImage);
// } else {
// imageView.setImageResource(R.drawable.no_artwork);
// }
// return true;
// }
//
// @Override
// public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
// if (spinner != null) {
// spinner.setVisibility(View.GONE);
// }
// // imageView.setImageDrawable(resource);
// return false;
// }
// })
// .into(imageView);
// }
//
// }
//
// }
//
// Path: WhatAndroid/src/main/java/what/whatandroid/callbacks/ViewArtistCallbacks.java
// public interface ViewArtistCallbacks {
// /**
// * Launch an artists activity viewing the artist
// *
// * @param id artist id to view
// */
// public void viewArtist(int id);
// }
// Path: WhatAndroid/src/main/java/what/whatandroid/torrentgroup/group/TorrentGroupOverviewFragment.java
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import java.util.List;
import api.torrents.torrents.Artist;
import api.torrents.torrents.EditionTorrents;
import api.torrents.torrents.MusicInfo;
import api.torrents.torrents.TorrentGroup;
import what.whatandroid.R;
import what.whatandroid.WhatApplication;
import what.whatandroid.callbacks.LoadingListener;
import what.whatandroid.callbacks.SetTitleCallback;
import what.whatandroid.callbacks.ViewArtistCallbacks;
import what.whatandroid.settings.SettingsActivity;
import what.whatandroid.views.ImageDialog;
package what.whatandroid.torrentgroup.group;
/**
* Fragment for viewing a torrent group's information
*/
public class TorrentGroupOverviewFragment extends Fragment implements View.OnClickListener, LoadingListener<TorrentGroup> {
/**
* Torrent group being shown
*/
private TorrentGroup group;
/**
* Callbacks to the parent activity for setting the title and viewing artists
*/
private SetTitleCallback setTitle;
|
private ViewArtistCallbacks viewArtist;
|
Gwindow/WhatAndroid
|
WhatAndroid/src/main/java/what/whatandroid/torrentgroup/group/TorrentGroupOverviewFragment.java
|
// Path: WhatAndroid/src/main/java/what/whatandroid/WhatApplication.java
// public class WhatApplication extends Application {
//
// //TODO: Developers put your local Gazelle install IP here instead of testing on the live site
// //I recommend setting up with Vagrant: https://github.com/dr4g0nnn/VagrantGazelle
// public static final String DEFAULT_SITE = "";
//
// @Override
// public void onCreate() {
// super.onCreate();
//
// initSoup(DEFAULT_SITE);
// if (SettingsActivity.lightThemeEnabled(getApplicationContext())) {
// AppCompatDelegate.setDefaultNightMode(
// AppCompatDelegate.MODE_NIGHT_NO);
// } else {
// AppCompatDelegate.setDefaultNightMode(
// AppCompatDelegate.MODE_NIGHT_YES);
// }
// }
//
// /**
// * Initialize MySoup so that we can start making API requests
// */
// public void initSoup(String site) {
// MySoup.setSite(site, true);
// MySoup.setUserAgent("WhatAndroid Android");
// }
//
// /**
// * Main method for all image displaying operations
// * Fail tracking is done here instead of wherever this method is called from.
// */
//
// public static void loadImage(Context context, final String url, final ImageView imageView, final ProgressBar spinner, final ImageLoadFailTracker failTracker, final Integer failImage) {
//
// if (failTracker != null && failTracker.failed(url)) {
// if (spinner != null) spinner.setVisibility(View.GONE);
// if (failImage != null) {
// imageView.setImageResource(failImage);
// } else {
// imageView.setImageResource(R.drawable.no_artwork);
// }
// } else {
// if (spinner != null) spinner.setVisibility(View.VISIBLE);
// Glide.with(context)
// .load(url)
// .listener(new RequestListener<String, GlideDrawable>() {
// @Override
// public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
// if (spinner != null) {
// spinner.setVisibility(View.GONE);
// }
// if (failTracker != null) {
// failTracker.addFailed(url);
// }
// if (failImage != null) {
// imageView.setImageResource(failImage);
// } else {
// imageView.setImageResource(R.drawable.no_artwork);
// }
// return true;
// }
//
// @Override
// public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
// if (spinner != null) {
// spinner.setVisibility(View.GONE);
// }
// // imageView.setImageDrawable(resource);
// return false;
// }
// })
// .into(imageView);
// }
//
// }
//
// }
//
// Path: WhatAndroid/src/main/java/what/whatandroid/callbacks/ViewArtistCallbacks.java
// public interface ViewArtistCallbacks {
// /**
// * Launch an artists activity viewing the artist
// *
// * @param id artist id to view
// */
// public void viewArtist(int id);
// }
|
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import java.util.List;
import api.torrents.torrents.Artist;
import api.torrents.torrents.EditionTorrents;
import api.torrents.torrents.MusicInfo;
import api.torrents.torrents.TorrentGroup;
import what.whatandroid.R;
import what.whatandroid.WhatApplication;
import what.whatandroid.callbacks.LoadingListener;
import what.whatandroid.callbacks.SetTitleCallback;
import what.whatandroid.callbacks.ViewArtistCallbacks;
import what.whatandroid.settings.SettingsActivity;
import what.whatandroid.views.ImageDialog;
|
/**
* When the image in the header is clicked toggle expand/hide on it
*/
@Override
public void onClick(View v) {
if (group != null) {
if (v.getId() == R.id.image) {
ImageDialog dialog = ImageDialog.newInstance(group.getResponse().getGroup().getWikiImage());
dialog.show(getChildFragmentManager(), "image_dialog");
} else if (v.getId() == R.id.artist_a) {
viewArtist.viewArtist(group.getResponse().getGroup().getMusicInfo().getArtists().get(0).getId().intValue());
} else if (v.getId() == R.id.artist_b) {
viewArtist.viewArtist(group.getResponse().getGroup().getMusicInfo().getArtists().get(1).getId().intValue());
}
}
}
/**
* Update all the torrent group information being shown
*/
public void populateViews() {
List<EditionTorrents> editions = group.getEditions();
setTitle.setTitle(group.getResponse().getGroup().getName());
String imgUrl = group.getResponse().getGroup().getWikiImage();
if (!SettingsActivity.imagesEnabled(getActivity())) {
artContainer.setVisibility(View.GONE);
} else {
artContainer.setVisibility(View.VISIBLE);
|
// Path: WhatAndroid/src/main/java/what/whatandroid/WhatApplication.java
// public class WhatApplication extends Application {
//
// //TODO: Developers put your local Gazelle install IP here instead of testing on the live site
// //I recommend setting up with Vagrant: https://github.com/dr4g0nnn/VagrantGazelle
// public static final String DEFAULT_SITE = "";
//
// @Override
// public void onCreate() {
// super.onCreate();
//
// initSoup(DEFAULT_SITE);
// if (SettingsActivity.lightThemeEnabled(getApplicationContext())) {
// AppCompatDelegate.setDefaultNightMode(
// AppCompatDelegate.MODE_NIGHT_NO);
// } else {
// AppCompatDelegate.setDefaultNightMode(
// AppCompatDelegate.MODE_NIGHT_YES);
// }
// }
//
// /**
// * Initialize MySoup so that we can start making API requests
// */
// public void initSoup(String site) {
// MySoup.setSite(site, true);
// MySoup.setUserAgent("WhatAndroid Android");
// }
//
// /**
// * Main method for all image displaying operations
// * Fail tracking is done here instead of wherever this method is called from.
// */
//
// public static void loadImage(Context context, final String url, final ImageView imageView, final ProgressBar spinner, final ImageLoadFailTracker failTracker, final Integer failImage) {
//
// if (failTracker != null && failTracker.failed(url)) {
// if (spinner != null) spinner.setVisibility(View.GONE);
// if (failImage != null) {
// imageView.setImageResource(failImage);
// } else {
// imageView.setImageResource(R.drawable.no_artwork);
// }
// } else {
// if (spinner != null) spinner.setVisibility(View.VISIBLE);
// Glide.with(context)
// .load(url)
// .listener(new RequestListener<String, GlideDrawable>() {
// @Override
// public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
// if (spinner != null) {
// spinner.setVisibility(View.GONE);
// }
// if (failTracker != null) {
// failTracker.addFailed(url);
// }
// if (failImage != null) {
// imageView.setImageResource(failImage);
// } else {
// imageView.setImageResource(R.drawable.no_artwork);
// }
// return true;
// }
//
// @Override
// public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
// if (spinner != null) {
// spinner.setVisibility(View.GONE);
// }
// // imageView.setImageDrawable(resource);
// return false;
// }
// })
// .into(imageView);
// }
//
// }
//
// }
//
// Path: WhatAndroid/src/main/java/what/whatandroid/callbacks/ViewArtistCallbacks.java
// public interface ViewArtistCallbacks {
// /**
// * Launch an artists activity viewing the artist
// *
// * @param id artist id to view
// */
// public void viewArtist(int id);
// }
// Path: WhatAndroid/src/main/java/what/whatandroid/torrentgroup/group/TorrentGroupOverviewFragment.java
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import java.util.List;
import api.torrents.torrents.Artist;
import api.torrents.torrents.EditionTorrents;
import api.torrents.torrents.MusicInfo;
import api.torrents.torrents.TorrentGroup;
import what.whatandroid.R;
import what.whatandroid.WhatApplication;
import what.whatandroid.callbacks.LoadingListener;
import what.whatandroid.callbacks.SetTitleCallback;
import what.whatandroid.callbacks.ViewArtistCallbacks;
import what.whatandroid.settings.SettingsActivity;
import what.whatandroid.views.ImageDialog;
/**
* When the image in the header is clicked toggle expand/hide on it
*/
@Override
public void onClick(View v) {
if (group != null) {
if (v.getId() == R.id.image) {
ImageDialog dialog = ImageDialog.newInstance(group.getResponse().getGroup().getWikiImage());
dialog.show(getChildFragmentManager(), "image_dialog");
} else if (v.getId() == R.id.artist_a) {
viewArtist.viewArtist(group.getResponse().getGroup().getMusicInfo().getArtists().get(0).getId().intValue());
} else if (v.getId() == R.id.artist_b) {
viewArtist.viewArtist(group.getResponse().getGroup().getMusicInfo().getArtists().get(1).getId().intValue());
}
}
}
/**
* Update all the torrent group information being shown
*/
public void populateViews() {
List<EditionTorrents> editions = group.getEditions();
setTitle.setTitle(group.getResponse().getGroup().getName());
String imgUrl = group.getResponse().getGroup().getWikiImage();
if (!SettingsActivity.imagesEnabled(getActivity())) {
artContainer.setVisibility(View.GONE);
} else {
artContainer.setVisibility(View.VISIBLE);
|
WhatApplication.loadImage(getActivity(), imgUrl, image, spinner, null, null);
|
Gwindow/WhatAndroid
|
WhatAndroid/src/main/java/what/whatandroid/notifications/NotificationsListAdapter.java
|
// Path: WhatAndroid/src/main/java/what/whatandroid/WhatApplication.java
// public class WhatApplication extends Application {
//
// //TODO: Developers put your local Gazelle install IP here instead of testing on the live site
// //I recommend setting up with Vagrant: https://github.com/dr4g0nnn/VagrantGazelle
// public static final String DEFAULT_SITE = "";
//
// @Override
// public void onCreate() {
// super.onCreate();
//
// initSoup(DEFAULT_SITE);
// if (SettingsActivity.lightThemeEnabled(getApplicationContext())) {
// AppCompatDelegate.setDefaultNightMode(
// AppCompatDelegate.MODE_NIGHT_NO);
// } else {
// AppCompatDelegate.setDefaultNightMode(
// AppCompatDelegate.MODE_NIGHT_YES);
// }
// }
//
// /**
// * Initialize MySoup so that we can start making API requests
// */
// public void initSoup(String site) {
// MySoup.setSite(site, true);
// MySoup.setUserAgent("WhatAndroid Android");
// }
//
// /**
// * Main method for all image displaying operations
// * Fail tracking is done here instead of wherever this method is called from.
// */
//
// public static void loadImage(Context context, final String url, final ImageView imageView, final ProgressBar spinner, final ImageLoadFailTracker failTracker, final Integer failImage) {
//
// if (failTracker != null && failTracker.failed(url)) {
// if (spinner != null) spinner.setVisibility(View.GONE);
// if (failImage != null) {
// imageView.setImageResource(failImage);
// } else {
// imageView.setImageResource(R.drawable.no_artwork);
// }
// } else {
// if (spinner != null) spinner.setVisibility(View.VISIBLE);
// Glide.with(context)
// .load(url)
// .listener(new RequestListener<String, GlideDrawable>() {
// @Override
// public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
// if (spinner != null) {
// spinner.setVisibility(View.GONE);
// }
// if (failTracker != null) {
// failTracker.addFailed(url);
// }
// if (failImage != null) {
// imageView.setImageResource(failImage);
// } else {
// imageView.setImageResource(R.drawable.no_artwork);
// }
// return true;
// }
//
// @Override
// public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
// if (spinner != null) {
// spinner.setVisibility(View.GONE);
// }
// // imageView.setImageDrawable(resource);
// return false;
// }
// })
// .into(imageView);
// }
//
// }
//
// }
//
// Path: WhatAndroid/src/main/java/what/whatandroid/callbacks/ViewTorrentCallbacks.java
// public interface ViewTorrentCallbacks {
// /**
// * Request to view a torrent group with some id
// *
// * @param id the id of the torrent group to view
// */
// public void viewTorrentGroup(int id);
//
// /**
// * Request to view a torrent within some group
// *
// * @param group torrent group id
// * @param torrent torrent id to view
// */
// public void viewTorrent(int group, int torrent);
// }
|
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import api.cli.Utils;
import api.notifications.Torrent;
import what.whatandroid.R;
import what.whatandroid.WhatApplication;
import what.whatandroid.callbacks.ViewTorrentCallbacks;
import what.whatandroid.imgloader.ImageLoadFailTracker;
import what.whatandroid.settings.SettingsActivity;
|
package what.whatandroid.notifications;
/**
* Displays a list of the user's torrent notifications
*/
public class NotificationsListAdapter extends ArrayAdapter<Torrent> implements AdapterView.OnItemClickListener {
private final LayoutInflater inflater;
|
// Path: WhatAndroid/src/main/java/what/whatandroid/WhatApplication.java
// public class WhatApplication extends Application {
//
// //TODO: Developers put your local Gazelle install IP here instead of testing on the live site
// //I recommend setting up with Vagrant: https://github.com/dr4g0nnn/VagrantGazelle
// public static final String DEFAULT_SITE = "";
//
// @Override
// public void onCreate() {
// super.onCreate();
//
// initSoup(DEFAULT_SITE);
// if (SettingsActivity.lightThemeEnabled(getApplicationContext())) {
// AppCompatDelegate.setDefaultNightMode(
// AppCompatDelegate.MODE_NIGHT_NO);
// } else {
// AppCompatDelegate.setDefaultNightMode(
// AppCompatDelegate.MODE_NIGHT_YES);
// }
// }
//
// /**
// * Initialize MySoup so that we can start making API requests
// */
// public void initSoup(String site) {
// MySoup.setSite(site, true);
// MySoup.setUserAgent("WhatAndroid Android");
// }
//
// /**
// * Main method for all image displaying operations
// * Fail tracking is done here instead of wherever this method is called from.
// */
//
// public static void loadImage(Context context, final String url, final ImageView imageView, final ProgressBar spinner, final ImageLoadFailTracker failTracker, final Integer failImage) {
//
// if (failTracker != null && failTracker.failed(url)) {
// if (spinner != null) spinner.setVisibility(View.GONE);
// if (failImage != null) {
// imageView.setImageResource(failImage);
// } else {
// imageView.setImageResource(R.drawable.no_artwork);
// }
// } else {
// if (spinner != null) spinner.setVisibility(View.VISIBLE);
// Glide.with(context)
// .load(url)
// .listener(new RequestListener<String, GlideDrawable>() {
// @Override
// public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
// if (spinner != null) {
// spinner.setVisibility(View.GONE);
// }
// if (failTracker != null) {
// failTracker.addFailed(url);
// }
// if (failImage != null) {
// imageView.setImageResource(failImage);
// } else {
// imageView.setImageResource(R.drawable.no_artwork);
// }
// return true;
// }
//
// @Override
// public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
// if (spinner != null) {
// spinner.setVisibility(View.GONE);
// }
// // imageView.setImageDrawable(resource);
// return false;
// }
// })
// .into(imageView);
// }
//
// }
//
// }
//
// Path: WhatAndroid/src/main/java/what/whatandroid/callbacks/ViewTorrentCallbacks.java
// public interface ViewTorrentCallbacks {
// /**
// * Request to view a torrent group with some id
// *
// * @param id the id of the torrent group to view
// */
// public void viewTorrentGroup(int id);
//
// /**
// * Request to view a torrent within some group
// *
// * @param group torrent group id
// * @param torrent torrent id to view
// */
// public void viewTorrent(int group, int torrent);
// }
// Path: WhatAndroid/src/main/java/what/whatandroid/notifications/NotificationsListAdapter.java
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import api.cli.Utils;
import api.notifications.Torrent;
import what.whatandroid.R;
import what.whatandroid.WhatApplication;
import what.whatandroid.callbacks.ViewTorrentCallbacks;
import what.whatandroid.imgloader.ImageLoadFailTracker;
import what.whatandroid.settings.SettingsActivity;
package what.whatandroid.notifications;
/**
* Displays a list of the user's torrent notifications
*/
public class NotificationsListAdapter extends ArrayAdapter<Torrent> implements AdapterView.OnItemClickListener {
private final LayoutInflater inflater;
|
private final ViewTorrentCallbacks viewTorrent;
|
Gwindow/WhatAndroid
|
WhatAndroid/src/main/java/what/whatandroid/notifications/NotificationsListAdapter.java
|
// Path: WhatAndroid/src/main/java/what/whatandroid/WhatApplication.java
// public class WhatApplication extends Application {
//
// //TODO: Developers put your local Gazelle install IP here instead of testing on the live site
// //I recommend setting up with Vagrant: https://github.com/dr4g0nnn/VagrantGazelle
// public static final String DEFAULT_SITE = "";
//
// @Override
// public void onCreate() {
// super.onCreate();
//
// initSoup(DEFAULT_SITE);
// if (SettingsActivity.lightThemeEnabled(getApplicationContext())) {
// AppCompatDelegate.setDefaultNightMode(
// AppCompatDelegate.MODE_NIGHT_NO);
// } else {
// AppCompatDelegate.setDefaultNightMode(
// AppCompatDelegate.MODE_NIGHT_YES);
// }
// }
//
// /**
// * Initialize MySoup so that we can start making API requests
// */
// public void initSoup(String site) {
// MySoup.setSite(site, true);
// MySoup.setUserAgent("WhatAndroid Android");
// }
//
// /**
// * Main method for all image displaying operations
// * Fail tracking is done here instead of wherever this method is called from.
// */
//
// public static void loadImage(Context context, final String url, final ImageView imageView, final ProgressBar spinner, final ImageLoadFailTracker failTracker, final Integer failImage) {
//
// if (failTracker != null && failTracker.failed(url)) {
// if (spinner != null) spinner.setVisibility(View.GONE);
// if (failImage != null) {
// imageView.setImageResource(failImage);
// } else {
// imageView.setImageResource(R.drawable.no_artwork);
// }
// } else {
// if (spinner != null) spinner.setVisibility(View.VISIBLE);
// Glide.with(context)
// .load(url)
// .listener(new RequestListener<String, GlideDrawable>() {
// @Override
// public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
// if (spinner != null) {
// spinner.setVisibility(View.GONE);
// }
// if (failTracker != null) {
// failTracker.addFailed(url);
// }
// if (failImage != null) {
// imageView.setImageResource(failImage);
// } else {
// imageView.setImageResource(R.drawable.no_artwork);
// }
// return true;
// }
//
// @Override
// public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
// if (spinner != null) {
// spinner.setVisibility(View.GONE);
// }
// // imageView.setImageDrawable(resource);
// return false;
// }
// })
// .into(imageView);
// }
//
// }
//
// }
//
// Path: WhatAndroid/src/main/java/what/whatandroid/callbacks/ViewTorrentCallbacks.java
// public interface ViewTorrentCallbacks {
// /**
// * Request to view a torrent group with some id
// *
// * @param id the id of the torrent group to view
// */
// public void viewTorrentGroup(int id);
//
// /**
// * Request to view a torrent within some group
// *
// * @param group torrent group id
// * @param torrent torrent id to view
// */
// public void viewTorrent(int group, int torrent);
// }
|
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import api.cli.Utils;
import api.notifications.Torrent;
import what.whatandroid.R;
import what.whatandroid.WhatApplication;
import what.whatandroid.callbacks.ViewTorrentCallbacks;
import what.whatandroid.imgloader.ImageLoadFailTracker;
import what.whatandroid.settings.SettingsActivity;
|
}
@Override
public View getView(int position, View convertView, ViewGroup parent){
ViewHolder holder;
if (convertView != null){
holder = (ViewHolder)convertView.getTag();
}
else {
convertView = inflater.inflate(R.layout.list_torrent_notification, parent, false);
holder = new ViewHolder();
holder.art = (ImageView)convertView.findViewById(R.id.art);
holder.spinner = (ProgressBar)convertView.findViewById(R.id.loading_indicator);
holder.artContainer = convertView.findViewById(R.id.art_container);
holder.artist = (TextView)convertView.findViewById(R.id.artist_name);
holder.title = (TextView)convertView.findViewById(R.id.album_name);
holder.year = (TextView)convertView.findViewById(R.id.album_year);
holder.tags = (TextView)convertView.findViewById(R.id.album_tags);
holder.size = (TextView)convertView.findViewById(R.id.size);
holder.snatches = (TextView)convertView.findViewById(R.id.snatches);
holder.seeders = (TextView)convertView.findViewById(R.id.seeders);
holder.leechers = (TextView)convertView.findViewById(R.id.leechers);
convertView.setTag(holder);
}
Torrent t = getItem(position);
String coverUrl = t.getWikiImage();
if (!imagesEnabled) {
holder.artContainer.setVisibility(View.GONE);
} else {
holder.artContainer.setVisibility(View.VISIBLE);
|
// Path: WhatAndroid/src/main/java/what/whatandroid/WhatApplication.java
// public class WhatApplication extends Application {
//
// //TODO: Developers put your local Gazelle install IP here instead of testing on the live site
// //I recommend setting up with Vagrant: https://github.com/dr4g0nnn/VagrantGazelle
// public static final String DEFAULT_SITE = "";
//
// @Override
// public void onCreate() {
// super.onCreate();
//
// initSoup(DEFAULT_SITE);
// if (SettingsActivity.lightThemeEnabled(getApplicationContext())) {
// AppCompatDelegate.setDefaultNightMode(
// AppCompatDelegate.MODE_NIGHT_NO);
// } else {
// AppCompatDelegate.setDefaultNightMode(
// AppCompatDelegate.MODE_NIGHT_YES);
// }
// }
//
// /**
// * Initialize MySoup so that we can start making API requests
// */
// public void initSoup(String site) {
// MySoup.setSite(site, true);
// MySoup.setUserAgent("WhatAndroid Android");
// }
//
// /**
// * Main method for all image displaying operations
// * Fail tracking is done here instead of wherever this method is called from.
// */
//
// public static void loadImage(Context context, final String url, final ImageView imageView, final ProgressBar spinner, final ImageLoadFailTracker failTracker, final Integer failImage) {
//
// if (failTracker != null && failTracker.failed(url)) {
// if (spinner != null) spinner.setVisibility(View.GONE);
// if (failImage != null) {
// imageView.setImageResource(failImage);
// } else {
// imageView.setImageResource(R.drawable.no_artwork);
// }
// } else {
// if (spinner != null) spinner.setVisibility(View.VISIBLE);
// Glide.with(context)
// .load(url)
// .listener(new RequestListener<String, GlideDrawable>() {
// @Override
// public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
// if (spinner != null) {
// spinner.setVisibility(View.GONE);
// }
// if (failTracker != null) {
// failTracker.addFailed(url);
// }
// if (failImage != null) {
// imageView.setImageResource(failImage);
// } else {
// imageView.setImageResource(R.drawable.no_artwork);
// }
// return true;
// }
//
// @Override
// public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
// if (spinner != null) {
// spinner.setVisibility(View.GONE);
// }
// // imageView.setImageDrawable(resource);
// return false;
// }
// })
// .into(imageView);
// }
//
// }
//
// }
//
// Path: WhatAndroid/src/main/java/what/whatandroid/callbacks/ViewTorrentCallbacks.java
// public interface ViewTorrentCallbacks {
// /**
// * Request to view a torrent group with some id
// *
// * @param id the id of the torrent group to view
// */
// public void viewTorrentGroup(int id);
//
// /**
// * Request to view a torrent within some group
// *
// * @param group torrent group id
// * @param torrent torrent id to view
// */
// public void viewTorrent(int group, int torrent);
// }
// Path: WhatAndroid/src/main/java/what/whatandroid/notifications/NotificationsListAdapter.java
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import api.cli.Utils;
import api.notifications.Torrent;
import what.whatandroid.R;
import what.whatandroid.WhatApplication;
import what.whatandroid.callbacks.ViewTorrentCallbacks;
import what.whatandroid.imgloader.ImageLoadFailTracker;
import what.whatandroid.settings.SettingsActivity;
}
@Override
public View getView(int position, View convertView, ViewGroup parent){
ViewHolder holder;
if (convertView != null){
holder = (ViewHolder)convertView.getTag();
}
else {
convertView = inflater.inflate(R.layout.list_torrent_notification, parent, false);
holder = new ViewHolder();
holder.art = (ImageView)convertView.findViewById(R.id.art);
holder.spinner = (ProgressBar)convertView.findViewById(R.id.loading_indicator);
holder.artContainer = convertView.findViewById(R.id.art_container);
holder.artist = (TextView)convertView.findViewById(R.id.artist_name);
holder.title = (TextView)convertView.findViewById(R.id.album_name);
holder.year = (TextView)convertView.findViewById(R.id.album_year);
holder.tags = (TextView)convertView.findViewById(R.id.album_tags);
holder.size = (TextView)convertView.findViewById(R.id.size);
holder.snatches = (TextView)convertView.findViewById(R.id.snatches);
holder.seeders = (TextView)convertView.findViewById(R.id.seeders);
holder.leechers = (TextView)convertView.findViewById(R.id.leechers);
convertView.setTag(holder);
}
Torrent t = getItem(position);
String coverUrl = t.getWikiImage();
if (!imagesEnabled) {
holder.artContainer.setVisibility(View.GONE);
} else {
holder.artContainer.setVisibility(View.VISIBLE);
|
WhatApplication.loadImage(inflater.getContext(), coverUrl, holder.art, holder.spinner, imageFailTracker, null);
|
Gwindow/WhatAndroid
|
WhatAndroid/src/main/java/what/whatandroid/comments/tags/QuoteTagStyle.java
|
// Path: WhatAndroid/src/main/java/what/whatandroid/comments/spans/LargeQuoteSpan.java
// public class LargeQuoteSpan extends QuoteSpan {
// public LargeQuoteSpan(){
// }
//
// public LargeQuoteSpan(int color){
// super(color);
// }
//
// public LargeQuoteSpan(Parcel src){
// super(src);
// }
//
// @Override
// public int getLeadingMargin(boolean first){
// return super.getLeadingMargin(first) + 6;
// }
// }
|
import android.graphics.Typeface;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.style.StyleSpan;
import what.whatandroid.comments.spans.LargeQuoteSpan;
|
package what.whatandroid.comments.tags;
/**
* Handles site quote tags. Also applies newlines to beginning and end
* of the quote to make sure it's spaced properly
*/
public class QuoteTagStyle implements TagStyle {
@Override
public Spannable getStyle(CharSequence param, CharSequence text) {
SpannableStringBuilder ssb = new SpannableStringBuilder();
ssb.append("\n");
String user = param == null ? null : param.toString();
if (user != null) {
int nameEnd = user.indexOf('|');
if (nameEnd != -1) {
user = user.substring(0, nameEnd);
}
user += " wrote: \n";
ssb.append(user);
ssb.setSpan(new StyleSpan(Typeface.BOLD), 1, ssb.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
int end = ssb.length();
ssb.append(text);
|
// Path: WhatAndroid/src/main/java/what/whatandroid/comments/spans/LargeQuoteSpan.java
// public class LargeQuoteSpan extends QuoteSpan {
// public LargeQuoteSpan(){
// }
//
// public LargeQuoteSpan(int color){
// super(color);
// }
//
// public LargeQuoteSpan(Parcel src){
// super(src);
// }
//
// @Override
// public int getLeadingMargin(boolean first){
// return super.getLeadingMargin(first) + 6;
// }
// }
// Path: WhatAndroid/src/main/java/what/whatandroid/comments/tags/QuoteTagStyle.java
import android.graphics.Typeface;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.style.StyleSpan;
import what.whatandroid.comments.spans.LargeQuoteSpan;
package what.whatandroid.comments.tags;
/**
* Handles site quote tags. Also applies newlines to beginning and end
* of the quote to make sure it's spaced properly
*/
public class QuoteTagStyle implements TagStyle {
@Override
public Spannable getStyle(CharSequence param, CharSequence text) {
SpannableStringBuilder ssb = new SpannableStringBuilder();
ssb.append("\n");
String user = param == null ? null : param.toString();
if (user != null) {
int nameEnd = user.indexOf('|');
if (nameEnd != -1) {
user = user.substring(0, nameEnd);
}
user += " wrote: \n";
ssb.append(user);
ssb.setSpan(new StyleSpan(Typeface.BOLD), 1, ssb.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
int end = ssb.length();
ssb.append(text);
|
ssb.setSpan(new LargeQuoteSpan(0xff80cbc4), end, ssb.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
|
Gwindow/WhatAndroid
|
WhatAndroid/src/main/java/what/whatandroid/profile/ProfileFragment.java
|
// Path: WhatAndroid/src/main/java/what/whatandroid/WhatApplication.java
// public class WhatApplication extends Application {
//
// //TODO: Developers put your local Gazelle install IP here instead of testing on the live site
// //I recommend setting up with Vagrant: https://github.com/dr4g0nnn/VagrantGazelle
// public static final String DEFAULT_SITE = "";
//
// @Override
// public void onCreate() {
// super.onCreate();
//
// initSoup(DEFAULT_SITE);
// if (SettingsActivity.lightThemeEnabled(getApplicationContext())) {
// AppCompatDelegate.setDefaultNightMode(
// AppCompatDelegate.MODE_NIGHT_NO);
// } else {
// AppCompatDelegate.setDefaultNightMode(
// AppCompatDelegate.MODE_NIGHT_YES);
// }
// }
//
// /**
// * Initialize MySoup so that we can start making API requests
// */
// public void initSoup(String site) {
// MySoup.setSite(site, true);
// MySoup.setUserAgent("WhatAndroid Android");
// }
//
// /**
// * Main method for all image displaying operations
// * Fail tracking is done here instead of wherever this method is called from.
// */
//
// public static void loadImage(Context context, final String url, final ImageView imageView, final ProgressBar spinner, final ImageLoadFailTracker failTracker, final Integer failImage) {
//
// if (failTracker != null && failTracker.failed(url)) {
// if (spinner != null) spinner.setVisibility(View.GONE);
// if (failImage != null) {
// imageView.setImageResource(failImage);
// } else {
// imageView.setImageResource(R.drawable.no_artwork);
// }
// } else {
// if (spinner != null) spinner.setVisibility(View.VISIBLE);
// Glide.with(context)
// .load(url)
// .listener(new RequestListener<String, GlideDrawable>() {
// @Override
// public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
// if (spinner != null) {
// spinner.setVisibility(View.GONE);
// }
// if (failTracker != null) {
// failTracker.addFailed(url);
// }
// if (failImage != null) {
// imageView.setImageResource(failImage);
// } else {
// imageView.setImageResource(R.drawable.no_artwork);
// }
// return true;
// }
//
// @Override
// public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
// if (spinner != null) {
// spinner.setVisibility(View.GONE);
// }
// // imageView.setImageDrawable(resource);
// return false;
// }
// })
// .into(imageView);
// }
//
// }
//
// }
//
// Path: WhatAndroid/src/main/java/what/whatandroid/callbacks/OnLoggedInCallback.java
// public interface OnLoggedInCallback {
// /**
// * Function called when the user has logged in or has been confirmed to be logged in
// */
// public void onLoggedIn();
// }
|
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.support.v4.view.ViewPager;
import android.text.format.DateUtils;
import android.view.*;
import android.widget.*;
import api.cli.Utils;
import api.index.Index;
import api.soup.MySoup;
import api.user.Profile;
import api.user.User;
import api.user.UserProfile;
import api.user.recent.UserRecents;
import what.whatandroid.R;
import what.whatandroid.WhatApplication;
import what.whatandroid.callbacks.LoadingListener;
import what.whatandroid.callbacks.OnLoggedInCallback;
import what.whatandroid.callbacks.SetTitleCallback;
import what.whatandroid.forums.thread.ReplyDialogFragment;
import what.whatandroid.settings.SettingsActivity;
import java.util.Date;
|
ft.remove(prev);
}
ft.addToBackStack(null);
ReplyDialogFragment reply = ReplyDialogFragment.newInstance(messageDraft, messageSubject);
reply.setTargetFragment(this, 0);
reply.show(ft, "dialog");
}
/**
* Update the profile fields with the information we loaded. We need to do a ton of checks here to
* properly handle user's various paranoia configurations, which could cause us to get a null for any of the
* fields that can be hidden. We also hide the recent snatches/uploads if the user's paranoia is high (6+).
* When viewing our own profile we'll get all the data back but will still see our paranoia value so we need to
* ignore the paranoia if it's our own profile
*/
private void populateViews() {
Profile profile = userProfile.getUser().getProfile();
setTitle.setTitle(profile.getUsername());
username.setText(profile.getUsername());
userClass.setText(profile.getPersonal().getUserClass());
Date joinDate = MySoup.parseDate(profile.getStats().getJoinedDate());
joined.setText("Joined " + DateUtils.getRelativeTimeSpanString(joinDate.getTime(),
new Date().getTime(), DateUtils.WEEK_IN_MILLIS));
//We need to check all the paranoia cases that may cause a field to be missing and hide the views for it
String avatarUrl = profile.getAvatar();
if (!SettingsActivity.imagesEnabled(getActivity())) {
artContainer.setVisibility(View.GONE);
} else {
artContainer.setVisibility(View.VISIBLE);
|
// Path: WhatAndroid/src/main/java/what/whatandroid/WhatApplication.java
// public class WhatApplication extends Application {
//
// //TODO: Developers put your local Gazelle install IP here instead of testing on the live site
// //I recommend setting up with Vagrant: https://github.com/dr4g0nnn/VagrantGazelle
// public static final String DEFAULT_SITE = "";
//
// @Override
// public void onCreate() {
// super.onCreate();
//
// initSoup(DEFAULT_SITE);
// if (SettingsActivity.lightThemeEnabled(getApplicationContext())) {
// AppCompatDelegate.setDefaultNightMode(
// AppCompatDelegate.MODE_NIGHT_NO);
// } else {
// AppCompatDelegate.setDefaultNightMode(
// AppCompatDelegate.MODE_NIGHT_YES);
// }
// }
//
// /**
// * Initialize MySoup so that we can start making API requests
// */
// public void initSoup(String site) {
// MySoup.setSite(site, true);
// MySoup.setUserAgent("WhatAndroid Android");
// }
//
// /**
// * Main method for all image displaying operations
// * Fail tracking is done here instead of wherever this method is called from.
// */
//
// public static void loadImage(Context context, final String url, final ImageView imageView, final ProgressBar spinner, final ImageLoadFailTracker failTracker, final Integer failImage) {
//
// if (failTracker != null && failTracker.failed(url)) {
// if (spinner != null) spinner.setVisibility(View.GONE);
// if (failImage != null) {
// imageView.setImageResource(failImage);
// } else {
// imageView.setImageResource(R.drawable.no_artwork);
// }
// } else {
// if (spinner != null) spinner.setVisibility(View.VISIBLE);
// Glide.with(context)
// .load(url)
// .listener(new RequestListener<String, GlideDrawable>() {
// @Override
// public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
// if (spinner != null) {
// spinner.setVisibility(View.GONE);
// }
// if (failTracker != null) {
// failTracker.addFailed(url);
// }
// if (failImage != null) {
// imageView.setImageResource(failImage);
// } else {
// imageView.setImageResource(R.drawable.no_artwork);
// }
// return true;
// }
//
// @Override
// public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
// if (spinner != null) {
// spinner.setVisibility(View.GONE);
// }
// // imageView.setImageDrawable(resource);
// return false;
// }
// })
// .into(imageView);
// }
//
// }
//
// }
//
// Path: WhatAndroid/src/main/java/what/whatandroid/callbacks/OnLoggedInCallback.java
// public interface OnLoggedInCallback {
// /**
// * Function called when the user has logged in or has been confirmed to be logged in
// */
// public void onLoggedIn();
// }
// Path: WhatAndroid/src/main/java/what/whatandroid/profile/ProfileFragment.java
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.support.v4.view.ViewPager;
import android.text.format.DateUtils;
import android.view.*;
import android.widget.*;
import api.cli.Utils;
import api.index.Index;
import api.soup.MySoup;
import api.user.Profile;
import api.user.User;
import api.user.UserProfile;
import api.user.recent.UserRecents;
import what.whatandroid.R;
import what.whatandroid.WhatApplication;
import what.whatandroid.callbacks.LoadingListener;
import what.whatandroid.callbacks.OnLoggedInCallback;
import what.whatandroid.callbacks.SetTitleCallback;
import what.whatandroid.forums.thread.ReplyDialogFragment;
import what.whatandroid.settings.SettingsActivity;
import java.util.Date;
ft.remove(prev);
}
ft.addToBackStack(null);
ReplyDialogFragment reply = ReplyDialogFragment.newInstance(messageDraft, messageSubject);
reply.setTargetFragment(this, 0);
reply.show(ft, "dialog");
}
/**
* Update the profile fields with the information we loaded. We need to do a ton of checks here to
* properly handle user's various paranoia configurations, which could cause us to get a null for any of the
* fields that can be hidden. We also hide the recent snatches/uploads if the user's paranoia is high (6+).
* When viewing our own profile we'll get all the data back but will still see our paranoia value so we need to
* ignore the paranoia if it's our own profile
*/
private void populateViews() {
Profile profile = userProfile.getUser().getProfile();
setTitle.setTitle(profile.getUsername());
username.setText(profile.getUsername());
userClass.setText(profile.getPersonal().getUserClass());
Date joinDate = MySoup.parseDate(profile.getStats().getJoinedDate());
joined.setText("Joined " + DateUtils.getRelativeTimeSpanString(joinDate.getTime(),
new Date().getTime(), DateUtils.WEEK_IN_MILLIS));
//We need to check all the paranoia cases that may cause a field to be missing and hide the views for it
String avatarUrl = profile.getAvatar();
if (!SettingsActivity.imagesEnabled(getActivity())) {
artContainer.setVisibility(View.GONE);
} else {
artContainer.setVisibility(View.VISIBLE);
|
WhatApplication.loadImage(getActivity(), avatarUrl, avatar, spinner, null, null);
|
htrc/HTRC-Portal
|
app/controllers/UserManagement.java
|
// Path: app/edu/indiana/d2i/htrc/portal/exception/ChangePasswordUserAdminExceptionException.java
// public class ChangePasswordUserAdminExceptionException extends Exception {
// public ChangePasswordUserAdminExceptionException() {
// super();
// }
//
// public ChangePasswordUserAdminExceptionException(String message) {
// super(message);
// }
//
// public ChangePasswordUserAdminExceptionException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public ChangePasswordUserAdminExceptionException(Throwable cause) {
// super(cause);
// }
//
// protected ChangePasswordUserAdminExceptionException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
// super(message, cause, enableSuppression, writableStackTrace);
// }
// }
//
// Path: app/edu/indiana/d2i/htrc/portal/exception/UserAlreadyExistsException.java
// public class UserAlreadyExistsException extends Exception {
// public UserAlreadyExistsException(String message) {
// super(message);
// }
//
// public UserAlreadyExistsException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public UserAlreadyExistsException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: app/models/Token.java
// @Entity
// public class Token extends Model {
// @Id
// @GeneratedValue(strategy = GenerationType.IDENTITY)
// public Long id;
// public String userId;
// public String token;
// public Long createdTime;
// public String isTokenUsed = "NO";
//
// private static Logger.ALogger log = play.Logger.of("application");
// private static long validityPeriod = 3600; // in seconds
//
// public Token(String userId, String token, Long createdTime) {
// this.userId = userId;
// this.token = token;
// this.createdTime = createdTime;
// }
//
// public static Finder<Long, Token> find = new Finder<Long, Token>(Long.class, Token.class);
//
// public static Token findByToken(String token){
// log.info("Looking for token: "+ token);
// return find.where().eq("token", token).findUnique();
// }
//
// public static String generateToken(String userId, String userEmail) throws NoSuchAlgorithmException, UnsupportedEncodingException {
// char[] HEX_CHARS = "0123456789ABCDEF".toCharArray();
//
// MessageDigest messageDigestInstance = MessageDigest.getInstance("SHA-256");
//
// byte[] hash = messageDigestInstance.digest((new Date().toString() + userId + userEmail).getBytes("UTF-8"));
// StringBuilder sb = new StringBuilder(hash.length * 2);
// for (byte b : hash) {
// sb.append(HEX_CHARS[(b & 0xF0) >> 4]);
// sb.append(HEX_CHARS[b & 0x0F]);
// }
//
// String newToken = sb.toString();
// if(Token.findByToken(newToken) != null){
// Token alreadyExistToken = Token.findByToken(newToken);
// log.info("Token: "+newToken+" is already exist.");
// if(alreadyExistToken.userId.equals(userId)){
// alreadyExistToken.createdTime = new Date().getTime();
// alreadyExistToken.update();
// }else{
// log.error("Error in saving tokens.");
// }
//
// }else {
// Token token = new Token(userId,newToken,new Date().getTime());
// token.save();
// log.info("Token :"+ Token.findByToken(newToken).token + " is saved successfully.");
// }
// return newToken;
// }
//
// public static void deleteToken(String token){
// Token token1 = Token.findByToken(token);
// if(token1 != null){
// token1.delete();
// }
// }
//
// public static void replaceToken(Token token1){
// token1.update();
// }
//
// public static void deleteAllTokens(){
// List<Token> tokenList = find.all();
// for(Token token1 : tokenList){
// token1.delete();
// }
//
// }
//
// public static boolean isTokenExpired(Token token){
// log.info("Validity period = " + validityPeriod + " Current time = " + new Date().getTime());
//
// return validityPeriod < (new Date().getTime() - token.createdTime)/1000;
// }
//
//
//
// }
|
import com.fasterxml.jackson.databind.node.ObjectNode;
import edu.indiana.d2i.htrc.portal.*;
import edu.indiana.d2i.htrc.portal.exception.ChangePasswordUserAdminExceptionException;
import edu.indiana.d2i.htrc.portal.exception.UserAlreadyExistsException;
import models.Token;
import org.pac4j.play.java.JavaController;
import play.Logger;
import play.data.Form;
import play.libs.Json;
import play.mvc.Result;
import views.html.*;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.UnsupportedEncodingException;
import java.rmi.RemoteException;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import static play.data.Form.form;
|
if (passwordValidate(password, confirmPassword,userId) != null) {
return passwordValidate(password, confirmPassword,userId);
}
if (!email.equals(confirmEmail)) {
return "Emails are not matching.";
}
if (!isValidEmail(email)) {
return "Email is not an institutional email. Please enter your institutional email." +
"If you don't have an institutional email or if your email is not recognized by our system, " +
"please press 'Request Account' with your current email address ";
}
if (acknowledgement == null) {
return "You have not acknowledge the user registration acknowledgement. Please acknowledge.";
}else {
List<Map.Entry<String, String>> claims = new ArrayList<>();
claims.add(new AbstractMap.SimpleEntry<>(
"http://wso2.org/claims/givenname", firstName));
claims.add(new AbstractMap.SimpleEntry<>(
"http://wso2.org/claims/lastname", lastName));
claims.add(new AbstractMap.SimpleEntry<>(
"http://wso2.org/claims/emailaddress", email));
try {
userManager.createUser(userId, password, email, claims);
sendUserRegistrationEmail(email, userId, firstName);
log.info("User " + firstName + " " + lastName + " has acknowledge the user registration acknowledgement."
+ " User ID: " + userId);
setStatus("Success");
|
// Path: app/edu/indiana/d2i/htrc/portal/exception/ChangePasswordUserAdminExceptionException.java
// public class ChangePasswordUserAdminExceptionException extends Exception {
// public ChangePasswordUserAdminExceptionException() {
// super();
// }
//
// public ChangePasswordUserAdminExceptionException(String message) {
// super(message);
// }
//
// public ChangePasswordUserAdminExceptionException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public ChangePasswordUserAdminExceptionException(Throwable cause) {
// super(cause);
// }
//
// protected ChangePasswordUserAdminExceptionException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
// super(message, cause, enableSuppression, writableStackTrace);
// }
// }
//
// Path: app/edu/indiana/d2i/htrc/portal/exception/UserAlreadyExistsException.java
// public class UserAlreadyExistsException extends Exception {
// public UserAlreadyExistsException(String message) {
// super(message);
// }
//
// public UserAlreadyExistsException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public UserAlreadyExistsException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: app/models/Token.java
// @Entity
// public class Token extends Model {
// @Id
// @GeneratedValue(strategy = GenerationType.IDENTITY)
// public Long id;
// public String userId;
// public String token;
// public Long createdTime;
// public String isTokenUsed = "NO";
//
// private static Logger.ALogger log = play.Logger.of("application");
// private static long validityPeriod = 3600; // in seconds
//
// public Token(String userId, String token, Long createdTime) {
// this.userId = userId;
// this.token = token;
// this.createdTime = createdTime;
// }
//
// public static Finder<Long, Token> find = new Finder<Long, Token>(Long.class, Token.class);
//
// public static Token findByToken(String token){
// log.info("Looking for token: "+ token);
// return find.where().eq("token", token).findUnique();
// }
//
// public static String generateToken(String userId, String userEmail) throws NoSuchAlgorithmException, UnsupportedEncodingException {
// char[] HEX_CHARS = "0123456789ABCDEF".toCharArray();
//
// MessageDigest messageDigestInstance = MessageDigest.getInstance("SHA-256");
//
// byte[] hash = messageDigestInstance.digest((new Date().toString() + userId + userEmail).getBytes("UTF-8"));
// StringBuilder sb = new StringBuilder(hash.length * 2);
// for (byte b : hash) {
// sb.append(HEX_CHARS[(b & 0xF0) >> 4]);
// sb.append(HEX_CHARS[b & 0x0F]);
// }
//
// String newToken = sb.toString();
// if(Token.findByToken(newToken) != null){
// Token alreadyExistToken = Token.findByToken(newToken);
// log.info("Token: "+newToken+" is already exist.");
// if(alreadyExistToken.userId.equals(userId)){
// alreadyExistToken.createdTime = new Date().getTime();
// alreadyExistToken.update();
// }else{
// log.error("Error in saving tokens.");
// }
//
// }else {
// Token token = new Token(userId,newToken,new Date().getTime());
// token.save();
// log.info("Token :"+ Token.findByToken(newToken).token + " is saved successfully.");
// }
// return newToken;
// }
//
// public static void deleteToken(String token){
// Token token1 = Token.findByToken(token);
// if(token1 != null){
// token1.delete();
// }
// }
//
// public static void replaceToken(Token token1){
// token1.update();
// }
//
// public static void deleteAllTokens(){
// List<Token> tokenList = find.all();
// for(Token token1 : tokenList){
// token1.delete();
// }
//
// }
//
// public static boolean isTokenExpired(Token token){
// log.info("Validity period = " + validityPeriod + " Current time = " + new Date().getTime());
//
// return validityPeriod < (new Date().getTime() - token.createdTime)/1000;
// }
//
//
//
// }
// Path: app/controllers/UserManagement.java
import com.fasterxml.jackson.databind.node.ObjectNode;
import edu.indiana.d2i.htrc.portal.*;
import edu.indiana.d2i.htrc.portal.exception.ChangePasswordUserAdminExceptionException;
import edu.indiana.d2i.htrc.portal.exception.UserAlreadyExistsException;
import models.Token;
import org.pac4j.play.java.JavaController;
import play.Logger;
import play.data.Form;
import play.libs.Json;
import play.mvc.Result;
import views.html.*;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.UnsupportedEncodingException;
import java.rmi.RemoteException;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import static play.data.Form.form;
if (passwordValidate(password, confirmPassword,userId) != null) {
return passwordValidate(password, confirmPassword,userId);
}
if (!email.equals(confirmEmail)) {
return "Emails are not matching.";
}
if (!isValidEmail(email)) {
return "Email is not an institutional email. Please enter your institutional email." +
"If you don't have an institutional email or if your email is not recognized by our system, " +
"please press 'Request Account' with your current email address ";
}
if (acknowledgement == null) {
return "You have not acknowledge the user registration acknowledgement. Please acknowledge.";
}else {
List<Map.Entry<String, String>> claims = new ArrayList<>();
claims.add(new AbstractMap.SimpleEntry<>(
"http://wso2.org/claims/givenname", firstName));
claims.add(new AbstractMap.SimpleEntry<>(
"http://wso2.org/claims/lastname", lastName));
claims.add(new AbstractMap.SimpleEntry<>(
"http://wso2.org/claims/emailaddress", email));
try {
userManager.createUser(userId, password, email, claims);
sendUserRegistrationEmail(email, userId, firstName);
log.info("User " + firstName + " " + lastName + " has acknowledge the user registration acknowledgement."
+ " User ID: " + userId);
setStatus("Success");
|
} catch (UserAlreadyExistsException e) {
|
htrc/HTRC-Portal
|
app/edu/indiana/d2i/htrc/portal/HTRCUserManagerUtility.java
|
// Path: app/edu/indiana/d2i/htrc/portal/exception/ChangePasswordUserAdminExceptionException.java
// public class ChangePasswordUserAdminExceptionException extends Exception {
// public ChangePasswordUserAdminExceptionException() {
// super();
// }
//
// public ChangePasswordUserAdminExceptionException(String message) {
// super(message);
// }
//
// public ChangePasswordUserAdminExceptionException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public ChangePasswordUserAdminExceptionException(Throwable cause) {
// super(cause);
// }
//
// protected ChangePasswordUserAdminExceptionException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
// super(message, cause, enableSuppression, writableStackTrace);
// }
// }
//
// Path: app/edu/indiana/d2i/htrc/portal/exception/EmailAlreadyExistsException.java
// public class EmailAlreadyExistsException extends Exception {
// public EmailAlreadyExistsException(String message) {
// super(message);
// }
//
// public EmailAlreadyExistsException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public EmailAlreadyExistsException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: app/edu/indiana/d2i/htrc/portal/exception/RoleNameAlreadyExistsException.java
// public class RoleNameAlreadyExistsException extends Exception {
// public RoleNameAlreadyExistsException(String message) {
// super(message);
// }
//
// public RoleNameAlreadyExistsException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public RoleNameAlreadyExistsException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: app/edu/indiana/d2i/htrc/portal/exception/UserAlreadyExistsException.java
// public class UserAlreadyExistsException extends Exception {
// public UserAlreadyExistsException(String message) {
// super(message);
// }
//
// public UserAlreadyExistsException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public UserAlreadyExistsException(Throwable cause) {
// super(cause);
// }
// }
|
import edu.indiana.d2i.htrc.portal.exception.ChangePasswordUserAdminExceptionException;
import edu.indiana.d2i.htrc.portal.exception.EmailAlreadyExistsException;
import edu.indiana.d2i.htrc.portal.exception.RoleNameAlreadyExistsException;
import edu.indiana.d2i.htrc.portal.exception.UserAlreadyExistsException;
import edu.indiana.d2i.htrc.wso2is.extensions.stub.types.UserInfoRequest;
import edu.indiana.d2i.htrc.wso2is.extensions.stub.types.UserInfoResponse;
import org.apache.axis2.client.Options;
import org.apache.axis2.context.ConfigurationContext;
import org.apache.axis2.context.ConfigurationContextFactory;
import org.apache.axis2.transport.http.HTTPConstants;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import org.wso2.carbon.authenticator.stub.AuthenticationAdminStub;
import org.wso2.carbon.identity.oauth.stub.OAuthAdminServiceStub;
import org.wso2.carbon.registry.core.Collection;
import org.wso2.carbon.registry.extensions.stub.ResourceAdminServiceStub;
import org.wso2.carbon.registry.ws.client.registry.WSRegistryServiceClient;
import org.wso2.carbon.user.mgt.common.UserAdminException;
import org.wso2.carbon.user.mgt.stub.UserAdminStub;
import edu.indiana.d2i.htrc.wso2is.extensions.stub.ExtendedUserAdminStub;
import org.wso2.carbon.user.mgt.stub.types.carbon.ClaimValue;
import org.wso2.carbon.user.mgt.stub.types.carbon.FlaggedName;
import org.wso2.carbon.user.mgt.stub.types.carbon.UserRealmInfo;
import org.wso2.carbon.utils.NetworkUtils;
import play.Logger;
import java.rmi.RemoteException;
import java.util.*;
import java.util.regex.Pattern;
|
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* Create a new user for the HTRC platform
*
* @param userName The user name
* @param password The user's isPassword
* @param claims The <code>ClaimValue[]</code> array of profile claims
* (see <a href="https://htrc3.pti.indiana.edu:9443/carbon/claim-mgt/claim-view.jsp?store=Internal&dialect=http://wso2.org/claims">available claims</a>)
* // * @param permissions The array of permission keys to assign to the user, for example: "/permission/admin/login" (can be <code>null</code>)
* @throws UserAlreadyExistsException Thrown if an error occurred
* @see #getRequiredUserClaims()
* @see #getAvailablePermissions()
*/
public void createUser(String userName, String password, String email, List<Map.Entry<String, String>> claims) throws Exception { // TODO: Review this
if (userName == null) {
throw new NullPointerException("User name null.");
}
if (password == null) {
throw new NullPointerException("Password null.");
}
if (isUserExists(userName)) {
String message = "User with name " + userName + " already exists.";
log.warn(message);
|
// Path: app/edu/indiana/d2i/htrc/portal/exception/ChangePasswordUserAdminExceptionException.java
// public class ChangePasswordUserAdminExceptionException extends Exception {
// public ChangePasswordUserAdminExceptionException() {
// super();
// }
//
// public ChangePasswordUserAdminExceptionException(String message) {
// super(message);
// }
//
// public ChangePasswordUserAdminExceptionException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public ChangePasswordUserAdminExceptionException(Throwable cause) {
// super(cause);
// }
//
// protected ChangePasswordUserAdminExceptionException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
// super(message, cause, enableSuppression, writableStackTrace);
// }
// }
//
// Path: app/edu/indiana/d2i/htrc/portal/exception/EmailAlreadyExistsException.java
// public class EmailAlreadyExistsException extends Exception {
// public EmailAlreadyExistsException(String message) {
// super(message);
// }
//
// public EmailAlreadyExistsException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public EmailAlreadyExistsException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: app/edu/indiana/d2i/htrc/portal/exception/RoleNameAlreadyExistsException.java
// public class RoleNameAlreadyExistsException extends Exception {
// public RoleNameAlreadyExistsException(String message) {
// super(message);
// }
//
// public RoleNameAlreadyExistsException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public RoleNameAlreadyExistsException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: app/edu/indiana/d2i/htrc/portal/exception/UserAlreadyExistsException.java
// public class UserAlreadyExistsException extends Exception {
// public UserAlreadyExistsException(String message) {
// super(message);
// }
//
// public UserAlreadyExistsException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public UserAlreadyExistsException(Throwable cause) {
// super(cause);
// }
// }
// Path: app/edu/indiana/d2i/htrc/portal/HTRCUserManagerUtility.java
import edu.indiana.d2i.htrc.portal.exception.ChangePasswordUserAdminExceptionException;
import edu.indiana.d2i.htrc.portal.exception.EmailAlreadyExistsException;
import edu.indiana.d2i.htrc.portal.exception.RoleNameAlreadyExistsException;
import edu.indiana.d2i.htrc.portal.exception.UserAlreadyExistsException;
import edu.indiana.d2i.htrc.wso2is.extensions.stub.types.UserInfoRequest;
import edu.indiana.d2i.htrc.wso2is.extensions.stub.types.UserInfoResponse;
import org.apache.axis2.client.Options;
import org.apache.axis2.context.ConfigurationContext;
import org.apache.axis2.context.ConfigurationContextFactory;
import org.apache.axis2.transport.http.HTTPConstants;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import org.wso2.carbon.authenticator.stub.AuthenticationAdminStub;
import org.wso2.carbon.identity.oauth.stub.OAuthAdminServiceStub;
import org.wso2.carbon.registry.core.Collection;
import org.wso2.carbon.registry.extensions.stub.ResourceAdminServiceStub;
import org.wso2.carbon.registry.ws.client.registry.WSRegistryServiceClient;
import org.wso2.carbon.user.mgt.common.UserAdminException;
import org.wso2.carbon.user.mgt.stub.UserAdminStub;
import edu.indiana.d2i.htrc.wso2is.extensions.stub.ExtendedUserAdminStub;
import org.wso2.carbon.user.mgt.stub.types.carbon.ClaimValue;
import org.wso2.carbon.user.mgt.stub.types.carbon.FlaggedName;
import org.wso2.carbon.user.mgt.stub.types.carbon.UserRealmInfo;
import org.wso2.carbon.utils.NetworkUtils;
import play.Logger;
import java.rmi.RemoteException;
import java.util.*;
import java.util.regex.Pattern;
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* Create a new user for the HTRC platform
*
* @param userName The user name
* @param password The user's isPassword
* @param claims The <code>ClaimValue[]</code> array of profile claims
* (see <a href="https://htrc3.pti.indiana.edu:9443/carbon/claim-mgt/claim-view.jsp?store=Internal&dialect=http://wso2.org/claims">available claims</a>)
* // * @param permissions The array of permission keys to assign to the user, for example: "/permission/admin/login" (can be <code>null</code>)
* @throws UserAlreadyExistsException Thrown if an error occurred
* @see #getRequiredUserClaims()
* @see #getAvailablePermissions()
*/
public void createUser(String userName, String password, String email, List<Map.Entry<String, String>> claims) throws Exception { // TODO: Review this
if (userName == null) {
throw new NullPointerException("User name null.");
}
if (password == null) {
throw new NullPointerException("Password null.");
}
if (isUserExists(userName)) {
String message = "User with name " + userName + " already exists.";
log.warn(message);
|
throw new UserAlreadyExistsException(message);
|
htrc/HTRC-Portal
|
app/edu/indiana/d2i/htrc/portal/HTRCUserManagerUtility.java
|
// Path: app/edu/indiana/d2i/htrc/portal/exception/ChangePasswordUserAdminExceptionException.java
// public class ChangePasswordUserAdminExceptionException extends Exception {
// public ChangePasswordUserAdminExceptionException() {
// super();
// }
//
// public ChangePasswordUserAdminExceptionException(String message) {
// super(message);
// }
//
// public ChangePasswordUserAdminExceptionException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public ChangePasswordUserAdminExceptionException(Throwable cause) {
// super(cause);
// }
//
// protected ChangePasswordUserAdminExceptionException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
// super(message, cause, enableSuppression, writableStackTrace);
// }
// }
//
// Path: app/edu/indiana/d2i/htrc/portal/exception/EmailAlreadyExistsException.java
// public class EmailAlreadyExistsException extends Exception {
// public EmailAlreadyExistsException(String message) {
// super(message);
// }
//
// public EmailAlreadyExistsException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public EmailAlreadyExistsException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: app/edu/indiana/d2i/htrc/portal/exception/RoleNameAlreadyExistsException.java
// public class RoleNameAlreadyExistsException extends Exception {
// public RoleNameAlreadyExistsException(String message) {
// super(message);
// }
//
// public RoleNameAlreadyExistsException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public RoleNameAlreadyExistsException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: app/edu/indiana/d2i/htrc/portal/exception/UserAlreadyExistsException.java
// public class UserAlreadyExistsException extends Exception {
// public UserAlreadyExistsException(String message) {
// super(message);
// }
//
// public UserAlreadyExistsException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public UserAlreadyExistsException(Throwable cause) {
// super(cause);
// }
// }
|
import edu.indiana.d2i.htrc.portal.exception.ChangePasswordUserAdminExceptionException;
import edu.indiana.d2i.htrc.portal.exception.EmailAlreadyExistsException;
import edu.indiana.d2i.htrc.portal.exception.RoleNameAlreadyExistsException;
import edu.indiana.d2i.htrc.portal.exception.UserAlreadyExistsException;
import edu.indiana.d2i.htrc.wso2is.extensions.stub.types.UserInfoRequest;
import edu.indiana.d2i.htrc.wso2is.extensions.stub.types.UserInfoResponse;
import org.apache.axis2.client.Options;
import org.apache.axis2.context.ConfigurationContext;
import org.apache.axis2.context.ConfigurationContextFactory;
import org.apache.axis2.transport.http.HTTPConstants;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import org.wso2.carbon.authenticator.stub.AuthenticationAdminStub;
import org.wso2.carbon.identity.oauth.stub.OAuthAdminServiceStub;
import org.wso2.carbon.registry.core.Collection;
import org.wso2.carbon.registry.extensions.stub.ResourceAdminServiceStub;
import org.wso2.carbon.registry.ws.client.registry.WSRegistryServiceClient;
import org.wso2.carbon.user.mgt.common.UserAdminException;
import org.wso2.carbon.user.mgt.stub.UserAdminStub;
import edu.indiana.d2i.htrc.wso2is.extensions.stub.ExtendedUserAdminStub;
import org.wso2.carbon.user.mgt.stub.types.carbon.ClaimValue;
import org.wso2.carbon.user.mgt.stub.types.carbon.FlaggedName;
import org.wso2.carbon.user.mgt.stub.types.carbon.UserRealmInfo;
import org.wso2.carbon.utils.NetworkUtils;
import play.Logger;
import java.rmi.RemoteException;
import java.util.*;
import java.util.regex.Pattern;
|
/**
* Create a new user for the HTRC platform
*
* @param userName The user name
* @param password The user's isPassword
* @param claims The <code>ClaimValue[]</code> array of profile claims
* (see <a href="https://htrc3.pti.indiana.edu:9443/carbon/claim-mgt/claim-view.jsp?store=Internal&dialect=http://wso2.org/claims">available claims</a>)
* // * @param permissions The array of permission keys to assign to the user, for example: "/permission/admin/login" (can be <code>null</code>)
* @throws UserAlreadyExistsException Thrown if an error occurred
* @see #getRequiredUserClaims()
* @see #getAvailablePermissions()
*/
public void createUser(String userName, String password, String email, List<Map.Entry<String, String>> claims) throws Exception { // TODO: Review this
if (userName == null) {
throw new NullPointerException("User name null.");
}
if (password == null) {
throw new NullPointerException("Password null.");
}
if (isUserExists(userName)) {
String message = "User with name " + userName + " already exists.";
log.warn(message);
throw new UserAlreadyExistsException(message);
}
if (roleNameExists(userName)) {
String message = userName + " is a already exist role name.";
log.warn(message);
|
// Path: app/edu/indiana/d2i/htrc/portal/exception/ChangePasswordUserAdminExceptionException.java
// public class ChangePasswordUserAdminExceptionException extends Exception {
// public ChangePasswordUserAdminExceptionException() {
// super();
// }
//
// public ChangePasswordUserAdminExceptionException(String message) {
// super(message);
// }
//
// public ChangePasswordUserAdminExceptionException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public ChangePasswordUserAdminExceptionException(Throwable cause) {
// super(cause);
// }
//
// protected ChangePasswordUserAdminExceptionException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
// super(message, cause, enableSuppression, writableStackTrace);
// }
// }
//
// Path: app/edu/indiana/d2i/htrc/portal/exception/EmailAlreadyExistsException.java
// public class EmailAlreadyExistsException extends Exception {
// public EmailAlreadyExistsException(String message) {
// super(message);
// }
//
// public EmailAlreadyExistsException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public EmailAlreadyExistsException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: app/edu/indiana/d2i/htrc/portal/exception/RoleNameAlreadyExistsException.java
// public class RoleNameAlreadyExistsException extends Exception {
// public RoleNameAlreadyExistsException(String message) {
// super(message);
// }
//
// public RoleNameAlreadyExistsException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public RoleNameAlreadyExistsException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: app/edu/indiana/d2i/htrc/portal/exception/UserAlreadyExistsException.java
// public class UserAlreadyExistsException extends Exception {
// public UserAlreadyExistsException(String message) {
// super(message);
// }
//
// public UserAlreadyExistsException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public UserAlreadyExistsException(Throwable cause) {
// super(cause);
// }
// }
// Path: app/edu/indiana/d2i/htrc/portal/HTRCUserManagerUtility.java
import edu.indiana.d2i.htrc.portal.exception.ChangePasswordUserAdminExceptionException;
import edu.indiana.d2i.htrc.portal.exception.EmailAlreadyExistsException;
import edu.indiana.d2i.htrc.portal.exception.RoleNameAlreadyExistsException;
import edu.indiana.d2i.htrc.portal.exception.UserAlreadyExistsException;
import edu.indiana.d2i.htrc.wso2is.extensions.stub.types.UserInfoRequest;
import edu.indiana.d2i.htrc.wso2is.extensions.stub.types.UserInfoResponse;
import org.apache.axis2.client.Options;
import org.apache.axis2.context.ConfigurationContext;
import org.apache.axis2.context.ConfigurationContextFactory;
import org.apache.axis2.transport.http.HTTPConstants;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import org.wso2.carbon.authenticator.stub.AuthenticationAdminStub;
import org.wso2.carbon.identity.oauth.stub.OAuthAdminServiceStub;
import org.wso2.carbon.registry.core.Collection;
import org.wso2.carbon.registry.extensions.stub.ResourceAdminServiceStub;
import org.wso2.carbon.registry.ws.client.registry.WSRegistryServiceClient;
import org.wso2.carbon.user.mgt.common.UserAdminException;
import org.wso2.carbon.user.mgt.stub.UserAdminStub;
import edu.indiana.d2i.htrc.wso2is.extensions.stub.ExtendedUserAdminStub;
import org.wso2.carbon.user.mgt.stub.types.carbon.ClaimValue;
import org.wso2.carbon.user.mgt.stub.types.carbon.FlaggedName;
import org.wso2.carbon.user.mgt.stub.types.carbon.UserRealmInfo;
import org.wso2.carbon.utils.NetworkUtils;
import play.Logger;
import java.rmi.RemoteException;
import java.util.*;
import java.util.regex.Pattern;
/**
* Create a new user for the HTRC platform
*
* @param userName The user name
* @param password The user's isPassword
* @param claims The <code>ClaimValue[]</code> array of profile claims
* (see <a href="https://htrc3.pti.indiana.edu:9443/carbon/claim-mgt/claim-view.jsp?store=Internal&dialect=http://wso2.org/claims">available claims</a>)
* // * @param permissions The array of permission keys to assign to the user, for example: "/permission/admin/login" (can be <code>null</code>)
* @throws UserAlreadyExistsException Thrown if an error occurred
* @see #getRequiredUserClaims()
* @see #getAvailablePermissions()
*/
public void createUser(String userName, String password, String email, List<Map.Entry<String, String>> claims) throws Exception { // TODO: Review this
if (userName == null) {
throw new NullPointerException("User name null.");
}
if (password == null) {
throw new NullPointerException("Password null.");
}
if (isUserExists(userName)) {
String message = "User with name " + userName + " already exists.";
log.warn(message);
throw new UserAlreadyExistsException(message);
}
if (roleNameExists(userName)) {
String message = userName + " is a already exist role name.";
log.warn(message);
|
throw new RoleNameAlreadyExistsException(message);
|
htrc/HTRC-Portal
|
app/edu/indiana/d2i/htrc/portal/HTRCUserManagerUtility.java
|
// Path: app/edu/indiana/d2i/htrc/portal/exception/ChangePasswordUserAdminExceptionException.java
// public class ChangePasswordUserAdminExceptionException extends Exception {
// public ChangePasswordUserAdminExceptionException() {
// super();
// }
//
// public ChangePasswordUserAdminExceptionException(String message) {
// super(message);
// }
//
// public ChangePasswordUserAdminExceptionException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public ChangePasswordUserAdminExceptionException(Throwable cause) {
// super(cause);
// }
//
// protected ChangePasswordUserAdminExceptionException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
// super(message, cause, enableSuppression, writableStackTrace);
// }
// }
//
// Path: app/edu/indiana/d2i/htrc/portal/exception/EmailAlreadyExistsException.java
// public class EmailAlreadyExistsException extends Exception {
// public EmailAlreadyExistsException(String message) {
// super(message);
// }
//
// public EmailAlreadyExistsException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public EmailAlreadyExistsException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: app/edu/indiana/d2i/htrc/portal/exception/RoleNameAlreadyExistsException.java
// public class RoleNameAlreadyExistsException extends Exception {
// public RoleNameAlreadyExistsException(String message) {
// super(message);
// }
//
// public RoleNameAlreadyExistsException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public RoleNameAlreadyExistsException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: app/edu/indiana/d2i/htrc/portal/exception/UserAlreadyExistsException.java
// public class UserAlreadyExistsException extends Exception {
// public UserAlreadyExistsException(String message) {
// super(message);
// }
//
// public UserAlreadyExistsException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public UserAlreadyExistsException(Throwable cause) {
// super(cause);
// }
// }
|
import edu.indiana.d2i.htrc.portal.exception.ChangePasswordUserAdminExceptionException;
import edu.indiana.d2i.htrc.portal.exception.EmailAlreadyExistsException;
import edu.indiana.d2i.htrc.portal.exception.RoleNameAlreadyExistsException;
import edu.indiana.d2i.htrc.portal.exception.UserAlreadyExistsException;
import edu.indiana.d2i.htrc.wso2is.extensions.stub.types.UserInfoRequest;
import edu.indiana.d2i.htrc.wso2is.extensions.stub.types.UserInfoResponse;
import org.apache.axis2.client.Options;
import org.apache.axis2.context.ConfigurationContext;
import org.apache.axis2.context.ConfigurationContextFactory;
import org.apache.axis2.transport.http.HTTPConstants;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import org.wso2.carbon.authenticator.stub.AuthenticationAdminStub;
import org.wso2.carbon.identity.oauth.stub.OAuthAdminServiceStub;
import org.wso2.carbon.registry.core.Collection;
import org.wso2.carbon.registry.extensions.stub.ResourceAdminServiceStub;
import org.wso2.carbon.registry.ws.client.registry.WSRegistryServiceClient;
import org.wso2.carbon.user.mgt.common.UserAdminException;
import org.wso2.carbon.user.mgt.stub.UserAdminStub;
import edu.indiana.d2i.htrc.wso2is.extensions.stub.ExtendedUserAdminStub;
import org.wso2.carbon.user.mgt.stub.types.carbon.ClaimValue;
import org.wso2.carbon.user.mgt.stub.types.carbon.FlaggedName;
import org.wso2.carbon.user.mgt.stub.types.carbon.UserRealmInfo;
import org.wso2.carbon.utils.NetworkUtils;
import play.Logger;
import java.rmi.RemoteException;
import java.util.*;
import java.util.regex.Pattern;
|
* @throws UserAlreadyExistsException Thrown if an error occurred
* @see #getRequiredUserClaims()
* @see #getAvailablePermissions()
*/
public void createUser(String userName, String password, String email, List<Map.Entry<String, String>> claims) throws Exception { // TODO: Review this
if (userName == null) {
throw new NullPointerException("User name null.");
}
if (password == null) {
throw new NullPointerException("Password null.");
}
if (isUserExists(userName)) {
String message = "User with name " + userName + " already exists.";
log.warn(message);
throw new UserAlreadyExistsException(message);
}
if (roleNameExists(userName)) {
String message = userName + " is a already exist role name.";
log.warn(message);
throw new RoleNameAlreadyExistsException(message);
}
List<String> usersWithEmail = getUserIdsFromEmail(email);
if (usersWithEmail != null && usersWithEmail.size() > 0) {
String message = email + " is already used for user accounts: " + usersWithEmail;
log.warn(message);
|
// Path: app/edu/indiana/d2i/htrc/portal/exception/ChangePasswordUserAdminExceptionException.java
// public class ChangePasswordUserAdminExceptionException extends Exception {
// public ChangePasswordUserAdminExceptionException() {
// super();
// }
//
// public ChangePasswordUserAdminExceptionException(String message) {
// super(message);
// }
//
// public ChangePasswordUserAdminExceptionException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public ChangePasswordUserAdminExceptionException(Throwable cause) {
// super(cause);
// }
//
// protected ChangePasswordUserAdminExceptionException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
// super(message, cause, enableSuppression, writableStackTrace);
// }
// }
//
// Path: app/edu/indiana/d2i/htrc/portal/exception/EmailAlreadyExistsException.java
// public class EmailAlreadyExistsException extends Exception {
// public EmailAlreadyExistsException(String message) {
// super(message);
// }
//
// public EmailAlreadyExistsException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public EmailAlreadyExistsException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: app/edu/indiana/d2i/htrc/portal/exception/RoleNameAlreadyExistsException.java
// public class RoleNameAlreadyExistsException extends Exception {
// public RoleNameAlreadyExistsException(String message) {
// super(message);
// }
//
// public RoleNameAlreadyExistsException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public RoleNameAlreadyExistsException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: app/edu/indiana/d2i/htrc/portal/exception/UserAlreadyExistsException.java
// public class UserAlreadyExistsException extends Exception {
// public UserAlreadyExistsException(String message) {
// super(message);
// }
//
// public UserAlreadyExistsException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public UserAlreadyExistsException(Throwable cause) {
// super(cause);
// }
// }
// Path: app/edu/indiana/d2i/htrc/portal/HTRCUserManagerUtility.java
import edu.indiana.d2i.htrc.portal.exception.ChangePasswordUserAdminExceptionException;
import edu.indiana.d2i.htrc.portal.exception.EmailAlreadyExistsException;
import edu.indiana.d2i.htrc.portal.exception.RoleNameAlreadyExistsException;
import edu.indiana.d2i.htrc.portal.exception.UserAlreadyExistsException;
import edu.indiana.d2i.htrc.wso2is.extensions.stub.types.UserInfoRequest;
import edu.indiana.d2i.htrc.wso2is.extensions.stub.types.UserInfoResponse;
import org.apache.axis2.client.Options;
import org.apache.axis2.context.ConfigurationContext;
import org.apache.axis2.context.ConfigurationContextFactory;
import org.apache.axis2.transport.http.HTTPConstants;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import org.wso2.carbon.authenticator.stub.AuthenticationAdminStub;
import org.wso2.carbon.identity.oauth.stub.OAuthAdminServiceStub;
import org.wso2.carbon.registry.core.Collection;
import org.wso2.carbon.registry.extensions.stub.ResourceAdminServiceStub;
import org.wso2.carbon.registry.ws.client.registry.WSRegistryServiceClient;
import org.wso2.carbon.user.mgt.common.UserAdminException;
import org.wso2.carbon.user.mgt.stub.UserAdminStub;
import edu.indiana.d2i.htrc.wso2is.extensions.stub.ExtendedUserAdminStub;
import org.wso2.carbon.user.mgt.stub.types.carbon.ClaimValue;
import org.wso2.carbon.user.mgt.stub.types.carbon.FlaggedName;
import org.wso2.carbon.user.mgt.stub.types.carbon.UserRealmInfo;
import org.wso2.carbon.utils.NetworkUtils;
import play.Logger;
import java.rmi.RemoteException;
import java.util.*;
import java.util.regex.Pattern;
* @throws UserAlreadyExistsException Thrown if an error occurred
* @see #getRequiredUserClaims()
* @see #getAvailablePermissions()
*/
public void createUser(String userName, String password, String email, List<Map.Entry<String, String>> claims) throws Exception { // TODO: Review this
if (userName == null) {
throw new NullPointerException("User name null.");
}
if (password == null) {
throw new NullPointerException("Password null.");
}
if (isUserExists(userName)) {
String message = "User with name " + userName + " already exists.";
log.warn(message);
throw new UserAlreadyExistsException(message);
}
if (roleNameExists(userName)) {
String message = userName + " is a already exist role name.";
log.warn(message);
throw new RoleNameAlreadyExistsException(message);
}
List<String> usersWithEmail = getUserIdsFromEmail(email);
if (usersWithEmail != null && usersWithEmail.size() > 0) {
String message = email + " is already used for user accounts: " + usersWithEmail;
log.warn(message);
|
throw new EmailAlreadyExistsException(message);
|
htrc/HTRC-Portal
|
app/edu/indiana/d2i/htrc/portal/HTRCUserManagerUtility.java
|
// Path: app/edu/indiana/d2i/htrc/portal/exception/ChangePasswordUserAdminExceptionException.java
// public class ChangePasswordUserAdminExceptionException extends Exception {
// public ChangePasswordUserAdminExceptionException() {
// super();
// }
//
// public ChangePasswordUserAdminExceptionException(String message) {
// super(message);
// }
//
// public ChangePasswordUserAdminExceptionException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public ChangePasswordUserAdminExceptionException(Throwable cause) {
// super(cause);
// }
//
// protected ChangePasswordUserAdminExceptionException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
// super(message, cause, enableSuppression, writableStackTrace);
// }
// }
//
// Path: app/edu/indiana/d2i/htrc/portal/exception/EmailAlreadyExistsException.java
// public class EmailAlreadyExistsException extends Exception {
// public EmailAlreadyExistsException(String message) {
// super(message);
// }
//
// public EmailAlreadyExistsException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public EmailAlreadyExistsException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: app/edu/indiana/d2i/htrc/portal/exception/RoleNameAlreadyExistsException.java
// public class RoleNameAlreadyExistsException extends Exception {
// public RoleNameAlreadyExistsException(String message) {
// super(message);
// }
//
// public RoleNameAlreadyExistsException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public RoleNameAlreadyExistsException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: app/edu/indiana/d2i/htrc/portal/exception/UserAlreadyExistsException.java
// public class UserAlreadyExistsException extends Exception {
// public UserAlreadyExistsException(String message) {
// super(message);
// }
//
// public UserAlreadyExistsException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public UserAlreadyExistsException(Throwable cause) {
// super(cause);
// }
// }
|
import edu.indiana.d2i.htrc.portal.exception.ChangePasswordUserAdminExceptionException;
import edu.indiana.d2i.htrc.portal.exception.EmailAlreadyExistsException;
import edu.indiana.d2i.htrc.portal.exception.RoleNameAlreadyExistsException;
import edu.indiana.d2i.htrc.portal.exception.UserAlreadyExistsException;
import edu.indiana.d2i.htrc.wso2is.extensions.stub.types.UserInfoRequest;
import edu.indiana.d2i.htrc.wso2is.extensions.stub.types.UserInfoResponse;
import org.apache.axis2.client.Options;
import org.apache.axis2.context.ConfigurationContext;
import org.apache.axis2.context.ConfigurationContextFactory;
import org.apache.axis2.transport.http.HTTPConstants;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import org.wso2.carbon.authenticator.stub.AuthenticationAdminStub;
import org.wso2.carbon.identity.oauth.stub.OAuthAdminServiceStub;
import org.wso2.carbon.registry.core.Collection;
import org.wso2.carbon.registry.extensions.stub.ResourceAdminServiceStub;
import org.wso2.carbon.registry.ws.client.registry.WSRegistryServiceClient;
import org.wso2.carbon.user.mgt.common.UserAdminException;
import org.wso2.carbon.user.mgt.stub.UserAdminStub;
import edu.indiana.d2i.htrc.wso2is.extensions.stub.ExtendedUserAdminStub;
import org.wso2.carbon.user.mgt.stub.types.carbon.ClaimValue;
import org.wso2.carbon.user.mgt.stub.types.carbon.FlaggedName;
import org.wso2.carbon.user.mgt.stub.types.carbon.UserRealmInfo;
import org.wso2.carbon.utils.NetworkUtils;
import play.Logger;
import java.rmi.RemoteException;
import java.util.*;
import java.util.regex.Pattern;
|
public boolean roleNameExists(String roleName) {
FlaggedName[] roles;
try {
roles = userAdmin.getAllRolesNames(roleName, 10);
} catch (Exception e) {
if (e.getMessage().contains("401 Error: Unauthorized")) {
log.warn("Unauthorized error in roleNameExists method while invoking admin service due to session timeout.", e);
userAdmin._getServiceClient().getOptions().setProperty(HTTPConstants.COOKIE_STRING,
authenticateWithWSO2Server(isURL, isUserName, isPassword));
return roleNameExists(roleName);
}
throw new RuntimeException(e);
}
for (FlaggedName role : roles) {
if (role.getItemName().equals(roleName)) {
log.info("Role name " + roleName + " already exists");
return true;
}
}
return false;
}
/**
* Change User isPassword
*
* @param userName The User's username
* @param newPassword The User's new isPassword
* @throws ChangePasswordUserAdminExceptionException
*/
|
// Path: app/edu/indiana/d2i/htrc/portal/exception/ChangePasswordUserAdminExceptionException.java
// public class ChangePasswordUserAdminExceptionException extends Exception {
// public ChangePasswordUserAdminExceptionException() {
// super();
// }
//
// public ChangePasswordUserAdminExceptionException(String message) {
// super(message);
// }
//
// public ChangePasswordUserAdminExceptionException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public ChangePasswordUserAdminExceptionException(Throwable cause) {
// super(cause);
// }
//
// protected ChangePasswordUserAdminExceptionException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
// super(message, cause, enableSuppression, writableStackTrace);
// }
// }
//
// Path: app/edu/indiana/d2i/htrc/portal/exception/EmailAlreadyExistsException.java
// public class EmailAlreadyExistsException extends Exception {
// public EmailAlreadyExistsException(String message) {
// super(message);
// }
//
// public EmailAlreadyExistsException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public EmailAlreadyExistsException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: app/edu/indiana/d2i/htrc/portal/exception/RoleNameAlreadyExistsException.java
// public class RoleNameAlreadyExistsException extends Exception {
// public RoleNameAlreadyExistsException(String message) {
// super(message);
// }
//
// public RoleNameAlreadyExistsException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public RoleNameAlreadyExistsException(Throwable cause) {
// super(cause);
// }
// }
//
// Path: app/edu/indiana/d2i/htrc/portal/exception/UserAlreadyExistsException.java
// public class UserAlreadyExistsException extends Exception {
// public UserAlreadyExistsException(String message) {
// super(message);
// }
//
// public UserAlreadyExistsException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public UserAlreadyExistsException(Throwable cause) {
// super(cause);
// }
// }
// Path: app/edu/indiana/d2i/htrc/portal/HTRCUserManagerUtility.java
import edu.indiana.d2i.htrc.portal.exception.ChangePasswordUserAdminExceptionException;
import edu.indiana.d2i.htrc.portal.exception.EmailAlreadyExistsException;
import edu.indiana.d2i.htrc.portal.exception.RoleNameAlreadyExistsException;
import edu.indiana.d2i.htrc.portal.exception.UserAlreadyExistsException;
import edu.indiana.d2i.htrc.wso2is.extensions.stub.types.UserInfoRequest;
import edu.indiana.d2i.htrc.wso2is.extensions.stub.types.UserInfoResponse;
import org.apache.axis2.client.Options;
import org.apache.axis2.context.ConfigurationContext;
import org.apache.axis2.context.ConfigurationContextFactory;
import org.apache.axis2.transport.http.HTTPConstants;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import org.wso2.carbon.authenticator.stub.AuthenticationAdminStub;
import org.wso2.carbon.identity.oauth.stub.OAuthAdminServiceStub;
import org.wso2.carbon.registry.core.Collection;
import org.wso2.carbon.registry.extensions.stub.ResourceAdminServiceStub;
import org.wso2.carbon.registry.ws.client.registry.WSRegistryServiceClient;
import org.wso2.carbon.user.mgt.common.UserAdminException;
import org.wso2.carbon.user.mgt.stub.UserAdminStub;
import edu.indiana.d2i.htrc.wso2is.extensions.stub.ExtendedUserAdminStub;
import org.wso2.carbon.user.mgt.stub.types.carbon.ClaimValue;
import org.wso2.carbon.user.mgt.stub.types.carbon.FlaggedName;
import org.wso2.carbon.user.mgt.stub.types.carbon.UserRealmInfo;
import org.wso2.carbon.utils.NetworkUtils;
import play.Logger;
import java.rmi.RemoteException;
import java.util.*;
import java.util.regex.Pattern;
public boolean roleNameExists(String roleName) {
FlaggedName[] roles;
try {
roles = userAdmin.getAllRolesNames(roleName, 10);
} catch (Exception e) {
if (e.getMessage().contains("401 Error: Unauthorized")) {
log.warn("Unauthorized error in roleNameExists method while invoking admin service due to session timeout.", e);
userAdmin._getServiceClient().getOptions().setProperty(HTTPConstants.COOKIE_STRING,
authenticateWithWSO2Server(isURL, isUserName, isPassword));
return roleNameExists(roleName);
}
throw new RuntimeException(e);
}
for (FlaggedName role : roles) {
if (role.getItemName().equals(roleName)) {
log.info("Role name " + roleName + " already exists");
return true;
}
}
return false;
}
/**
* Change User isPassword
*
* @param userName The User's username
* @param newPassword The User's new isPassword
* @throws ChangePasswordUserAdminExceptionException
*/
|
public void changePassword(String userName, String newPassword) throws ChangePasswordUserAdminExceptionException {
|
htrc/HTRC-Portal
|
app/edu/indiana/d2i/htrc/portal/HTRCExperimentalAnalysisServiceClient.java
|
// Path: app/edu/indiana/d2i/htrc/sloan/bean/VMImageDetails.java
// public class VMImageDetails {
// private String vmImageName;
// private String vmImageDescription;
// private String vmImageStatus;
//
// public VMImageDetails(String imageName, String imageDescription, String imageStatus){
// this.vmImageName = imageName;
// this.vmImageDescription = imageDescription;
// this.vmImageStatus = imageStatus;
// }
//
// public String getVmImageName() {
// return vmImageName;
// }
//
// public void setVmImageName(String vmImageName) {
// this.vmImageName = vmImageName;
// }
//
// public String getVmImageDescription() {
// return vmImageDescription;
// }
//
// public void setVmImageDescription(String vmImageDescription) {
// this.vmImageDescription = vmImageDescription;
// }
//
// public String getVmImageStatus() {
// return vmImageStatus;
// }
//
// public void setVmImageStatus(String vmImageStatus) {
// this.vmImageStatus = vmImageStatus;
// }
// }
//
// Path: app/edu/indiana/d2i/htrc/sloan/bean/VMStatus.java
// public class VMStatus {
// private String vmId;
// private String mode;
// private String state;
// private long vncPort;
// private long sshPort;
// private String publicIp;
// private long vcpu;
// private long memory;
// private long volumeSize;
// private String imageName;
// private String vmIntialLogingId;
// private String vmInitialLogingPassword;
//
// public String getVmId() {
// return vmId;
// }
//
// public void setVmId(String vmId) {
// this.vmId = vmId;
// }
//
// public String getMode() {
// return mode;
// }
//
// public void setMode(String mode) {
// this.mode = mode;
// }
//
// public String getState() {
// return state;
// }
//
// public void setState(String state) {
// this.state = state;
// }
//
// public long getVncPort() {
// return vncPort;
// }
//
// public void setVncPort(long vncPort) {
// this.vncPort = vncPort;
// }
//
// public long getSshPort() {
// return sshPort;
// }
//
// public void setSshPort(long sshPort) {
// this.sshPort = sshPort;
// }
//
// public String getPublicIp() {
// return publicIp;
// }
//
// public void setPublicIp(String publicIp) {
// this.publicIp = publicIp;
// }
//
// public long getVcpu() {
// return vcpu;
// }
//
// public void setVcpu(long vcpu) {
// this.vcpu = vcpu;
// }
//
// public long getMemory() {
// return memory;
// }
//
// public void setMemory(long memory) {
// this.memory = memory;
// }
//
// public long getVolumeSize() {
// return volumeSize;
// }
//
// public void setVolumeSize(long volumeSize) {
// this.volumeSize = volumeSize;
// }
//
// public String getImageName() {
// return imageName;
// }
//
// public void setImageName(String imageName) {
// this.imageName = imageName;
// }
//
// public String getVmIntialLogingId() {
// return vmIntialLogingId;
// }
//
// public void setVmIntialLogingId(String vmIntialLogingId) {
// this.vmIntialLogingId = vmIntialLogingId;
// }
//
// public String getVmInitialLogingPassword() {
// return vmInitialLogingPassword;
// }
//
// public void setVmInitialLogingPassword(String vmInitialLogingPassword) {
// this.vmInitialLogingPassword = vmInitialLogingPassword;
// }
// }
|
import edu.indiana.d2i.htrc.sloan.bean.VMImageDetails;
import edu.indiana.d2i.htrc.sloan.bean.VMStatus;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.contrib.ssl.EasySSLProtocolSocketFactory;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.protocol.Protocol;
import org.apache.commons.httpclient.protocol.ProtocolSocketFactory;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import play.Logger;
import play.mvc.Http;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
|
post.setParameter("imagename", imageName);
post.setParameter("loginusername", loginUerName);
post.setParameter("loginpassword", loginPassword);
post.setParameter("memory", memory);
post.setParameter("vcpu", vcpu);
// post.setRequestBody((org.apache.commons.httpclient.NameValuePair[]) urlParameters);
int response = client.executeMethod(post);
this.responseCode = response;
if (response == 200) {
String jsonStr = post.getResponseBodyAsString();
log.info(Arrays.toString(post.getRequestHeaders()));
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(jsonStr);
JSONObject jsonObject = (JSONObject) obj;
return ((String) jsonObject.get("vmid"));
} catch (ParseException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
} else {
this.responseCode = response;
log.error(post.getResponseBodyAsString());
throw new IOException("Response code " + response + " for " + createVMUrl + " message: \n " + post.getResponseBodyAsString());
}
return null;
}
|
// Path: app/edu/indiana/d2i/htrc/sloan/bean/VMImageDetails.java
// public class VMImageDetails {
// private String vmImageName;
// private String vmImageDescription;
// private String vmImageStatus;
//
// public VMImageDetails(String imageName, String imageDescription, String imageStatus){
// this.vmImageName = imageName;
// this.vmImageDescription = imageDescription;
// this.vmImageStatus = imageStatus;
// }
//
// public String getVmImageName() {
// return vmImageName;
// }
//
// public void setVmImageName(String vmImageName) {
// this.vmImageName = vmImageName;
// }
//
// public String getVmImageDescription() {
// return vmImageDescription;
// }
//
// public void setVmImageDescription(String vmImageDescription) {
// this.vmImageDescription = vmImageDescription;
// }
//
// public String getVmImageStatus() {
// return vmImageStatus;
// }
//
// public void setVmImageStatus(String vmImageStatus) {
// this.vmImageStatus = vmImageStatus;
// }
// }
//
// Path: app/edu/indiana/d2i/htrc/sloan/bean/VMStatus.java
// public class VMStatus {
// private String vmId;
// private String mode;
// private String state;
// private long vncPort;
// private long sshPort;
// private String publicIp;
// private long vcpu;
// private long memory;
// private long volumeSize;
// private String imageName;
// private String vmIntialLogingId;
// private String vmInitialLogingPassword;
//
// public String getVmId() {
// return vmId;
// }
//
// public void setVmId(String vmId) {
// this.vmId = vmId;
// }
//
// public String getMode() {
// return mode;
// }
//
// public void setMode(String mode) {
// this.mode = mode;
// }
//
// public String getState() {
// return state;
// }
//
// public void setState(String state) {
// this.state = state;
// }
//
// public long getVncPort() {
// return vncPort;
// }
//
// public void setVncPort(long vncPort) {
// this.vncPort = vncPort;
// }
//
// public long getSshPort() {
// return sshPort;
// }
//
// public void setSshPort(long sshPort) {
// this.sshPort = sshPort;
// }
//
// public String getPublicIp() {
// return publicIp;
// }
//
// public void setPublicIp(String publicIp) {
// this.publicIp = publicIp;
// }
//
// public long getVcpu() {
// return vcpu;
// }
//
// public void setVcpu(long vcpu) {
// this.vcpu = vcpu;
// }
//
// public long getMemory() {
// return memory;
// }
//
// public void setMemory(long memory) {
// this.memory = memory;
// }
//
// public long getVolumeSize() {
// return volumeSize;
// }
//
// public void setVolumeSize(long volumeSize) {
// this.volumeSize = volumeSize;
// }
//
// public String getImageName() {
// return imageName;
// }
//
// public void setImageName(String imageName) {
// this.imageName = imageName;
// }
//
// public String getVmIntialLogingId() {
// return vmIntialLogingId;
// }
//
// public void setVmIntialLogingId(String vmIntialLogingId) {
// this.vmIntialLogingId = vmIntialLogingId;
// }
//
// public String getVmInitialLogingPassword() {
// return vmInitialLogingPassword;
// }
//
// public void setVmInitialLogingPassword(String vmInitialLogingPassword) {
// this.vmInitialLogingPassword = vmInitialLogingPassword;
// }
// }
// Path: app/edu/indiana/d2i/htrc/portal/HTRCExperimentalAnalysisServiceClient.java
import edu.indiana.d2i.htrc.sloan.bean.VMImageDetails;
import edu.indiana.d2i.htrc.sloan.bean.VMStatus;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.contrib.ssl.EasySSLProtocolSocketFactory;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.protocol.Protocol;
import org.apache.commons.httpclient.protocol.ProtocolSocketFactory;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import play.Logger;
import play.mvc.Http;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
post.setParameter("imagename", imageName);
post.setParameter("loginusername", loginUerName);
post.setParameter("loginpassword", loginPassword);
post.setParameter("memory", memory);
post.setParameter("vcpu", vcpu);
// post.setRequestBody((org.apache.commons.httpclient.NameValuePair[]) urlParameters);
int response = client.executeMethod(post);
this.responseCode = response;
if (response == 200) {
String jsonStr = post.getResponseBodyAsString();
log.info(Arrays.toString(post.getRequestHeaders()));
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(jsonStr);
JSONObject jsonObject = (JSONObject) obj;
return ((String) jsonObject.get("vmid"));
} catch (ParseException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
} else {
this.responseCode = response;
log.error(post.getResponseBodyAsString());
throw new IOException("Response code " + response + " for " + createVMUrl + " message: \n " + post.getResponseBodyAsString());
}
return null;
}
|
public List<VMImageDetails> listVMImages(Http.Session session) throws IOException, GeneralSecurityException {
|
htrc/HTRC-Portal
|
app/edu/indiana/d2i/htrc/portal/HTRCExperimentalAnalysisServiceClient.java
|
// Path: app/edu/indiana/d2i/htrc/sloan/bean/VMImageDetails.java
// public class VMImageDetails {
// private String vmImageName;
// private String vmImageDescription;
// private String vmImageStatus;
//
// public VMImageDetails(String imageName, String imageDescription, String imageStatus){
// this.vmImageName = imageName;
// this.vmImageDescription = imageDescription;
// this.vmImageStatus = imageStatus;
// }
//
// public String getVmImageName() {
// return vmImageName;
// }
//
// public void setVmImageName(String vmImageName) {
// this.vmImageName = vmImageName;
// }
//
// public String getVmImageDescription() {
// return vmImageDescription;
// }
//
// public void setVmImageDescription(String vmImageDescription) {
// this.vmImageDescription = vmImageDescription;
// }
//
// public String getVmImageStatus() {
// return vmImageStatus;
// }
//
// public void setVmImageStatus(String vmImageStatus) {
// this.vmImageStatus = vmImageStatus;
// }
// }
//
// Path: app/edu/indiana/d2i/htrc/sloan/bean/VMStatus.java
// public class VMStatus {
// private String vmId;
// private String mode;
// private String state;
// private long vncPort;
// private long sshPort;
// private String publicIp;
// private long vcpu;
// private long memory;
// private long volumeSize;
// private String imageName;
// private String vmIntialLogingId;
// private String vmInitialLogingPassword;
//
// public String getVmId() {
// return vmId;
// }
//
// public void setVmId(String vmId) {
// this.vmId = vmId;
// }
//
// public String getMode() {
// return mode;
// }
//
// public void setMode(String mode) {
// this.mode = mode;
// }
//
// public String getState() {
// return state;
// }
//
// public void setState(String state) {
// this.state = state;
// }
//
// public long getVncPort() {
// return vncPort;
// }
//
// public void setVncPort(long vncPort) {
// this.vncPort = vncPort;
// }
//
// public long getSshPort() {
// return sshPort;
// }
//
// public void setSshPort(long sshPort) {
// this.sshPort = sshPort;
// }
//
// public String getPublicIp() {
// return publicIp;
// }
//
// public void setPublicIp(String publicIp) {
// this.publicIp = publicIp;
// }
//
// public long getVcpu() {
// return vcpu;
// }
//
// public void setVcpu(long vcpu) {
// this.vcpu = vcpu;
// }
//
// public long getMemory() {
// return memory;
// }
//
// public void setMemory(long memory) {
// this.memory = memory;
// }
//
// public long getVolumeSize() {
// return volumeSize;
// }
//
// public void setVolumeSize(long volumeSize) {
// this.volumeSize = volumeSize;
// }
//
// public String getImageName() {
// return imageName;
// }
//
// public void setImageName(String imageName) {
// this.imageName = imageName;
// }
//
// public String getVmIntialLogingId() {
// return vmIntialLogingId;
// }
//
// public void setVmIntialLogingId(String vmIntialLogingId) {
// this.vmIntialLogingId = vmIntialLogingId;
// }
//
// public String getVmInitialLogingPassword() {
// return vmInitialLogingPassword;
// }
//
// public void setVmInitialLogingPassword(String vmInitialLogingPassword) {
// this.vmInitialLogingPassword = vmInitialLogingPassword;
// }
// }
|
import edu.indiana.d2i.htrc.sloan.bean.VMImageDetails;
import edu.indiana.d2i.htrc.sloan.bean.VMStatus;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.contrib.ssl.EasySSLProtocolSocketFactory;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.protocol.Protocol;
import org.apache.commons.httpclient.protocol.ProtocolSocketFactory;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import play.Logger;
import play.mvc.Http;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
|
if (response == 200) {
String jsonStr = getMethod.getResponseBodyAsString();
log.info(Arrays.toString(getMethod.getRequestHeaders()));
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(jsonStr);
JSONObject jsonObject = (JSONObject) obj;
JSONArray jsonArray = (JSONArray) jsonObject.get("imageInfo");
for (Object aJsonArray : jsonArray) {
JSONObject infoObject = (JSONObject) aJsonArray;
String name = (String) infoObject.get("imageName");
String description = (String) infoObject.get("imageDescription");
String status = (String) infoObject.get("imageStatus");
VMImageDetails vmDetails = new VMImageDetails(name, description,status);
if (!vmDetailsList.contains(vmDetails)) {
vmDetailsList.add(vmDetails);
}
}
} catch (ParseException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
return vmDetailsList;
} else {
this.responseCode = response;
throw new IOException("Response code " + response + " for " + listVMImageUrl + " message: \n " + getMethod.getResponseBodyAsString());
}
}
|
// Path: app/edu/indiana/d2i/htrc/sloan/bean/VMImageDetails.java
// public class VMImageDetails {
// private String vmImageName;
// private String vmImageDescription;
// private String vmImageStatus;
//
// public VMImageDetails(String imageName, String imageDescription, String imageStatus){
// this.vmImageName = imageName;
// this.vmImageDescription = imageDescription;
// this.vmImageStatus = imageStatus;
// }
//
// public String getVmImageName() {
// return vmImageName;
// }
//
// public void setVmImageName(String vmImageName) {
// this.vmImageName = vmImageName;
// }
//
// public String getVmImageDescription() {
// return vmImageDescription;
// }
//
// public void setVmImageDescription(String vmImageDescription) {
// this.vmImageDescription = vmImageDescription;
// }
//
// public String getVmImageStatus() {
// return vmImageStatus;
// }
//
// public void setVmImageStatus(String vmImageStatus) {
// this.vmImageStatus = vmImageStatus;
// }
// }
//
// Path: app/edu/indiana/d2i/htrc/sloan/bean/VMStatus.java
// public class VMStatus {
// private String vmId;
// private String mode;
// private String state;
// private long vncPort;
// private long sshPort;
// private String publicIp;
// private long vcpu;
// private long memory;
// private long volumeSize;
// private String imageName;
// private String vmIntialLogingId;
// private String vmInitialLogingPassword;
//
// public String getVmId() {
// return vmId;
// }
//
// public void setVmId(String vmId) {
// this.vmId = vmId;
// }
//
// public String getMode() {
// return mode;
// }
//
// public void setMode(String mode) {
// this.mode = mode;
// }
//
// public String getState() {
// return state;
// }
//
// public void setState(String state) {
// this.state = state;
// }
//
// public long getVncPort() {
// return vncPort;
// }
//
// public void setVncPort(long vncPort) {
// this.vncPort = vncPort;
// }
//
// public long getSshPort() {
// return sshPort;
// }
//
// public void setSshPort(long sshPort) {
// this.sshPort = sshPort;
// }
//
// public String getPublicIp() {
// return publicIp;
// }
//
// public void setPublicIp(String publicIp) {
// this.publicIp = publicIp;
// }
//
// public long getVcpu() {
// return vcpu;
// }
//
// public void setVcpu(long vcpu) {
// this.vcpu = vcpu;
// }
//
// public long getMemory() {
// return memory;
// }
//
// public void setMemory(long memory) {
// this.memory = memory;
// }
//
// public long getVolumeSize() {
// return volumeSize;
// }
//
// public void setVolumeSize(long volumeSize) {
// this.volumeSize = volumeSize;
// }
//
// public String getImageName() {
// return imageName;
// }
//
// public void setImageName(String imageName) {
// this.imageName = imageName;
// }
//
// public String getVmIntialLogingId() {
// return vmIntialLogingId;
// }
//
// public void setVmIntialLogingId(String vmIntialLogingId) {
// this.vmIntialLogingId = vmIntialLogingId;
// }
//
// public String getVmInitialLogingPassword() {
// return vmInitialLogingPassword;
// }
//
// public void setVmInitialLogingPassword(String vmInitialLogingPassword) {
// this.vmInitialLogingPassword = vmInitialLogingPassword;
// }
// }
// Path: app/edu/indiana/d2i/htrc/portal/HTRCExperimentalAnalysisServiceClient.java
import edu.indiana.d2i.htrc.sloan.bean.VMImageDetails;
import edu.indiana.d2i.htrc.sloan.bean.VMStatus;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.contrib.ssl.EasySSLProtocolSocketFactory;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.protocol.Protocol;
import org.apache.commons.httpclient.protocol.ProtocolSocketFactory;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import play.Logger;
import play.mvc.Http;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
if (response == 200) {
String jsonStr = getMethod.getResponseBodyAsString();
log.info(Arrays.toString(getMethod.getRequestHeaders()));
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(jsonStr);
JSONObject jsonObject = (JSONObject) obj;
JSONArray jsonArray = (JSONArray) jsonObject.get("imageInfo");
for (Object aJsonArray : jsonArray) {
JSONObject infoObject = (JSONObject) aJsonArray;
String name = (String) infoObject.get("imageName");
String description = (String) infoObject.get("imageDescription");
String status = (String) infoObject.get("imageStatus");
VMImageDetails vmDetails = new VMImageDetails(name, description,status);
if (!vmDetailsList.contains(vmDetails)) {
vmDetailsList.add(vmDetails);
}
}
} catch (ParseException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
return vmDetailsList;
} else {
this.responseCode = response;
throw new IOException("Response code " + response + " for " + listVMImageUrl + " message: \n " + getMethod.getResponseBodyAsString());
}
}
|
public List<VMStatus> listVMs(Http.Session session) throws GeneralSecurityException, IOException {
|
thymeleaf/thymeleaf-itutorial
|
src/main/java/org/thymeleaf/itutorial/ExerciseController.java
|
// Path: src/main/java/org/thymeleaf/itutorial/beans/Customer.java
// public class Customer {
//
// private Integer id;
// private String firstName;
// private String lastName;
// private Gender gender;
// private PaymentMethod paymentMethod;
// private int balance;
// private String personalWebsite;
//
// public Customer() {
// super();
// }
//
// public Customer(
// final Integer id, final String firstName, final String lastName,
// final Gender gender, final PaymentMethod paymentMethod,
// final int balance, final String personalWebsite) {
// super();
// this.id = id;
// this.firstName = firstName;
// this.lastName = lastName;
// this.gender = gender;
// this.paymentMethod = paymentMethod;
// this.balance = balance;
// this.personalWebsite = personalWebsite;
// }
//
// public Integer getId() {
// return this.id;
// }
//
// public void setId(final Integer id) {
// this.id = id;
// }
//
// public int getBalance() {
// return this.balance;
// }
//
// public void setBalance(final int balance) {
// this.balance = balance;
// }
//
// public String getFirstName() {
// return this.firstName;
// }
//
// public void setFirstName(final String firstName) {
// this.firstName = firstName;
// }
//
// public Gender getGender() {
// return this.gender;
// }
//
// public void setGender(final Gender gender) {
// this.gender = gender;
// }
//
// public String getLastName() {
// return this.lastName;
// }
//
// public void setLastName(final String lastName) {
// this.lastName = lastName;
// }
//
// public PaymentMethod getPaymentMethod() {
// return this.paymentMethod;
// }
//
// public void setPaymentMethod(final PaymentMethod paymentMethod) {
// this.paymentMethod = paymentMethod;
// }
//
// public String getPersonalWebsite() {
// return personalWebsite;
// }
//
// public void setPersonalWebsite(String personalWebsite) {
// this.personalWebsite = personalWebsite;
// }
// }
//
// Path: src/main/java/org/thymeleaf/itutorial/IndexController.java
// public static final String THYMELEAF_VERSION_PARAMETER = "thymeleafVersion";
|
import java.io.IOException;
import javax.servlet.ServletContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.thymeleaf.itutorial.beans.Customer;
import static org.thymeleaf.itutorial.IndexController.THYMELEAF_VERSION_PARAMETER;
|
/*
* =============================================================================
*
* Copyright (c) 2011-2014, The THYMELEAF team (http://www.thymeleaf.org)
*
* 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.thymeleaf.itutorial;
@Controller
public class ExerciseController {
private static final String CHARSET = "UTF-8";
@Autowired private ServletContext servletContext;
@RequestMapping(value = "/exercise/{index}", method = RequestMethod.GET)
public String exercise(@PathVariable("index") final Integer index, final Model model) throws IOException {
Exercise exercise = Exercise.get(index);
String question = new ExerciseResourceLoader(servletContext, exercise).getResource("question.html", CHARSET);
model.addAttribute("question", question);
model.addAttribute("exercise", exercise);
|
// Path: src/main/java/org/thymeleaf/itutorial/beans/Customer.java
// public class Customer {
//
// private Integer id;
// private String firstName;
// private String lastName;
// private Gender gender;
// private PaymentMethod paymentMethod;
// private int balance;
// private String personalWebsite;
//
// public Customer() {
// super();
// }
//
// public Customer(
// final Integer id, final String firstName, final String lastName,
// final Gender gender, final PaymentMethod paymentMethod,
// final int balance, final String personalWebsite) {
// super();
// this.id = id;
// this.firstName = firstName;
// this.lastName = lastName;
// this.gender = gender;
// this.paymentMethod = paymentMethod;
// this.balance = balance;
// this.personalWebsite = personalWebsite;
// }
//
// public Integer getId() {
// return this.id;
// }
//
// public void setId(final Integer id) {
// this.id = id;
// }
//
// public int getBalance() {
// return this.balance;
// }
//
// public void setBalance(final int balance) {
// this.balance = balance;
// }
//
// public String getFirstName() {
// return this.firstName;
// }
//
// public void setFirstName(final String firstName) {
// this.firstName = firstName;
// }
//
// public Gender getGender() {
// return this.gender;
// }
//
// public void setGender(final Gender gender) {
// this.gender = gender;
// }
//
// public String getLastName() {
// return this.lastName;
// }
//
// public void setLastName(final String lastName) {
// this.lastName = lastName;
// }
//
// public PaymentMethod getPaymentMethod() {
// return this.paymentMethod;
// }
//
// public void setPaymentMethod(final PaymentMethod paymentMethod) {
// this.paymentMethod = paymentMethod;
// }
//
// public String getPersonalWebsite() {
// return personalWebsite;
// }
//
// public void setPersonalWebsite(String personalWebsite) {
// this.personalWebsite = personalWebsite;
// }
// }
//
// Path: src/main/java/org/thymeleaf/itutorial/IndexController.java
// public static final String THYMELEAF_VERSION_PARAMETER = "thymeleafVersion";
// Path: src/main/java/org/thymeleaf/itutorial/ExerciseController.java
import java.io.IOException;
import javax.servlet.ServletContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.thymeleaf.itutorial.beans.Customer;
import static org.thymeleaf.itutorial.IndexController.THYMELEAF_VERSION_PARAMETER;
/*
* =============================================================================
*
* Copyright (c) 2011-2014, The THYMELEAF team (http://www.thymeleaf.org)
*
* 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.thymeleaf.itutorial;
@Controller
public class ExerciseController {
private static final String CHARSET = "UTF-8";
@Autowired private ServletContext servletContext;
@RequestMapping(value = "/exercise/{index}", method = RequestMethod.GET)
public String exercise(@PathVariable("index") final Integer index, final Model model) throws IOException {
Exercise exercise = Exercise.get(index);
String question = new ExerciseResourceLoader(servletContext, exercise).getResource("question.html", CHARSET);
model.addAttribute("question", question);
model.addAttribute("exercise", exercise);
|
model.addAttribute("thymeleafVersion", servletContext.getInitParameter(THYMELEAF_VERSION_PARAMETER));
|
thymeleaf/thymeleaf-itutorial
|
src/main/java/org/thymeleaf/itutorial/ExerciseController.java
|
// Path: src/main/java/org/thymeleaf/itutorial/beans/Customer.java
// public class Customer {
//
// private Integer id;
// private String firstName;
// private String lastName;
// private Gender gender;
// private PaymentMethod paymentMethod;
// private int balance;
// private String personalWebsite;
//
// public Customer() {
// super();
// }
//
// public Customer(
// final Integer id, final String firstName, final String lastName,
// final Gender gender, final PaymentMethod paymentMethod,
// final int balance, final String personalWebsite) {
// super();
// this.id = id;
// this.firstName = firstName;
// this.lastName = lastName;
// this.gender = gender;
// this.paymentMethod = paymentMethod;
// this.balance = balance;
// this.personalWebsite = personalWebsite;
// }
//
// public Integer getId() {
// return this.id;
// }
//
// public void setId(final Integer id) {
// this.id = id;
// }
//
// public int getBalance() {
// return this.balance;
// }
//
// public void setBalance(final int balance) {
// this.balance = balance;
// }
//
// public String getFirstName() {
// return this.firstName;
// }
//
// public void setFirstName(final String firstName) {
// this.firstName = firstName;
// }
//
// public Gender getGender() {
// return this.gender;
// }
//
// public void setGender(final Gender gender) {
// this.gender = gender;
// }
//
// public String getLastName() {
// return this.lastName;
// }
//
// public void setLastName(final String lastName) {
// this.lastName = lastName;
// }
//
// public PaymentMethod getPaymentMethod() {
// return this.paymentMethod;
// }
//
// public void setPaymentMethod(final PaymentMethod paymentMethod) {
// this.paymentMethod = paymentMethod;
// }
//
// public String getPersonalWebsite() {
// return personalWebsite;
// }
//
// public void setPersonalWebsite(String personalWebsite) {
// this.personalWebsite = personalWebsite;
// }
// }
//
// Path: src/main/java/org/thymeleaf/itutorial/IndexController.java
// public static final String THYMELEAF_VERSION_PARAMETER = "thymeleafVersion";
|
import java.io.IOException;
import javax.servlet.ServletContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.thymeleaf.itutorial.beans.Customer;
import static org.thymeleaf.itutorial.IndexController.THYMELEAF_VERSION_PARAMETER;
|
/*
* =============================================================================
*
* Copyright (c) 2011-2014, The THYMELEAF team (http://www.thymeleaf.org)
*
* 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.thymeleaf.itutorial;
@Controller
public class ExerciseController {
private static final String CHARSET = "UTF-8";
@Autowired private ServletContext servletContext;
@RequestMapping(value = "/exercise/{index}", method = RequestMethod.GET)
public String exercise(@PathVariable("index") final Integer index, final Model model) throws IOException {
Exercise exercise = Exercise.get(index);
String question = new ExerciseResourceLoader(servletContext, exercise).getResource("question.html", CHARSET);
model.addAttribute("question", question);
model.addAttribute("exercise", exercise);
model.addAttribute("thymeleafVersion", servletContext.getInitParameter(THYMELEAF_VERSION_PARAMETER));
return "exercise.html";
}
// Auxiliar mapping for Exercise 11.
@RequestMapping("/exercise11/product.html")
public String product(@RequestParam("action") String action, Model model) {
model.addAttribute("product", DAO.loadProduct());
if ("view".equals(action)) {
return "/exercise11/viewProduct.html";
} else if ("edit".equals(action)) {
return "/exercise11/editProduct.html";
} else {
throw new IllegalArgumentException("Action -" + action +"- not recognized");
}
}
// Auxiliar mapping for Exercise 12.
@RequestMapping("/exercise12/saveCustomer.html")
|
// Path: src/main/java/org/thymeleaf/itutorial/beans/Customer.java
// public class Customer {
//
// private Integer id;
// private String firstName;
// private String lastName;
// private Gender gender;
// private PaymentMethod paymentMethod;
// private int balance;
// private String personalWebsite;
//
// public Customer() {
// super();
// }
//
// public Customer(
// final Integer id, final String firstName, final String lastName,
// final Gender gender, final PaymentMethod paymentMethod,
// final int balance, final String personalWebsite) {
// super();
// this.id = id;
// this.firstName = firstName;
// this.lastName = lastName;
// this.gender = gender;
// this.paymentMethod = paymentMethod;
// this.balance = balance;
// this.personalWebsite = personalWebsite;
// }
//
// public Integer getId() {
// return this.id;
// }
//
// public void setId(final Integer id) {
// this.id = id;
// }
//
// public int getBalance() {
// return this.balance;
// }
//
// public void setBalance(final int balance) {
// this.balance = balance;
// }
//
// public String getFirstName() {
// return this.firstName;
// }
//
// public void setFirstName(final String firstName) {
// this.firstName = firstName;
// }
//
// public Gender getGender() {
// return this.gender;
// }
//
// public void setGender(final Gender gender) {
// this.gender = gender;
// }
//
// public String getLastName() {
// return this.lastName;
// }
//
// public void setLastName(final String lastName) {
// this.lastName = lastName;
// }
//
// public PaymentMethod getPaymentMethod() {
// return this.paymentMethod;
// }
//
// public void setPaymentMethod(final PaymentMethod paymentMethod) {
// this.paymentMethod = paymentMethod;
// }
//
// public String getPersonalWebsite() {
// return personalWebsite;
// }
//
// public void setPersonalWebsite(String personalWebsite) {
// this.personalWebsite = personalWebsite;
// }
// }
//
// Path: src/main/java/org/thymeleaf/itutorial/IndexController.java
// public static final String THYMELEAF_VERSION_PARAMETER = "thymeleafVersion";
// Path: src/main/java/org/thymeleaf/itutorial/ExerciseController.java
import java.io.IOException;
import javax.servlet.ServletContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.thymeleaf.itutorial.beans.Customer;
import static org.thymeleaf.itutorial.IndexController.THYMELEAF_VERSION_PARAMETER;
/*
* =============================================================================
*
* Copyright (c) 2011-2014, The THYMELEAF team (http://www.thymeleaf.org)
*
* 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.thymeleaf.itutorial;
@Controller
public class ExerciseController {
private static final String CHARSET = "UTF-8";
@Autowired private ServletContext servletContext;
@RequestMapping(value = "/exercise/{index}", method = RequestMethod.GET)
public String exercise(@PathVariable("index") final Integer index, final Model model) throws IOException {
Exercise exercise = Exercise.get(index);
String question = new ExerciseResourceLoader(servletContext, exercise).getResource("question.html", CHARSET);
model.addAttribute("question", question);
model.addAttribute("exercise", exercise);
model.addAttribute("thymeleafVersion", servletContext.getInitParameter(THYMELEAF_VERSION_PARAMETER));
return "exercise.html";
}
// Auxiliar mapping for Exercise 11.
@RequestMapping("/exercise11/product.html")
public String product(@RequestParam("action") String action, Model model) {
model.addAttribute("product", DAO.loadProduct());
if ("view".equals(action)) {
return "/exercise11/viewProduct.html";
} else if ("edit".equals(action)) {
return "/exercise11/editProduct.html";
} else {
throw new IllegalArgumentException("Action -" + action +"- not recognized");
}
}
// Auxiliar mapping for Exercise 12.
@RequestMapping("/exercise12/saveCustomer.html")
|
public String saveCustomer(Customer customer, Model model) {
|
thymeleaf/thymeleaf-itutorial
|
src/main/java/org/thymeleaf/itutorial/DAO.java
|
// Path: src/main/java/org/thymeleaf/itutorial/beans/Customer.java
// public class Customer {
//
// private Integer id;
// private String firstName;
// private String lastName;
// private Gender gender;
// private PaymentMethod paymentMethod;
// private int balance;
// private String personalWebsite;
//
// public Customer() {
// super();
// }
//
// public Customer(
// final Integer id, final String firstName, final String lastName,
// final Gender gender, final PaymentMethod paymentMethod,
// final int balance, final String personalWebsite) {
// super();
// this.id = id;
// this.firstName = firstName;
// this.lastName = lastName;
// this.gender = gender;
// this.paymentMethod = paymentMethod;
// this.balance = balance;
// this.personalWebsite = personalWebsite;
// }
//
// public Integer getId() {
// return this.id;
// }
//
// public void setId(final Integer id) {
// this.id = id;
// }
//
// public int getBalance() {
// return this.balance;
// }
//
// public void setBalance(final int balance) {
// this.balance = balance;
// }
//
// public String getFirstName() {
// return this.firstName;
// }
//
// public void setFirstName(final String firstName) {
// this.firstName = firstName;
// }
//
// public Gender getGender() {
// return this.gender;
// }
//
// public void setGender(final Gender gender) {
// this.gender = gender;
// }
//
// public String getLastName() {
// return this.lastName;
// }
//
// public void setLastName(final String lastName) {
// this.lastName = lastName;
// }
//
// public PaymentMethod getPaymentMethod() {
// return this.paymentMethod;
// }
//
// public void setPaymentMethod(final PaymentMethod paymentMethod) {
// this.paymentMethod = paymentMethod;
// }
//
// public String getPersonalWebsite() {
// return personalWebsite;
// }
//
// public void setPersonalWebsite(String personalWebsite) {
// this.personalWebsite = personalWebsite;
// }
// }
//
// Path: src/main/java/org/thymeleaf/itutorial/beans/Gender.java
// public enum Gender {
//
// FEMALE("Female gender"),
// MALE("Male gender");
//
// private String description;
//
// Gender(final String description) {
// this.description = description;
// }
//
// public String getDescription() {
// return this.description;
// }
//
// }
//
// Path: src/main/java/org/thymeleaf/itutorial/beans/PaymentMethod.java
// public enum PaymentMethod {
//
// CREDIT_CARD("Credit card payment"),
// DIRECT_DEBIT("Direct debit payment"),
// BANK_TRANSFER("Bank transfer payment");
//
// private String description;
//
// PaymentMethod(final String description) {
// this.description = description;
// }
//
// public String getDescription() {
// return this.description;
// }
//
// }
//
// Path: src/main/java/org/thymeleaf/itutorial/beans/Product.java
// public class Product {
//
// private String description;
// private Integer price;
// private Date availableFrom;
//
// public Product(final String description, final Integer price, final Date availableFrom) {
// this.description = description;
// this.price = price;
// this.availableFrom = availableFrom;
// }
//
// public Date getAvailableFrom() {
// return this.availableFrom;
// }
//
// public void setAvailableFrom(final Date availableFrom) {
// this.availableFrom = availableFrom;
// }
//
// public String getDescription() {
// return this.description;
// }
//
// public void setDescription(final String description) {
// this.description = description;
// }
//
// public Integer getPrice() {
// return this.price;
// }
//
// public void setPrice(final Integer price) {
// this.price = price;
// }
//
// }
//
// Path: src/main/java/org/thymeleaf/itutorial/beans/Amount.java
// public class Amount {
//
// private final BigDecimal amount;
//
// public Amount(final BigDecimal amount) {
// this.amount = amount;
// }
//
// public BigDecimal getAmount() {
// return amount;
// }
//
// @Override
// public String toString() {
// return amount.toString();
// }
// }
|
import org.thymeleaf.itutorial.beans.Product;
import org.thymeleaf.itutorial.beans.Amount;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.thymeleaf.itutorial.beans.Customer;
import org.thymeleaf.itutorial.beans.Gender;
import org.thymeleaf.itutorial.beans.PaymentMethod;
|
/*
* =============================================================================
*
* Copyright (c) 2011-2014, The THYMELEAF team (http://www.thymeleaf.org)
*
* 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.thymeleaf.itutorial;
/**
* Mock persistence.
*/
public class DAO {
private static final String NO_WEBSITE = null;
|
// Path: src/main/java/org/thymeleaf/itutorial/beans/Customer.java
// public class Customer {
//
// private Integer id;
// private String firstName;
// private String lastName;
// private Gender gender;
// private PaymentMethod paymentMethod;
// private int balance;
// private String personalWebsite;
//
// public Customer() {
// super();
// }
//
// public Customer(
// final Integer id, final String firstName, final String lastName,
// final Gender gender, final PaymentMethod paymentMethod,
// final int balance, final String personalWebsite) {
// super();
// this.id = id;
// this.firstName = firstName;
// this.lastName = lastName;
// this.gender = gender;
// this.paymentMethod = paymentMethod;
// this.balance = balance;
// this.personalWebsite = personalWebsite;
// }
//
// public Integer getId() {
// return this.id;
// }
//
// public void setId(final Integer id) {
// this.id = id;
// }
//
// public int getBalance() {
// return this.balance;
// }
//
// public void setBalance(final int balance) {
// this.balance = balance;
// }
//
// public String getFirstName() {
// return this.firstName;
// }
//
// public void setFirstName(final String firstName) {
// this.firstName = firstName;
// }
//
// public Gender getGender() {
// return this.gender;
// }
//
// public void setGender(final Gender gender) {
// this.gender = gender;
// }
//
// public String getLastName() {
// return this.lastName;
// }
//
// public void setLastName(final String lastName) {
// this.lastName = lastName;
// }
//
// public PaymentMethod getPaymentMethod() {
// return this.paymentMethod;
// }
//
// public void setPaymentMethod(final PaymentMethod paymentMethod) {
// this.paymentMethod = paymentMethod;
// }
//
// public String getPersonalWebsite() {
// return personalWebsite;
// }
//
// public void setPersonalWebsite(String personalWebsite) {
// this.personalWebsite = personalWebsite;
// }
// }
//
// Path: src/main/java/org/thymeleaf/itutorial/beans/Gender.java
// public enum Gender {
//
// FEMALE("Female gender"),
// MALE("Male gender");
//
// private String description;
//
// Gender(final String description) {
// this.description = description;
// }
//
// public String getDescription() {
// return this.description;
// }
//
// }
//
// Path: src/main/java/org/thymeleaf/itutorial/beans/PaymentMethod.java
// public enum PaymentMethod {
//
// CREDIT_CARD("Credit card payment"),
// DIRECT_DEBIT("Direct debit payment"),
// BANK_TRANSFER("Bank transfer payment");
//
// private String description;
//
// PaymentMethod(final String description) {
// this.description = description;
// }
//
// public String getDescription() {
// return this.description;
// }
//
// }
//
// Path: src/main/java/org/thymeleaf/itutorial/beans/Product.java
// public class Product {
//
// private String description;
// private Integer price;
// private Date availableFrom;
//
// public Product(final String description, final Integer price, final Date availableFrom) {
// this.description = description;
// this.price = price;
// this.availableFrom = availableFrom;
// }
//
// public Date getAvailableFrom() {
// return this.availableFrom;
// }
//
// public void setAvailableFrom(final Date availableFrom) {
// this.availableFrom = availableFrom;
// }
//
// public String getDescription() {
// return this.description;
// }
//
// public void setDescription(final String description) {
// this.description = description;
// }
//
// public Integer getPrice() {
// return this.price;
// }
//
// public void setPrice(final Integer price) {
// this.price = price;
// }
//
// }
//
// Path: src/main/java/org/thymeleaf/itutorial/beans/Amount.java
// public class Amount {
//
// private final BigDecimal amount;
//
// public Amount(final BigDecimal amount) {
// this.amount = amount;
// }
//
// public BigDecimal getAmount() {
// return amount;
// }
//
// @Override
// public String toString() {
// return amount.toString();
// }
// }
// Path: src/main/java/org/thymeleaf/itutorial/DAO.java
import org.thymeleaf.itutorial.beans.Product;
import org.thymeleaf.itutorial.beans.Amount;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.thymeleaf.itutorial.beans.Customer;
import org.thymeleaf.itutorial.beans.Gender;
import org.thymeleaf.itutorial.beans.PaymentMethod;
/*
* =============================================================================
*
* Copyright (c) 2011-2014, The THYMELEAF team (http://www.thymeleaf.org)
*
* 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.thymeleaf.itutorial;
/**
* Mock persistence.
*/
public class DAO {
private static final String NO_WEBSITE = null;
|
public static Product loadProduct() {
|
thymeleaf/thymeleaf-itutorial
|
src/main/java/org/thymeleaf/itutorial/DAO.java
|
// Path: src/main/java/org/thymeleaf/itutorial/beans/Customer.java
// public class Customer {
//
// private Integer id;
// private String firstName;
// private String lastName;
// private Gender gender;
// private PaymentMethod paymentMethod;
// private int balance;
// private String personalWebsite;
//
// public Customer() {
// super();
// }
//
// public Customer(
// final Integer id, final String firstName, final String lastName,
// final Gender gender, final PaymentMethod paymentMethod,
// final int balance, final String personalWebsite) {
// super();
// this.id = id;
// this.firstName = firstName;
// this.lastName = lastName;
// this.gender = gender;
// this.paymentMethod = paymentMethod;
// this.balance = balance;
// this.personalWebsite = personalWebsite;
// }
//
// public Integer getId() {
// return this.id;
// }
//
// public void setId(final Integer id) {
// this.id = id;
// }
//
// public int getBalance() {
// return this.balance;
// }
//
// public void setBalance(final int balance) {
// this.balance = balance;
// }
//
// public String getFirstName() {
// return this.firstName;
// }
//
// public void setFirstName(final String firstName) {
// this.firstName = firstName;
// }
//
// public Gender getGender() {
// return this.gender;
// }
//
// public void setGender(final Gender gender) {
// this.gender = gender;
// }
//
// public String getLastName() {
// return this.lastName;
// }
//
// public void setLastName(final String lastName) {
// this.lastName = lastName;
// }
//
// public PaymentMethod getPaymentMethod() {
// return this.paymentMethod;
// }
//
// public void setPaymentMethod(final PaymentMethod paymentMethod) {
// this.paymentMethod = paymentMethod;
// }
//
// public String getPersonalWebsite() {
// return personalWebsite;
// }
//
// public void setPersonalWebsite(String personalWebsite) {
// this.personalWebsite = personalWebsite;
// }
// }
//
// Path: src/main/java/org/thymeleaf/itutorial/beans/Gender.java
// public enum Gender {
//
// FEMALE("Female gender"),
// MALE("Male gender");
//
// private String description;
//
// Gender(final String description) {
// this.description = description;
// }
//
// public String getDescription() {
// return this.description;
// }
//
// }
//
// Path: src/main/java/org/thymeleaf/itutorial/beans/PaymentMethod.java
// public enum PaymentMethod {
//
// CREDIT_CARD("Credit card payment"),
// DIRECT_DEBIT("Direct debit payment"),
// BANK_TRANSFER("Bank transfer payment");
//
// private String description;
//
// PaymentMethod(final String description) {
// this.description = description;
// }
//
// public String getDescription() {
// return this.description;
// }
//
// }
//
// Path: src/main/java/org/thymeleaf/itutorial/beans/Product.java
// public class Product {
//
// private String description;
// private Integer price;
// private Date availableFrom;
//
// public Product(final String description, final Integer price, final Date availableFrom) {
// this.description = description;
// this.price = price;
// this.availableFrom = availableFrom;
// }
//
// public Date getAvailableFrom() {
// return this.availableFrom;
// }
//
// public void setAvailableFrom(final Date availableFrom) {
// this.availableFrom = availableFrom;
// }
//
// public String getDescription() {
// return this.description;
// }
//
// public void setDescription(final String description) {
// this.description = description;
// }
//
// public Integer getPrice() {
// return this.price;
// }
//
// public void setPrice(final Integer price) {
// this.price = price;
// }
//
// }
//
// Path: src/main/java/org/thymeleaf/itutorial/beans/Amount.java
// public class Amount {
//
// private final BigDecimal amount;
//
// public Amount(final BigDecimal amount) {
// this.amount = amount;
// }
//
// public BigDecimal getAmount() {
// return amount;
// }
//
// @Override
// public String toString() {
// return amount.toString();
// }
// }
|
import org.thymeleaf.itutorial.beans.Product;
import org.thymeleaf.itutorial.beans.Amount;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.thymeleaf.itutorial.beans.Customer;
import org.thymeleaf.itutorial.beans.Gender;
import org.thymeleaf.itutorial.beans.PaymentMethod;
|
public static Product loadProduct() {
try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
return new Product("Wooden wardrobe with glass doors", Integer.valueOf(850), sdf.parse("2013-02-18"));
} catch (ParseException ex) {
throw new RuntimeException("Invalid date");
}
}
public static List<Product> loadAllProducts() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
List<Product> products = new ArrayList<Product>();
try {
products.add(new Product("Chair", Integer.valueOf(25), sdf.parse("2013-02-18")));
products.add(new Product("Table", Integer.valueOf(150), sdf.parse("2013-02-15")));
products.add(new Product("Armchair", Integer.valueOf(85), sdf.parse("2013-02-20")));
products.add(new Product("Wardrobe", Integer.valueOf(450), sdf.parse("2013-02-21")));
products.add(new Product("Kitchen table", Integer.valueOf(49), sdf.parse("2013-02-15")));
products.add(new Product("Bookcase", Integer.valueOf(80), sdf.parse("2013-02-17")));
} catch (ParseException ex) {
throw new RuntimeException("Invalid date");
}
return products;
}
public static Customer loadCustomer() {
Customer customer = new Customer();
customer.setId(Integer.valueOf(1085));
customer.setFirstName("Peter");
customer.setLastName("Jackson");
|
// Path: src/main/java/org/thymeleaf/itutorial/beans/Customer.java
// public class Customer {
//
// private Integer id;
// private String firstName;
// private String lastName;
// private Gender gender;
// private PaymentMethod paymentMethod;
// private int balance;
// private String personalWebsite;
//
// public Customer() {
// super();
// }
//
// public Customer(
// final Integer id, final String firstName, final String lastName,
// final Gender gender, final PaymentMethod paymentMethod,
// final int balance, final String personalWebsite) {
// super();
// this.id = id;
// this.firstName = firstName;
// this.lastName = lastName;
// this.gender = gender;
// this.paymentMethod = paymentMethod;
// this.balance = balance;
// this.personalWebsite = personalWebsite;
// }
//
// public Integer getId() {
// return this.id;
// }
//
// public void setId(final Integer id) {
// this.id = id;
// }
//
// public int getBalance() {
// return this.balance;
// }
//
// public void setBalance(final int balance) {
// this.balance = balance;
// }
//
// public String getFirstName() {
// return this.firstName;
// }
//
// public void setFirstName(final String firstName) {
// this.firstName = firstName;
// }
//
// public Gender getGender() {
// return this.gender;
// }
//
// public void setGender(final Gender gender) {
// this.gender = gender;
// }
//
// public String getLastName() {
// return this.lastName;
// }
//
// public void setLastName(final String lastName) {
// this.lastName = lastName;
// }
//
// public PaymentMethod getPaymentMethod() {
// return this.paymentMethod;
// }
//
// public void setPaymentMethod(final PaymentMethod paymentMethod) {
// this.paymentMethod = paymentMethod;
// }
//
// public String getPersonalWebsite() {
// return personalWebsite;
// }
//
// public void setPersonalWebsite(String personalWebsite) {
// this.personalWebsite = personalWebsite;
// }
// }
//
// Path: src/main/java/org/thymeleaf/itutorial/beans/Gender.java
// public enum Gender {
//
// FEMALE("Female gender"),
// MALE("Male gender");
//
// private String description;
//
// Gender(final String description) {
// this.description = description;
// }
//
// public String getDescription() {
// return this.description;
// }
//
// }
//
// Path: src/main/java/org/thymeleaf/itutorial/beans/PaymentMethod.java
// public enum PaymentMethod {
//
// CREDIT_CARD("Credit card payment"),
// DIRECT_DEBIT("Direct debit payment"),
// BANK_TRANSFER("Bank transfer payment");
//
// private String description;
//
// PaymentMethod(final String description) {
// this.description = description;
// }
//
// public String getDescription() {
// return this.description;
// }
//
// }
//
// Path: src/main/java/org/thymeleaf/itutorial/beans/Product.java
// public class Product {
//
// private String description;
// private Integer price;
// private Date availableFrom;
//
// public Product(final String description, final Integer price, final Date availableFrom) {
// this.description = description;
// this.price = price;
// this.availableFrom = availableFrom;
// }
//
// public Date getAvailableFrom() {
// return this.availableFrom;
// }
//
// public void setAvailableFrom(final Date availableFrom) {
// this.availableFrom = availableFrom;
// }
//
// public String getDescription() {
// return this.description;
// }
//
// public void setDescription(final String description) {
// this.description = description;
// }
//
// public Integer getPrice() {
// return this.price;
// }
//
// public void setPrice(final Integer price) {
// this.price = price;
// }
//
// }
//
// Path: src/main/java/org/thymeleaf/itutorial/beans/Amount.java
// public class Amount {
//
// private final BigDecimal amount;
//
// public Amount(final BigDecimal amount) {
// this.amount = amount;
// }
//
// public BigDecimal getAmount() {
// return amount;
// }
//
// @Override
// public String toString() {
// return amount.toString();
// }
// }
// Path: src/main/java/org/thymeleaf/itutorial/DAO.java
import org.thymeleaf.itutorial.beans.Product;
import org.thymeleaf.itutorial.beans.Amount;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.thymeleaf.itutorial.beans.Customer;
import org.thymeleaf.itutorial.beans.Gender;
import org.thymeleaf.itutorial.beans.PaymentMethod;
public static Product loadProduct() {
try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
return new Product("Wooden wardrobe with glass doors", Integer.valueOf(850), sdf.parse("2013-02-18"));
} catch (ParseException ex) {
throw new RuntimeException("Invalid date");
}
}
public static List<Product> loadAllProducts() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
List<Product> products = new ArrayList<Product>();
try {
products.add(new Product("Chair", Integer.valueOf(25), sdf.parse("2013-02-18")));
products.add(new Product("Table", Integer.valueOf(150), sdf.parse("2013-02-15")));
products.add(new Product("Armchair", Integer.valueOf(85), sdf.parse("2013-02-20")));
products.add(new Product("Wardrobe", Integer.valueOf(450), sdf.parse("2013-02-21")));
products.add(new Product("Kitchen table", Integer.valueOf(49), sdf.parse("2013-02-15")));
products.add(new Product("Bookcase", Integer.valueOf(80), sdf.parse("2013-02-17")));
} catch (ParseException ex) {
throw new RuntimeException("Invalid date");
}
return products;
}
public static Customer loadCustomer() {
Customer customer = new Customer();
customer.setId(Integer.valueOf(1085));
customer.setFirstName("Peter");
customer.setLastName("Jackson");
|
customer.setGender(Gender.MALE);
|
thymeleaf/thymeleaf-itutorial
|
src/main/java/org/thymeleaf/itutorial/DAO.java
|
// Path: src/main/java/org/thymeleaf/itutorial/beans/Customer.java
// public class Customer {
//
// private Integer id;
// private String firstName;
// private String lastName;
// private Gender gender;
// private PaymentMethod paymentMethod;
// private int balance;
// private String personalWebsite;
//
// public Customer() {
// super();
// }
//
// public Customer(
// final Integer id, final String firstName, final String lastName,
// final Gender gender, final PaymentMethod paymentMethod,
// final int balance, final String personalWebsite) {
// super();
// this.id = id;
// this.firstName = firstName;
// this.lastName = lastName;
// this.gender = gender;
// this.paymentMethod = paymentMethod;
// this.balance = balance;
// this.personalWebsite = personalWebsite;
// }
//
// public Integer getId() {
// return this.id;
// }
//
// public void setId(final Integer id) {
// this.id = id;
// }
//
// public int getBalance() {
// return this.balance;
// }
//
// public void setBalance(final int balance) {
// this.balance = balance;
// }
//
// public String getFirstName() {
// return this.firstName;
// }
//
// public void setFirstName(final String firstName) {
// this.firstName = firstName;
// }
//
// public Gender getGender() {
// return this.gender;
// }
//
// public void setGender(final Gender gender) {
// this.gender = gender;
// }
//
// public String getLastName() {
// return this.lastName;
// }
//
// public void setLastName(final String lastName) {
// this.lastName = lastName;
// }
//
// public PaymentMethod getPaymentMethod() {
// return this.paymentMethod;
// }
//
// public void setPaymentMethod(final PaymentMethod paymentMethod) {
// this.paymentMethod = paymentMethod;
// }
//
// public String getPersonalWebsite() {
// return personalWebsite;
// }
//
// public void setPersonalWebsite(String personalWebsite) {
// this.personalWebsite = personalWebsite;
// }
// }
//
// Path: src/main/java/org/thymeleaf/itutorial/beans/Gender.java
// public enum Gender {
//
// FEMALE("Female gender"),
// MALE("Male gender");
//
// private String description;
//
// Gender(final String description) {
// this.description = description;
// }
//
// public String getDescription() {
// return this.description;
// }
//
// }
//
// Path: src/main/java/org/thymeleaf/itutorial/beans/PaymentMethod.java
// public enum PaymentMethod {
//
// CREDIT_CARD("Credit card payment"),
// DIRECT_DEBIT("Direct debit payment"),
// BANK_TRANSFER("Bank transfer payment");
//
// private String description;
//
// PaymentMethod(final String description) {
// this.description = description;
// }
//
// public String getDescription() {
// return this.description;
// }
//
// }
//
// Path: src/main/java/org/thymeleaf/itutorial/beans/Product.java
// public class Product {
//
// private String description;
// private Integer price;
// private Date availableFrom;
//
// public Product(final String description, final Integer price, final Date availableFrom) {
// this.description = description;
// this.price = price;
// this.availableFrom = availableFrom;
// }
//
// public Date getAvailableFrom() {
// return this.availableFrom;
// }
//
// public void setAvailableFrom(final Date availableFrom) {
// this.availableFrom = availableFrom;
// }
//
// public String getDescription() {
// return this.description;
// }
//
// public void setDescription(final String description) {
// this.description = description;
// }
//
// public Integer getPrice() {
// return this.price;
// }
//
// public void setPrice(final Integer price) {
// this.price = price;
// }
//
// }
//
// Path: src/main/java/org/thymeleaf/itutorial/beans/Amount.java
// public class Amount {
//
// private final BigDecimal amount;
//
// public Amount(final BigDecimal amount) {
// this.amount = amount;
// }
//
// public BigDecimal getAmount() {
// return amount;
// }
//
// @Override
// public String toString() {
// return amount.toString();
// }
// }
|
import org.thymeleaf.itutorial.beans.Product;
import org.thymeleaf.itutorial.beans.Amount;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.thymeleaf.itutorial.beans.Customer;
import org.thymeleaf.itutorial.beans.Gender;
import org.thymeleaf.itutorial.beans.PaymentMethod;
|
try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
return new Product("Wooden wardrobe with glass doors", Integer.valueOf(850), sdf.parse("2013-02-18"));
} catch (ParseException ex) {
throw new RuntimeException("Invalid date");
}
}
public static List<Product> loadAllProducts() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
List<Product> products = new ArrayList<Product>();
try {
products.add(new Product("Chair", Integer.valueOf(25), sdf.parse("2013-02-18")));
products.add(new Product("Table", Integer.valueOf(150), sdf.parse("2013-02-15")));
products.add(new Product("Armchair", Integer.valueOf(85), sdf.parse("2013-02-20")));
products.add(new Product("Wardrobe", Integer.valueOf(450), sdf.parse("2013-02-21")));
products.add(new Product("Kitchen table", Integer.valueOf(49), sdf.parse("2013-02-15")));
products.add(new Product("Bookcase", Integer.valueOf(80), sdf.parse("2013-02-17")));
} catch (ParseException ex) {
throw new RuntimeException("Invalid date");
}
return products;
}
public static Customer loadCustomer() {
Customer customer = new Customer();
customer.setId(Integer.valueOf(1085));
customer.setFirstName("Peter");
customer.setLastName("Jackson");
customer.setGender(Gender.MALE);
|
// Path: src/main/java/org/thymeleaf/itutorial/beans/Customer.java
// public class Customer {
//
// private Integer id;
// private String firstName;
// private String lastName;
// private Gender gender;
// private PaymentMethod paymentMethod;
// private int balance;
// private String personalWebsite;
//
// public Customer() {
// super();
// }
//
// public Customer(
// final Integer id, final String firstName, final String lastName,
// final Gender gender, final PaymentMethod paymentMethod,
// final int balance, final String personalWebsite) {
// super();
// this.id = id;
// this.firstName = firstName;
// this.lastName = lastName;
// this.gender = gender;
// this.paymentMethod = paymentMethod;
// this.balance = balance;
// this.personalWebsite = personalWebsite;
// }
//
// public Integer getId() {
// return this.id;
// }
//
// public void setId(final Integer id) {
// this.id = id;
// }
//
// public int getBalance() {
// return this.balance;
// }
//
// public void setBalance(final int balance) {
// this.balance = balance;
// }
//
// public String getFirstName() {
// return this.firstName;
// }
//
// public void setFirstName(final String firstName) {
// this.firstName = firstName;
// }
//
// public Gender getGender() {
// return this.gender;
// }
//
// public void setGender(final Gender gender) {
// this.gender = gender;
// }
//
// public String getLastName() {
// return this.lastName;
// }
//
// public void setLastName(final String lastName) {
// this.lastName = lastName;
// }
//
// public PaymentMethod getPaymentMethod() {
// return this.paymentMethod;
// }
//
// public void setPaymentMethod(final PaymentMethod paymentMethod) {
// this.paymentMethod = paymentMethod;
// }
//
// public String getPersonalWebsite() {
// return personalWebsite;
// }
//
// public void setPersonalWebsite(String personalWebsite) {
// this.personalWebsite = personalWebsite;
// }
// }
//
// Path: src/main/java/org/thymeleaf/itutorial/beans/Gender.java
// public enum Gender {
//
// FEMALE("Female gender"),
// MALE("Male gender");
//
// private String description;
//
// Gender(final String description) {
// this.description = description;
// }
//
// public String getDescription() {
// return this.description;
// }
//
// }
//
// Path: src/main/java/org/thymeleaf/itutorial/beans/PaymentMethod.java
// public enum PaymentMethod {
//
// CREDIT_CARD("Credit card payment"),
// DIRECT_DEBIT("Direct debit payment"),
// BANK_TRANSFER("Bank transfer payment");
//
// private String description;
//
// PaymentMethod(final String description) {
// this.description = description;
// }
//
// public String getDescription() {
// return this.description;
// }
//
// }
//
// Path: src/main/java/org/thymeleaf/itutorial/beans/Product.java
// public class Product {
//
// private String description;
// private Integer price;
// private Date availableFrom;
//
// public Product(final String description, final Integer price, final Date availableFrom) {
// this.description = description;
// this.price = price;
// this.availableFrom = availableFrom;
// }
//
// public Date getAvailableFrom() {
// return this.availableFrom;
// }
//
// public void setAvailableFrom(final Date availableFrom) {
// this.availableFrom = availableFrom;
// }
//
// public String getDescription() {
// return this.description;
// }
//
// public void setDescription(final String description) {
// this.description = description;
// }
//
// public Integer getPrice() {
// return this.price;
// }
//
// public void setPrice(final Integer price) {
// this.price = price;
// }
//
// }
//
// Path: src/main/java/org/thymeleaf/itutorial/beans/Amount.java
// public class Amount {
//
// private final BigDecimal amount;
//
// public Amount(final BigDecimal amount) {
// this.amount = amount;
// }
//
// public BigDecimal getAmount() {
// return amount;
// }
//
// @Override
// public String toString() {
// return amount.toString();
// }
// }
// Path: src/main/java/org/thymeleaf/itutorial/DAO.java
import org.thymeleaf.itutorial.beans.Product;
import org.thymeleaf.itutorial.beans.Amount;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.thymeleaf.itutorial.beans.Customer;
import org.thymeleaf.itutorial.beans.Gender;
import org.thymeleaf.itutorial.beans.PaymentMethod;
try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
return new Product("Wooden wardrobe with glass doors", Integer.valueOf(850), sdf.parse("2013-02-18"));
} catch (ParseException ex) {
throw new RuntimeException("Invalid date");
}
}
public static List<Product> loadAllProducts() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
List<Product> products = new ArrayList<Product>();
try {
products.add(new Product("Chair", Integer.valueOf(25), sdf.parse("2013-02-18")));
products.add(new Product("Table", Integer.valueOf(150), sdf.parse("2013-02-15")));
products.add(new Product("Armchair", Integer.valueOf(85), sdf.parse("2013-02-20")));
products.add(new Product("Wardrobe", Integer.valueOf(450), sdf.parse("2013-02-21")));
products.add(new Product("Kitchen table", Integer.valueOf(49), sdf.parse("2013-02-15")));
products.add(new Product("Bookcase", Integer.valueOf(80), sdf.parse("2013-02-17")));
} catch (ParseException ex) {
throw new RuntimeException("Invalid date");
}
return products;
}
public static Customer loadCustomer() {
Customer customer = new Customer();
customer.setId(Integer.valueOf(1085));
customer.setFirstName("Peter");
customer.setLastName("Jackson");
customer.setGender(Gender.MALE);
|
customer.setPaymentMethod(PaymentMethod.DIRECT_DEBIT);
|
thymeleaf/thymeleaf-itutorial
|
src/main/java/org/thymeleaf/itutorial/TemplateExecutor.java
|
// Path: src/main/java/org/thymeleaf/itutorial/beans/Gender.java
// public enum Gender {
//
// FEMALE("Female gender"),
// MALE("Male gender");
//
// private String description;
//
// Gender(final String description) {
// this.description = description;
// }
//
// public String getDescription() {
// return this.description;
// }
//
// }
//
// Path: src/main/java/org/thymeleaf/itutorial/beans/PaymentMethod.java
// public enum PaymentMethod {
//
// CREDIT_CARD("Credit card payment"),
// DIRECT_DEBIT("Direct debit payment"),
// BANK_TRANSFER("Bank transfer payment");
//
// private String description;
//
// PaymentMethod(final String description) {
// this.description = description;
// }
//
// public String getDescription() {
// return this.description;
// }
//
// }
//
// Path: src/main/java/org/thymeleaf/tools/memoryexecutor/StaticTemplateExecutor.java
// public class StaticTemplateExecutor {
//
// private static final String TEMPLATE_NAME = "custom";
//
// private final String templateMode;
//
// private final IContext context;
//
// private final IMessageResolver messageResolver;
//
// public StaticTemplateExecutor(final IContext context, final IMessageResolver messageResolver, final String templateMode) {
// Validate.notNull(context, "Context must be non-null");
// Validate.notNull(templateMode, "Template mode must be non-null");
// Validate.notNull(messageResolver, "MessageResolver must be non-null");
// this.context = context;
// this.templateMode = templateMode;
// this.messageResolver = messageResolver;
// }
//
// public String processTemplateCode(final String code) {
// Validate.notNull(code, "Code must be non-null");
// ITemplateResolver templateResolver = new MemoryTemplateResolver(code, templateMode);
// SpringTemplateEngine templateEngine = new SpringTemplateEngine();
// templateEngine.setMessageResolver(messageResolver);
// templateEngine.setTemplateResolver(templateResolver);
// templateEngine.initialize();
// return templateEngine.process(TEMPLATE_NAME, context);
// }
// }
|
import org.thymeleaf.templatemode.StandardTemplateModeHandlers;
import org.thymeleaf.tools.memoryexecutor.StaticTemplateExecutor;
import java.util.Locale;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.context.ApplicationContext;
import org.springframework.context.MessageSource;
import org.springframework.core.convert.ConversionService;
import org.thymeleaf.context.IWebContext;
import org.thymeleaf.itutorial.beans.Gender;
import org.thymeleaf.itutorial.beans.PaymentMethod;
import org.thymeleaf.spring3.messageresolver.SpringMessageResolver;
|
/*
* =============================================================================
*
* Copyright (c) 2011-2014, The THYMELEAF team (http://www.thymeleaf.org)
*
* 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.thymeleaf.itutorial;
public class TemplateExecutor {
private final StaticTemplateExecutor executor;
public TemplateExecutor(
final HttpServletRequest request, final HttpServletResponse response,
final ServletContext servletContext, final MessageSource messageSource,
final Locale locale, final ApplicationContext applicationContext,
final ConversionService conversionService) {
IWebContext context = new OfflineSpringWebContext(request, response, servletContext, applicationContext, conversionService);
// Model attributes
context.getVariables().put("product", DAO.loadProduct());
context.getVariables().put("productList", DAO.loadAllProducts());
context.getVariables().put("html", "This is an <em>HTML</em> text. <b>Enjoy yourself!</b>");
context.getVariables().put("customer", DAO.loadCustomer());
context.getVariables().put("customerName", "Dr. Julius Erwing");
context.getVariables().put("customerList", DAO.loadAllCustomers());
|
// Path: src/main/java/org/thymeleaf/itutorial/beans/Gender.java
// public enum Gender {
//
// FEMALE("Female gender"),
// MALE("Male gender");
//
// private String description;
//
// Gender(final String description) {
// this.description = description;
// }
//
// public String getDescription() {
// return this.description;
// }
//
// }
//
// Path: src/main/java/org/thymeleaf/itutorial/beans/PaymentMethod.java
// public enum PaymentMethod {
//
// CREDIT_CARD("Credit card payment"),
// DIRECT_DEBIT("Direct debit payment"),
// BANK_TRANSFER("Bank transfer payment");
//
// private String description;
//
// PaymentMethod(final String description) {
// this.description = description;
// }
//
// public String getDescription() {
// return this.description;
// }
//
// }
//
// Path: src/main/java/org/thymeleaf/tools/memoryexecutor/StaticTemplateExecutor.java
// public class StaticTemplateExecutor {
//
// private static final String TEMPLATE_NAME = "custom";
//
// private final String templateMode;
//
// private final IContext context;
//
// private final IMessageResolver messageResolver;
//
// public StaticTemplateExecutor(final IContext context, final IMessageResolver messageResolver, final String templateMode) {
// Validate.notNull(context, "Context must be non-null");
// Validate.notNull(templateMode, "Template mode must be non-null");
// Validate.notNull(messageResolver, "MessageResolver must be non-null");
// this.context = context;
// this.templateMode = templateMode;
// this.messageResolver = messageResolver;
// }
//
// public String processTemplateCode(final String code) {
// Validate.notNull(code, "Code must be non-null");
// ITemplateResolver templateResolver = new MemoryTemplateResolver(code, templateMode);
// SpringTemplateEngine templateEngine = new SpringTemplateEngine();
// templateEngine.setMessageResolver(messageResolver);
// templateEngine.setTemplateResolver(templateResolver);
// templateEngine.initialize();
// return templateEngine.process(TEMPLATE_NAME, context);
// }
// }
// Path: src/main/java/org/thymeleaf/itutorial/TemplateExecutor.java
import org.thymeleaf.templatemode.StandardTemplateModeHandlers;
import org.thymeleaf.tools.memoryexecutor.StaticTemplateExecutor;
import java.util.Locale;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.context.ApplicationContext;
import org.springframework.context.MessageSource;
import org.springframework.core.convert.ConversionService;
import org.thymeleaf.context.IWebContext;
import org.thymeleaf.itutorial.beans.Gender;
import org.thymeleaf.itutorial.beans.PaymentMethod;
import org.thymeleaf.spring3.messageresolver.SpringMessageResolver;
/*
* =============================================================================
*
* Copyright (c) 2011-2014, The THYMELEAF team (http://www.thymeleaf.org)
*
* 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.thymeleaf.itutorial;
public class TemplateExecutor {
private final StaticTemplateExecutor executor;
public TemplateExecutor(
final HttpServletRequest request, final HttpServletResponse response,
final ServletContext servletContext, final MessageSource messageSource,
final Locale locale, final ApplicationContext applicationContext,
final ConversionService conversionService) {
IWebContext context = new OfflineSpringWebContext(request, response, servletContext, applicationContext, conversionService);
// Model attributes
context.getVariables().put("product", DAO.loadProduct());
context.getVariables().put("productList", DAO.loadAllProducts());
context.getVariables().put("html", "This is an <em>HTML</em> text. <b>Enjoy yourself!</b>");
context.getVariables().put("customer", DAO.loadCustomer());
context.getVariables().put("customerName", "Dr. Julius Erwing");
context.getVariables().put("customerList", DAO.loadAllCustomers());
|
context.getVariables().put("genders", Gender.values());
|
thymeleaf/thymeleaf-itutorial
|
src/main/java/org/thymeleaf/itutorial/TemplateExecutor.java
|
// Path: src/main/java/org/thymeleaf/itutorial/beans/Gender.java
// public enum Gender {
//
// FEMALE("Female gender"),
// MALE("Male gender");
//
// private String description;
//
// Gender(final String description) {
// this.description = description;
// }
//
// public String getDescription() {
// return this.description;
// }
//
// }
//
// Path: src/main/java/org/thymeleaf/itutorial/beans/PaymentMethod.java
// public enum PaymentMethod {
//
// CREDIT_CARD("Credit card payment"),
// DIRECT_DEBIT("Direct debit payment"),
// BANK_TRANSFER("Bank transfer payment");
//
// private String description;
//
// PaymentMethod(final String description) {
// this.description = description;
// }
//
// public String getDescription() {
// return this.description;
// }
//
// }
//
// Path: src/main/java/org/thymeleaf/tools/memoryexecutor/StaticTemplateExecutor.java
// public class StaticTemplateExecutor {
//
// private static final String TEMPLATE_NAME = "custom";
//
// private final String templateMode;
//
// private final IContext context;
//
// private final IMessageResolver messageResolver;
//
// public StaticTemplateExecutor(final IContext context, final IMessageResolver messageResolver, final String templateMode) {
// Validate.notNull(context, "Context must be non-null");
// Validate.notNull(templateMode, "Template mode must be non-null");
// Validate.notNull(messageResolver, "MessageResolver must be non-null");
// this.context = context;
// this.templateMode = templateMode;
// this.messageResolver = messageResolver;
// }
//
// public String processTemplateCode(final String code) {
// Validate.notNull(code, "Code must be non-null");
// ITemplateResolver templateResolver = new MemoryTemplateResolver(code, templateMode);
// SpringTemplateEngine templateEngine = new SpringTemplateEngine();
// templateEngine.setMessageResolver(messageResolver);
// templateEngine.setTemplateResolver(templateResolver);
// templateEngine.initialize();
// return templateEngine.process(TEMPLATE_NAME, context);
// }
// }
|
import org.thymeleaf.templatemode.StandardTemplateModeHandlers;
import org.thymeleaf.tools.memoryexecutor.StaticTemplateExecutor;
import java.util.Locale;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.context.ApplicationContext;
import org.springframework.context.MessageSource;
import org.springframework.core.convert.ConversionService;
import org.thymeleaf.context.IWebContext;
import org.thymeleaf.itutorial.beans.Gender;
import org.thymeleaf.itutorial.beans.PaymentMethod;
import org.thymeleaf.spring3.messageresolver.SpringMessageResolver;
|
/*
* =============================================================================
*
* Copyright (c) 2011-2014, The THYMELEAF team (http://www.thymeleaf.org)
*
* 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.thymeleaf.itutorial;
public class TemplateExecutor {
private final StaticTemplateExecutor executor;
public TemplateExecutor(
final HttpServletRequest request, final HttpServletResponse response,
final ServletContext servletContext, final MessageSource messageSource,
final Locale locale, final ApplicationContext applicationContext,
final ConversionService conversionService) {
IWebContext context = new OfflineSpringWebContext(request, response, servletContext, applicationContext, conversionService);
// Model attributes
context.getVariables().put("product", DAO.loadProduct());
context.getVariables().put("productList", DAO.loadAllProducts());
context.getVariables().put("html", "This is an <em>HTML</em> text. <b>Enjoy yourself!</b>");
context.getVariables().put("customer", DAO.loadCustomer());
context.getVariables().put("customerName", "Dr. Julius Erwing");
context.getVariables().put("customerList", DAO.loadAllCustomers());
context.getVariables().put("genders", Gender.values());
|
// Path: src/main/java/org/thymeleaf/itutorial/beans/Gender.java
// public enum Gender {
//
// FEMALE("Female gender"),
// MALE("Male gender");
//
// private String description;
//
// Gender(final String description) {
// this.description = description;
// }
//
// public String getDescription() {
// return this.description;
// }
//
// }
//
// Path: src/main/java/org/thymeleaf/itutorial/beans/PaymentMethod.java
// public enum PaymentMethod {
//
// CREDIT_CARD("Credit card payment"),
// DIRECT_DEBIT("Direct debit payment"),
// BANK_TRANSFER("Bank transfer payment");
//
// private String description;
//
// PaymentMethod(final String description) {
// this.description = description;
// }
//
// public String getDescription() {
// return this.description;
// }
//
// }
//
// Path: src/main/java/org/thymeleaf/tools/memoryexecutor/StaticTemplateExecutor.java
// public class StaticTemplateExecutor {
//
// private static final String TEMPLATE_NAME = "custom";
//
// private final String templateMode;
//
// private final IContext context;
//
// private final IMessageResolver messageResolver;
//
// public StaticTemplateExecutor(final IContext context, final IMessageResolver messageResolver, final String templateMode) {
// Validate.notNull(context, "Context must be non-null");
// Validate.notNull(templateMode, "Template mode must be non-null");
// Validate.notNull(messageResolver, "MessageResolver must be non-null");
// this.context = context;
// this.templateMode = templateMode;
// this.messageResolver = messageResolver;
// }
//
// public String processTemplateCode(final String code) {
// Validate.notNull(code, "Code must be non-null");
// ITemplateResolver templateResolver = new MemoryTemplateResolver(code, templateMode);
// SpringTemplateEngine templateEngine = new SpringTemplateEngine();
// templateEngine.setMessageResolver(messageResolver);
// templateEngine.setTemplateResolver(templateResolver);
// templateEngine.initialize();
// return templateEngine.process(TEMPLATE_NAME, context);
// }
// }
// Path: src/main/java/org/thymeleaf/itutorial/TemplateExecutor.java
import org.thymeleaf.templatemode.StandardTemplateModeHandlers;
import org.thymeleaf.tools.memoryexecutor.StaticTemplateExecutor;
import java.util.Locale;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.context.ApplicationContext;
import org.springframework.context.MessageSource;
import org.springframework.core.convert.ConversionService;
import org.thymeleaf.context.IWebContext;
import org.thymeleaf.itutorial.beans.Gender;
import org.thymeleaf.itutorial.beans.PaymentMethod;
import org.thymeleaf.spring3.messageresolver.SpringMessageResolver;
/*
* =============================================================================
*
* Copyright (c) 2011-2014, The THYMELEAF team (http://www.thymeleaf.org)
*
* 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.thymeleaf.itutorial;
public class TemplateExecutor {
private final StaticTemplateExecutor executor;
public TemplateExecutor(
final HttpServletRequest request, final HttpServletResponse response,
final ServletContext servletContext, final MessageSource messageSource,
final Locale locale, final ApplicationContext applicationContext,
final ConversionService conversionService) {
IWebContext context = new OfflineSpringWebContext(request, response, servletContext, applicationContext, conversionService);
// Model attributes
context.getVariables().put("product", DAO.loadProduct());
context.getVariables().put("productList", DAO.loadAllProducts());
context.getVariables().put("html", "This is an <em>HTML</em> text. <b>Enjoy yourself!</b>");
context.getVariables().put("customer", DAO.loadCustomer());
context.getVariables().put("customerName", "Dr. Julius Erwing");
context.getVariables().put("customerList", DAO.loadAllCustomers());
context.getVariables().put("genders", Gender.values());
|
context.getVariables().put("paymentMethods", PaymentMethod.values());
|
thymeleaf/thymeleaf-itutorial
|
src/main/java/org/thymeleaf/itutorial/Exercise.java
|
// Path: src/main/java/org/thymeleaf/itutorial/ModelAttribute.java
// public enum ModelAttribute {
//
// PRODUCT("product", "code/Product.java"),
// PRODUCT_LIST("productList", "code/Product.java"),
// HTML("html", null),
// CUSTOMER_NAME("customerName", null),
// CUSTOMER("customer", "code/Customer.java"),
// CUSTOMER_LIST("customerList", "code/Customer.java"),
// GENDER("(Gender.java)", "code/Gender.java"),
// PAYMENT_METHOD("(PaymentMethod.java)", "code/PaymentMethod.java"),
// MESSAGES_EN("(messages_en)", "classes/messages_en.properties"),
// MESSAGES_ES("(messages_es)", "classes/messages_es.properties"),
// MESSAGES_FR("(messages_fr)", "classes/messages_fr.properties"),
// AMOUNT("price", "code/Amount.java"),
// RELEASE_DATE("releaseDate", null),
// PRODUCT_ID("productId", null),
// PRODUCT_NAME("productName", null);
//
// private final String name;
// private final String file;
//
// private ModelAttribute(String name, String file) {
// this.name = name;
// this.file = file;
// }
//
// public String getName() {
// return name;
// }
//
// public String getFile() {
// return file;
// }
// }
|
import static org.thymeleaf.itutorial.ModelAttribute.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
|
/*
* =============================================================================
*
* Copyright (c) 2011-2014, The THYMELEAF team (http://www.thymeleaf.org)
*
* 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.thymeleaf.itutorial;
public enum Exercise {
EXERCISE01("exercise01", "Exercise 1: bean values", false, Arrays.asList(PRODUCT)),
EXERCISE02("exercise02", "Exercise 2: simple formatting", false, Arrays.asList(PRODUCT)),
EXERCISE03("exercise03", "Exercise 3: string concatenation", false, Arrays.asList(PRODUCT)),
EXERCISE04("exercise04", "Exercise 4: internationalization", true, Arrays.asList(MESSAGES_EN, MESSAGES_ES, MESSAGES_FR)),
EXERCISE05("exercise05", "Exercise 5: escaped and unescaped text", false, Arrays.asList(HTML)),
EXERCISE06("exercise06", "Exercise 6: iteration", false, Arrays.asList(PRODUCT_LIST)),
EXERCISE07("exercise07", "Exercise 7: iteration stats", false, Arrays.asList(PRODUCT_LIST)),
EXERCISE08("exercise08", "Exercise 8: conditions", false, Arrays.asList(PRODUCT_LIST)),
EXERCISE09("exercise09", "Exercise 9: more on conditions", false, Arrays.asList(CUSTOMER_LIST, GENDER, PAYMENT_METHOD)),
EXERCISE10("exercise10", "Exercise 10: Spring expression language", false, new ArrayList()),
EXERCISE11("exercise11", "Exercise 11: links", false, new ArrayList()),
EXERCISE12("exercise12", "Exercise 12: forms", false, Arrays.asList(CUSTOMER, GENDER, PAYMENT_METHOD)),
EXERCISE13("exercise13", "Exercise 13: inlining", false, Arrays.asList(CUSTOMER_NAME)),
EXERCISE14("exercise14", "Exercise 14: same template fragments", false, new ArrayList()),
EXERCISE15("exercise15", "Exercise 15: parameterizable fragments", false, new ArrayList()),
EXERCISE16("exercise16", "Exercise 16: literal substitutions", false, Arrays.asList(CUSTOMER_NAME)),
EXERCISE17("exercise17", "Exercise 17: comments", false, new ArrayList()),
EXERCISE18("exercise18", "Exercise 18: data-* syntax", false, new ArrayList()),
EXERCISE19("exercise19", "Exercise 19: conditional th:remove", false, Arrays.asList(CUSTOMER_LIST)),
EXERCISE20("exercise20", "Exercise 20: conversion service", false, Arrays.asList(AMOUNT, RELEASE_DATE)),
EXERCISE21("exercise21", "Exercise 21: template uri variables", false, Arrays.asList(PRODUCT_ID, PRODUCT_NAME));
private final String path;
private final String description;
private final boolean i18nExercise;
|
// Path: src/main/java/org/thymeleaf/itutorial/ModelAttribute.java
// public enum ModelAttribute {
//
// PRODUCT("product", "code/Product.java"),
// PRODUCT_LIST("productList", "code/Product.java"),
// HTML("html", null),
// CUSTOMER_NAME("customerName", null),
// CUSTOMER("customer", "code/Customer.java"),
// CUSTOMER_LIST("customerList", "code/Customer.java"),
// GENDER("(Gender.java)", "code/Gender.java"),
// PAYMENT_METHOD("(PaymentMethod.java)", "code/PaymentMethod.java"),
// MESSAGES_EN("(messages_en)", "classes/messages_en.properties"),
// MESSAGES_ES("(messages_es)", "classes/messages_es.properties"),
// MESSAGES_FR("(messages_fr)", "classes/messages_fr.properties"),
// AMOUNT("price", "code/Amount.java"),
// RELEASE_DATE("releaseDate", null),
// PRODUCT_ID("productId", null),
// PRODUCT_NAME("productName", null);
//
// private final String name;
// private final String file;
//
// private ModelAttribute(String name, String file) {
// this.name = name;
// this.file = file;
// }
//
// public String getName() {
// return name;
// }
//
// public String getFile() {
// return file;
// }
// }
// Path: src/main/java/org/thymeleaf/itutorial/Exercise.java
import static org.thymeleaf.itutorial.ModelAttribute.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/*
* =============================================================================
*
* Copyright (c) 2011-2014, The THYMELEAF team (http://www.thymeleaf.org)
*
* 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.thymeleaf.itutorial;
public enum Exercise {
EXERCISE01("exercise01", "Exercise 1: bean values", false, Arrays.asList(PRODUCT)),
EXERCISE02("exercise02", "Exercise 2: simple formatting", false, Arrays.asList(PRODUCT)),
EXERCISE03("exercise03", "Exercise 3: string concatenation", false, Arrays.asList(PRODUCT)),
EXERCISE04("exercise04", "Exercise 4: internationalization", true, Arrays.asList(MESSAGES_EN, MESSAGES_ES, MESSAGES_FR)),
EXERCISE05("exercise05", "Exercise 5: escaped and unescaped text", false, Arrays.asList(HTML)),
EXERCISE06("exercise06", "Exercise 6: iteration", false, Arrays.asList(PRODUCT_LIST)),
EXERCISE07("exercise07", "Exercise 7: iteration stats", false, Arrays.asList(PRODUCT_LIST)),
EXERCISE08("exercise08", "Exercise 8: conditions", false, Arrays.asList(PRODUCT_LIST)),
EXERCISE09("exercise09", "Exercise 9: more on conditions", false, Arrays.asList(CUSTOMER_LIST, GENDER, PAYMENT_METHOD)),
EXERCISE10("exercise10", "Exercise 10: Spring expression language", false, new ArrayList()),
EXERCISE11("exercise11", "Exercise 11: links", false, new ArrayList()),
EXERCISE12("exercise12", "Exercise 12: forms", false, Arrays.asList(CUSTOMER, GENDER, PAYMENT_METHOD)),
EXERCISE13("exercise13", "Exercise 13: inlining", false, Arrays.asList(CUSTOMER_NAME)),
EXERCISE14("exercise14", "Exercise 14: same template fragments", false, new ArrayList()),
EXERCISE15("exercise15", "Exercise 15: parameterizable fragments", false, new ArrayList()),
EXERCISE16("exercise16", "Exercise 16: literal substitutions", false, Arrays.asList(CUSTOMER_NAME)),
EXERCISE17("exercise17", "Exercise 17: comments", false, new ArrayList()),
EXERCISE18("exercise18", "Exercise 18: data-* syntax", false, new ArrayList()),
EXERCISE19("exercise19", "Exercise 19: conditional th:remove", false, Arrays.asList(CUSTOMER_LIST)),
EXERCISE20("exercise20", "Exercise 20: conversion service", false, Arrays.asList(AMOUNT, RELEASE_DATE)),
EXERCISE21("exercise21", "Exercise 21: template uri variables", false, Arrays.asList(PRODUCT_ID, PRODUCT_NAME));
private final String path;
private final String description;
private final boolean i18nExercise;
|
private final List<ModelAttribute> attributes;
|
rey5137/material
|
material/src/main/java/com/rey/material/app/BottomSheetDialog.java
|
// Path: material/src/main/java/com/rey/material/drawable/BlankDrawable.java
// public class BlankDrawable extends Drawable {
//
// private static BlankDrawable mInstance;
//
// public static BlankDrawable getInstance(){
// if(mInstance == null)
// synchronized (BlankDrawable.class) {
// if(mInstance == null)
// mInstance = new BlankDrawable();
// }
//
// return mInstance;
// }
//
// @Override
// public void draw(Canvas canvas) {}
//
// @Override
// public void setAlpha(int alpha) {}
//
// @Override
// public void setColorFilter(ColorFilter cf) {}
//
// @Override
// public int getOpacity() {
// return PixelFormat.TRANSPARENT;
// }
//
// }
|
import android.content.Context;
import android.content.res.TypedArray;
import android.os.Handler;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.Interpolator;
import android.view.animation.Transformation;
import android.widget.FrameLayout;
import com.rey.material.R;
import com.rey.material.drawable.BlankDrawable;
|
private GestureDetector mGestureDetector;
private int mMinFlingVelocity;
private final Handler mHandler = new Handler();
private final Runnable mDismissAction = new Runnable() {
public void run() {
//dirty fix for java.lang.IllegalArgumentException: View not attached to window manager
try {
BottomSheetDialog.super.dismiss();
}
catch(IllegalArgumentException ex){}
}
};
private boolean mRunShowAnimation = false;
private Animation mAnimation;
private boolean mDismissPending = false;
public BottomSheetDialog(Context context) {
this(context, R.style.Material_App_BottomSheetDialog);
}
public BottomSheetDialog(Context context, int style) {
super(context, style);
//Override style to ensure not show window's title or background.
//TODO: find a way to ensure windowIsFloating attribute is false.
requestWindowFeature(Window.FEATURE_NO_TITLE);
|
// Path: material/src/main/java/com/rey/material/drawable/BlankDrawable.java
// public class BlankDrawable extends Drawable {
//
// private static BlankDrawable mInstance;
//
// public static BlankDrawable getInstance(){
// if(mInstance == null)
// synchronized (BlankDrawable.class) {
// if(mInstance == null)
// mInstance = new BlankDrawable();
// }
//
// return mInstance;
// }
//
// @Override
// public void draw(Canvas canvas) {}
//
// @Override
// public void setAlpha(int alpha) {}
//
// @Override
// public void setColorFilter(ColorFilter cf) {}
//
// @Override
// public int getOpacity() {
// return PixelFormat.TRANSPARENT;
// }
//
// }
// Path: material/src/main/java/com/rey/material/app/BottomSheetDialog.java
import android.content.Context;
import android.content.res.TypedArray;
import android.os.Handler;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.Interpolator;
import android.view.animation.Transformation;
import android.widget.FrameLayout;
import com.rey.material.R;
import com.rey.material.drawable.BlankDrawable;
private GestureDetector mGestureDetector;
private int mMinFlingVelocity;
private final Handler mHandler = new Handler();
private final Runnable mDismissAction = new Runnable() {
public void run() {
//dirty fix for java.lang.IllegalArgumentException: View not attached to window manager
try {
BottomSheetDialog.super.dismiss();
}
catch(IllegalArgumentException ex){}
}
};
private boolean mRunShowAnimation = false;
private Animation mAnimation;
private boolean mDismissPending = false;
public BottomSheetDialog(Context context) {
this(context, R.style.Material_App_BottomSheetDialog);
}
public BottomSheetDialog(Context context, int style) {
super(context, style);
//Override style to ensure not show window's title or background.
//TODO: find a way to ensure windowIsFloating attribute is false.
requestWindowFeature(Window.FEATURE_NO_TITLE);
|
getWindow().setBackgroundDrawable(BlankDrawable.getInstance());
|
LibrePlan/libreplan
|
libreplan-webapp/src/main/java/org/libreplan/importers/SchedulerManager.java
|
// Path: libreplan-business/src/main/java/org/libreplan/business/common/entities/Connector.java
// public class Connector extends BaseEntity {
//
// public static Connector create(String name) {
// return create(new Connector(name));
// }
//
// private String name;
//
// private List<ConnectorProperty> properties = new ArrayList<>();
//
// /**
// * Constructor for Hibernate. Do not use!
// */
// protected Connector() {
// }
//
// private Connector(String name) {
// this.name = name;
// }
//
// @NotEmpty(message = "name not specified")
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// @Valid
// public List<ConnectorProperty> getProperties() {
// return Collections.unmodifiableList(properties);
// }
//
// public void setProperties(List<ConnectorProperty> properties) {
// this.properties = properties;
// }
//
// public void addProperty(ConnectorProperty property) {
// properties.add(property);
// }
//
// public Map<String, String> getPropertiesAsMap() {
// Map<String, String> map = new HashMap<>();
// for (ConnectorProperty property : properties) {
// map.put(property.getKey(), property.getValue());
// }
//
// return map;
// }
//
// @AssertTrue(message = "connector name is already being used")
// public boolean isUniqueConnectorNameConstraint() {
// if ( StringUtils.isBlank(name) ) {
// return true;
// }
//
// IConnectorDAO connectorDAO = Registry.getConnectorDAO();
// if ( isNewObject() ) {
// return !connectorDAO.existsByNameAnotherTransaction(this);
// } else {
// Connector found = connectorDAO.findUniqueByNameAnotherTransaction(name);
//
// return found == null || found.getId().equals(getId());
// }
//
// }
//
// public boolean isActivated() {
// return getPropertiesAsMap().get(PredefinedConnectorProperties.ACTIVATED).equalsIgnoreCase("Y");
// }
//
// /**
// * Check if connector's connections values are valid
// *
// * @return true if connection values are valid
// */
// public boolean areConnectionValuesValid() {
// String serverUrl = getPropertiesAsMap().get(PredefinedConnectorProperties.SERVER_URL);
// try {
// new URL(serverUrl);
// } catch (MalformedURLException e) {
// return false;
// }
//
// return !StringUtils.isBlank(getPropertiesAsMap().get(PredefinedConnectorProperties.USERNAME)) &&
// !StringUtils.isBlank(getPropertiesAsMap().get(PredefinedConnectorProperties.PASSWORD));
//
// }
// }
|
import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.libreplan.business.common.daos.IConnectorDAO;
import org.libreplan.business.common.daos.IJobSchedulerConfigurationDAO;
import org.libreplan.business.common.entities.Connector;
import org.libreplan.business.common.entities.JobClassNameEnum;
import org.libreplan.business.common.entities.JobSchedulerConfiguration;
import org.quartz.CronExpression;
import org.quartz.CronTrigger;
import org.quartz.JobExecutionContext;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.TriggerKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Scope;
import org.springframework.scheduling.quartz.CronTriggerFactoryBean;
import org.springframework.scheduling.quartz.JobDetailFactoryBean;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
|
return;
}
if ( !jobSchedulerConfiguration.isSchedule() ) {
deleteJob(jobSchedulerConfiguration);
return;
}
scheduleNewJob(jobSchedulerConfiguration);
}
/**
* Check if {@link JobSchedulerConfiguration} has a connector
*
* @param connectorName
* the connector to check for
* @return true if connector is not null or empty
*/
private boolean hasConnector(String connectorName) {
return !StringUtils.isBlank(connectorName);
}
/**
* Check if the specified <code>{@link Connector}</code> is activated
*
* @param connectorName
* the connector to check for activated
* @return true if activated
*/
private boolean isConnectorActivated(String connectorName) {
|
// Path: libreplan-business/src/main/java/org/libreplan/business/common/entities/Connector.java
// public class Connector extends BaseEntity {
//
// public static Connector create(String name) {
// return create(new Connector(name));
// }
//
// private String name;
//
// private List<ConnectorProperty> properties = new ArrayList<>();
//
// /**
// * Constructor for Hibernate. Do not use!
// */
// protected Connector() {
// }
//
// private Connector(String name) {
// this.name = name;
// }
//
// @NotEmpty(message = "name not specified")
// public String getName() {
// return name;
// }
//
// public void setName(String name) {
// this.name = name;
// }
//
// @Valid
// public List<ConnectorProperty> getProperties() {
// return Collections.unmodifiableList(properties);
// }
//
// public void setProperties(List<ConnectorProperty> properties) {
// this.properties = properties;
// }
//
// public void addProperty(ConnectorProperty property) {
// properties.add(property);
// }
//
// public Map<String, String> getPropertiesAsMap() {
// Map<String, String> map = new HashMap<>();
// for (ConnectorProperty property : properties) {
// map.put(property.getKey(), property.getValue());
// }
//
// return map;
// }
//
// @AssertTrue(message = "connector name is already being used")
// public boolean isUniqueConnectorNameConstraint() {
// if ( StringUtils.isBlank(name) ) {
// return true;
// }
//
// IConnectorDAO connectorDAO = Registry.getConnectorDAO();
// if ( isNewObject() ) {
// return !connectorDAO.existsByNameAnotherTransaction(this);
// } else {
// Connector found = connectorDAO.findUniqueByNameAnotherTransaction(name);
//
// return found == null || found.getId().equals(getId());
// }
//
// }
//
// public boolean isActivated() {
// return getPropertiesAsMap().get(PredefinedConnectorProperties.ACTIVATED).equalsIgnoreCase("Y");
// }
//
// /**
// * Check if connector's connections values are valid
// *
// * @return true if connection values are valid
// */
// public boolean areConnectionValuesValid() {
// String serverUrl = getPropertiesAsMap().get(PredefinedConnectorProperties.SERVER_URL);
// try {
// new URL(serverUrl);
// } catch (MalformedURLException e) {
// return false;
// }
//
// return !StringUtils.isBlank(getPropertiesAsMap().get(PredefinedConnectorProperties.USERNAME)) &&
// !StringUtils.isBlank(getPropertiesAsMap().get(PredefinedConnectorProperties.PASSWORD));
//
// }
// }
// Path: libreplan-webapp/src/main/java/org/libreplan/importers/SchedulerManager.java
import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.libreplan.business.common.daos.IConnectorDAO;
import org.libreplan.business.common.daos.IJobSchedulerConfigurationDAO;
import org.libreplan.business.common.entities.Connector;
import org.libreplan.business.common.entities.JobClassNameEnum;
import org.libreplan.business.common.entities.JobSchedulerConfiguration;
import org.quartz.CronExpression;
import org.quartz.CronTrigger;
import org.quartz.JobExecutionContext;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.TriggerKey;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Scope;
import org.springframework.scheduling.quartz.CronTriggerFactoryBean;
import org.springframework.scheduling.quartz.JobDetailFactoryBean;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
return;
}
if ( !jobSchedulerConfiguration.isSchedule() ) {
deleteJob(jobSchedulerConfiguration);
return;
}
scheduleNewJob(jobSchedulerConfiguration);
}
/**
* Check if {@link JobSchedulerConfiguration} has a connector
*
* @param connectorName
* the connector to check for
* @return true if connector is not null or empty
*/
private boolean hasConnector(String connectorName) {
return !StringUtils.isBlank(connectorName);
}
/**
* Check if the specified <code>{@link Connector}</code> is activated
*
* @param connectorName
* the connector to check for activated
* @return true if activated
*/
private boolean isConnectorActivated(String connectorName) {
|
Connector connector = connectorDAO.findUniqueByName(connectorName);
|
LibrePlan/libreplan
|
libreplan-business/src/main/java/org/libreplan/business/users/entities/User.java
|
// Path: libreplan-business/src/main/java/org/libreplan/business/settings/entities/Language.java
// public enum Language {
//
// BROWSER_LANGUAGE(_("Use browser language configuration"), null),
// GALICIAN_LANGUAGE("Galego", new Locale("gl")),
// SPANISH_LANGUAGE("Español", new Locale("es")),
// ENGLISH_LANGUAGE("English", Locale.ENGLISH),
// RUSSIAN_LANGUAGE("Pусский", new Locale("ru")),
// PORTUGUESE_LANGUAGE("Português", new Locale("pt")),
// ITALIAN_LANGUAGE("Italiano", new Locale("it")),
// FRENCH_LANGUAGE("Français", new Locale("fr")),
// DUTCH_LANGUAGE("Nederlands", new Locale("nl")),
// POLISH_LANGUAGE("Polski", new Locale("pl")),
// CZECH_LANGUAGE("Čeština", new Locale("cs")),
// GERMAN_LANGUAGE("Deutsch", new Locale("de")),
// CATALAN_LANGUAGE("Català", new Locale("ca")),
// CHINESE_LANGUAGE("中文", new Locale("zh_CN")),
// NORWEGIAN_LANGUAGE("Norwegian Bokmål", new Locale("nb")),
// PERSIAN_LANGUAGE("پﺍﺮﺳی", new Locale("fa_IR")),
// JAPANESE_LANGUAGE("日本語", new Locale("ja")),
// PORTUGESE_BRAZIL_LANGUAGE("Portugese (Brazil) ", new Locale("pt_BR")),
// SWEDISCH_LANGUAGE("Svenska", new Locale("sv_SE"));
//
// private final String displayName;
//
// private Locale locale;
//
// private Language(String displayName, Locale locale) {
// this.displayName = displayName;
// this.locale = locale;
// }
//
// public String getDisplayName() {
// return displayName;
// }
//
// public Locale getLocale() {
// return locale;
// }
//
// }
|
import org.libreplan.business.common.IHumanIdentifiable;
import org.libreplan.business.common.Registry;
import org.libreplan.business.common.entities.Configuration;
import org.libreplan.business.common.exceptions.InstanceNotFoundException;
import org.libreplan.business.labels.entities.Label;
import org.libreplan.business.resources.entities.Criterion;
import org.libreplan.business.resources.entities.Worker;
import org.libreplan.business.scenarios.entities.Scenario;
import org.libreplan.business.settings.entities.Language;
import org.libreplan.business.users.daos.IUserDAO;
import static org.libreplan.business.i18n.I18nHelper._;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.validation.constraints.AssertTrue;
import org.hibernate.validator.constraints.NotEmpty;
import org.libreplan.business.common.BaseEntity;
|
/*
* This file is part of LibrePlan
*
* Copyright (C) 2009-2010 Fundación para o Fomento da Calidade Industrial e
* Desenvolvemento Tecnolóxico de Galicia
* Copyright (C) 2010-2013 Igalia, S.L.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.libreplan.business.users.entities;
/**
* Entity for modeling a user.
*
* @author Fernando Bellas Permuy <fbellas@udc.es>
* @author Jacobo Aragunde Perez <jaragunde@igalia.com>
* @author Cristina Alvarino Perez <cristina.alvarino@comtecsf.es>
* @author Ignacio Diaz Teijido <ignacio.diaz@comtecsf.es>
* @author Manuel Rego Casasnovas <rego@igalia.com>
* @author Javier Moran Rua <jmoran@igalia.com>
* @author Lorenzo Tilve Álvaro <ltilve@igalia.com>
*/
public class User extends BaseEntity implements IHumanIdentifiable{
private String loginName = "";
private String password = "";
|
// Path: libreplan-business/src/main/java/org/libreplan/business/settings/entities/Language.java
// public enum Language {
//
// BROWSER_LANGUAGE(_("Use browser language configuration"), null),
// GALICIAN_LANGUAGE("Galego", new Locale("gl")),
// SPANISH_LANGUAGE("Español", new Locale("es")),
// ENGLISH_LANGUAGE("English", Locale.ENGLISH),
// RUSSIAN_LANGUAGE("Pусский", new Locale("ru")),
// PORTUGUESE_LANGUAGE("Português", new Locale("pt")),
// ITALIAN_LANGUAGE("Italiano", new Locale("it")),
// FRENCH_LANGUAGE("Français", new Locale("fr")),
// DUTCH_LANGUAGE("Nederlands", new Locale("nl")),
// POLISH_LANGUAGE("Polski", new Locale("pl")),
// CZECH_LANGUAGE("Čeština", new Locale("cs")),
// GERMAN_LANGUAGE("Deutsch", new Locale("de")),
// CATALAN_LANGUAGE("Català", new Locale("ca")),
// CHINESE_LANGUAGE("中文", new Locale("zh_CN")),
// NORWEGIAN_LANGUAGE("Norwegian Bokmål", new Locale("nb")),
// PERSIAN_LANGUAGE("پﺍﺮﺳی", new Locale("fa_IR")),
// JAPANESE_LANGUAGE("日本語", new Locale("ja")),
// PORTUGESE_BRAZIL_LANGUAGE("Portugese (Brazil) ", new Locale("pt_BR")),
// SWEDISCH_LANGUAGE("Svenska", new Locale("sv_SE"));
//
// private final String displayName;
//
// private Locale locale;
//
// private Language(String displayName, Locale locale) {
// this.displayName = displayName;
// this.locale = locale;
// }
//
// public String getDisplayName() {
// return displayName;
// }
//
// public Locale getLocale() {
// return locale;
// }
//
// }
// Path: libreplan-business/src/main/java/org/libreplan/business/users/entities/User.java
import org.libreplan.business.common.IHumanIdentifiable;
import org.libreplan.business.common.Registry;
import org.libreplan.business.common.entities.Configuration;
import org.libreplan.business.common.exceptions.InstanceNotFoundException;
import org.libreplan.business.labels.entities.Label;
import org.libreplan.business.resources.entities.Criterion;
import org.libreplan.business.resources.entities.Worker;
import org.libreplan.business.scenarios.entities.Scenario;
import org.libreplan.business.settings.entities.Language;
import org.libreplan.business.users.daos.IUserDAO;
import static org.libreplan.business.i18n.I18nHelper._;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.validation.constraints.AssertTrue;
import org.hibernate.validator.constraints.NotEmpty;
import org.libreplan.business.common.BaseEntity;
/*
* This file is part of LibrePlan
*
* Copyright (C) 2009-2010 Fundación para o Fomento da Calidade Industrial e
* Desenvolvemento Tecnolóxico de Galicia
* Copyright (C) 2010-2013 Igalia, S.L.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.libreplan.business.users.entities;
/**
* Entity for modeling a user.
*
* @author Fernando Bellas Permuy <fbellas@udc.es>
* @author Jacobo Aragunde Perez <jaragunde@igalia.com>
* @author Cristina Alvarino Perez <cristina.alvarino@comtecsf.es>
* @author Ignacio Diaz Teijido <ignacio.diaz@comtecsf.es>
* @author Manuel Rego Casasnovas <rego@igalia.com>
* @author Javier Moran Rua <jmoran@igalia.com>
* @author Lorenzo Tilve Álvaro <ltilve@igalia.com>
*/
public class User extends BaseEntity implements IHumanIdentifiable{
private String loginName = "";
private String password = "";
|
private Language applicationLanguage = Language.BROWSER_LANGUAGE;
|
csulennon/TaskManagerMaster
|
taskmanagermaster/src/com/kongderui/ui/swipemenulistview/SwipeMenuAdapter.java
|
// Path: taskmanagermaster/src/com/kongderui/ui/swipemenulistview/SwipeMenuListView.java
// public static interface OnMenuItemClickListener {
// boolean onMenuItemClick(int position, SwipeMenu menu, int index);
// }
//
// Path: taskmanagermaster/src/com/kongderui/ui/swipemenulistview/SwipeMenuView.java
// public static interface OnSwipeItemClickListener {
// void onItemClick(SwipeMenuView view, SwipeMenu menu, int index);
// }
|
import android.content.Context;
import android.database.DataSetObserver;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.WrapperListAdapter;
import com.kongderui.ui.swipemenulistview.SwipeMenuListView.OnMenuItemClickListener;
import com.kongderui.ui.swipemenulistview.SwipeMenuView.OnSwipeItemClickListener;
|
package com.kongderui.ui.swipemenulistview;
/**
*
* @author baoyz
* @date 2014-8-24
*
*/
public class SwipeMenuAdapter implements WrapperListAdapter,
OnSwipeItemClickListener {
private ListAdapter mAdapter;
private Context mContext;
|
// Path: taskmanagermaster/src/com/kongderui/ui/swipemenulistview/SwipeMenuListView.java
// public static interface OnMenuItemClickListener {
// boolean onMenuItemClick(int position, SwipeMenu menu, int index);
// }
//
// Path: taskmanagermaster/src/com/kongderui/ui/swipemenulistview/SwipeMenuView.java
// public static interface OnSwipeItemClickListener {
// void onItemClick(SwipeMenuView view, SwipeMenu menu, int index);
// }
// Path: taskmanagermaster/src/com/kongderui/ui/swipemenulistview/SwipeMenuAdapter.java
import android.content.Context;
import android.database.DataSetObserver;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.WrapperListAdapter;
import com.kongderui.ui.swipemenulistview.SwipeMenuListView.OnMenuItemClickListener;
import com.kongderui.ui.swipemenulistview.SwipeMenuView.OnSwipeItemClickListener;
package com.kongderui.ui.swipemenulistview;
/**
*
* @author baoyz
* @date 2014-8-24
*
*/
public class SwipeMenuAdapter implements WrapperListAdapter,
OnSwipeItemClickListener {
private ListAdapter mAdapter;
private Context mContext;
|
private OnMenuItemClickListener onMenuItemClickListener;
|
csulennon/TaskManagerMaster
|
taskmanagermaster/src/com/kongderui/taskmanager/db/DBHelper.java
|
// Path: taskmanagermaster/src/com/kongderui/taskmanager/TaskManagerApp.java
// public class TaskManagerApp extends Application {
//
// private static Context mContext = null;
// private static TaskManagerApp mAppSelf = null;
//
// public TaskManagerApp() {
// mAppSelf = this;
// }
//
// public static Context getmContext() {
// return mContext;
// }
//
//
//
// public static Context getAppContext() {
// if(mContext == null) {
// mContext = mAppSelf.getApplicationContext();
// }
// return mContext;
// }
//
//
//
//
//
//
// }
//
// Path: taskmanagermaster/src/com/kongderui/taskmanager/util/TMLog.java
// public class TMLog {
//
// public static void e(String msg) {
// Log.e("TMError:", msg);
// }
//
// public static void i(String msg) {
// Log.i("TMInfo:", msg);
// }
//
// public static void i(int msg) {
// Log.i("TMInfo:", msg+"");
// }
//
// public static void w(String msg) {
// Log.w("TMWarning:", msg);
// }
//
// public static void d(String msg) {
// Log.d("TMDebug:", msg);
// }
//
// }
|
import java.util.concurrent.atomic.AtomicInteger;
import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import com.kongderui.taskmanager.TaskManagerApp;
import com.kongderui.taskmanager.util.TMLog;
|
package com.kongderui.taskmanager.db;
public class DBHelper extends SQLiteOpenHelper {
private static DBHelper mDBHelper = null;
private static final String DATABASE_TASKMANAGER = "taskmanager.db";
private static final int DATABASE_VERSION = 1;
private static final String SQL_CREATE_TASK = "CREATE TABLE IF NOT EXISTS task (_id INTEGER PRIMARY KEY AUTOINCREMENT, title VARCHAR(200), content VARCHAR(500), type integer, starttime integer, endtime integer, duration integer, extra text)";
private SQLiteDatabase mDatabase = null;
private final AtomicInteger mOpenCounter = new AtomicInteger();
@Override
public SQLiteDatabase getWritableDatabase() {
return openDatabase();
}
public DBHelper(Context context) {
super(context, DATABASE_TASKMANAGER, null, DATABASE_VERSION);
}
/* »ñÈ¡Êý¾Ý¿â²Ù×÷¶ÔÏóʵÀý */
public static synchronized DBHelper getInstance() {
if (mDBHelper == null) {
|
// Path: taskmanagermaster/src/com/kongderui/taskmanager/TaskManagerApp.java
// public class TaskManagerApp extends Application {
//
// private static Context mContext = null;
// private static TaskManagerApp mAppSelf = null;
//
// public TaskManagerApp() {
// mAppSelf = this;
// }
//
// public static Context getmContext() {
// return mContext;
// }
//
//
//
// public static Context getAppContext() {
// if(mContext == null) {
// mContext = mAppSelf.getApplicationContext();
// }
// return mContext;
// }
//
//
//
//
//
//
// }
//
// Path: taskmanagermaster/src/com/kongderui/taskmanager/util/TMLog.java
// public class TMLog {
//
// public static void e(String msg) {
// Log.e("TMError:", msg);
// }
//
// public static void i(String msg) {
// Log.i("TMInfo:", msg);
// }
//
// public static void i(int msg) {
// Log.i("TMInfo:", msg+"");
// }
//
// public static void w(String msg) {
// Log.w("TMWarning:", msg);
// }
//
// public static void d(String msg) {
// Log.d("TMDebug:", msg);
// }
//
// }
// Path: taskmanagermaster/src/com/kongderui/taskmanager/db/DBHelper.java
import java.util.concurrent.atomic.AtomicInteger;
import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import com.kongderui.taskmanager.TaskManagerApp;
import com.kongderui.taskmanager.util.TMLog;
package com.kongderui.taskmanager.db;
public class DBHelper extends SQLiteOpenHelper {
private static DBHelper mDBHelper = null;
private static final String DATABASE_TASKMANAGER = "taskmanager.db";
private static final int DATABASE_VERSION = 1;
private static final String SQL_CREATE_TASK = "CREATE TABLE IF NOT EXISTS task (_id INTEGER PRIMARY KEY AUTOINCREMENT, title VARCHAR(200), content VARCHAR(500), type integer, starttime integer, endtime integer, duration integer, extra text)";
private SQLiteDatabase mDatabase = null;
private final AtomicInteger mOpenCounter = new AtomicInteger();
@Override
public SQLiteDatabase getWritableDatabase() {
return openDatabase();
}
public DBHelper(Context context) {
super(context, DATABASE_TASKMANAGER, null, DATABASE_VERSION);
}
/* »ñÈ¡Êý¾Ý¿â²Ù×÷¶ÔÏóʵÀý */
public static synchronized DBHelper getInstance() {
if (mDBHelper == null) {
|
Context context = TaskManagerApp.getAppContext();
|
csulennon/TaskManagerMaster
|
taskmanagermaster/src/com/kongderui/taskmanager/db/DBHelper.java
|
// Path: taskmanagermaster/src/com/kongderui/taskmanager/TaskManagerApp.java
// public class TaskManagerApp extends Application {
//
// private static Context mContext = null;
// private static TaskManagerApp mAppSelf = null;
//
// public TaskManagerApp() {
// mAppSelf = this;
// }
//
// public static Context getmContext() {
// return mContext;
// }
//
//
//
// public static Context getAppContext() {
// if(mContext == null) {
// mContext = mAppSelf.getApplicationContext();
// }
// return mContext;
// }
//
//
//
//
//
//
// }
//
// Path: taskmanagermaster/src/com/kongderui/taskmanager/util/TMLog.java
// public class TMLog {
//
// public static void e(String msg) {
// Log.e("TMError:", msg);
// }
//
// public static void i(String msg) {
// Log.i("TMInfo:", msg);
// }
//
// public static void i(int msg) {
// Log.i("TMInfo:", msg+"");
// }
//
// public static void w(String msg) {
// Log.w("TMWarning:", msg);
// }
//
// public static void d(String msg) {
// Log.d("TMDebug:", msg);
// }
//
// }
|
import java.util.concurrent.atomic.AtomicInteger;
import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import com.kongderui.taskmanager.TaskManagerApp;
import com.kongderui.taskmanager.util.TMLog;
|
package com.kongderui.taskmanager.db;
public class DBHelper extends SQLiteOpenHelper {
private static DBHelper mDBHelper = null;
private static final String DATABASE_TASKMANAGER = "taskmanager.db";
private static final int DATABASE_VERSION = 1;
private static final String SQL_CREATE_TASK = "CREATE TABLE IF NOT EXISTS task (_id INTEGER PRIMARY KEY AUTOINCREMENT, title VARCHAR(200), content VARCHAR(500), type integer, starttime integer, endtime integer, duration integer, extra text)";
private SQLiteDatabase mDatabase = null;
private final AtomicInteger mOpenCounter = new AtomicInteger();
@Override
public SQLiteDatabase getWritableDatabase() {
return openDatabase();
}
public DBHelper(Context context) {
super(context, DATABASE_TASKMANAGER, null, DATABASE_VERSION);
}
/* »ñÈ¡Êý¾Ý¿â²Ù×÷¶ÔÏóʵÀý */
public static synchronized DBHelper getInstance() {
if (mDBHelper == null) {
Context context = TaskManagerApp.getAppContext();
mDBHelper = new DBHelper(context);
}
return mDBHelper;
}
@Override
public void onCreate(SQLiteDatabase db) {
|
// Path: taskmanagermaster/src/com/kongderui/taskmanager/TaskManagerApp.java
// public class TaskManagerApp extends Application {
//
// private static Context mContext = null;
// private static TaskManagerApp mAppSelf = null;
//
// public TaskManagerApp() {
// mAppSelf = this;
// }
//
// public static Context getmContext() {
// return mContext;
// }
//
//
//
// public static Context getAppContext() {
// if(mContext == null) {
// mContext = mAppSelf.getApplicationContext();
// }
// return mContext;
// }
//
//
//
//
//
//
// }
//
// Path: taskmanagermaster/src/com/kongderui/taskmanager/util/TMLog.java
// public class TMLog {
//
// public static void e(String msg) {
// Log.e("TMError:", msg);
// }
//
// public static void i(String msg) {
// Log.i("TMInfo:", msg);
// }
//
// public static void i(int msg) {
// Log.i("TMInfo:", msg+"");
// }
//
// public static void w(String msg) {
// Log.w("TMWarning:", msg);
// }
//
// public static void d(String msg) {
// Log.d("TMDebug:", msg);
// }
//
// }
// Path: taskmanagermaster/src/com/kongderui/taskmanager/db/DBHelper.java
import java.util.concurrent.atomic.AtomicInteger;
import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import com.kongderui.taskmanager.TaskManagerApp;
import com.kongderui.taskmanager.util.TMLog;
package com.kongderui.taskmanager.db;
public class DBHelper extends SQLiteOpenHelper {
private static DBHelper mDBHelper = null;
private static final String DATABASE_TASKMANAGER = "taskmanager.db";
private static final int DATABASE_VERSION = 1;
private static final String SQL_CREATE_TASK = "CREATE TABLE IF NOT EXISTS task (_id INTEGER PRIMARY KEY AUTOINCREMENT, title VARCHAR(200), content VARCHAR(500), type integer, starttime integer, endtime integer, duration integer, extra text)";
private SQLiteDatabase mDatabase = null;
private final AtomicInteger mOpenCounter = new AtomicInteger();
@Override
public SQLiteDatabase getWritableDatabase() {
return openDatabase();
}
public DBHelper(Context context) {
super(context, DATABASE_TASKMANAGER, null, DATABASE_VERSION);
}
/* »ñÈ¡Êý¾Ý¿â²Ù×÷¶ÔÏóʵÀý */
public static synchronized DBHelper getInstance() {
if (mDBHelper == null) {
Context context = TaskManagerApp.getAppContext();
mDBHelper = new DBHelper(context);
}
return mDBHelper;
}
@Override
public void onCreate(SQLiteDatabase db) {
|
TMLog.d("´´½¨Êý¾Ý¿â");
|
csulennon/TaskManagerMaster
|
taskmanagermaster/src/com/kongderui/taskmanager/bean/Task.java
|
// Path: taskmanagermaster/src/com/kongderui/taskmanager/util/DateTimeUtils.java
// public class DateTimeUtils {
// private static SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//
// public static long getCurrentTime() {
// return System.currentTimeMillis();
// }
//
// public static String getCurrentTimeString() {
// return format.format(new Date());
// }
//
// public static String getFormatDateTime(long time) {
// return format.format(new Date(time));
// }
//
// public static String getHumanReadableTimeString(int seconde) {
// String str = "";
// int d = 0;
// int h = 0;
// int m = 0;
// int s = 0;
// if (seconde < 60) {
// str = seconde + "Ãë";
// } else if (seconde < 60 * 60) {
// h = seconde / 60;
// s = seconde % 60;
// str = h + "·Ö" + (seconde % 60) + "Ãë";
// } else if (seconde < 60 * 60 * 24) {
// h = seconde / (60 * 60);
// m = (seconde % (60 * 60)) / 60;
// s = seconde % 60;
// str = h + "Сʱ" + m + "·ÖÖÓ" + s;
// } else {
// d = seconde / (60 * 60 * 24);
// h = (seconde % (60 * 60 * 24)) / (60 * 60);
// m = (seconde % (60 * 60)) / 60;
// s = seconde % 60;
// str = d + "Ìì" + h + "Сʱ" + m + "·ÖÖÓ" + s + "Ãë";
// }
// return str;
// }
//
// public static String secToTime(int time) {
// String timeStr = null;
// int hour = 0;
// int minute = 0;
// int second = 0;
// if (time <= 0)
// return "00:00";
// else {
// minute = time / 60;
// if (minute < 60) {
// second = time % 60;
// timeStr = unitFormat(minute) + ":" + unitFormat(second);
// } else {
// hour = minute / 60;
// if (hour > 99)
// return "99:59:59";
// minute = minute % 60;
// second = time - hour * 3600 - minute * 60;
// timeStr = unitFormat(hour) + ":" + unitFormat(minute) + ":" + unitFormat(second);
// }
// }
// return timeStr;
// }
//
// public static String unitFormat(int i) {
// String retStr = null;
// if (i >= 0 && i < 10)
// retStr = "0" + Integer.toString(i);
// else
// retStr = "" + i;
// return retStr;
// }
//
// }
|
import java.io.Serializable;
import com.kongderui.taskmanager.util.DateTimeUtils;
|
}
public static int getTypeUnknown() {
return TYPE_UNKNOWN;
}
public static int getTypeHavedone() {
return TYPE_HAVEDONE;
}
public static int getTypeTodo() {
return TYPE_TODO;
}
public static int getTypeTimeout() {
return TYPE_TIMEOUT;
}
public static int getTypeDoing() {
return TYPE_DOING;
}
@Override
public String toString() {
|
// Path: taskmanagermaster/src/com/kongderui/taskmanager/util/DateTimeUtils.java
// public class DateTimeUtils {
// private static SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//
// public static long getCurrentTime() {
// return System.currentTimeMillis();
// }
//
// public static String getCurrentTimeString() {
// return format.format(new Date());
// }
//
// public static String getFormatDateTime(long time) {
// return format.format(new Date(time));
// }
//
// public static String getHumanReadableTimeString(int seconde) {
// String str = "";
// int d = 0;
// int h = 0;
// int m = 0;
// int s = 0;
// if (seconde < 60) {
// str = seconde + "Ãë";
// } else if (seconde < 60 * 60) {
// h = seconde / 60;
// s = seconde % 60;
// str = h + "·Ö" + (seconde % 60) + "Ãë";
// } else if (seconde < 60 * 60 * 24) {
// h = seconde / (60 * 60);
// m = (seconde % (60 * 60)) / 60;
// s = seconde % 60;
// str = h + "Сʱ" + m + "·ÖÖÓ" + s;
// } else {
// d = seconde / (60 * 60 * 24);
// h = (seconde % (60 * 60 * 24)) / (60 * 60);
// m = (seconde % (60 * 60)) / 60;
// s = seconde % 60;
// str = d + "Ìì" + h + "Сʱ" + m + "·ÖÖÓ" + s + "Ãë";
// }
// return str;
// }
//
// public static String secToTime(int time) {
// String timeStr = null;
// int hour = 0;
// int minute = 0;
// int second = 0;
// if (time <= 0)
// return "00:00";
// else {
// minute = time / 60;
// if (minute < 60) {
// second = time % 60;
// timeStr = unitFormat(minute) + ":" + unitFormat(second);
// } else {
// hour = minute / 60;
// if (hour > 99)
// return "99:59:59";
// minute = minute % 60;
// second = time - hour * 3600 - minute * 60;
// timeStr = unitFormat(hour) + ":" + unitFormat(minute) + ":" + unitFormat(second);
// }
// }
// return timeStr;
// }
//
// public static String unitFormat(int i) {
// String retStr = null;
// if (i >= 0 && i < 10)
// retStr = "0" + Integer.toString(i);
// else
// retStr = "" + i;
// return retStr;
// }
//
// }
// Path: taskmanagermaster/src/com/kongderui/taskmanager/bean/Task.java
import java.io.Serializable;
import com.kongderui.taskmanager.util.DateTimeUtils;
}
public static int getTypeUnknown() {
return TYPE_UNKNOWN;
}
public static int getTypeHavedone() {
return TYPE_HAVEDONE;
}
public static int getTypeTodo() {
return TYPE_TODO;
}
public static int getTypeTimeout() {
return TYPE_TIMEOUT;
}
public static int getTypeDoing() {
return TYPE_DOING;
}
@Override
public String toString() {
|
String str = "Task [id=" + id + ", title=" + title + ", content=" + content + ", startTime=" + DateTimeUtils.getFormatDateTime(startTime) +
|
alexruiz/fest-util
|
src/main/java/org/fest/util/Throwables.java
|
// Path: src/main/java/org/fest/util/Lists.java
// public static @NotNull <T> ArrayList<T> newArrayList(@NotNull T... elements) {
// checkNotNull(elements);
// ArrayList<T> list = newArrayList();
// for (T e : elements) {
// list.add(e);
// }
// return list;
// }
//
// Path: src/main/java/org/fest/util/Preconditions.java
// public static @NotNull <T> T checkNotNull(@Nullable T reference) {
// if (reference == null) {
// throw new NullPointerException();
// }
// return reference;
// }
|
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.List;
import static org.fest.util.Lists.newArrayList;
import static org.fest.util.Preconditions.checkNotNull;
|
/*
* Created on Dec 13, 2008
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* Copyright @2008-2013 the original author or authors.
*/
package org.fest.util;
/**
* Utility methods related to {@link Throwable}s.
*
* @author Alex Ruiz
*/
// TODO(Alex): Clean up this code.
public final class Throwables {
private Throwables() {
}
/**
* Appends the stack trace of the current thread to the one in the given {@link Throwable}.
*
* @param t the given {@code Throwable}.
* @param startingMethod the name of the method used as the starting point of the current thread's stack trace.
*/
// TODO(Alex): Rename to 'appendStackTrace'
public static void appendStackTraceInCurentThreadToThrowable(@NotNull Throwable t, @NotNull String startingMethod) {
|
// Path: src/main/java/org/fest/util/Lists.java
// public static @NotNull <T> ArrayList<T> newArrayList(@NotNull T... elements) {
// checkNotNull(elements);
// ArrayList<T> list = newArrayList();
// for (T e : elements) {
// list.add(e);
// }
// return list;
// }
//
// Path: src/main/java/org/fest/util/Preconditions.java
// public static @NotNull <T> T checkNotNull(@Nullable T reference) {
// if (reference == null) {
// throw new NullPointerException();
// }
// return reference;
// }
// Path: src/main/java/org/fest/util/Throwables.java
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.List;
import static org.fest.util.Lists.newArrayList;
import static org.fest.util.Preconditions.checkNotNull;
/*
* Created on Dec 13, 2008
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* Copyright @2008-2013 the original author or authors.
*/
package org.fest.util;
/**
* Utility methods related to {@link Throwable}s.
*
* @author Alex Ruiz
*/
// TODO(Alex): Clean up this code.
public final class Throwables {
private Throwables() {
}
/**
* Appends the stack trace of the current thread to the one in the given {@link Throwable}.
*
* @param t the given {@code Throwable}.
* @param startingMethod the name of the method used as the starting point of the current thread's stack trace.
*/
// TODO(Alex): Rename to 'appendStackTrace'
public static void appendStackTraceInCurentThreadToThrowable(@NotNull Throwable t, @NotNull String startingMethod) {
|
List<StackTraceElement> stackTrace = newArrayList(checkNotNull(t.getStackTrace()));
|
alexruiz/fest-util
|
src/main/java/org/fest/util/Throwables.java
|
// Path: src/main/java/org/fest/util/Lists.java
// public static @NotNull <T> ArrayList<T> newArrayList(@NotNull T... elements) {
// checkNotNull(elements);
// ArrayList<T> list = newArrayList();
// for (T e : elements) {
// list.add(e);
// }
// return list;
// }
//
// Path: src/main/java/org/fest/util/Preconditions.java
// public static @NotNull <T> T checkNotNull(@Nullable T reference) {
// if (reference == null) {
// throw new NullPointerException();
// }
// return reference;
// }
|
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.List;
import static org.fest.util.Lists.newArrayList;
import static org.fest.util.Preconditions.checkNotNull;
|
/*
* Created on Dec 13, 2008
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* Copyright @2008-2013 the original author or authors.
*/
package org.fest.util;
/**
* Utility methods related to {@link Throwable}s.
*
* @author Alex Ruiz
*/
// TODO(Alex): Clean up this code.
public final class Throwables {
private Throwables() {
}
/**
* Appends the stack trace of the current thread to the one in the given {@link Throwable}.
*
* @param t the given {@code Throwable}.
* @param startingMethod the name of the method used as the starting point of the current thread's stack trace.
*/
// TODO(Alex): Rename to 'appendStackTrace'
public static void appendStackTraceInCurentThreadToThrowable(@NotNull Throwable t, @NotNull String startingMethod) {
|
// Path: src/main/java/org/fest/util/Lists.java
// public static @NotNull <T> ArrayList<T> newArrayList(@NotNull T... elements) {
// checkNotNull(elements);
// ArrayList<T> list = newArrayList();
// for (T e : elements) {
// list.add(e);
// }
// return list;
// }
//
// Path: src/main/java/org/fest/util/Preconditions.java
// public static @NotNull <T> T checkNotNull(@Nullable T reference) {
// if (reference == null) {
// throw new NullPointerException();
// }
// return reference;
// }
// Path: src/main/java/org/fest/util/Throwables.java
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.List;
import static org.fest.util.Lists.newArrayList;
import static org.fest.util.Preconditions.checkNotNull;
/*
* Created on Dec 13, 2008
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* Copyright @2008-2013 the original author or authors.
*/
package org.fest.util;
/**
* Utility methods related to {@link Throwable}s.
*
* @author Alex Ruiz
*/
// TODO(Alex): Clean up this code.
public final class Throwables {
private Throwables() {
}
/**
* Appends the stack trace of the current thread to the one in the given {@link Throwable}.
*
* @param t the given {@code Throwable}.
* @param startingMethod the name of the method used as the starting point of the current thread's stack trace.
*/
// TODO(Alex): Rename to 'appendStackTrace'
public static void appendStackTraceInCurentThreadToThrowable(@NotNull Throwable t, @NotNull String startingMethod) {
|
List<StackTraceElement> stackTrace = newArrayList(checkNotNull(t.getStackTrace()));
|
alexruiz/fest-util
|
src/main/java/org/fest/util/Strings.java
|
// Path: src/main/java/org/fest/util/Preconditions.java
// public static @NotNull <T> T checkNotNull(@Nullable T reference) {
// if (reference == null) {
// throw new NullPointerException();
// }
// return reference;
// }
|
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import static org.fest.util.Preconditions.checkNotNull;
|
/*
* Created on Jun 2, 2006
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* Copyright @2006-2013 the original author or authors.
*/
package org.fest.util;
/**
* Utility methods related to {@code String}s.
*
* @author Alex Ruiz
*/
public final class Strings {
private Strings() {
}
/**
* Indicates whether the given {@code String} is {@code null} or empty.
*
* @param s the {@code String} to check.
* @return {@code true} if the given {@code String} is {@code null} or empty, otherwise {@code false}.
*/
public static boolean isNullOrEmpty(@Nullable String s) {
return s == null || s.length() == 0;
}
/**
* Returns the given {@code String} surrounded by single quotes, or {@code null} if the given {@code String} is {@code
* null}.
*
* @param s the given {@code String}.
* @return the given {@code String} surrounded by single quotes, or {@code null} if the given {@code String} is {@code
* null}.
*/
public static @Nullable String quote(@Nullable String s) {
return s != null ? String.format("'%s'", s) : null;
}
/**
* Returns the given object surrounded by single quotes, only if the object is a {@code String}.
*
* @param o the given object.
* @return the given object surrounded by single quotes, only if the object is a {@code String}.
* @see #quote(String)
*/
public static @Nullable Object quote(@Nullable Object o) {
return o instanceof String ? quote(o.toString()) : o;
}
/**
* Concatenates the given objects into a single {@code String}. This method is more efficient than concatenating using
* "+", since only one {@link StringBuilder} is created.
*
* @param objects the objects to concatenate.
* @return a {@code String} containing the given objects, or empty {@code String} if the given array is empty.
*/
public static @NotNull String concat(@NotNull Object... objects) {
|
// Path: src/main/java/org/fest/util/Preconditions.java
// public static @NotNull <T> T checkNotNull(@Nullable T reference) {
// if (reference == null) {
// throw new NullPointerException();
// }
// return reference;
// }
// Path: src/main/java/org/fest/util/Strings.java
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import static org.fest.util.Preconditions.checkNotNull;
/*
* Created on Jun 2, 2006
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* Copyright @2006-2013 the original author or authors.
*/
package org.fest.util;
/**
* Utility methods related to {@code String}s.
*
* @author Alex Ruiz
*/
public final class Strings {
private Strings() {
}
/**
* Indicates whether the given {@code String} is {@code null} or empty.
*
* @param s the {@code String} to check.
* @return {@code true} if the given {@code String} is {@code null} or empty, otherwise {@code false}.
*/
public static boolean isNullOrEmpty(@Nullable String s) {
return s == null || s.length() == 0;
}
/**
* Returns the given {@code String} surrounded by single quotes, or {@code null} if the given {@code String} is {@code
* null}.
*
* @param s the given {@code String}.
* @return the given {@code String} surrounded by single quotes, or {@code null} if the given {@code String} is {@code
* null}.
*/
public static @Nullable String quote(@Nullable String s) {
return s != null ? String.format("'%s'", s) : null;
}
/**
* Returns the given object surrounded by single quotes, only if the object is a {@code String}.
*
* @param o the given object.
* @return the given object surrounded by single quotes, only if the object is a {@code String}.
* @see #quote(String)
*/
public static @Nullable Object quote(@Nullable Object o) {
return o instanceof String ? quote(o.toString()) : o;
}
/**
* Concatenates the given objects into a single {@code String}. This method is more efficient than concatenating using
* "+", since only one {@link StringBuilder} is created.
*
* @param objects the objects to concatenate.
* @return a {@code String} containing the given objects, or empty {@code String} if the given array is empty.
*/
public static @NotNull String concat(@NotNull Object... objects) {
|
checkNotNull(objects);
|
alexruiz/fest-util
|
src/test/java/org/fest/util/Introspection_getProperty_Test.java
|
// Path: src/main/java/org/fest/util/Introspection.java
// public static @NotNull PropertyDescriptor getProperty(@NotNull String propertyName, @NotNull Object target) {
// checkNotNullOrEmpty(propertyName);
// checkNotNull(target);
// BeanInfo beanInfo;
// Class<?> type = target.getClass();
// try {
// beanInfo = Introspector.getBeanInfo(type);
// } catch (Throwable t) {
// String msg = String.format("Unable to get BeanInfo for type %s", type.getName());
// throw new IntrospectionError(checkNotNull(msg), t);
// }
// for (PropertyDescriptor descriptor : beanInfo.getPropertyDescriptors()) {
// if (propertyName.equals(descriptor.getName())) {
// return descriptor;
// }
// }
// throw propertyNotFoundError(propertyName, target);
// }
|
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import java.beans.PropertyDescriptor;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertNotNull;
import static org.fest.util.Introspection.getProperty;
import static org.junit.rules.ExpectedException.none;
|
/*
* Created on Jun 28, 2010
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* Copyright @2010-2013 the original author or authors.
*/
package org.fest.util;
/**
* Tests for {@link Introspection#getProperty(String, Object)}.
*
* @author Joel Costigliola
*/
public class Introspection_getProperty_Test {
@Rule public ExpectedException thrown = none();
private Employee judy;
@Before
public void initData() {
judy = new Employee(100000.0, 31);
}
@Test
public void get_descriptor_for_property() {
|
// Path: src/main/java/org/fest/util/Introspection.java
// public static @NotNull PropertyDescriptor getProperty(@NotNull String propertyName, @NotNull Object target) {
// checkNotNullOrEmpty(propertyName);
// checkNotNull(target);
// BeanInfo beanInfo;
// Class<?> type = target.getClass();
// try {
// beanInfo = Introspector.getBeanInfo(type);
// } catch (Throwable t) {
// String msg = String.format("Unable to get BeanInfo for type %s", type.getName());
// throw new IntrospectionError(checkNotNull(msg), t);
// }
// for (PropertyDescriptor descriptor : beanInfo.getPropertyDescriptors()) {
// if (propertyName.equals(descriptor.getName())) {
// return descriptor;
// }
// }
// throw propertyNotFoundError(propertyName, target);
// }
// Path: src/test/java/org/fest/util/Introspection_getProperty_Test.java
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import java.beans.PropertyDescriptor;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertNotNull;
import static org.fest.util.Introspection.getProperty;
import static org.junit.rules.ExpectedException.none;
/*
* Created on Jun 28, 2010
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* Copyright @2010-2013 the original author or authors.
*/
package org.fest.util;
/**
* Tests for {@link Introspection#getProperty(String, Object)}.
*
* @author Joel Costigliola
*/
public class Introspection_getProperty_Test {
@Rule public ExpectedException thrown = none();
private Employee judy;
@Before
public void initData() {
judy = new Employee(100000.0, 31);
}
@Test
public void get_descriptor_for_property() {
|
PropertyDescriptor propertyDescriptor = getProperty("age", judy);
|
alexruiz/fest-util
|
src/test/java/org/fest/util/ArrayFormatter_format_Test.java
|
// Path: src/main/java/org/fest/util/Strings.java
// public static @Nullable String quote(@Nullable String s) {
// return s != null ? String.format("'%s'", s) : null;
// }
|
import org.junit.BeforeClass;
import org.junit.Test;
import static org.fest.util.Strings.quote;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
|
@Test
public void should_format_Object_array() {
assertEquals("['Hello', 'Anakin']", formatter.format(new Object[]{"Hello", new Person("Anakin")}));
}
@Test
public void should_format_Object_array_that_has_primitive_array_as_element() {
boolean booleans[] = {true, false};
Object[] array = {"Hello", booleans};
assertEquals("['Hello', [true, false]]", formatter.format(array));
}
@Test
public void should_format_Object_array_having_itself_as_element() {
Object[] array1 = {"Hello", "World"};
Object[] array2 = {array1};
array1[1] = array2;
assertEquals("[['Hello', [...]]]", formatter.format(array2));
}
private static class Person {
private final String name;
Person(String name) {
this.name = name;
}
@Override
public String toString() {
|
// Path: src/main/java/org/fest/util/Strings.java
// public static @Nullable String quote(@Nullable String s) {
// return s != null ? String.format("'%s'", s) : null;
// }
// Path: src/test/java/org/fest/util/ArrayFormatter_format_Test.java
import org.junit.BeforeClass;
import org.junit.Test;
import static org.fest.util.Strings.quote;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
@Test
public void should_format_Object_array() {
assertEquals("['Hello', 'Anakin']", formatter.format(new Object[]{"Hello", new Person("Anakin")}));
}
@Test
public void should_format_Object_array_that_has_primitive_array_as_element() {
boolean booleans[] = {true, false};
Object[] array = {"Hello", booleans};
assertEquals("['Hello', [true, false]]", formatter.format(array));
}
@Test
public void should_format_Object_array_having_itself_as_element() {
Object[] array1 = {"Hello", "World"};
Object[] array2 = {array1};
array1[1] = array2;
assertEquals("[['Hello', [...]]]", formatter.format(array2));
}
private static class Person {
private final String name;
Person(String name) {
this.name = name;
}
@Override
public String toString() {
|
return quote(name);
|
alexruiz/fest-util
|
src/main/java/org/fest/util/Objects.java
|
// Path: src/main/java/org/fest/util/Arrays.java
// public static boolean isArray(@Nullable Object o) {
// return o != null && o.getClass().isArray();
// }
//
// Path: src/main/java/org/fest/util/Preconditions.java
// public static @NotNull <T> T checkNotNull(@Nullable T reference) {
// if (reference == null) {
// throw new NullPointerException();
// }
// return reference;
// }
|
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.lang.reflect.Array;
import static org.fest.util.Arrays.isArray;
import static org.fest.util.Preconditions.checkNotNull;
|
/*
* Created on Jun 2, 2006
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* Copyright @2006-2013 the original author or authors.
*/
package org.fest.util;
/**
* Utility methods related to objects.
*
* @author Alex Ruiz
* @author Joel Costigliola
*/
public final class Objects {
/**
* Prime number used to calculate the hash code of objects.
*/
public static final int HASH_CODE_PRIME = 31;
private Objects() {
}
/**
* Indicates whether the given objects are equal.
*
* @param o1 one of the objects to compare.
* @param o2 one of the objects to compare.
* @return {@code true} if the given objects are equal or if both objects are {@code null}.
*/
public static boolean areEqual(@Nullable Object o1, @Nullable Object o2) {
if (o1 == null) {
return o2 == null;
}
if (o1.equals(o2)) {
return true;
}
return areEqualArrays(o1, o2);
}
private static boolean areEqualArrays(@Nullable Object o1, @Nullable Object o2) {
|
// Path: src/main/java/org/fest/util/Arrays.java
// public static boolean isArray(@Nullable Object o) {
// return o != null && o.getClass().isArray();
// }
//
// Path: src/main/java/org/fest/util/Preconditions.java
// public static @NotNull <T> T checkNotNull(@Nullable T reference) {
// if (reference == null) {
// throw new NullPointerException();
// }
// return reference;
// }
// Path: src/main/java/org/fest/util/Objects.java
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.lang.reflect.Array;
import static org.fest.util.Arrays.isArray;
import static org.fest.util.Preconditions.checkNotNull;
/*
* Created on Jun 2, 2006
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* Copyright @2006-2013 the original author or authors.
*/
package org.fest.util;
/**
* Utility methods related to objects.
*
* @author Alex Ruiz
* @author Joel Costigliola
*/
public final class Objects {
/**
* Prime number used to calculate the hash code of objects.
*/
public static final int HASH_CODE_PRIME = 31;
private Objects() {
}
/**
* Indicates whether the given objects are equal.
*
* @param o1 one of the objects to compare.
* @param o2 one of the objects to compare.
* @return {@code true} if the given objects are equal or if both objects are {@code null}.
*/
public static boolean areEqual(@Nullable Object o1, @Nullable Object o2) {
if (o1 == null) {
return o2 == null;
}
if (o1.equals(o2)) {
return true;
}
return areEqualArrays(o1, o2);
}
private static boolean areEqualArrays(@Nullable Object o1, @Nullable Object o2) {
|
if (!isArray(o1) || !isArray(o2)) {
|
alexruiz/fest-util
|
src/main/java/org/fest/util/Objects.java
|
// Path: src/main/java/org/fest/util/Arrays.java
// public static boolean isArray(@Nullable Object o) {
// return o != null && o.getClass().isArray();
// }
//
// Path: src/main/java/org/fest/util/Preconditions.java
// public static @NotNull <T> T checkNotNull(@Nullable T reference) {
// if (reference == null) {
// throw new NullPointerException();
// }
// return reference;
// }
|
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.lang.reflect.Array;
import static org.fest.util.Arrays.isArray;
import static org.fest.util.Preconditions.checkNotNull;
|
private static boolean areEqualArrays(@Nullable Object o1, @Nullable Object o2) {
if (!isArray(o1) || !isArray(o2)) {
return false;
}
if (o1 == o2) {
return true;
}
int size = Array.getLength(o1);
if (Array.getLength(o2) != size) {
return false;
}
for (int i = 0; i < size; i++) {
Object e1 = Array.get(o1, i);
Object e2 = Array.get(o2, i);
if (!areEqual(e1, e2)) {
return false;
}
}
return true;
}
/**
* Returns an array containing the names of the given types.
*
* @param types the given types.
* @return the names of the given types stored in an array.
* @throws NullPointerException if the given array of types is {@code null}.
*/
public static @NotNull String[] namesOf(@NotNull Class<?>... types) {
|
// Path: src/main/java/org/fest/util/Arrays.java
// public static boolean isArray(@Nullable Object o) {
// return o != null && o.getClass().isArray();
// }
//
// Path: src/main/java/org/fest/util/Preconditions.java
// public static @NotNull <T> T checkNotNull(@Nullable T reference) {
// if (reference == null) {
// throw new NullPointerException();
// }
// return reference;
// }
// Path: src/main/java/org/fest/util/Objects.java
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.lang.reflect.Array;
import static org.fest.util.Arrays.isArray;
import static org.fest.util.Preconditions.checkNotNull;
private static boolean areEqualArrays(@Nullable Object o1, @Nullable Object o2) {
if (!isArray(o1) || !isArray(o2)) {
return false;
}
if (o1 == o2) {
return true;
}
int size = Array.getLength(o1);
if (Array.getLength(o2) != size) {
return false;
}
for (int i = 0; i < size; i++) {
Object e1 = Array.get(o1, i);
Object e2 = Array.get(o2, i);
if (!areEqual(e1, e2)) {
return false;
}
}
return true;
}
/**
* Returns an array containing the names of the given types.
*
* @param types the given types.
* @return the names of the given types stored in an array.
* @throws NullPointerException if the given array of types is {@code null}.
*/
public static @NotNull String[] namesOf(@NotNull Class<?>... types) {
|
checkNotNull(types);
|
alexruiz/fest-util
|
src/test/java/org/fest/util/Collections_duplicatesFrom_Test.java
|
// Path: src/main/java/org/fest/util/Collections.java
// public static @NotNull <T> Collection<T> duplicatesFrom(@Nullable Collection<T> c) {
// Set<T> duplicates = new LinkedHashSet<T>();
// if (c == null) {
// return duplicates;
// }
// Set<T> unique = newHashSet();
// for (T e : c) {
// if (unique.contains(e)) {
// duplicates.add(e);
// continue;
// }
// unique.add(e);
// }
// return duplicates;
// }
|
import org.junit.Test;
import java.util.ArrayList;
import java.util.Collection;
import static java.util.Arrays.asList;
import static org.fest.util.Collections.duplicatesFrom;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertTrue;
|
/*
* Created on Apr 29, 2007
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* Copyright @2007-2013 the original author or authors.
*/
package org.fest.util;
/**
* Tests for {@link Collections#duplicatesFrom(Collection)}.
*
* @author Yvonne Wang
* @author Alex Ruiz
* @author Joel Costigliola
*/
public class Collections_duplicatesFrom_Test {
@Test
public void should_return_existing_duplicates() {
|
// Path: src/main/java/org/fest/util/Collections.java
// public static @NotNull <T> Collection<T> duplicatesFrom(@Nullable Collection<T> c) {
// Set<T> duplicates = new LinkedHashSet<T>();
// if (c == null) {
// return duplicates;
// }
// Set<T> unique = newHashSet();
// for (T e : c) {
// if (unique.contains(e)) {
// duplicates.add(e);
// continue;
// }
// unique.add(e);
// }
// return duplicates;
// }
// Path: src/test/java/org/fest/util/Collections_duplicatesFrom_Test.java
import org.junit.Test;
import java.util.ArrayList;
import java.util.Collection;
import static java.util.Arrays.asList;
import static org.fest.util.Collections.duplicatesFrom;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertTrue;
/*
* Created on Apr 29, 2007
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* Copyright @2007-2013 the original author or authors.
*/
package org.fest.util;
/**
* Tests for {@link Collections#duplicatesFrom(Collection)}.
*
* @author Yvonne Wang
* @author Alex Ruiz
* @author Joel Costigliola
*/
public class Collections_duplicatesFrom_Test {
@Test
public void should_return_existing_duplicates() {
|
Collection<String> duplicates = duplicatesFrom(asList("Merry", "Frodo", "Merry", "Sam", "Frodo"));
|
alexruiz/fest-util
|
src/test/java/org/fest/util/Iterables_sizeOf_Test.java
|
// Path: src/main/java/org/fest/util/Lists.java
// public static @NotNull <T> ArrayList<T> newArrayList(@NotNull T... elements) {
// checkNotNull(elements);
// ArrayList<T> list = newArrayList();
// for (T e : elements) {
// list.add(e);
// }
// return list;
// }
|
import org.junit.Test;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import static junit.framework.Assert.assertEquals;
import static org.fest.util.Lists.newArrayList;
|
/*
* Created on Apr 29, 2007
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* Copyright @2007-2013 the original author or authors.
*/
package org.fest.util;
/**
* Tests for {@link Iterables#sizeOf(Iterable)}.
*
* @author Joel Costigliola
* @author Alex Ruiz
*/
public class Iterables_sizeOf_Test {
@Test
public void should_return_zero_if_iterable_is_empty() {
assertEquals(0, Iterables.sizeOf(new ArrayList<String>()));
}
@Test(expected = NullPointerException.class)
public void should_throws_exception_if_iterable_is_null() {
Iterables.sizeOf(null);
}
@Test
public void should_return_iterable_size() {
|
// Path: src/main/java/org/fest/util/Lists.java
// public static @NotNull <T> ArrayList<T> newArrayList(@NotNull T... elements) {
// checkNotNull(elements);
// ArrayList<T> list = newArrayList();
// for (T e : elements) {
// list.add(e);
// }
// return list;
// }
// Path: src/test/java/org/fest/util/Iterables_sizeOf_Test.java
import org.junit.Test;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import static junit.framework.Assert.assertEquals;
import static org.fest.util.Lists.newArrayList;
/*
* Created on Apr 29, 2007
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* Copyright @2007-2013 the original author or authors.
*/
package org.fest.util;
/**
* Tests for {@link Iterables#sizeOf(Iterable)}.
*
* @author Joel Costigliola
* @author Alex Ruiz
*/
public class Iterables_sizeOf_Test {
@Test
public void should_return_zero_if_iterable_is_empty() {
assertEquals(0, Iterables.sizeOf(new ArrayList<String>()));
}
@Test(expected = NullPointerException.class)
public void should_throws_exception_if_iterable_is_null() {
Iterables.sizeOf(null);
}
@Test
public void should_return_iterable_size() {
|
List<String> list = newArrayList("Frodo", "Sam");
|
alexruiz/fest-util
|
src/main/java/org/fest/util/ToString.java
|
// Path: src/main/java/org/fest/util/Arrays.java
// public static boolean isArray(@Nullable Object o) {
// return o != null && o.getClass().isArray();
// }
//
// Path: src/main/java/org/fest/util/Preconditions.java
// public static @NotNull <T> T checkNotNull(@Nullable T reference) {
// if (reference == null) {
// throw new NullPointerException();
// }
// return reference;
// }
//
// Path: src/main/java/org/fest/util/Strings.java
// public static @Nullable String quote(@Nullable String s) {
// return s != null ? String.format("'%s'", s) : null;
// }
|
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.util.*;
import static org.fest.util.Arrays.isArray;
import static org.fest.util.Preconditions.checkNotNull;
import static org.fest.util.Strings.quote;
|
/*
* Created on Oct 7, 2009
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* Copyright @2009-2013 the original author or authors.
*/
package org.fest.util;
/**
* Obtains the {@code toString} representation of an object.
*
* @author Alex Ruiz
* @author Joel Costigliola
* @author Yvonne Wang
*/
public final class ToString {
private ToString() {
}
/**
* Returns the {@code toString} representation of the given object. It may or not the object's own implementation of
* {@code toString}.
*
* @param o the given object.
* @return the {@code toString} representation of the given object.
*/
public static @Nullable String toStringOf(@Nullable Object o) {
|
// Path: src/main/java/org/fest/util/Arrays.java
// public static boolean isArray(@Nullable Object o) {
// return o != null && o.getClass().isArray();
// }
//
// Path: src/main/java/org/fest/util/Preconditions.java
// public static @NotNull <T> T checkNotNull(@Nullable T reference) {
// if (reference == null) {
// throw new NullPointerException();
// }
// return reference;
// }
//
// Path: src/main/java/org/fest/util/Strings.java
// public static @Nullable String quote(@Nullable String s) {
// return s != null ? String.format("'%s'", s) : null;
// }
// Path: src/main/java/org/fest/util/ToString.java
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.util.*;
import static org.fest.util.Arrays.isArray;
import static org.fest.util.Preconditions.checkNotNull;
import static org.fest.util.Strings.quote;
/*
* Created on Oct 7, 2009
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* Copyright @2009-2013 the original author or authors.
*/
package org.fest.util;
/**
* Obtains the {@code toString} representation of an object.
*
* @author Alex Ruiz
* @author Joel Costigliola
* @author Yvonne Wang
*/
public final class ToString {
private ToString() {
}
/**
* Returns the {@code toString} representation of the given object. It may or not the object's own implementation of
* {@code toString}.
*
* @param o the given object.
* @return the {@code toString} representation of the given object.
*/
public static @Nullable String toStringOf(@Nullable Object o) {
|
if (isArray(o)) {
|
alexruiz/fest-util
|
src/main/java/org/fest/util/ToString.java
|
// Path: src/main/java/org/fest/util/Arrays.java
// public static boolean isArray(@Nullable Object o) {
// return o != null && o.getClass().isArray();
// }
//
// Path: src/main/java/org/fest/util/Preconditions.java
// public static @NotNull <T> T checkNotNull(@Nullable T reference) {
// if (reference == null) {
// throw new NullPointerException();
// }
// return reference;
// }
//
// Path: src/main/java/org/fest/util/Strings.java
// public static @Nullable String quote(@Nullable String s) {
// return s != null ? String.format("'%s'", s) : null;
// }
|
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.util.*;
import static org.fest.util.Arrays.isArray;
import static org.fest.util.Preconditions.checkNotNull;
import static org.fest.util.Strings.quote;
|
*/
public static @Nullable String toStringOf(@Nullable Object o) {
if (isArray(o)) {
return Arrays.format(o);
}
if (o instanceof Calendar) {
return toStringOf(o);
}
if (o instanceof Class<?>) {
return toStringOf((Class<?>) o);
}
if (o instanceof Collection<?>) {
return toStringOf((Collection<?>) o);
}
if (o instanceof Date) {
return toStringOf(o);
}
if (o instanceof Float) {
return toStringOf((Float) o);
}
if (o instanceof Long) {
return toStringOf((Long) o);
}
if (o instanceof File) {
return toStringOf((File) o);
}
if (o instanceof Map<?, ?>) {
return toStringOf((Map<?, ?>) o);
}
if (o instanceof String) {
|
// Path: src/main/java/org/fest/util/Arrays.java
// public static boolean isArray(@Nullable Object o) {
// return o != null && o.getClass().isArray();
// }
//
// Path: src/main/java/org/fest/util/Preconditions.java
// public static @NotNull <T> T checkNotNull(@Nullable T reference) {
// if (reference == null) {
// throw new NullPointerException();
// }
// return reference;
// }
//
// Path: src/main/java/org/fest/util/Strings.java
// public static @Nullable String quote(@Nullable String s) {
// return s != null ? String.format("'%s'", s) : null;
// }
// Path: src/main/java/org/fest/util/ToString.java
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.util.*;
import static org.fest.util.Arrays.isArray;
import static org.fest.util.Preconditions.checkNotNull;
import static org.fest.util.Strings.quote;
*/
public static @Nullable String toStringOf(@Nullable Object o) {
if (isArray(o)) {
return Arrays.format(o);
}
if (o instanceof Calendar) {
return toStringOf(o);
}
if (o instanceof Class<?>) {
return toStringOf((Class<?>) o);
}
if (o instanceof Collection<?>) {
return toStringOf((Collection<?>) o);
}
if (o instanceof Date) {
return toStringOf(o);
}
if (o instanceof Float) {
return toStringOf((Float) o);
}
if (o instanceof Long) {
return toStringOf((Long) o);
}
if (o instanceof File) {
return toStringOf((File) o);
}
if (o instanceof Map<?, ?>) {
return toStringOf((Map<?, ?>) o);
}
if (o instanceof String) {
|
return quote((String) o);
|
alexruiz/fest-util
|
src/main/java/org/fest/util/ToString.java
|
// Path: src/main/java/org/fest/util/Arrays.java
// public static boolean isArray(@Nullable Object o) {
// return o != null && o.getClass().isArray();
// }
//
// Path: src/main/java/org/fest/util/Preconditions.java
// public static @NotNull <T> T checkNotNull(@Nullable T reference) {
// if (reference == null) {
// throw new NullPointerException();
// }
// return reference;
// }
//
// Path: src/main/java/org/fest/util/Strings.java
// public static @Nullable String quote(@Nullable String s) {
// return s != null ? String.format("'%s'", s) : null;
// }
|
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.util.*;
import static org.fest.util.Arrays.isArray;
import static org.fest.util.Preconditions.checkNotNull;
import static org.fest.util.Strings.quote;
|
if (o instanceof Collection<?>) {
return toStringOf((Collection<?>) o);
}
if (o instanceof Date) {
return toStringOf(o);
}
if (o instanceof Float) {
return toStringOf((Float) o);
}
if (o instanceof Long) {
return toStringOf((Long) o);
}
if (o instanceof File) {
return toStringOf((File) o);
}
if (o instanceof Map<?, ?>) {
return toStringOf((Map<?, ?>) o);
}
if (o instanceof String) {
return quote((String) o);
}
if (o instanceof Comparator) {
return toStringOf((Comparator<?>) o);
}
return o == null ? null : o.toString();
}
private static @NotNull String toStringOf(@NotNull Comparator<?> comparator) {
String typeName = comparator.getClass().getSimpleName();
String toString = quote(!typeName.isEmpty() ? typeName : "Anonymous Comparator class");
|
// Path: src/main/java/org/fest/util/Arrays.java
// public static boolean isArray(@Nullable Object o) {
// return o != null && o.getClass().isArray();
// }
//
// Path: src/main/java/org/fest/util/Preconditions.java
// public static @NotNull <T> T checkNotNull(@Nullable T reference) {
// if (reference == null) {
// throw new NullPointerException();
// }
// return reference;
// }
//
// Path: src/main/java/org/fest/util/Strings.java
// public static @Nullable String quote(@Nullable String s) {
// return s != null ? String.format("'%s'", s) : null;
// }
// Path: src/main/java/org/fest/util/ToString.java
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.util.*;
import static org.fest.util.Arrays.isArray;
import static org.fest.util.Preconditions.checkNotNull;
import static org.fest.util.Strings.quote;
if (o instanceof Collection<?>) {
return toStringOf((Collection<?>) o);
}
if (o instanceof Date) {
return toStringOf(o);
}
if (o instanceof Float) {
return toStringOf((Float) o);
}
if (o instanceof Long) {
return toStringOf((Long) o);
}
if (o instanceof File) {
return toStringOf((File) o);
}
if (o instanceof Map<?, ?>) {
return toStringOf((Map<?, ?>) o);
}
if (o instanceof String) {
return quote((String) o);
}
if (o instanceof Comparator) {
return toStringOf((Comparator<?>) o);
}
return o == null ? null : o.toString();
}
private static @NotNull String toStringOf(@NotNull Comparator<?> comparator) {
String typeName = comparator.getClass().getSimpleName();
String toString = quote(!typeName.isEmpty() ? typeName : "Anonymous Comparator class");
|
return checkNotNull(toString);
|
alexruiz/fest-util
|
src/main/java/org/fest/util/Types.java
|
// Path: src/main/java/org/fest/util/Lists.java
// public static @NotNull <T> ArrayList<T> newArrayList(@NotNull T... elements) {
// checkNotNull(elements);
// ArrayList<T> list = newArrayList();
// for (T e : elements) {
// list.add(e);
// }
// return list;
// }
//
// Path: src/main/java/org/fest/util/Preconditions.java
// public static @NotNull <T> T checkNotNull(@Nullable T reference) {
// if (reference == null) {
// throw new NullPointerException();
// }
// return reference;
// }
|
import java.util.Collection;
import java.util.List;
import java.util.Queue;
import java.util.Set;
import static org.fest.util.Lists.newArrayList;
import static org.fest.util.Preconditions.checkNotNull;
|
/*
* Created on Oct 7, 2010
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* Copyright @2010-2013 the original author or authors.
*/
package org.fest.util;
/**
* Utilities related to Java data types.
*
* @author Alex Ruiz
*/
public final class Types {
private static final Class<?>[] PRIMITIVE_TYPES =
{boolean.class, byte.class, short.class, int.class, long.class, float.class, double.class, char.class};
private static final Class<?>[] COLLECTION_TYPES = {Collection.class, List.class, Queue.class, Set.class};
private Types() {
}
public static List<Class<?>> primitiveTypes() {
|
// Path: src/main/java/org/fest/util/Lists.java
// public static @NotNull <T> ArrayList<T> newArrayList(@NotNull T... elements) {
// checkNotNull(elements);
// ArrayList<T> list = newArrayList();
// for (T e : elements) {
// list.add(e);
// }
// return list;
// }
//
// Path: src/main/java/org/fest/util/Preconditions.java
// public static @NotNull <T> T checkNotNull(@Nullable T reference) {
// if (reference == null) {
// throw new NullPointerException();
// }
// return reference;
// }
// Path: src/main/java/org/fest/util/Types.java
import java.util.Collection;
import java.util.List;
import java.util.Queue;
import java.util.Set;
import static org.fest.util.Lists.newArrayList;
import static org.fest.util.Preconditions.checkNotNull;
/*
* Created on Oct 7, 2010
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* Copyright @2010-2013 the original author or authors.
*/
package org.fest.util;
/**
* Utilities related to Java data types.
*
* @author Alex Ruiz
*/
public final class Types {
private static final Class<?>[] PRIMITIVE_TYPES =
{boolean.class, byte.class, short.class, int.class, long.class, float.class, double.class, char.class};
private static final Class<?>[] COLLECTION_TYPES = {Collection.class, List.class, Queue.class, Set.class};
private Types() {
}
public static List<Class<?>> primitiveTypes() {
|
return newArrayList(checkNotNull(PRIMITIVE_TYPES));
|
alexruiz/fest-util
|
src/main/java/org/fest/util/Types.java
|
// Path: src/main/java/org/fest/util/Lists.java
// public static @NotNull <T> ArrayList<T> newArrayList(@NotNull T... elements) {
// checkNotNull(elements);
// ArrayList<T> list = newArrayList();
// for (T e : elements) {
// list.add(e);
// }
// return list;
// }
//
// Path: src/main/java/org/fest/util/Preconditions.java
// public static @NotNull <T> T checkNotNull(@Nullable T reference) {
// if (reference == null) {
// throw new NullPointerException();
// }
// return reference;
// }
|
import java.util.Collection;
import java.util.List;
import java.util.Queue;
import java.util.Set;
import static org.fest.util.Lists.newArrayList;
import static org.fest.util.Preconditions.checkNotNull;
|
/*
* Created on Oct 7, 2010
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* Copyright @2010-2013 the original author or authors.
*/
package org.fest.util;
/**
* Utilities related to Java data types.
*
* @author Alex Ruiz
*/
public final class Types {
private static final Class<?>[] PRIMITIVE_TYPES =
{boolean.class, byte.class, short.class, int.class, long.class, float.class, double.class, char.class};
private static final Class<?>[] COLLECTION_TYPES = {Collection.class, List.class, Queue.class, Set.class};
private Types() {
}
public static List<Class<?>> primitiveTypes() {
|
// Path: src/main/java/org/fest/util/Lists.java
// public static @NotNull <T> ArrayList<T> newArrayList(@NotNull T... elements) {
// checkNotNull(elements);
// ArrayList<T> list = newArrayList();
// for (T e : elements) {
// list.add(e);
// }
// return list;
// }
//
// Path: src/main/java/org/fest/util/Preconditions.java
// public static @NotNull <T> T checkNotNull(@Nullable T reference) {
// if (reference == null) {
// throw new NullPointerException();
// }
// return reference;
// }
// Path: src/main/java/org/fest/util/Types.java
import java.util.Collection;
import java.util.List;
import java.util.Queue;
import java.util.Set;
import static org.fest.util.Lists.newArrayList;
import static org.fest.util.Preconditions.checkNotNull;
/*
* Created on Oct 7, 2010
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* Copyright @2010-2013 the original author or authors.
*/
package org.fest.util;
/**
* Utilities related to Java data types.
*
* @author Alex Ruiz
*/
public final class Types {
private static final Class<?>[] PRIMITIVE_TYPES =
{boolean.class, byte.class, short.class, int.class, long.class, float.class, double.class, char.class};
private static final Class<?>[] COLLECTION_TYPES = {Collection.class, List.class, Queue.class, Set.class};
private Types() {
}
public static List<Class<?>> primitiveTypes() {
|
return newArrayList(checkNotNull(PRIMITIVE_TYPES));
|
alexruiz/fest-util
|
src/test/java/org/fest/util/FolderFixture.java
|
// Path: src/main/java/org/fest/util/Arrays.java
// public static <T> boolean isNullOrEmpty(@Nullable T[] array) {
// return array == null || !hasElements(array);
// }
//
// Path: src/main/java/org/fest/util/Strings.java
// public static @NotNull String concat(@NotNull Object... objects) {
// checkNotNull(objects);
// StringBuilder b = new StringBuilder();
// for (Object o : objects) {
// b.append(o);
// }
// return b.toString();
// }
//
// Path: src/main/java/org/fest/util/Strings.java
// public static @Nullable String quote(@Nullable String s) {
// return s != null ? String.format("'%s'", s) : null;
// }
|
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
import static java.io.File.separator;
import static java.lang.String.format;
import static org.fest.util.Arrays.isNullOrEmpty;
import static org.fest.util.Strings.concat;
import static org.fest.util.Strings.quote;
import static org.junit.Assert.assertTrue;
|
/*
* Created on Sep 25, 2006
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* Copyright @2006-2013 the original author or authors.
*/
package org.fest.util;
/**
* Creates and deletes directories in the file system.
*
* @author Yvonne Wang
* @author Alex Ruiz
*/
public final class FolderFixture {
private static Logger logger = Logger.getLogger(FolderFixture.class.getName());
private final List<FolderFixture> folders = new ArrayList<FolderFixture>();
private final List<FileFixture> files = new ArrayList<FileFixture>();
private final String name;
private final FolderFixture parent;
private File dir;
public FolderFixture(String name) {
this(name, null);
}
public FolderFixture(String name, FolderFixture parent) {
this.name = name;
this.parent = parent;
create();
}
File dir() {
return dir;
}
private void create() {
String path = relativePath();
dir = new File(path);
if (!dir.exists()) {
assertTrue(dir.mkdir());
|
// Path: src/main/java/org/fest/util/Arrays.java
// public static <T> boolean isNullOrEmpty(@Nullable T[] array) {
// return array == null || !hasElements(array);
// }
//
// Path: src/main/java/org/fest/util/Strings.java
// public static @NotNull String concat(@NotNull Object... objects) {
// checkNotNull(objects);
// StringBuilder b = new StringBuilder();
// for (Object o : objects) {
// b.append(o);
// }
// return b.toString();
// }
//
// Path: src/main/java/org/fest/util/Strings.java
// public static @Nullable String quote(@Nullable String s) {
// return s != null ? String.format("'%s'", s) : null;
// }
// Path: src/test/java/org/fest/util/FolderFixture.java
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
import static java.io.File.separator;
import static java.lang.String.format;
import static org.fest.util.Arrays.isNullOrEmpty;
import static org.fest.util.Strings.concat;
import static org.fest.util.Strings.quote;
import static org.junit.Assert.assertTrue;
/*
* Created on Sep 25, 2006
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* Copyright @2006-2013 the original author or authors.
*/
package org.fest.util;
/**
* Creates and deletes directories in the file system.
*
* @author Yvonne Wang
* @author Alex Ruiz
*/
public final class FolderFixture {
private static Logger logger = Logger.getLogger(FolderFixture.class.getName());
private final List<FolderFixture> folders = new ArrayList<FolderFixture>();
private final List<FileFixture> files = new ArrayList<FileFixture>();
private final String name;
private final FolderFixture parent;
private File dir;
public FolderFixture(String name) {
this(name, null);
}
public FolderFixture(String name, FolderFixture parent) {
this.name = name;
this.parent = parent;
create();
}
File dir() {
return dir;
}
private void create() {
String path = relativePath();
dir = new File(path);
if (!dir.exists()) {
assertTrue(dir.mkdir());
|
logger.info(format("Created directory %s", quote(path)));
|
alexruiz/fest-util
|
src/test/java/org/fest/util/FolderFixture.java
|
// Path: src/main/java/org/fest/util/Arrays.java
// public static <T> boolean isNullOrEmpty(@Nullable T[] array) {
// return array == null || !hasElements(array);
// }
//
// Path: src/main/java/org/fest/util/Strings.java
// public static @NotNull String concat(@NotNull Object... objects) {
// checkNotNull(objects);
// StringBuilder b = new StringBuilder();
// for (Object o : objects) {
// b.append(o);
// }
// return b.toString();
// }
//
// Path: src/main/java/org/fest/util/Strings.java
// public static @Nullable String quote(@Nullable String s) {
// return s != null ? String.format("'%s'", s) : null;
// }
|
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
import static java.io.File.separator;
import static java.lang.String.format;
import static org.fest.util.Arrays.isNullOrEmpty;
import static org.fest.util.Strings.concat;
import static org.fest.util.Strings.quote;
import static org.junit.Assert.assertTrue;
|
public FolderFixture addFolder(String folderName) {
FolderFixture child = new FolderFixture(folderName, this);
folders.add(child);
return child;
}
public FolderFixture addFiles(String... names) throws IOException {
for (String file : names) {
files.add(new FileFixture(file, this));
}
return this;
}
public void delete() {
for (FolderFixture folder : folders) {
folder.delete();
}
for (FileFixture file : files) {
file.delete();
}
String path = relativePath();
boolean dirDeleted = dir.delete();
if (!dirDeleted) {
throw new AssertionError(String.format("Unable to delete directory %s", quote(path)));
}
logger.info(format("The directory %s was deleted", quote(path)));
}
String relativePath() {
|
// Path: src/main/java/org/fest/util/Arrays.java
// public static <T> boolean isNullOrEmpty(@Nullable T[] array) {
// return array == null || !hasElements(array);
// }
//
// Path: src/main/java/org/fest/util/Strings.java
// public static @NotNull String concat(@NotNull Object... objects) {
// checkNotNull(objects);
// StringBuilder b = new StringBuilder();
// for (Object o : objects) {
// b.append(o);
// }
// return b.toString();
// }
//
// Path: src/main/java/org/fest/util/Strings.java
// public static @Nullable String quote(@Nullable String s) {
// return s != null ? String.format("'%s'", s) : null;
// }
// Path: src/test/java/org/fest/util/FolderFixture.java
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
import static java.io.File.separator;
import static java.lang.String.format;
import static org.fest.util.Arrays.isNullOrEmpty;
import static org.fest.util.Strings.concat;
import static org.fest.util.Strings.quote;
import static org.junit.Assert.assertTrue;
public FolderFixture addFolder(String folderName) {
FolderFixture child = new FolderFixture(folderName, this);
folders.add(child);
return child;
}
public FolderFixture addFiles(String... names) throws IOException {
for (String file : names) {
files.add(new FileFixture(file, this));
}
return this;
}
public void delete() {
for (FolderFixture folder : folders) {
folder.delete();
}
for (FileFixture file : files) {
file.delete();
}
String path = relativePath();
boolean dirDeleted = dir.delete();
if (!dirDeleted) {
throw new AssertionError(String.format("Unable to delete directory %s", quote(path)));
}
logger.info(format("The directory %s was deleted", quote(path)));
}
String relativePath() {
|
return parent != null ? concat(parent.relativePath(), separator, name) : name;
|
alexruiz/fest-util
|
src/test/java/org/fest/util/FolderFixture.java
|
// Path: src/main/java/org/fest/util/Arrays.java
// public static <T> boolean isNullOrEmpty(@Nullable T[] array) {
// return array == null || !hasElements(array);
// }
//
// Path: src/main/java/org/fest/util/Strings.java
// public static @NotNull String concat(@NotNull Object... objects) {
// checkNotNull(objects);
// StringBuilder b = new StringBuilder();
// for (Object o : objects) {
// b.append(o);
// }
// return b.toString();
// }
//
// Path: src/main/java/org/fest/util/Strings.java
// public static @Nullable String quote(@Nullable String s) {
// return s != null ? String.format("'%s'", s) : null;
// }
|
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
import static java.io.File.separator;
import static java.lang.String.format;
import static org.fest.util.Arrays.isNullOrEmpty;
import static org.fest.util.Strings.concat;
import static org.fest.util.Strings.quote;
import static org.junit.Assert.assertTrue;
|
}
public FolderFixture addFiles(String... names) throws IOException {
for (String file : names) {
files.add(new FileFixture(file, this));
}
return this;
}
public void delete() {
for (FolderFixture folder : folders) {
folder.delete();
}
for (FileFixture file : files) {
file.delete();
}
String path = relativePath();
boolean dirDeleted = dir.delete();
if (!dirDeleted) {
throw new AssertionError(String.format("Unable to delete directory %s", quote(path)));
}
logger.info(format("The directory %s was deleted", quote(path)));
}
String relativePath() {
return parent != null ? concat(parent.relativePath(), separator, name) : name;
}
public FolderFixture folder(String path) {
String[] names = path.split(separatorAsRegEx());
|
// Path: src/main/java/org/fest/util/Arrays.java
// public static <T> boolean isNullOrEmpty(@Nullable T[] array) {
// return array == null || !hasElements(array);
// }
//
// Path: src/main/java/org/fest/util/Strings.java
// public static @NotNull String concat(@NotNull Object... objects) {
// checkNotNull(objects);
// StringBuilder b = new StringBuilder();
// for (Object o : objects) {
// b.append(o);
// }
// return b.toString();
// }
//
// Path: src/main/java/org/fest/util/Strings.java
// public static @Nullable String quote(@Nullable String s) {
// return s != null ? String.format("'%s'", s) : null;
// }
// Path: src/test/java/org/fest/util/FolderFixture.java
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
import static java.io.File.separator;
import static java.lang.String.format;
import static org.fest.util.Arrays.isNullOrEmpty;
import static org.fest.util.Strings.concat;
import static org.fest.util.Strings.quote;
import static org.junit.Assert.assertTrue;
}
public FolderFixture addFiles(String... names) throws IOException {
for (String file : names) {
files.add(new FileFixture(file, this));
}
return this;
}
public void delete() {
for (FolderFixture folder : folders) {
folder.delete();
}
for (FileFixture file : files) {
file.delete();
}
String path = relativePath();
boolean dirDeleted = dir.delete();
if (!dirDeleted) {
throw new AssertionError(String.format("Unable to delete directory %s", quote(path)));
}
logger.info(format("The directory %s was deleted", quote(path)));
}
String relativePath() {
return parent != null ? concat(parent.relativePath(), separator, name) : name;
}
public FolderFixture folder(String path) {
String[] names = path.split(separatorAsRegEx());
|
if (isNullOrEmpty(names)) {
|
alexruiz/fest-util
|
src/test/java/org/fest/util/FileFixture.java
|
// Path: src/main/java/org/fest/util/Strings.java
// public static @NotNull String concat(@NotNull Object... objects) {
// checkNotNull(objects);
// StringBuilder b = new StringBuilder();
// for (Object o : objects) {
// b.append(o);
// }
// return b.toString();
// }
//
// Path: src/main/java/org/fest/util/Strings.java
// public static @Nullable String quote(@Nullable String s) {
// return s != null ? String.format("'%s'", s) : null;
// }
|
import java.io.File;
import java.io.IOException;
import java.util.logging.Logger;
import static java.io.File.separator;
import static java.lang.String.format;
import static org.fest.util.Strings.concat;
import static org.fest.util.Strings.quote;
|
/*
* Created on Sep 25, 2006
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* Copyright @2006-2013 the original author or authors.
*/
package org.fest.util;
/**
* Creates and deletes files in the file system.
*
* @author Yvonne Wang
* @author Alex Ruiz
*/
public final class FileFixture {
private static Logger logger = Logger.getLogger(FolderFixture.class.getName());
final String name;
final FolderFixture parent;
private File file;
public FileFixture(String name, FolderFixture parent) throws IOException {
this.name = name;
this.parent = parent;
create();
}
private void create() throws IOException {
String path = relativePath();
file = new File(path);
if (!file.exists()) {
boolean fileCreated = file.createNewFile();
if (!fileCreated) {
|
// Path: src/main/java/org/fest/util/Strings.java
// public static @NotNull String concat(@NotNull Object... objects) {
// checkNotNull(objects);
// StringBuilder b = new StringBuilder();
// for (Object o : objects) {
// b.append(o);
// }
// return b.toString();
// }
//
// Path: src/main/java/org/fest/util/Strings.java
// public static @Nullable String quote(@Nullable String s) {
// return s != null ? String.format("'%s'", s) : null;
// }
// Path: src/test/java/org/fest/util/FileFixture.java
import java.io.File;
import java.io.IOException;
import java.util.logging.Logger;
import static java.io.File.separator;
import static java.lang.String.format;
import static org.fest.util.Strings.concat;
import static org.fest.util.Strings.quote;
/*
* Created on Sep 25, 2006
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* Copyright @2006-2013 the original author or authors.
*/
package org.fest.util;
/**
* Creates and deletes files in the file system.
*
* @author Yvonne Wang
* @author Alex Ruiz
*/
public final class FileFixture {
private static Logger logger = Logger.getLogger(FolderFixture.class.getName());
final String name;
final FolderFixture parent;
private File file;
public FileFixture(String name, FolderFixture parent) throws IOException {
this.name = name;
this.parent = parent;
create();
}
private void create() throws IOException {
String path = relativePath();
file = new File(path);
if (!file.exists()) {
boolean fileCreated = file.createNewFile();
if (!fileCreated) {
|
throw new AssertionError(format("Unable to create file %s", quote(path)));
|
alexruiz/fest-util
|
src/test/java/org/fest/util/FileFixture.java
|
// Path: src/main/java/org/fest/util/Strings.java
// public static @NotNull String concat(@NotNull Object... objects) {
// checkNotNull(objects);
// StringBuilder b = new StringBuilder();
// for (Object o : objects) {
// b.append(o);
// }
// return b.toString();
// }
//
// Path: src/main/java/org/fest/util/Strings.java
// public static @Nullable String quote(@Nullable String s) {
// return s != null ? String.format("'%s'", s) : null;
// }
|
import java.io.File;
import java.io.IOException;
import java.util.logging.Logger;
import static java.io.File.separator;
import static java.lang.String.format;
import static org.fest.util.Strings.concat;
import static org.fest.util.Strings.quote;
|
this.parent = parent;
create();
}
private void create() throws IOException {
String path = relativePath();
file = new File(path);
if (!file.exists()) {
boolean fileCreated = file.createNewFile();
if (!fileCreated) {
throw new AssertionError(format("Unable to create file %s", quote(path)));
}
logger.info(format("Created file %s", quote(path)));
}
if (!file.isFile()) {
throw new AssertionError(format("%s should be a file", quote(path)));
}
logger.info(format("The file %s exists", quote(path)));
}
public void delete() {
String path = relativePath();
boolean fileDeleted = file.delete();
if (!fileDeleted) {
throw new AssertionError(String.format("Unable to delete file %s", quote(path)));
}
logger.info(format("The file %s was deleted", quote(path)));
}
String relativePath() {
|
// Path: src/main/java/org/fest/util/Strings.java
// public static @NotNull String concat(@NotNull Object... objects) {
// checkNotNull(objects);
// StringBuilder b = new StringBuilder();
// for (Object o : objects) {
// b.append(o);
// }
// return b.toString();
// }
//
// Path: src/main/java/org/fest/util/Strings.java
// public static @Nullable String quote(@Nullable String s) {
// return s != null ? String.format("'%s'", s) : null;
// }
// Path: src/test/java/org/fest/util/FileFixture.java
import java.io.File;
import java.io.IOException;
import java.util.logging.Logger;
import static java.io.File.separator;
import static java.lang.String.format;
import static org.fest.util.Strings.concat;
import static org.fest.util.Strings.quote;
this.parent = parent;
create();
}
private void create() throws IOException {
String path = relativePath();
file = new File(path);
if (!file.exists()) {
boolean fileCreated = file.createNewFile();
if (!fileCreated) {
throw new AssertionError(format("Unable to create file %s", quote(path)));
}
logger.info(format("Created file %s", quote(path)));
}
if (!file.isFile()) {
throw new AssertionError(format("%s should be a file", quote(path)));
}
logger.info(format("The file %s exists", quote(path)));
}
public void delete() {
String path = relativePath();
boolean fileDeleted = file.delete();
if (!fileDeleted) {
throw new AssertionError(String.format("Unable to delete file %s", quote(path)));
}
logger.info(format("The file %s was deleted", quote(path)));
}
String relativePath() {
|
return parent != null ? concat(parent.relativePath(), separator, name) : name;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.