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
akjava/html5gwt
src/com/akjava/gwt/html5/client/speechrecognition/SpeechRecognition.java
// Path: src/com/akjava/gwt/html5/client/speechrecognition/listeners/SpeechRecognitionAudioEndListener.java // public interface SpeechRecognitionAudioEndListener { // public void onAudioEnd(); // } // // Path: src/com/akjava/gwt/html5/client/speechrecognition/listeners/SpeechRecognitionAudioStartListener.java // public interface SpeechRecognitionAudioStartListener { // public void onAudioStart(); // } // // Path: src/com/akjava/gwt/html5/client/speechrecognition/listeners/SpeechRecognitionEndListener.java // public interface SpeechRecognitionEndListener { // public void onEnd(); // } // // Path: src/com/akjava/gwt/html5/client/speechrecognition/listeners/SpeechRecognitionResultListener.java // public interface SpeechRecognitionResultListener { // public void onResult(SpeechRecognitionEvent event); // } // // Path: src/com/akjava/gwt/html5/client/speechrecognition/listeners/SpeechRecognitionSoundEndListener.java // public interface SpeechRecognitionSoundEndListener { // public void onSoundEnd(); // } // // Path: src/com/akjava/gwt/html5/client/speechrecognition/listeners/SpeechRecognitionSpeechStartListener.java // public interface SpeechRecognitionSpeechStartListener { // public void onSpeechStart(); // }
import com.akjava.gwt.html5.client.speechrecognition.listeners.SpeechRecognitionAudioEndListener; import com.akjava.gwt.html5.client.speechrecognition.listeners.SpeechRecognitionAudioStartListener; import com.akjava.gwt.html5.client.speechrecognition.listeners.SpeechRecognitionEndListener; import com.akjava.gwt.html5.client.speechrecognition.listeners.SpeechRecognitionErrorListener; import com.akjava.gwt.html5.client.speechrecognition.listeners.SpeechRecognitionNomatchListener; import com.akjava.gwt.html5.client.speechrecognition.listeners.SpeechRecognitionResultListener; import com.akjava.gwt.html5.client.speechrecognition.listeners.SpeechRecognitionSoundEndListener; import com.akjava.gwt.html5.client.speechrecognition.listeners.SpeechRecognitionSoundStartListener; import com.akjava.gwt.html5.client.speechrecognition.listeners.SpeechRecognitionSpeechEndListener; import com.akjava.gwt.html5.client.speechrecognition.listeners.SpeechRecognitionSpeechStartListener; import com.akjava.gwt.html5.client.speechrecognition.listeners.SpeechRecognitionStartListener; import com.google.gwt.core.client.JavaScriptObject;
listener.@com.akjava.gwt.html5.client.speechrecognition.listeners.SpeechRecognitionResultListener::onResult(Lcom/akjava/gwt/html5/client/speechrecognition/SpeechRecognitionEvent;)(event); }; }-*/; public final native void setOnError(SpeechRecognitionErrorListener listener)/*-{ this.onerror=function (event) { listener.@com.akjava.gwt.html5.client.speechrecognition.listeners.SpeechRecognitionErrorListener::onError(Lcom/akjava/gwt/html5/client/speechrecognition/SpeechRecognitionError;)(event); }; }-*/; public final native void setOnAudioStart(SpeechRecognitionAudioStartListener listener)/*-{ this.onaudiostart=function () { listener.@com.akjava.gwt.html5.client.speechrecognition.listeners.SpeechRecognitionAudioStartListener::onAudioStart()(); }; }-*/; public final native void setOnSoundStart(SpeechRecognitionSoundStartListener listener)/*-{ this.onsoundstart=function () { listener.@com.akjava.gwt.html5.client.speechrecognition.listeners.SpeechRecognitionSoundStartListener::onSoundStart()(); }; }-*/; public final native void setOnSpeechStart(SpeechRecognitionSpeechStartListener listener)/*-{ this.onspeechstart=function () { listener.@com.akjava.gwt.html5.client.speechrecognition.listeners.SpeechRecognitionSpeechStartListener::onSpeechStart()(); }; }-*/; public final native void setOnSpeechEnd(SpeechRecognitionSpeechEndListener listener)/*-{ this.onspeechend=function () { listener.@com.akjava.gwt.html5.client.speechrecognition.listeners.SpeechRecognitionSpeechEndListener::onSpeechEnd()(); }; }-*/;
// Path: src/com/akjava/gwt/html5/client/speechrecognition/listeners/SpeechRecognitionAudioEndListener.java // public interface SpeechRecognitionAudioEndListener { // public void onAudioEnd(); // } // // Path: src/com/akjava/gwt/html5/client/speechrecognition/listeners/SpeechRecognitionAudioStartListener.java // public interface SpeechRecognitionAudioStartListener { // public void onAudioStart(); // } // // Path: src/com/akjava/gwt/html5/client/speechrecognition/listeners/SpeechRecognitionEndListener.java // public interface SpeechRecognitionEndListener { // public void onEnd(); // } // // Path: src/com/akjava/gwt/html5/client/speechrecognition/listeners/SpeechRecognitionResultListener.java // public interface SpeechRecognitionResultListener { // public void onResult(SpeechRecognitionEvent event); // } // // Path: src/com/akjava/gwt/html5/client/speechrecognition/listeners/SpeechRecognitionSoundEndListener.java // public interface SpeechRecognitionSoundEndListener { // public void onSoundEnd(); // } // // Path: src/com/akjava/gwt/html5/client/speechrecognition/listeners/SpeechRecognitionSpeechStartListener.java // public interface SpeechRecognitionSpeechStartListener { // public void onSpeechStart(); // } // Path: src/com/akjava/gwt/html5/client/speechrecognition/SpeechRecognition.java import com.akjava.gwt.html5.client.speechrecognition.listeners.SpeechRecognitionAudioEndListener; import com.akjava.gwt.html5.client.speechrecognition.listeners.SpeechRecognitionAudioStartListener; import com.akjava.gwt.html5.client.speechrecognition.listeners.SpeechRecognitionEndListener; import com.akjava.gwt.html5.client.speechrecognition.listeners.SpeechRecognitionErrorListener; import com.akjava.gwt.html5.client.speechrecognition.listeners.SpeechRecognitionNomatchListener; import com.akjava.gwt.html5.client.speechrecognition.listeners.SpeechRecognitionResultListener; import com.akjava.gwt.html5.client.speechrecognition.listeners.SpeechRecognitionSoundEndListener; import com.akjava.gwt.html5.client.speechrecognition.listeners.SpeechRecognitionSoundStartListener; import com.akjava.gwt.html5.client.speechrecognition.listeners.SpeechRecognitionSpeechEndListener; import com.akjava.gwt.html5.client.speechrecognition.listeners.SpeechRecognitionSpeechStartListener; import com.akjava.gwt.html5.client.speechrecognition.listeners.SpeechRecognitionStartListener; import com.google.gwt.core.client.JavaScriptObject; listener.@com.akjava.gwt.html5.client.speechrecognition.listeners.SpeechRecognitionResultListener::onResult(Lcom/akjava/gwt/html5/client/speechrecognition/SpeechRecognitionEvent;)(event); }; }-*/; public final native void setOnError(SpeechRecognitionErrorListener listener)/*-{ this.onerror=function (event) { listener.@com.akjava.gwt.html5.client.speechrecognition.listeners.SpeechRecognitionErrorListener::onError(Lcom/akjava/gwt/html5/client/speechrecognition/SpeechRecognitionError;)(event); }; }-*/; public final native void setOnAudioStart(SpeechRecognitionAudioStartListener listener)/*-{ this.onaudiostart=function () { listener.@com.akjava.gwt.html5.client.speechrecognition.listeners.SpeechRecognitionAudioStartListener::onAudioStart()(); }; }-*/; public final native void setOnSoundStart(SpeechRecognitionSoundStartListener listener)/*-{ this.onsoundstart=function () { listener.@com.akjava.gwt.html5.client.speechrecognition.listeners.SpeechRecognitionSoundStartListener::onSoundStart()(); }; }-*/; public final native void setOnSpeechStart(SpeechRecognitionSpeechStartListener listener)/*-{ this.onspeechstart=function () { listener.@com.akjava.gwt.html5.client.speechrecognition.listeners.SpeechRecognitionSpeechStartListener::onSpeechStart()(); }; }-*/; public final native void setOnSpeechEnd(SpeechRecognitionSpeechEndListener listener)/*-{ this.onspeechend=function () { listener.@com.akjava.gwt.html5.client.speechrecognition.listeners.SpeechRecognitionSpeechEndListener::onSpeechEnd()(); }; }-*/;
public final native void setOnSoundEnd(SpeechRecognitionSoundEndListener listener)/*-{
akjava/html5gwt
src/com/akjava/gwt/html5/client/speechrecognition/SpeechRecognition.java
// Path: src/com/akjava/gwt/html5/client/speechrecognition/listeners/SpeechRecognitionAudioEndListener.java // public interface SpeechRecognitionAudioEndListener { // public void onAudioEnd(); // } // // Path: src/com/akjava/gwt/html5/client/speechrecognition/listeners/SpeechRecognitionAudioStartListener.java // public interface SpeechRecognitionAudioStartListener { // public void onAudioStart(); // } // // Path: src/com/akjava/gwt/html5/client/speechrecognition/listeners/SpeechRecognitionEndListener.java // public interface SpeechRecognitionEndListener { // public void onEnd(); // } // // Path: src/com/akjava/gwt/html5/client/speechrecognition/listeners/SpeechRecognitionResultListener.java // public interface SpeechRecognitionResultListener { // public void onResult(SpeechRecognitionEvent event); // } // // Path: src/com/akjava/gwt/html5/client/speechrecognition/listeners/SpeechRecognitionSoundEndListener.java // public interface SpeechRecognitionSoundEndListener { // public void onSoundEnd(); // } // // Path: src/com/akjava/gwt/html5/client/speechrecognition/listeners/SpeechRecognitionSpeechStartListener.java // public interface SpeechRecognitionSpeechStartListener { // public void onSpeechStart(); // }
import com.akjava.gwt.html5.client.speechrecognition.listeners.SpeechRecognitionAudioEndListener; import com.akjava.gwt.html5.client.speechrecognition.listeners.SpeechRecognitionAudioStartListener; import com.akjava.gwt.html5.client.speechrecognition.listeners.SpeechRecognitionEndListener; import com.akjava.gwt.html5.client.speechrecognition.listeners.SpeechRecognitionErrorListener; import com.akjava.gwt.html5.client.speechrecognition.listeners.SpeechRecognitionNomatchListener; import com.akjava.gwt.html5.client.speechrecognition.listeners.SpeechRecognitionResultListener; import com.akjava.gwt.html5.client.speechrecognition.listeners.SpeechRecognitionSoundEndListener; import com.akjava.gwt.html5.client.speechrecognition.listeners.SpeechRecognitionSoundStartListener; import com.akjava.gwt.html5.client.speechrecognition.listeners.SpeechRecognitionSpeechEndListener; import com.akjava.gwt.html5.client.speechrecognition.listeners.SpeechRecognitionSpeechStartListener; import com.akjava.gwt.html5.client.speechrecognition.listeners.SpeechRecognitionStartListener; import com.google.gwt.core.client.JavaScriptObject;
this.onerror=function (event) { listener.@com.akjava.gwt.html5.client.speechrecognition.listeners.SpeechRecognitionErrorListener::onError(Lcom/akjava/gwt/html5/client/speechrecognition/SpeechRecognitionError;)(event); }; }-*/; public final native void setOnAudioStart(SpeechRecognitionAudioStartListener listener)/*-{ this.onaudiostart=function () { listener.@com.akjava.gwt.html5.client.speechrecognition.listeners.SpeechRecognitionAudioStartListener::onAudioStart()(); }; }-*/; public final native void setOnSoundStart(SpeechRecognitionSoundStartListener listener)/*-{ this.onsoundstart=function () { listener.@com.akjava.gwt.html5.client.speechrecognition.listeners.SpeechRecognitionSoundStartListener::onSoundStart()(); }; }-*/; public final native void setOnSpeechStart(SpeechRecognitionSpeechStartListener listener)/*-{ this.onspeechstart=function () { listener.@com.akjava.gwt.html5.client.speechrecognition.listeners.SpeechRecognitionSpeechStartListener::onSpeechStart()(); }; }-*/; public final native void setOnSpeechEnd(SpeechRecognitionSpeechEndListener listener)/*-{ this.onspeechend=function () { listener.@com.akjava.gwt.html5.client.speechrecognition.listeners.SpeechRecognitionSpeechEndListener::onSpeechEnd()(); }; }-*/; public final native void setOnSoundEnd(SpeechRecognitionSoundEndListener listener)/*-{ this.onsoundend=function () { listener.@com.akjava.gwt.html5.client.speechrecognition.listeners.SpeechRecognitionSoundEndListener::onSoundEnd()(); }; }-*/;
// Path: src/com/akjava/gwt/html5/client/speechrecognition/listeners/SpeechRecognitionAudioEndListener.java // public interface SpeechRecognitionAudioEndListener { // public void onAudioEnd(); // } // // Path: src/com/akjava/gwt/html5/client/speechrecognition/listeners/SpeechRecognitionAudioStartListener.java // public interface SpeechRecognitionAudioStartListener { // public void onAudioStart(); // } // // Path: src/com/akjava/gwt/html5/client/speechrecognition/listeners/SpeechRecognitionEndListener.java // public interface SpeechRecognitionEndListener { // public void onEnd(); // } // // Path: src/com/akjava/gwt/html5/client/speechrecognition/listeners/SpeechRecognitionResultListener.java // public interface SpeechRecognitionResultListener { // public void onResult(SpeechRecognitionEvent event); // } // // Path: src/com/akjava/gwt/html5/client/speechrecognition/listeners/SpeechRecognitionSoundEndListener.java // public interface SpeechRecognitionSoundEndListener { // public void onSoundEnd(); // } // // Path: src/com/akjava/gwt/html5/client/speechrecognition/listeners/SpeechRecognitionSpeechStartListener.java // public interface SpeechRecognitionSpeechStartListener { // public void onSpeechStart(); // } // Path: src/com/akjava/gwt/html5/client/speechrecognition/SpeechRecognition.java import com.akjava.gwt.html5.client.speechrecognition.listeners.SpeechRecognitionAudioEndListener; import com.akjava.gwt.html5.client.speechrecognition.listeners.SpeechRecognitionAudioStartListener; import com.akjava.gwt.html5.client.speechrecognition.listeners.SpeechRecognitionEndListener; import com.akjava.gwt.html5.client.speechrecognition.listeners.SpeechRecognitionErrorListener; import com.akjava.gwt.html5.client.speechrecognition.listeners.SpeechRecognitionNomatchListener; import com.akjava.gwt.html5.client.speechrecognition.listeners.SpeechRecognitionResultListener; import com.akjava.gwt.html5.client.speechrecognition.listeners.SpeechRecognitionSoundEndListener; import com.akjava.gwt.html5.client.speechrecognition.listeners.SpeechRecognitionSoundStartListener; import com.akjava.gwt.html5.client.speechrecognition.listeners.SpeechRecognitionSpeechEndListener; import com.akjava.gwt.html5.client.speechrecognition.listeners.SpeechRecognitionSpeechStartListener; import com.akjava.gwt.html5.client.speechrecognition.listeners.SpeechRecognitionStartListener; import com.google.gwt.core.client.JavaScriptObject; this.onerror=function (event) { listener.@com.akjava.gwt.html5.client.speechrecognition.listeners.SpeechRecognitionErrorListener::onError(Lcom/akjava/gwt/html5/client/speechrecognition/SpeechRecognitionError;)(event); }; }-*/; public final native void setOnAudioStart(SpeechRecognitionAudioStartListener listener)/*-{ this.onaudiostart=function () { listener.@com.akjava.gwt.html5.client.speechrecognition.listeners.SpeechRecognitionAudioStartListener::onAudioStart()(); }; }-*/; public final native void setOnSoundStart(SpeechRecognitionSoundStartListener listener)/*-{ this.onsoundstart=function () { listener.@com.akjava.gwt.html5.client.speechrecognition.listeners.SpeechRecognitionSoundStartListener::onSoundStart()(); }; }-*/; public final native void setOnSpeechStart(SpeechRecognitionSpeechStartListener listener)/*-{ this.onspeechstart=function () { listener.@com.akjava.gwt.html5.client.speechrecognition.listeners.SpeechRecognitionSpeechStartListener::onSpeechStart()(); }; }-*/; public final native void setOnSpeechEnd(SpeechRecognitionSpeechEndListener listener)/*-{ this.onspeechend=function () { listener.@com.akjava.gwt.html5.client.speechrecognition.listeners.SpeechRecognitionSpeechEndListener::onSpeechEnd()(); }; }-*/; public final native void setOnSoundEnd(SpeechRecognitionSoundEndListener listener)/*-{ this.onsoundend=function () { listener.@com.akjava.gwt.html5.client.speechrecognition.listeners.SpeechRecognitionSoundEndListener::onSoundEnd()(); }; }-*/;
public final native void setOnAudioEnd(SpeechRecognitionAudioEndListener listener)/*-{
akjava/html5gwt
src/com/akjava/gwt/html5/client/speechrecognition/SpeechRecognition.java
// Path: src/com/akjava/gwt/html5/client/speechrecognition/listeners/SpeechRecognitionAudioEndListener.java // public interface SpeechRecognitionAudioEndListener { // public void onAudioEnd(); // } // // Path: src/com/akjava/gwt/html5/client/speechrecognition/listeners/SpeechRecognitionAudioStartListener.java // public interface SpeechRecognitionAudioStartListener { // public void onAudioStart(); // } // // Path: src/com/akjava/gwt/html5/client/speechrecognition/listeners/SpeechRecognitionEndListener.java // public interface SpeechRecognitionEndListener { // public void onEnd(); // } // // Path: src/com/akjava/gwt/html5/client/speechrecognition/listeners/SpeechRecognitionResultListener.java // public interface SpeechRecognitionResultListener { // public void onResult(SpeechRecognitionEvent event); // } // // Path: src/com/akjava/gwt/html5/client/speechrecognition/listeners/SpeechRecognitionSoundEndListener.java // public interface SpeechRecognitionSoundEndListener { // public void onSoundEnd(); // } // // Path: src/com/akjava/gwt/html5/client/speechrecognition/listeners/SpeechRecognitionSpeechStartListener.java // public interface SpeechRecognitionSpeechStartListener { // public void onSpeechStart(); // }
import com.akjava.gwt.html5.client.speechrecognition.listeners.SpeechRecognitionAudioEndListener; import com.akjava.gwt.html5.client.speechrecognition.listeners.SpeechRecognitionAudioStartListener; import com.akjava.gwt.html5.client.speechrecognition.listeners.SpeechRecognitionEndListener; import com.akjava.gwt.html5.client.speechrecognition.listeners.SpeechRecognitionErrorListener; import com.akjava.gwt.html5.client.speechrecognition.listeners.SpeechRecognitionNomatchListener; import com.akjava.gwt.html5.client.speechrecognition.listeners.SpeechRecognitionResultListener; import com.akjava.gwt.html5.client.speechrecognition.listeners.SpeechRecognitionSoundEndListener; import com.akjava.gwt.html5.client.speechrecognition.listeners.SpeechRecognitionSoundStartListener; import com.akjava.gwt.html5.client.speechrecognition.listeners.SpeechRecognitionSpeechEndListener; import com.akjava.gwt.html5.client.speechrecognition.listeners.SpeechRecognitionSpeechStartListener; import com.akjava.gwt.html5.client.speechrecognition.listeners.SpeechRecognitionStartListener; import com.google.gwt.core.client.JavaScriptObject;
public final native void setOnSpeechStart(SpeechRecognitionSpeechStartListener listener)/*-{ this.onspeechstart=function () { listener.@com.akjava.gwt.html5.client.speechrecognition.listeners.SpeechRecognitionSpeechStartListener::onSpeechStart()(); }; }-*/; public final native void setOnSpeechEnd(SpeechRecognitionSpeechEndListener listener)/*-{ this.onspeechend=function () { listener.@com.akjava.gwt.html5.client.speechrecognition.listeners.SpeechRecognitionSpeechEndListener::onSpeechEnd()(); }; }-*/; public final native void setOnSoundEnd(SpeechRecognitionSoundEndListener listener)/*-{ this.onsoundend=function () { listener.@com.akjava.gwt.html5.client.speechrecognition.listeners.SpeechRecognitionSoundEndListener::onSoundEnd()(); }; }-*/; public final native void setOnAudioEnd(SpeechRecognitionAudioEndListener listener)/*-{ this.onaudioend=function () { listener.@com.akjava.gwt.html5.client.speechrecognition.listeners.SpeechRecognitionAudioEndListener::onAudioEnd()(); }; }-*/; public final native void setOnNomatch(SpeechRecognitionNomatchListener listener)/*-{ this.onnomatch=function (event) { listener.@com.akjava.gwt.html5.client.speechrecognition.listeners.SpeechRecognitionNomatchListener::onNomatch(Lcom/akjava/gwt/html5/client/speechrecognition/SpeechRecognitionEvent;)(event); }; }-*/; public final native void setOnStart(SpeechRecognitionStartListener listener)/*-{ this.onstart=function (e) { listener.@com.akjava.gwt.html5.client.speechrecognition.listeners.SpeechRecognitionStartListener::onStart()(); }; }-*/;
// Path: src/com/akjava/gwt/html5/client/speechrecognition/listeners/SpeechRecognitionAudioEndListener.java // public interface SpeechRecognitionAudioEndListener { // public void onAudioEnd(); // } // // Path: src/com/akjava/gwt/html5/client/speechrecognition/listeners/SpeechRecognitionAudioStartListener.java // public interface SpeechRecognitionAudioStartListener { // public void onAudioStart(); // } // // Path: src/com/akjava/gwt/html5/client/speechrecognition/listeners/SpeechRecognitionEndListener.java // public interface SpeechRecognitionEndListener { // public void onEnd(); // } // // Path: src/com/akjava/gwt/html5/client/speechrecognition/listeners/SpeechRecognitionResultListener.java // public interface SpeechRecognitionResultListener { // public void onResult(SpeechRecognitionEvent event); // } // // Path: src/com/akjava/gwt/html5/client/speechrecognition/listeners/SpeechRecognitionSoundEndListener.java // public interface SpeechRecognitionSoundEndListener { // public void onSoundEnd(); // } // // Path: src/com/akjava/gwt/html5/client/speechrecognition/listeners/SpeechRecognitionSpeechStartListener.java // public interface SpeechRecognitionSpeechStartListener { // public void onSpeechStart(); // } // Path: src/com/akjava/gwt/html5/client/speechrecognition/SpeechRecognition.java import com.akjava.gwt.html5.client.speechrecognition.listeners.SpeechRecognitionAudioEndListener; import com.akjava.gwt.html5.client.speechrecognition.listeners.SpeechRecognitionAudioStartListener; import com.akjava.gwt.html5.client.speechrecognition.listeners.SpeechRecognitionEndListener; import com.akjava.gwt.html5.client.speechrecognition.listeners.SpeechRecognitionErrorListener; import com.akjava.gwt.html5.client.speechrecognition.listeners.SpeechRecognitionNomatchListener; import com.akjava.gwt.html5.client.speechrecognition.listeners.SpeechRecognitionResultListener; import com.akjava.gwt.html5.client.speechrecognition.listeners.SpeechRecognitionSoundEndListener; import com.akjava.gwt.html5.client.speechrecognition.listeners.SpeechRecognitionSoundStartListener; import com.akjava.gwt.html5.client.speechrecognition.listeners.SpeechRecognitionSpeechEndListener; import com.akjava.gwt.html5.client.speechrecognition.listeners.SpeechRecognitionSpeechStartListener; import com.akjava.gwt.html5.client.speechrecognition.listeners.SpeechRecognitionStartListener; import com.google.gwt.core.client.JavaScriptObject; public final native void setOnSpeechStart(SpeechRecognitionSpeechStartListener listener)/*-{ this.onspeechstart=function () { listener.@com.akjava.gwt.html5.client.speechrecognition.listeners.SpeechRecognitionSpeechStartListener::onSpeechStart()(); }; }-*/; public final native void setOnSpeechEnd(SpeechRecognitionSpeechEndListener listener)/*-{ this.onspeechend=function () { listener.@com.akjava.gwt.html5.client.speechrecognition.listeners.SpeechRecognitionSpeechEndListener::onSpeechEnd()(); }; }-*/; public final native void setOnSoundEnd(SpeechRecognitionSoundEndListener listener)/*-{ this.onsoundend=function () { listener.@com.akjava.gwt.html5.client.speechrecognition.listeners.SpeechRecognitionSoundEndListener::onSoundEnd()(); }; }-*/; public final native void setOnAudioEnd(SpeechRecognitionAudioEndListener listener)/*-{ this.onaudioend=function () { listener.@com.akjava.gwt.html5.client.speechrecognition.listeners.SpeechRecognitionAudioEndListener::onAudioEnd()(); }; }-*/; public final native void setOnNomatch(SpeechRecognitionNomatchListener listener)/*-{ this.onnomatch=function (event) { listener.@com.akjava.gwt.html5.client.speechrecognition.listeners.SpeechRecognitionNomatchListener::onNomatch(Lcom/akjava/gwt/html5/client/speechrecognition/SpeechRecognitionEvent;)(event); }; }-*/; public final native void setOnStart(SpeechRecognitionStartListener listener)/*-{ this.onstart=function (e) { listener.@com.akjava.gwt.html5.client.speechrecognition.listeners.SpeechRecognitionStartListener::onStart()(); }; }-*/;
public final native void setOnEnd(SpeechRecognitionEndListener listener)/*-{
akjava/html5gwt
src/com/akjava/gwt/html5/client/file/FileUploadForm.java
// Path: src/com/akjava/gwt/html5/client/file/ui/DropVerticalPanelBase.java // public class DropVerticalPanelBase extends VerticalPanel implements HasDropHandlers, HasDragOverHandlers, // HasDragLeaveHandlers{ // // /** // * // */ // @Override // public HandlerRegistration addDropHandler(DropHandler handler) { // return addBitlessDomHandler(handler, DropEvent.getType()); // } // // @Override // public HandlerRegistration addDragOverHandler(DragOverHandler handler) { // return addBitlessDomHandler(handler, DragOverEvent.getType()); // } // // @Override // public HandlerRegistration addDragLeaveHandler(DragLeaveHandler handler) { // return addBitlessDomHandler(handler, DragLeaveEvent.getType()); // } // // public HandlerRegistration addMouseWheelHandler(MouseWheelHandler handler) { // return addDomHandler(handler, MouseWheelEvent.getType()); // } // }
import java.util.ArrayList; import java.util.List; import com.akjava.gwt.html5.client.file.ui.DropVerticalPanelBase; import com.google.common.base.Joiner; import com.google.common.collect.Iterables; import com.google.gwt.dom.client.Document; import com.google.gwt.user.client.ui.FileUpload; import com.google.gwt.user.client.ui.FormPanel;
package com.akjava.gwt.html5.client.file; public class FileUploadForm extends FormPanel{ private FileUpload fileUpload;
// Path: src/com/akjava/gwt/html5/client/file/ui/DropVerticalPanelBase.java // public class DropVerticalPanelBase extends VerticalPanel implements HasDropHandlers, HasDragOverHandlers, // HasDragLeaveHandlers{ // // /** // * // */ // @Override // public HandlerRegistration addDropHandler(DropHandler handler) { // return addBitlessDomHandler(handler, DropEvent.getType()); // } // // @Override // public HandlerRegistration addDragOverHandler(DragOverHandler handler) { // return addBitlessDomHandler(handler, DragOverEvent.getType()); // } // // @Override // public HandlerRegistration addDragLeaveHandler(DragLeaveHandler handler) { // return addBitlessDomHandler(handler, DragLeaveEvent.getType()); // } // // public HandlerRegistration addMouseWheelHandler(MouseWheelHandler handler) { // return addDomHandler(handler, MouseWheelEvent.getType()); // } // } // Path: src/com/akjava/gwt/html5/client/file/FileUploadForm.java import java.util.ArrayList; import java.util.List; import com.akjava.gwt.html5.client.file.ui.DropVerticalPanelBase; import com.google.common.base.Joiner; import com.google.common.collect.Iterables; import com.google.gwt.dom.client.Document; import com.google.gwt.user.client.ui.FileUpload; import com.google.gwt.user.client.ui.FormPanel; package com.akjava.gwt.html5.client.file; public class FileUploadForm extends FormPanel{ private FileUpload fileUpload;
private DropVerticalPanelBase dropPanel;
akjava/html5gwt
src/com/akjava/gwt/html5/client/file/RequestFileSystem.java
// Path: src/com/akjava/gwt/html5/client/file/callback/FileErrorCallback.java // public interface FileErrorCallback{ // public void fileErrorCallback(FileError fileError); // }
import com.akjava.gwt.html5.client.file.callback.FileErrorCallback;
package com.akjava.gwt.html5.client.file; public class RequestFileSystem { /* * window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem; window.requestFileSystem(type, size, successCallback, opt_errorCallback) */ public static final int TEMPORARY=0; public static final int PERSISTENT=1;
// Path: src/com/akjava/gwt/html5/client/file/callback/FileErrorCallback.java // public interface FileErrorCallback{ // public void fileErrorCallback(FileError fileError); // } // Path: src/com/akjava/gwt/html5/client/file/RequestFileSystem.java import com.akjava.gwt.html5.client.file.callback.FileErrorCallback; package com.akjava.gwt.html5.client.file; public class RequestFileSystem { /* * window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem; window.requestFileSystem(type, size, successCallback, opt_errorCallback) */ public static final int TEMPORARY=0; public static final int PERSISTENT=1;
public static final native void requestFileSystem(int type,double size,FileSystemCallback successCallback,FileErrorCallback errorCallback)/*-{
akjava/html5gwt
src/com/akjava/gwt/html5/client/file/FileWriter.java
// Path: src/com/akjava/gwt/html5/client/file/callback/ProgressEventCallback.java // public interface ProgressEventCallback { // public void progressEventCallback(ProgressEvent progressEvent); // }
import com.akjava.gwt.html5.client.file.callback.ProgressEventCallback; import com.google.gwt.core.client.JavaScriptObject;
var bb = new $wnd.BlobBuilder(); // Note: window.WebKitBlobBuilder in Chrome 12. var text='hello'; this.write(bb.getBlob('text/plain')); }-*/; public final native void write(JavaScriptObject blob)/*-{ this.write(blob); }-*/; public final long getLength(){ return (long)length(); } public final native void truncate(double length)/*-{ this.truncate(length); }-*/; public final native void seek(double value)/*-{ return this.seek(value); }-*/; public final native double length()/*-{ return this.length; }-*/;
// Path: src/com/akjava/gwt/html5/client/file/callback/ProgressEventCallback.java // public interface ProgressEventCallback { // public void progressEventCallback(ProgressEvent progressEvent); // } // Path: src/com/akjava/gwt/html5/client/file/FileWriter.java import com.akjava.gwt.html5.client.file.callback.ProgressEventCallback; import com.google.gwt.core.client.JavaScriptObject; var bb = new $wnd.BlobBuilder(); // Note: window.WebKitBlobBuilder in Chrome 12. var text='hello'; this.write(bb.getBlob('text/plain')); }-*/; public final native void write(JavaScriptObject blob)/*-{ this.write(blob); }-*/; public final long getLength(){ return (long)length(); } public final native void truncate(double length)/*-{ this.truncate(length); }-*/; public final native void seek(double value)/*-{ return this.seek(value); }-*/; public final native double length()/*-{ return this.length; }-*/;
public final native void setOnWriteEnd(ProgressEventCallback callback)/*-{
akjava/html5gwt
src/com/akjava/gwt/html5/client/file/webkit/FileEntry.java
// Path: src/com/akjava/gwt/html5/client/file/callback/FileEntryCallback.java // public interface FileEntryCallback { // public void fileEntryCallback(FileEntry file); // } // // Path: src/com/akjava/gwt/html5/client/file/callback/FileErrorCallback.java // public interface FileErrorCallback{ // public void fileErrorCallback(FileError fileError); // } // // Path: src/com/akjava/gwt/html5/client/file/callback/VoidCallback.java // public interface VoidCallback { // public void callback(); // }
import com.akjava.gwt.html5.client.file.DirectoryReader; import com.akjava.gwt.html5.client.file.callback.FileEntryCallback; import com.akjava.gwt.html5.client.file.callback.FileErrorCallback; import com.akjava.gwt.html5.client.file.callback.FileWriterCallback; import com.akjava.gwt.html5.client.file.callback.VoidCallback; import com.google.gwt.core.client.JavaScriptObject;
}); }-*/; //TODO support error public final native void file(FilePathCallback callback,String parent)/*-{ this.file( function(file){ callback.@com.akjava.gwt.html5.client.file.webkit.FilePathCallback::callback(Lcom/akjava/gwt/html5/client/file/File;Ljava/lang/String;)(file,parent) }); }-*/; //for directory only public final native DirectoryReader getReader()/*-{ return this.createReader(); }-*/; //TODO implement copyTo,moveTo //TODO implement resolveLocalFileSystemURL public final native String toURL()/*-{ return this.toURL(); }-*/;
// Path: src/com/akjava/gwt/html5/client/file/callback/FileEntryCallback.java // public interface FileEntryCallback { // public void fileEntryCallback(FileEntry file); // } // // Path: src/com/akjava/gwt/html5/client/file/callback/FileErrorCallback.java // public interface FileErrorCallback{ // public void fileErrorCallback(FileError fileError); // } // // Path: src/com/akjava/gwt/html5/client/file/callback/VoidCallback.java // public interface VoidCallback { // public void callback(); // } // Path: src/com/akjava/gwt/html5/client/file/webkit/FileEntry.java import com.akjava.gwt.html5.client.file.DirectoryReader; import com.akjava.gwt.html5.client.file.callback.FileEntryCallback; import com.akjava.gwt.html5.client.file.callback.FileErrorCallback; import com.akjava.gwt.html5.client.file.callback.FileWriterCallback; import com.akjava.gwt.html5.client.file.callback.VoidCallback; import com.google.gwt.core.client.JavaScriptObject; }); }-*/; //TODO support error public final native void file(FilePathCallback callback,String parent)/*-{ this.file( function(file){ callback.@com.akjava.gwt.html5.client.file.webkit.FilePathCallback::callback(Lcom/akjava/gwt/html5/client/file/File;Ljava/lang/String;)(file,parent) }); }-*/; //for directory only public final native DirectoryReader getReader()/*-{ return this.createReader(); }-*/; //TODO implement copyTo,moveTo //TODO implement resolveLocalFileSystemURL public final native String toURL()/*-{ return this.toURL(); }-*/;
public final native void remove(VoidCallback simpleCallback,FileErrorCallback errorCallback)/*-{
akjava/html5gwt
src/com/akjava/gwt/html5/client/file/webkit/FileEntry.java
// Path: src/com/akjava/gwt/html5/client/file/callback/FileEntryCallback.java // public interface FileEntryCallback { // public void fileEntryCallback(FileEntry file); // } // // Path: src/com/akjava/gwt/html5/client/file/callback/FileErrorCallback.java // public interface FileErrorCallback{ // public void fileErrorCallback(FileError fileError); // } // // Path: src/com/akjava/gwt/html5/client/file/callback/VoidCallback.java // public interface VoidCallback { // public void callback(); // }
import com.akjava.gwt.html5.client.file.DirectoryReader; import com.akjava.gwt.html5.client.file.callback.FileEntryCallback; import com.akjava.gwt.html5.client.file.callback.FileErrorCallback; import com.akjava.gwt.html5.client.file.callback.FileWriterCallback; import com.akjava.gwt.html5.client.file.callback.VoidCallback; import com.google.gwt.core.client.JavaScriptObject;
}); }-*/; //TODO support error public final native void file(FilePathCallback callback,String parent)/*-{ this.file( function(file){ callback.@com.akjava.gwt.html5.client.file.webkit.FilePathCallback::callback(Lcom/akjava/gwt/html5/client/file/File;Ljava/lang/String;)(file,parent) }); }-*/; //for directory only public final native DirectoryReader getReader()/*-{ return this.createReader(); }-*/; //TODO implement copyTo,moveTo //TODO implement resolveLocalFileSystemURL public final native String toURL()/*-{ return this.toURL(); }-*/;
// Path: src/com/akjava/gwt/html5/client/file/callback/FileEntryCallback.java // public interface FileEntryCallback { // public void fileEntryCallback(FileEntry file); // } // // Path: src/com/akjava/gwt/html5/client/file/callback/FileErrorCallback.java // public interface FileErrorCallback{ // public void fileErrorCallback(FileError fileError); // } // // Path: src/com/akjava/gwt/html5/client/file/callback/VoidCallback.java // public interface VoidCallback { // public void callback(); // } // Path: src/com/akjava/gwt/html5/client/file/webkit/FileEntry.java import com.akjava.gwt.html5.client.file.DirectoryReader; import com.akjava.gwt.html5.client.file.callback.FileEntryCallback; import com.akjava.gwt.html5.client.file.callback.FileErrorCallback; import com.akjava.gwt.html5.client.file.callback.FileWriterCallback; import com.akjava.gwt.html5.client.file.callback.VoidCallback; import com.google.gwt.core.client.JavaScriptObject; }); }-*/; //TODO support error public final native void file(FilePathCallback callback,String parent)/*-{ this.file( function(file){ callback.@com.akjava.gwt.html5.client.file.webkit.FilePathCallback::callback(Lcom/akjava/gwt/html5/client/file/File;Ljava/lang/String;)(file,parent) }); }-*/; //for directory only public final native DirectoryReader getReader()/*-{ return this.createReader(); }-*/; //TODO implement copyTo,moveTo //TODO implement resolveLocalFileSystemURL public final native String toURL()/*-{ return this.toURL(); }-*/;
public final native void remove(VoidCallback simpleCallback,FileErrorCallback errorCallback)/*-{
akjava/html5gwt
src/com/akjava/gwt/html5/client/file/webkit/FileEntry.java
// Path: src/com/akjava/gwt/html5/client/file/callback/FileEntryCallback.java // public interface FileEntryCallback { // public void fileEntryCallback(FileEntry file); // } // // Path: src/com/akjava/gwt/html5/client/file/callback/FileErrorCallback.java // public interface FileErrorCallback{ // public void fileErrorCallback(FileError fileError); // } // // Path: src/com/akjava/gwt/html5/client/file/callback/VoidCallback.java // public interface VoidCallback { // public void callback(); // }
import com.akjava.gwt.html5.client.file.DirectoryReader; import com.akjava.gwt.html5.client.file.callback.FileEntryCallback; import com.akjava.gwt.html5.client.file.callback.FileErrorCallback; import com.akjava.gwt.html5.client.file.callback.FileWriterCallback; import com.akjava.gwt.html5.client.file.callback.VoidCallback; import com.google.gwt.core.client.JavaScriptObject;
var callback=function(){ simpleCallback.@com.akjava.gwt.html5.client.file.callback.VoidCallback::callback()(); } var error=function(fileerror){ errorCallback.@com.akjava.gwt.html5.client.file.callback.FileErrorCallback::fileErrorCallback(Lcom/akjava/gwt/html5/client/file/FileError;)(fileerror); } this.remove(callback,error); }-*/; public final native void removeRecursively(VoidCallback simpleCallback,FileErrorCallback errorCallback)/*-{ var callback=function(){ simpleCallback.@com.akjava.gwt.html5.client.file.callback.VoidCallback::callback()(); } var error=function(fileerror){ errorCallback.@com.akjava.gwt.html5.client.file.callback.FileErrorCallback::fileErrorCallback(Lcom/akjava/gwt/html5/client/file/FileError;)(fileerror); } this.removeRecursively(callback,error); }-*/; //TODO implement removeRecursively() //TODO implement copyTo,moveTo;
// Path: src/com/akjava/gwt/html5/client/file/callback/FileEntryCallback.java // public interface FileEntryCallback { // public void fileEntryCallback(FileEntry file); // } // // Path: src/com/akjava/gwt/html5/client/file/callback/FileErrorCallback.java // public interface FileErrorCallback{ // public void fileErrorCallback(FileError fileError); // } // // Path: src/com/akjava/gwt/html5/client/file/callback/VoidCallback.java // public interface VoidCallback { // public void callback(); // } // Path: src/com/akjava/gwt/html5/client/file/webkit/FileEntry.java import com.akjava.gwt.html5.client.file.DirectoryReader; import com.akjava.gwt.html5.client.file.callback.FileEntryCallback; import com.akjava.gwt.html5.client.file.callback.FileErrorCallback; import com.akjava.gwt.html5.client.file.callback.FileWriterCallback; import com.akjava.gwt.html5.client.file.callback.VoidCallback; import com.google.gwt.core.client.JavaScriptObject; var callback=function(){ simpleCallback.@com.akjava.gwt.html5.client.file.callback.VoidCallback::callback()(); } var error=function(fileerror){ errorCallback.@com.akjava.gwt.html5.client.file.callback.FileErrorCallback::fileErrorCallback(Lcom/akjava/gwt/html5/client/file/FileError;)(fileerror); } this.remove(callback,error); }-*/; public final native void removeRecursively(VoidCallback simpleCallback,FileErrorCallback errorCallback)/*-{ var callback=function(){ simpleCallback.@com.akjava.gwt.html5.client.file.callback.VoidCallback::callback()(); } var error=function(fileerror){ errorCallback.@com.akjava.gwt.html5.client.file.callback.FileErrorCallback::fileErrorCallback(Lcom/akjava/gwt/html5/client/file/FileError;)(fileerror); } this.removeRecursively(callback,error); }-*/; //TODO implement removeRecursively() //TODO implement copyTo,moveTo;
public final native void getFile(String name,boolean create,boolean exclusive,FileEntryCallback callback,FileErrorCallback errorCallback)/*-{
akjava/html5gwt
src/com/akjava/gwt/html5/client/file/FileSystem.java
// Path: src/com/akjava/gwt/html5/client/file/webkit/FileEntry.java // public class FileEntry extends JavaScriptObject{ // // protected FileEntry(){} // // public final native boolean isFile()/*-{ // return this.isFile; // }-*/; // // public final native boolean isDirectory()/*-{ // return this.isDirectory; // }-*/; // // public final native String getName()/*-{ // return this.name; // }-*/; // // public final native String getFullPath()/*-{ // return this.fullPath; // }-*/; // // //TODO support error // public final native void file(FileCallback callback)/*-{ // // this.file( function(file){ // callback.@com.akjava.gwt.html5.client.file.webkit.FileCallback::callback(Lcom/akjava/gwt/html5/client/file/File;)(file) // }); // // }-*/; // // //TODO support error // public final native void file(FilePathCallback callback,String parent)/*-{ // // this.file( function(file){ // callback.@com.akjava.gwt.html5.client.file.webkit.FilePathCallback::callback(Lcom/akjava/gwt/html5/client/file/File;Ljava/lang/String;)(file,parent) // }); // // }-*/; // // // //for directory only // public final native DirectoryReader getReader()/*-{ // return this.createReader(); // }-*/; // // //TODO implement copyTo,moveTo // // //TODO implement resolveLocalFileSystemURL // // public final native String toURL()/*-{ // return this.toURL(); // }-*/; // // // // // public final native void remove(VoidCallback simpleCallback,FileErrorCallback errorCallback)/*-{ // // var callback=function(){ // simpleCallback.@com.akjava.gwt.html5.client.file.callback.VoidCallback::callback()(); // } // // var error=function(fileerror){ // errorCallback.@com.akjava.gwt.html5.client.file.callback.FileErrorCallback::fileErrorCallback(Lcom/akjava/gwt/html5/client/file/FileError;)(fileerror); // } // // this.remove(callback,error); // }-*/; // // public final native void removeRecursively(VoidCallback simpleCallback,FileErrorCallback errorCallback)/*-{ // // var callback=function(){ // simpleCallback.@com.akjava.gwt.html5.client.file.callback.VoidCallback::callback()(); // } // // var error=function(fileerror){ // errorCallback.@com.akjava.gwt.html5.client.file.callback.FileErrorCallback::fileErrorCallback(Lcom/akjava/gwt/html5/client/file/FileError;)(fileerror); // } // // this.removeRecursively(callback,error); // }-*/; // // //TODO implement removeRecursively() // // //TODO implement copyTo,moveTo; // // // public final native void getFile(String name,boolean create,boolean exclusive,FileEntryCallback callback,FileErrorCallback errorCallback)/*-{ // // var getfile=function(fileentry){ // callback.@com.akjava.gwt.html5.client.file.callback.FileEntryCallback::fileEntryCallback(Lcom/akjava/gwt/html5/client/file/webkit/FileEntry;)(fileentry); // // } // // var error=function(fileerror){ // errorCallback.@com.akjava.gwt.html5.client.file.callback.FileErrorCallback::fileErrorCallback(Lcom/akjava/gwt/html5/client/file/FileError;)(fileerror); // } // // this.getFile(name,{create:create,exclusive:exclusive},getfile,error); // }-*/; // // public final native void getDirectory(String name,boolean create,boolean exclusive,FileEntryCallback callback,FileErrorCallback errorCallback)/*-{ // // var getfile=function(fileentry){ // callback.@com.akjava.gwt.html5.client.file.callback.FileEntryCallback::fileEntryCallback(Lcom/akjava/gwt/html5/client/file/webkit/FileEntry;)(fileentry); // // } // // var error=function(fileerror){ // errorCallback.@com.akjava.gwt.html5.client.file.callback.FileErrorCallback::fileErrorCallback(Lcom/akjava/gwt/html5/client/file/FileError;)(fileerror); // } // // this.getDirectory(name,{create:create,exclusive:exclusive},getfile,error); // }-*/; // // public final native void createWriter(FileWriterCallback writerCallback,FileErrorCallback errorCallback)/*-{ // // var createWriter=function(filewriter){ // writerCallback.@com.akjava.gwt.html5.client.file.callback.FileWriterCallback::createWriterCallback(Lcom/akjava/gwt/html5/client/file/FileWriter;)(filewriter); // } // // var error=function(fileerror){ // errorCallback.@com.akjava.gwt.html5.client.file.callback.FileErrorCallback::fileErrorCallback(Lcom/akjava/gwt/html5/client/file/FileError;)(fileerror); // } // // this.createWriter(createWriter,error); // }-*/; // // }
import com.akjava.gwt.html5.client.file.webkit.FileEntry; import com.google.gwt.core.client.JavaScriptObject;
package com.akjava.gwt.html5.client.file; public class FileSystem extends JavaScriptObject{ protected FileSystem(){} public final native String getName() /*-{ return this.name; }-*/;
// Path: src/com/akjava/gwt/html5/client/file/webkit/FileEntry.java // public class FileEntry extends JavaScriptObject{ // // protected FileEntry(){} // // public final native boolean isFile()/*-{ // return this.isFile; // }-*/; // // public final native boolean isDirectory()/*-{ // return this.isDirectory; // }-*/; // // public final native String getName()/*-{ // return this.name; // }-*/; // // public final native String getFullPath()/*-{ // return this.fullPath; // }-*/; // // //TODO support error // public final native void file(FileCallback callback)/*-{ // // this.file( function(file){ // callback.@com.akjava.gwt.html5.client.file.webkit.FileCallback::callback(Lcom/akjava/gwt/html5/client/file/File;)(file) // }); // // }-*/; // // //TODO support error // public final native void file(FilePathCallback callback,String parent)/*-{ // // this.file( function(file){ // callback.@com.akjava.gwt.html5.client.file.webkit.FilePathCallback::callback(Lcom/akjava/gwt/html5/client/file/File;Ljava/lang/String;)(file,parent) // }); // // }-*/; // // // //for directory only // public final native DirectoryReader getReader()/*-{ // return this.createReader(); // }-*/; // // //TODO implement copyTo,moveTo // // //TODO implement resolveLocalFileSystemURL // // public final native String toURL()/*-{ // return this.toURL(); // }-*/; // // // // // public final native void remove(VoidCallback simpleCallback,FileErrorCallback errorCallback)/*-{ // // var callback=function(){ // simpleCallback.@com.akjava.gwt.html5.client.file.callback.VoidCallback::callback()(); // } // // var error=function(fileerror){ // errorCallback.@com.akjava.gwt.html5.client.file.callback.FileErrorCallback::fileErrorCallback(Lcom/akjava/gwt/html5/client/file/FileError;)(fileerror); // } // // this.remove(callback,error); // }-*/; // // public final native void removeRecursively(VoidCallback simpleCallback,FileErrorCallback errorCallback)/*-{ // // var callback=function(){ // simpleCallback.@com.akjava.gwt.html5.client.file.callback.VoidCallback::callback()(); // } // // var error=function(fileerror){ // errorCallback.@com.akjava.gwt.html5.client.file.callback.FileErrorCallback::fileErrorCallback(Lcom/akjava/gwt/html5/client/file/FileError;)(fileerror); // } // // this.removeRecursively(callback,error); // }-*/; // // //TODO implement removeRecursively() // // //TODO implement copyTo,moveTo; // // // public final native void getFile(String name,boolean create,boolean exclusive,FileEntryCallback callback,FileErrorCallback errorCallback)/*-{ // // var getfile=function(fileentry){ // callback.@com.akjava.gwt.html5.client.file.callback.FileEntryCallback::fileEntryCallback(Lcom/akjava/gwt/html5/client/file/webkit/FileEntry;)(fileentry); // // } // // var error=function(fileerror){ // errorCallback.@com.akjava.gwt.html5.client.file.callback.FileErrorCallback::fileErrorCallback(Lcom/akjava/gwt/html5/client/file/FileError;)(fileerror); // } // // this.getFile(name,{create:create,exclusive:exclusive},getfile,error); // }-*/; // // public final native void getDirectory(String name,boolean create,boolean exclusive,FileEntryCallback callback,FileErrorCallback errorCallback)/*-{ // // var getfile=function(fileentry){ // callback.@com.akjava.gwt.html5.client.file.callback.FileEntryCallback::fileEntryCallback(Lcom/akjava/gwt/html5/client/file/webkit/FileEntry;)(fileentry); // // } // // var error=function(fileerror){ // errorCallback.@com.akjava.gwt.html5.client.file.callback.FileErrorCallback::fileErrorCallback(Lcom/akjava/gwt/html5/client/file/FileError;)(fileerror); // } // // this.getDirectory(name,{create:create,exclusive:exclusive},getfile,error); // }-*/; // // public final native void createWriter(FileWriterCallback writerCallback,FileErrorCallback errorCallback)/*-{ // // var createWriter=function(filewriter){ // writerCallback.@com.akjava.gwt.html5.client.file.callback.FileWriterCallback::createWriterCallback(Lcom/akjava/gwt/html5/client/file/FileWriter;)(filewriter); // } // // var error=function(fileerror){ // errorCallback.@com.akjava.gwt.html5.client.file.callback.FileErrorCallback::fileErrorCallback(Lcom/akjava/gwt/html5/client/file/FileError;)(fileerror); // } // // this.createWriter(createWriter,error); // }-*/; // // } // Path: src/com/akjava/gwt/html5/client/file/FileSystem.java import com.akjava.gwt.html5.client.file.webkit.FileEntry; import com.google.gwt.core.client.JavaScriptObject; package com.akjava.gwt.html5.client.file; public class FileSystem extends JavaScriptObject{ protected FileSystem(){} public final native String getName() /*-{ return this.name; }-*/;
public final native FileEntry getRoot() /*-{
akjava/html5gwt
src/com/akjava/gwt/html5/client/file/ui/DropDockDataUrlRootPanel.java
// Path: src/com/akjava/gwt/html5/client/file/File.java // public class File extends Blob{ // // protected File(){} // // public final native String getFileName()/*-{ // return this.name; // }-*/; // // public final native int getFileSize()/*-{ // return this.size; // }-*/; // // // // public final native String getFileType()/*-{ // return this.type; // }-*/; // // public final native Blob slice(int start,int length)/*-{ // return this.slice(start,length); // }-*/; // } // // Path: src/com/akjava/gwt/html5/client/file/FileHandler.java // public interface FileHandler { // public void onLoad(); // }
import com.akjava.gwt.html5.client.file.File; import com.akjava.gwt.html5.client.file.FileHandler; import com.akjava.gwt.html5.client.file.FileReader; import com.google.common.base.Optional; import com.google.common.base.Predicate; import com.google.gwt.dom.client.Style.Unit;
package com.akjava.gwt.html5.client.file.ui; /* * this is usefull when do nothing drop rootPanel */ public abstract class DropDockDataUrlRootPanel extends DropDockRootPanel{ public DropDockDataUrlRootPanel(Unit unit,boolean addRootLayoutPanel) { super(unit,addRootLayoutPanel); } public DropDockDataUrlRootPanel() { super(Unit.PX,false); }
// Path: src/com/akjava/gwt/html5/client/file/File.java // public class File extends Blob{ // // protected File(){} // // public final native String getFileName()/*-{ // return this.name; // }-*/; // // public final native int getFileSize()/*-{ // return this.size; // }-*/; // // // // public final native String getFileType()/*-{ // return this.type; // }-*/; // // public final native Blob slice(int start,int length)/*-{ // return this.slice(start,length); // }-*/; // } // // Path: src/com/akjava/gwt/html5/client/file/FileHandler.java // public interface FileHandler { // public void onLoad(); // } // Path: src/com/akjava/gwt/html5/client/file/ui/DropDockDataUrlRootPanel.java import com.akjava.gwt.html5.client.file.File; import com.akjava.gwt.html5.client.file.FileHandler; import com.akjava.gwt.html5.client.file.FileReader; import com.google.common.base.Optional; import com.google.common.base.Predicate; import com.google.gwt.dom.client.Style.Unit; package com.akjava.gwt.html5.client.file.ui; /* * this is usefull when do nothing drop rootPanel */ public abstract class DropDockDataUrlRootPanel extends DropDockRootPanel{ public DropDockDataUrlRootPanel(Unit unit,boolean addRootLayoutPanel) { super(unit,addRootLayoutPanel); } public DropDockDataUrlRootPanel() { super(Unit.PX,false); }
private Predicate<File> filePredicate;
akjava/html5gwt
src/com/akjava/gwt/html5/client/file/ui/DropDockDataUrlRootPanel.java
// Path: src/com/akjava/gwt/html5/client/file/File.java // public class File extends Blob{ // // protected File(){} // // public final native String getFileName()/*-{ // return this.name; // }-*/; // // public final native int getFileSize()/*-{ // return this.size; // }-*/; // // // // public final native String getFileType()/*-{ // return this.type; // }-*/; // // public final native Blob slice(int start,int length)/*-{ // return this.slice(start,length); // }-*/; // } // // Path: src/com/akjava/gwt/html5/client/file/FileHandler.java // public interface FileHandler { // public void onLoad(); // }
import com.akjava.gwt.html5.client.file.File; import com.akjava.gwt.html5.client.file.FileHandler; import com.akjava.gwt.html5.client.file.FileReader; import com.google.common.base.Optional; import com.google.common.base.Predicate; import com.google.gwt.dom.client.Style.Unit;
package com.akjava.gwt.html5.client.file.ui; /* * this is usefull when do nothing drop rootPanel */ public abstract class DropDockDataUrlRootPanel extends DropDockRootPanel{ public DropDockDataUrlRootPanel(Unit unit,boolean addRootLayoutPanel) { super(unit,addRootLayoutPanel); } public DropDockDataUrlRootPanel() { super(Unit.PX,false); } private Predicate<File> filePredicate; public Predicate<File> getFilePredicate() { return filePredicate; } public void setFilePredicate(Predicate<File> filePredicate) { this.filePredicate = filePredicate; } @Override public void callback(final File file, final String parent) { if(file==null){ return; } if(filePredicate!=null && !filePredicate.apply(file)){ return; } final FileReader reader = FileReader.createFileReader();
// Path: src/com/akjava/gwt/html5/client/file/File.java // public class File extends Blob{ // // protected File(){} // // public final native String getFileName()/*-{ // return this.name; // }-*/; // // public final native int getFileSize()/*-{ // return this.size; // }-*/; // // // // public final native String getFileType()/*-{ // return this.type; // }-*/; // // public final native Blob slice(int start,int length)/*-{ // return this.slice(start,length); // }-*/; // } // // Path: src/com/akjava/gwt/html5/client/file/FileHandler.java // public interface FileHandler { // public void onLoad(); // } // Path: src/com/akjava/gwt/html5/client/file/ui/DropDockDataUrlRootPanel.java import com.akjava.gwt.html5.client.file.File; import com.akjava.gwt.html5.client.file.FileHandler; import com.akjava.gwt.html5.client.file.FileReader; import com.google.common.base.Optional; import com.google.common.base.Predicate; import com.google.gwt.dom.client.Style.Unit; package com.akjava.gwt.html5.client.file.ui; /* * this is usefull when do nothing drop rootPanel */ public abstract class DropDockDataUrlRootPanel extends DropDockRootPanel{ public DropDockDataUrlRootPanel(Unit unit,boolean addRootLayoutPanel) { super(unit,addRootLayoutPanel); } public DropDockDataUrlRootPanel() { super(Unit.PX,false); } private Predicate<File> filePredicate; public Predicate<File> getFilePredicate() { return filePredicate; } public void setFilePredicate(Predicate<File> filePredicate) { this.filePredicate = filePredicate; } @Override public void callback(final File file, final String parent) { if(file==null){ return; } if(filePredicate!=null && !filePredicate.apply(file)){ return; } final FileReader reader = FileReader.createFileReader();
reader.setOnLoad(new FileHandler() {
akjava/html5gwt
src/com/akjava/gwt/html5/client/extra/HTML5Builder.java
// Path: src/com/akjava/gwt/html5/client/IInputRange.java // public interface IInputRange { // public void setMax(int max); // public void setMin(int min); // public int getMin(); // public int getMax(); // public void setValue(Integer value); // public Integer getValue(); // public void setWidth(int width); // public void setHeight(int height); // public void setEnabled(boolean bool); // public void addInputRangeListener(InputRangeListener listener); // public void removeInputRangeListener(InputRangeListener listener); // } // // Path: src/com/akjava/gwt/html5/client/InputRangeListener.java // public interface InputRangeListener { // public void changed(int newValue); // }
import com.akjava.gwt.html5.client.IInputRange; import com.akjava.gwt.html5.client.InputRangeListener; import com.google.gwt.user.client.ui.Label;
package com.akjava.gwt.html5.client.extra; public class HTML5Builder { public static Label createRangeLabel(final String text,final IInputRange range){ final Label label=new Label(); label.setText(text+""+range.getValue()); label.setStylePrimaryName("title");
// Path: src/com/akjava/gwt/html5/client/IInputRange.java // public interface IInputRange { // public void setMax(int max); // public void setMin(int min); // public int getMin(); // public int getMax(); // public void setValue(Integer value); // public Integer getValue(); // public void setWidth(int width); // public void setHeight(int height); // public void setEnabled(boolean bool); // public void addInputRangeListener(InputRangeListener listener); // public void removeInputRangeListener(InputRangeListener listener); // } // // Path: src/com/akjava/gwt/html5/client/InputRangeListener.java // public interface InputRangeListener { // public void changed(int newValue); // } // Path: src/com/akjava/gwt/html5/client/extra/HTML5Builder.java import com.akjava.gwt.html5.client.IInputRange; import com.akjava.gwt.html5.client.InputRangeListener; import com.google.gwt.user.client.ui.Label; package com.akjava.gwt.html5.client.extra; public class HTML5Builder { public static Label createRangeLabel(final String text,final IInputRange range){ final Label label=new Label(); label.setText(text+""+range.getValue()); label.setStylePrimaryName("title");
range.addInputRangeListener(new InputRangeListener() {
akjava/html5gwt
src/com/akjava/gwt/html5/client/file/ui/DataUrlDropVerticalRootPanel.java
// Path: src/com/akjava/gwt/html5/client/file/File.java // public class File extends Blob{ // // protected File(){} // // public final native String getFileName()/*-{ // return this.name; // }-*/; // // public final native int getFileSize()/*-{ // return this.size; // }-*/; // // // // public final native String getFileType()/*-{ // return this.type; // }-*/; // // public final native Blob slice(int start,int length)/*-{ // return this.slice(start,length); // }-*/; // } // // Path: src/com/akjava/gwt/html5/client/file/FileHandler.java // public interface FileHandler { // public void onLoad(); // }
import com.akjava.gwt.html5.client.file.File; import com.akjava.gwt.html5.client.file.FileHandler; import com.akjava.gwt.html5.client.file.FileReader;
package com.akjava.gwt.html5.client.file.ui; /* * this is usefull when do nothing drop rootPanel */ public abstract class DataUrlDropVerticalRootPanel extends DropVerticalRootPanel{ public DataUrlDropVerticalRootPanel(boolean addRootLayoutPanel) { super(addRootLayoutPanel); } @Override
// Path: src/com/akjava/gwt/html5/client/file/File.java // public class File extends Blob{ // // protected File(){} // // public final native String getFileName()/*-{ // return this.name; // }-*/; // // public final native int getFileSize()/*-{ // return this.size; // }-*/; // // // // public final native String getFileType()/*-{ // return this.type; // }-*/; // // public final native Blob slice(int start,int length)/*-{ // return this.slice(start,length); // }-*/; // } // // Path: src/com/akjava/gwt/html5/client/file/FileHandler.java // public interface FileHandler { // public void onLoad(); // } // Path: src/com/akjava/gwt/html5/client/file/ui/DataUrlDropVerticalRootPanel.java import com.akjava.gwt.html5.client.file.File; import com.akjava.gwt.html5.client.file.FileHandler; import com.akjava.gwt.html5.client.file.FileReader; package com.akjava.gwt.html5.client.file.ui; /* * this is usefull when do nothing drop rootPanel */ public abstract class DataUrlDropVerticalRootPanel extends DropVerticalRootPanel{ public DataUrlDropVerticalRootPanel(boolean addRootLayoutPanel) { super(addRootLayoutPanel); } @Override
public void callback(final File file, String parent) {
akjava/html5gwt
src/com/akjava/gwt/html5/client/file/ui/DataUrlDropVerticalRootPanel.java
// Path: src/com/akjava/gwt/html5/client/file/File.java // public class File extends Blob{ // // protected File(){} // // public final native String getFileName()/*-{ // return this.name; // }-*/; // // public final native int getFileSize()/*-{ // return this.size; // }-*/; // // // // public final native String getFileType()/*-{ // return this.type; // }-*/; // // public final native Blob slice(int start,int length)/*-{ // return this.slice(start,length); // }-*/; // } // // Path: src/com/akjava/gwt/html5/client/file/FileHandler.java // public interface FileHandler { // public void onLoad(); // }
import com.akjava.gwt.html5.client.file.File; import com.akjava.gwt.html5.client.file.FileHandler; import com.akjava.gwt.html5.client.file.FileReader;
package com.akjava.gwt.html5.client.file.ui; /* * this is usefull when do nothing drop rootPanel */ public abstract class DataUrlDropVerticalRootPanel extends DropVerticalRootPanel{ public DataUrlDropVerticalRootPanel(boolean addRootLayoutPanel) { super(addRootLayoutPanel); } @Override public void callback(final File file, String parent) { if(file==null){ return; } final FileReader reader = FileReader.createFileReader();
// Path: src/com/akjava/gwt/html5/client/file/File.java // public class File extends Blob{ // // protected File(){} // // public final native String getFileName()/*-{ // return this.name; // }-*/; // // public final native int getFileSize()/*-{ // return this.size; // }-*/; // // // // public final native String getFileType()/*-{ // return this.type; // }-*/; // // public final native Blob slice(int start,int length)/*-{ // return this.slice(start,length); // }-*/; // } // // Path: src/com/akjava/gwt/html5/client/file/FileHandler.java // public interface FileHandler { // public void onLoad(); // } // Path: src/com/akjava/gwt/html5/client/file/ui/DataUrlDropVerticalRootPanel.java import com.akjava.gwt.html5.client.file.File; import com.akjava.gwt.html5.client.file.FileHandler; import com.akjava.gwt.html5.client.file.FileReader; package com.akjava.gwt.html5.client.file.ui; /* * this is usefull when do nothing drop rootPanel */ public abstract class DataUrlDropVerticalRootPanel extends DropVerticalRootPanel{ public DataUrlDropVerticalRootPanel(boolean addRootLayoutPanel) { super(addRootLayoutPanel); } @Override public void callback(final File file, String parent) { if(file==null){ return; } final FileReader reader = FileReader.createFileReader();
reader.setOnLoad(new FileHandler() {
akjava/html5gwt
src/com/akjava/gwt/html5/client/speechsynthesis/SpeechSynthesisUtterance.java
// Path: src/com/akjava/gwt/html5/client/speechsynthesis/listeners/SpeechSynthesisBoundaryListener.java // public interface SpeechSynthesisBoundaryListener { // public void onBoundary(SpeechSynthesisEvent event); // } // // Path: src/com/akjava/gwt/html5/client/speechsynthesis/listeners/SpeechSynthesisEndListener.java // public interface SpeechSynthesisEndListener { // public void onEnd(SpeechSynthesisEvent event); // } // // Path: src/com/akjava/gwt/html5/client/speechsynthesis/listeners/SpeechSynthesisErrorListener.java // public interface SpeechSynthesisErrorListener { // public void onError(SpeechSynthesisEvent event); // } // // Path: src/com/akjava/gwt/html5/client/speechsynthesis/listeners/SpeechSynthesisMarkListener.java // public interface SpeechSynthesisMarkListener { // public void onMark(SpeechSynthesisEvent event); // } // // Path: src/com/akjava/gwt/html5/client/speechsynthesis/listeners/SpeechSynthesisResumeListener.java // public interface SpeechSynthesisResumeListener { // public void onResume(SpeechSynthesisEvent event); // } // // Path: src/com/akjava/gwt/html5/client/speechsynthesis/listeners/SpeechSynthesisStartListener.java // public interface SpeechSynthesisStartListener { // public void onStart(SpeechSynthesisEvent event); // }
import com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisBoundaryListener; import com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisEndListener; import com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisErrorListener; import com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisMarkListener; import com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisPauseListener; import com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisResumeListener; import com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisStartListener; import com.google.gwt.core.client.JavaScriptObject;
package com.akjava.gwt.html5.client.speechsynthesis; //TODO support event public class SpeechSynthesisUtterance extends JavaScriptObject{ protected SpeechSynthesisUtterance(){} public static final native SpeechSynthesisUtterance create()/*-{ return new $wnd.SpeechSynthesisUtterance(); }-*/; public static final native SpeechSynthesisUtterance create(String text)/*-{ return new $wnd.SpeechSynthesisUtterance(text); }-*/; public final native void setText(String text)/*-{ this.text=text; }-*/; public final native void setLang(String lang)/*-{ this.lang=lang; }-*/; public final native void setVoiceURI(String voiceURI)/*-{ this.voiceURI=voiceURI; }-*/; public final native void setVolume(double volume)/*-{ this.volume=volume; }-*/; public final native void setRate(double rate)/*-{ this.rate=rate; }-*/; public final native void setPitch(double pitch)/*-{ this.pitch=pitch; }-*/; public final native void setVoice(Voice voice)/*-{ this.voice=voice; }-*/;
// Path: src/com/akjava/gwt/html5/client/speechsynthesis/listeners/SpeechSynthesisBoundaryListener.java // public interface SpeechSynthesisBoundaryListener { // public void onBoundary(SpeechSynthesisEvent event); // } // // Path: src/com/akjava/gwt/html5/client/speechsynthesis/listeners/SpeechSynthesisEndListener.java // public interface SpeechSynthesisEndListener { // public void onEnd(SpeechSynthesisEvent event); // } // // Path: src/com/akjava/gwt/html5/client/speechsynthesis/listeners/SpeechSynthesisErrorListener.java // public interface SpeechSynthesisErrorListener { // public void onError(SpeechSynthesisEvent event); // } // // Path: src/com/akjava/gwt/html5/client/speechsynthesis/listeners/SpeechSynthesisMarkListener.java // public interface SpeechSynthesisMarkListener { // public void onMark(SpeechSynthesisEvent event); // } // // Path: src/com/akjava/gwt/html5/client/speechsynthesis/listeners/SpeechSynthesisResumeListener.java // public interface SpeechSynthesisResumeListener { // public void onResume(SpeechSynthesisEvent event); // } // // Path: src/com/akjava/gwt/html5/client/speechsynthesis/listeners/SpeechSynthesisStartListener.java // public interface SpeechSynthesisStartListener { // public void onStart(SpeechSynthesisEvent event); // } // Path: src/com/akjava/gwt/html5/client/speechsynthesis/SpeechSynthesisUtterance.java import com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisBoundaryListener; import com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisEndListener; import com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisErrorListener; import com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisMarkListener; import com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisPauseListener; import com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisResumeListener; import com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisStartListener; import com.google.gwt.core.client.JavaScriptObject; package com.akjava.gwt.html5.client.speechsynthesis; //TODO support event public class SpeechSynthesisUtterance extends JavaScriptObject{ protected SpeechSynthesisUtterance(){} public static final native SpeechSynthesisUtterance create()/*-{ return new $wnd.SpeechSynthesisUtterance(); }-*/; public static final native SpeechSynthesisUtterance create(String text)/*-{ return new $wnd.SpeechSynthesisUtterance(text); }-*/; public final native void setText(String text)/*-{ this.text=text; }-*/; public final native void setLang(String lang)/*-{ this.lang=lang; }-*/; public final native void setVoiceURI(String voiceURI)/*-{ this.voiceURI=voiceURI; }-*/; public final native void setVolume(double volume)/*-{ this.volume=volume; }-*/; public final native void setRate(double rate)/*-{ this.rate=rate; }-*/; public final native void setPitch(double pitch)/*-{ this.pitch=pitch; }-*/; public final native void setVoice(Voice voice)/*-{ this.voice=voice; }-*/;
public final native void setOnEnd(SpeechSynthesisEndListener listener)/*-{
akjava/html5gwt
src/com/akjava/gwt/html5/client/speechsynthesis/SpeechSynthesisUtterance.java
// Path: src/com/akjava/gwt/html5/client/speechsynthesis/listeners/SpeechSynthesisBoundaryListener.java // public interface SpeechSynthesisBoundaryListener { // public void onBoundary(SpeechSynthesisEvent event); // } // // Path: src/com/akjava/gwt/html5/client/speechsynthesis/listeners/SpeechSynthesisEndListener.java // public interface SpeechSynthesisEndListener { // public void onEnd(SpeechSynthesisEvent event); // } // // Path: src/com/akjava/gwt/html5/client/speechsynthesis/listeners/SpeechSynthesisErrorListener.java // public interface SpeechSynthesisErrorListener { // public void onError(SpeechSynthesisEvent event); // } // // Path: src/com/akjava/gwt/html5/client/speechsynthesis/listeners/SpeechSynthesisMarkListener.java // public interface SpeechSynthesisMarkListener { // public void onMark(SpeechSynthesisEvent event); // } // // Path: src/com/akjava/gwt/html5/client/speechsynthesis/listeners/SpeechSynthesisResumeListener.java // public interface SpeechSynthesisResumeListener { // public void onResume(SpeechSynthesisEvent event); // } // // Path: src/com/akjava/gwt/html5/client/speechsynthesis/listeners/SpeechSynthesisStartListener.java // public interface SpeechSynthesisStartListener { // public void onStart(SpeechSynthesisEvent event); // }
import com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisBoundaryListener; import com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisEndListener; import com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisErrorListener; import com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisMarkListener; import com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisPauseListener; import com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisResumeListener; import com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisStartListener; import com.google.gwt.core.client.JavaScriptObject;
}-*/; public final native void setVoiceURI(String voiceURI)/*-{ this.voiceURI=voiceURI; }-*/; public final native void setVolume(double volume)/*-{ this.volume=volume; }-*/; public final native void setRate(double rate)/*-{ this.rate=rate; }-*/; public final native void setPitch(double pitch)/*-{ this.pitch=pitch; }-*/; public final native void setVoice(Voice voice)/*-{ this.voice=voice; }-*/; public final native void setOnEnd(SpeechSynthesisEndListener listener)/*-{ this.onend=function (event) { listener.@com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisEndListener::onEnd(Lcom/akjava/gwt/html5/client/speechsynthesis/SpeechSynthesisEvent;)(event); }; }-*/;
// Path: src/com/akjava/gwt/html5/client/speechsynthesis/listeners/SpeechSynthesisBoundaryListener.java // public interface SpeechSynthesisBoundaryListener { // public void onBoundary(SpeechSynthesisEvent event); // } // // Path: src/com/akjava/gwt/html5/client/speechsynthesis/listeners/SpeechSynthesisEndListener.java // public interface SpeechSynthesisEndListener { // public void onEnd(SpeechSynthesisEvent event); // } // // Path: src/com/akjava/gwt/html5/client/speechsynthesis/listeners/SpeechSynthesisErrorListener.java // public interface SpeechSynthesisErrorListener { // public void onError(SpeechSynthesisEvent event); // } // // Path: src/com/akjava/gwt/html5/client/speechsynthesis/listeners/SpeechSynthesisMarkListener.java // public interface SpeechSynthesisMarkListener { // public void onMark(SpeechSynthesisEvent event); // } // // Path: src/com/akjava/gwt/html5/client/speechsynthesis/listeners/SpeechSynthesisResumeListener.java // public interface SpeechSynthesisResumeListener { // public void onResume(SpeechSynthesisEvent event); // } // // Path: src/com/akjava/gwt/html5/client/speechsynthesis/listeners/SpeechSynthesisStartListener.java // public interface SpeechSynthesisStartListener { // public void onStart(SpeechSynthesisEvent event); // } // Path: src/com/akjava/gwt/html5/client/speechsynthesis/SpeechSynthesisUtterance.java import com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisBoundaryListener; import com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisEndListener; import com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisErrorListener; import com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisMarkListener; import com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisPauseListener; import com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisResumeListener; import com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisStartListener; import com.google.gwt.core.client.JavaScriptObject; }-*/; public final native void setVoiceURI(String voiceURI)/*-{ this.voiceURI=voiceURI; }-*/; public final native void setVolume(double volume)/*-{ this.volume=volume; }-*/; public final native void setRate(double rate)/*-{ this.rate=rate; }-*/; public final native void setPitch(double pitch)/*-{ this.pitch=pitch; }-*/; public final native void setVoice(Voice voice)/*-{ this.voice=voice; }-*/; public final native void setOnEnd(SpeechSynthesisEndListener listener)/*-{ this.onend=function (event) { listener.@com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisEndListener::onEnd(Lcom/akjava/gwt/html5/client/speechsynthesis/SpeechSynthesisEvent;)(event); }; }-*/;
public final native void setOnStart(SpeechSynthesisStartListener listener)/*-{
akjava/html5gwt
src/com/akjava/gwt/html5/client/speechsynthesis/SpeechSynthesisUtterance.java
// Path: src/com/akjava/gwt/html5/client/speechsynthesis/listeners/SpeechSynthesisBoundaryListener.java // public interface SpeechSynthesisBoundaryListener { // public void onBoundary(SpeechSynthesisEvent event); // } // // Path: src/com/akjava/gwt/html5/client/speechsynthesis/listeners/SpeechSynthesisEndListener.java // public interface SpeechSynthesisEndListener { // public void onEnd(SpeechSynthesisEvent event); // } // // Path: src/com/akjava/gwt/html5/client/speechsynthesis/listeners/SpeechSynthesisErrorListener.java // public interface SpeechSynthesisErrorListener { // public void onError(SpeechSynthesisEvent event); // } // // Path: src/com/akjava/gwt/html5/client/speechsynthesis/listeners/SpeechSynthesisMarkListener.java // public interface SpeechSynthesisMarkListener { // public void onMark(SpeechSynthesisEvent event); // } // // Path: src/com/akjava/gwt/html5/client/speechsynthesis/listeners/SpeechSynthesisResumeListener.java // public interface SpeechSynthesisResumeListener { // public void onResume(SpeechSynthesisEvent event); // } // // Path: src/com/akjava/gwt/html5/client/speechsynthesis/listeners/SpeechSynthesisStartListener.java // public interface SpeechSynthesisStartListener { // public void onStart(SpeechSynthesisEvent event); // }
import com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisBoundaryListener; import com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisEndListener; import com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisErrorListener; import com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisMarkListener; import com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisPauseListener; import com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisResumeListener; import com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisStartListener; import com.google.gwt.core.client.JavaScriptObject;
public final native void setVolume(double volume)/*-{ this.volume=volume; }-*/; public final native void setRate(double rate)/*-{ this.rate=rate; }-*/; public final native void setPitch(double pitch)/*-{ this.pitch=pitch; }-*/; public final native void setVoice(Voice voice)/*-{ this.voice=voice; }-*/; public final native void setOnEnd(SpeechSynthesisEndListener listener)/*-{ this.onend=function (event) { listener.@com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisEndListener::onEnd(Lcom/akjava/gwt/html5/client/speechsynthesis/SpeechSynthesisEvent;)(event); }; }-*/; public final native void setOnStart(SpeechSynthesisStartListener listener)/*-{ this.onstart=function (event) { listener.@com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisStartListener::onStart(Lcom/akjava/gwt/html5/client/speechsynthesis/SpeechSynthesisEvent;)(event); }; }-*/;
// Path: src/com/akjava/gwt/html5/client/speechsynthesis/listeners/SpeechSynthesisBoundaryListener.java // public interface SpeechSynthesisBoundaryListener { // public void onBoundary(SpeechSynthesisEvent event); // } // // Path: src/com/akjava/gwt/html5/client/speechsynthesis/listeners/SpeechSynthesisEndListener.java // public interface SpeechSynthesisEndListener { // public void onEnd(SpeechSynthesisEvent event); // } // // Path: src/com/akjava/gwt/html5/client/speechsynthesis/listeners/SpeechSynthesisErrorListener.java // public interface SpeechSynthesisErrorListener { // public void onError(SpeechSynthesisEvent event); // } // // Path: src/com/akjava/gwt/html5/client/speechsynthesis/listeners/SpeechSynthesisMarkListener.java // public interface SpeechSynthesisMarkListener { // public void onMark(SpeechSynthesisEvent event); // } // // Path: src/com/akjava/gwt/html5/client/speechsynthesis/listeners/SpeechSynthesisResumeListener.java // public interface SpeechSynthesisResumeListener { // public void onResume(SpeechSynthesisEvent event); // } // // Path: src/com/akjava/gwt/html5/client/speechsynthesis/listeners/SpeechSynthesisStartListener.java // public interface SpeechSynthesisStartListener { // public void onStart(SpeechSynthesisEvent event); // } // Path: src/com/akjava/gwt/html5/client/speechsynthesis/SpeechSynthesisUtterance.java import com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisBoundaryListener; import com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisEndListener; import com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisErrorListener; import com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisMarkListener; import com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisPauseListener; import com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisResumeListener; import com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisStartListener; import com.google.gwt.core.client.JavaScriptObject; public final native void setVolume(double volume)/*-{ this.volume=volume; }-*/; public final native void setRate(double rate)/*-{ this.rate=rate; }-*/; public final native void setPitch(double pitch)/*-{ this.pitch=pitch; }-*/; public final native void setVoice(Voice voice)/*-{ this.voice=voice; }-*/; public final native void setOnEnd(SpeechSynthesisEndListener listener)/*-{ this.onend=function (event) { listener.@com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisEndListener::onEnd(Lcom/akjava/gwt/html5/client/speechsynthesis/SpeechSynthesisEvent;)(event); }; }-*/; public final native void setOnStart(SpeechSynthesisStartListener listener)/*-{ this.onstart=function (event) { listener.@com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisStartListener::onStart(Lcom/akjava/gwt/html5/client/speechsynthesis/SpeechSynthesisEvent;)(event); }; }-*/;
public final native void setOnBoundary(SpeechSynthesisBoundaryListener listener)/*-{
akjava/html5gwt
src/com/akjava/gwt/html5/client/speechsynthesis/SpeechSynthesisUtterance.java
// Path: src/com/akjava/gwt/html5/client/speechsynthesis/listeners/SpeechSynthesisBoundaryListener.java // public interface SpeechSynthesisBoundaryListener { // public void onBoundary(SpeechSynthesisEvent event); // } // // Path: src/com/akjava/gwt/html5/client/speechsynthesis/listeners/SpeechSynthesisEndListener.java // public interface SpeechSynthesisEndListener { // public void onEnd(SpeechSynthesisEvent event); // } // // Path: src/com/akjava/gwt/html5/client/speechsynthesis/listeners/SpeechSynthesisErrorListener.java // public interface SpeechSynthesisErrorListener { // public void onError(SpeechSynthesisEvent event); // } // // Path: src/com/akjava/gwt/html5/client/speechsynthesis/listeners/SpeechSynthesisMarkListener.java // public interface SpeechSynthesisMarkListener { // public void onMark(SpeechSynthesisEvent event); // } // // Path: src/com/akjava/gwt/html5/client/speechsynthesis/listeners/SpeechSynthesisResumeListener.java // public interface SpeechSynthesisResumeListener { // public void onResume(SpeechSynthesisEvent event); // } // // Path: src/com/akjava/gwt/html5/client/speechsynthesis/listeners/SpeechSynthesisStartListener.java // public interface SpeechSynthesisStartListener { // public void onStart(SpeechSynthesisEvent event); // }
import com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisBoundaryListener; import com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisEndListener; import com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisErrorListener; import com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisMarkListener; import com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisPauseListener; import com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisResumeListener; import com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisStartListener; import com.google.gwt.core.client.JavaScriptObject;
this.rate=rate; }-*/; public final native void setPitch(double pitch)/*-{ this.pitch=pitch; }-*/; public final native void setVoice(Voice voice)/*-{ this.voice=voice; }-*/; public final native void setOnEnd(SpeechSynthesisEndListener listener)/*-{ this.onend=function (event) { listener.@com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisEndListener::onEnd(Lcom/akjava/gwt/html5/client/speechsynthesis/SpeechSynthesisEvent;)(event); }; }-*/; public final native void setOnStart(SpeechSynthesisStartListener listener)/*-{ this.onstart=function (event) { listener.@com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisStartListener::onStart(Lcom/akjava/gwt/html5/client/speechsynthesis/SpeechSynthesisEvent;)(event); }; }-*/; public final native void setOnBoundary(SpeechSynthesisBoundaryListener listener)/*-{ this.onboundary=function (event) { listener.@com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisBoundaryListener::onBoundary(Lcom/akjava/gwt/html5/client/speechsynthesis/SpeechSynthesisEvent;)(event); }; }-*/;
// Path: src/com/akjava/gwt/html5/client/speechsynthesis/listeners/SpeechSynthesisBoundaryListener.java // public interface SpeechSynthesisBoundaryListener { // public void onBoundary(SpeechSynthesisEvent event); // } // // Path: src/com/akjava/gwt/html5/client/speechsynthesis/listeners/SpeechSynthesisEndListener.java // public interface SpeechSynthesisEndListener { // public void onEnd(SpeechSynthesisEvent event); // } // // Path: src/com/akjava/gwt/html5/client/speechsynthesis/listeners/SpeechSynthesisErrorListener.java // public interface SpeechSynthesisErrorListener { // public void onError(SpeechSynthesisEvent event); // } // // Path: src/com/akjava/gwt/html5/client/speechsynthesis/listeners/SpeechSynthesisMarkListener.java // public interface SpeechSynthesisMarkListener { // public void onMark(SpeechSynthesisEvent event); // } // // Path: src/com/akjava/gwt/html5/client/speechsynthesis/listeners/SpeechSynthesisResumeListener.java // public interface SpeechSynthesisResumeListener { // public void onResume(SpeechSynthesisEvent event); // } // // Path: src/com/akjava/gwt/html5/client/speechsynthesis/listeners/SpeechSynthesisStartListener.java // public interface SpeechSynthesisStartListener { // public void onStart(SpeechSynthesisEvent event); // } // Path: src/com/akjava/gwt/html5/client/speechsynthesis/SpeechSynthesisUtterance.java import com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisBoundaryListener; import com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisEndListener; import com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisErrorListener; import com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisMarkListener; import com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisPauseListener; import com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisResumeListener; import com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisStartListener; import com.google.gwt.core.client.JavaScriptObject; this.rate=rate; }-*/; public final native void setPitch(double pitch)/*-{ this.pitch=pitch; }-*/; public final native void setVoice(Voice voice)/*-{ this.voice=voice; }-*/; public final native void setOnEnd(SpeechSynthesisEndListener listener)/*-{ this.onend=function (event) { listener.@com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisEndListener::onEnd(Lcom/akjava/gwt/html5/client/speechsynthesis/SpeechSynthesisEvent;)(event); }; }-*/; public final native void setOnStart(SpeechSynthesisStartListener listener)/*-{ this.onstart=function (event) { listener.@com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisStartListener::onStart(Lcom/akjava/gwt/html5/client/speechsynthesis/SpeechSynthesisEvent;)(event); }; }-*/; public final native void setOnBoundary(SpeechSynthesisBoundaryListener listener)/*-{ this.onboundary=function (event) { listener.@com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisBoundaryListener::onBoundary(Lcom/akjava/gwt/html5/client/speechsynthesis/SpeechSynthesisEvent;)(event); }; }-*/;
public final native void setOnError(SpeechSynthesisErrorListener listener)/*-{
akjava/html5gwt
src/com/akjava/gwt/html5/client/speechsynthesis/SpeechSynthesisUtterance.java
// Path: src/com/akjava/gwt/html5/client/speechsynthesis/listeners/SpeechSynthesisBoundaryListener.java // public interface SpeechSynthesisBoundaryListener { // public void onBoundary(SpeechSynthesisEvent event); // } // // Path: src/com/akjava/gwt/html5/client/speechsynthesis/listeners/SpeechSynthesisEndListener.java // public interface SpeechSynthesisEndListener { // public void onEnd(SpeechSynthesisEvent event); // } // // Path: src/com/akjava/gwt/html5/client/speechsynthesis/listeners/SpeechSynthesisErrorListener.java // public interface SpeechSynthesisErrorListener { // public void onError(SpeechSynthesisEvent event); // } // // Path: src/com/akjava/gwt/html5/client/speechsynthesis/listeners/SpeechSynthesisMarkListener.java // public interface SpeechSynthesisMarkListener { // public void onMark(SpeechSynthesisEvent event); // } // // Path: src/com/akjava/gwt/html5/client/speechsynthesis/listeners/SpeechSynthesisResumeListener.java // public interface SpeechSynthesisResumeListener { // public void onResume(SpeechSynthesisEvent event); // } // // Path: src/com/akjava/gwt/html5/client/speechsynthesis/listeners/SpeechSynthesisStartListener.java // public interface SpeechSynthesisStartListener { // public void onStart(SpeechSynthesisEvent event); // }
import com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisBoundaryListener; import com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisEndListener; import com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisErrorListener; import com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisMarkListener; import com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisPauseListener; import com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisResumeListener; import com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisStartListener; import com.google.gwt.core.client.JavaScriptObject;
}-*/; public final native void setVoice(Voice voice)/*-{ this.voice=voice; }-*/; public final native void setOnEnd(SpeechSynthesisEndListener listener)/*-{ this.onend=function (event) { listener.@com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisEndListener::onEnd(Lcom/akjava/gwt/html5/client/speechsynthesis/SpeechSynthesisEvent;)(event); }; }-*/; public final native void setOnStart(SpeechSynthesisStartListener listener)/*-{ this.onstart=function (event) { listener.@com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisStartListener::onStart(Lcom/akjava/gwt/html5/client/speechsynthesis/SpeechSynthesisEvent;)(event); }; }-*/; public final native void setOnBoundary(SpeechSynthesisBoundaryListener listener)/*-{ this.onboundary=function (event) { listener.@com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisBoundaryListener::onBoundary(Lcom/akjava/gwt/html5/client/speechsynthesis/SpeechSynthesisEvent;)(event); }; }-*/; public final native void setOnError(SpeechSynthesisErrorListener listener)/*-{ this.onerror=function (event) { listener.@com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisErrorListener::onError(Lcom/akjava/gwt/html5/client/speechsynthesis/SpeechSynthesisEvent;)(event); }; }-*/;
// Path: src/com/akjava/gwt/html5/client/speechsynthesis/listeners/SpeechSynthesisBoundaryListener.java // public interface SpeechSynthesisBoundaryListener { // public void onBoundary(SpeechSynthesisEvent event); // } // // Path: src/com/akjava/gwt/html5/client/speechsynthesis/listeners/SpeechSynthesisEndListener.java // public interface SpeechSynthesisEndListener { // public void onEnd(SpeechSynthesisEvent event); // } // // Path: src/com/akjava/gwt/html5/client/speechsynthesis/listeners/SpeechSynthesisErrorListener.java // public interface SpeechSynthesisErrorListener { // public void onError(SpeechSynthesisEvent event); // } // // Path: src/com/akjava/gwt/html5/client/speechsynthesis/listeners/SpeechSynthesisMarkListener.java // public interface SpeechSynthesisMarkListener { // public void onMark(SpeechSynthesisEvent event); // } // // Path: src/com/akjava/gwt/html5/client/speechsynthesis/listeners/SpeechSynthesisResumeListener.java // public interface SpeechSynthesisResumeListener { // public void onResume(SpeechSynthesisEvent event); // } // // Path: src/com/akjava/gwt/html5/client/speechsynthesis/listeners/SpeechSynthesisStartListener.java // public interface SpeechSynthesisStartListener { // public void onStart(SpeechSynthesisEvent event); // } // Path: src/com/akjava/gwt/html5/client/speechsynthesis/SpeechSynthesisUtterance.java import com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisBoundaryListener; import com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisEndListener; import com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisErrorListener; import com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisMarkListener; import com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisPauseListener; import com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisResumeListener; import com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisStartListener; import com.google.gwt.core.client.JavaScriptObject; }-*/; public final native void setVoice(Voice voice)/*-{ this.voice=voice; }-*/; public final native void setOnEnd(SpeechSynthesisEndListener listener)/*-{ this.onend=function (event) { listener.@com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisEndListener::onEnd(Lcom/akjava/gwt/html5/client/speechsynthesis/SpeechSynthesisEvent;)(event); }; }-*/; public final native void setOnStart(SpeechSynthesisStartListener listener)/*-{ this.onstart=function (event) { listener.@com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisStartListener::onStart(Lcom/akjava/gwt/html5/client/speechsynthesis/SpeechSynthesisEvent;)(event); }; }-*/; public final native void setOnBoundary(SpeechSynthesisBoundaryListener listener)/*-{ this.onboundary=function (event) { listener.@com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisBoundaryListener::onBoundary(Lcom/akjava/gwt/html5/client/speechsynthesis/SpeechSynthesisEvent;)(event); }; }-*/; public final native void setOnError(SpeechSynthesisErrorListener listener)/*-{ this.onerror=function (event) { listener.@com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisErrorListener::onError(Lcom/akjava/gwt/html5/client/speechsynthesis/SpeechSynthesisEvent;)(event); }; }-*/;
public final native void setOnMark(SpeechSynthesisMarkListener listener)/*-{
akjava/html5gwt
src/com/akjava/gwt/html5/client/speechsynthesis/SpeechSynthesisUtterance.java
// Path: src/com/akjava/gwt/html5/client/speechsynthesis/listeners/SpeechSynthesisBoundaryListener.java // public interface SpeechSynthesisBoundaryListener { // public void onBoundary(SpeechSynthesisEvent event); // } // // Path: src/com/akjava/gwt/html5/client/speechsynthesis/listeners/SpeechSynthesisEndListener.java // public interface SpeechSynthesisEndListener { // public void onEnd(SpeechSynthesisEvent event); // } // // Path: src/com/akjava/gwt/html5/client/speechsynthesis/listeners/SpeechSynthesisErrorListener.java // public interface SpeechSynthesisErrorListener { // public void onError(SpeechSynthesisEvent event); // } // // Path: src/com/akjava/gwt/html5/client/speechsynthesis/listeners/SpeechSynthesisMarkListener.java // public interface SpeechSynthesisMarkListener { // public void onMark(SpeechSynthesisEvent event); // } // // Path: src/com/akjava/gwt/html5/client/speechsynthesis/listeners/SpeechSynthesisResumeListener.java // public interface SpeechSynthesisResumeListener { // public void onResume(SpeechSynthesisEvent event); // } // // Path: src/com/akjava/gwt/html5/client/speechsynthesis/listeners/SpeechSynthesisStartListener.java // public interface SpeechSynthesisStartListener { // public void onStart(SpeechSynthesisEvent event); // }
import com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisBoundaryListener; import com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisEndListener; import com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisErrorListener; import com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisMarkListener; import com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisPauseListener; import com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisResumeListener; import com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisStartListener; import com.google.gwt.core.client.JavaScriptObject;
public final native void setOnStart(SpeechSynthesisStartListener listener)/*-{ this.onstart=function (event) { listener.@com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisStartListener::onStart(Lcom/akjava/gwt/html5/client/speechsynthesis/SpeechSynthesisEvent;)(event); }; }-*/; public final native void setOnBoundary(SpeechSynthesisBoundaryListener listener)/*-{ this.onboundary=function (event) { listener.@com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisBoundaryListener::onBoundary(Lcom/akjava/gwt/html5/client/speechsynthesis/SpeechSynthesisEvent;)(event); }; }-*/; public final native void setOnError(SpeechSynthesisErrorListener listener)/*-{ this.onerror=function (event) { listener.@com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisErrorListener::onError(Lcom/akjava/gwt/html5/client/speechsynthesis/SpeechSynthesisEvent;)(event); }; }-*/; public final native void setOnMark(SpeechSynthesisMarkListener listener)/*-{ this.onmark=function (event) { listener.@com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisMarkListener::onMark(Lcom/akjava/gwt/html5/client/speechsynthesis/SpeechSynthesisEvent;)(event); }; }-*/; public final native void setOnPause(SpeechSynthesisPauseListener listener)/*-{ this.onpause=function (event) { listener.@com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisPauseListener::onPause(Lcom/akjava/gwt/html5/client/speechsynthesis/SpeechSynthesisEvent;)(event); }; }-*/;
// Path: src/com/akjava/gwt/html5/client/speechsynthesis/listeners/SpeechSynthesisBoundaryListener.java // public interface SpeechSynthesisBoundaryListener { // public void onBoundary(SpeechSynthesisEvent event); // } // // Path: src/com/akjava/gwt/html5/client/speechsynthesis/listeners/SpeechSynthesisEndListener.java // public interface SpeechSynthesisEndListener { // public void onEnd(SpeechSynthesisEvent event); // } // // Path: src/com/akjava/gwt/html5/client/speechsynthesis/listeners/SpeechSynthesisErrorListener.java // public interface SpeechSynthesisErrorListener { // public void onError(SpeechSynthesisEvent event); // } // // Path: src/com/akjava/gwt/html5/client/speechsynthesis/listeners/SpeechSynthesisMarkListener.java // public interface SpeechSynthesisMarkListener { // public void onMark(SpeechSynthesisEvent event); // } // // Path: src/com/akjava/gwt/html5/client/speechsynthesis/listeners/SpeechSynthesisResumeListener.java // public interface SpeechSynthesisResumeListener { // public void onResume(SpeechSynthesisEvent event); // } // // Path: src/com/akjava/gwt/html5/client/speechsynthesis/listeners/SpeechSynthesisStartListener.java // public interface SpeechSynthesisStartListener { // public void onStart(SpeechSynthesisEvent event); // } // Path: src/com/akjava/gwt/html5/client/speechsynthesis/SpeechSynthesisUtterance.java import com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisBoundaryListener; import com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisEndListener; import com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisErrorListener; import com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisMarkListener; import com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisPauseListener; import com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisResumeListener; import com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisStartListener; import com.google.gwt.core.client.JavaScriptObject; public final native void setOnStart(SpeechSynthesisStartListener listener)/*-{ this.onstart=function (event) { listener.@com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisStartListener::onStart(Lcom/akjava/gwt/html5/client/speechsynthesis/SpeechSynthesisEvent;)(event); }; }-*/; public final native void setOnBoundary(SpeechSynthesisBoundaryListener listener)/*-{ this.onboundary=function (event) { listener.@com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisBoundaryListener::onBoundary(Lcom/akjava/gwt/html5/client/speechsynthesis/SpeechSynthesisEvent;)(event); }; }-*/; public final native void setOnError(SpeechSynthesisErrorListener listener)/*-{ this.onerror=function (event) { listener.@com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisErrorListener::onError(Lcom/akjava/gwt/html5/client/speechsynthesis/SpeechSynthesisEvent;)(event); }; }-*/; public final native void setOnMark(SpeechSynthesisMarkListener listener)/*-{ this.onmark=function (event) { listener.@com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisMarkListener::onMark(Lcom/akjava/gwt/html5/client/speechsynthesis/SpeechSynthesisEvent;)(event); }; }-*/; public final native void setOnPause(SpeechSynthesisPauseListener listener)/*-{ this.onpause=function (event) { listener.@com.akjava.gwt.html5.client.speechsynthesis.listeners.SpeechSynthesisPauseListener::onPause(Lcom/akjava/gwt/html5/client/speechsynthesis/SpeechSynthesisEvent;)(event); }; }-*/;
public final native void setOnResume(SpeechSynthesisResumeListener listener)/*-{
PowerBack/AnKey
AnKey/presenter/src/main/java/net/qiujuer/powerback/ankey/presenter/KeyVerifyPresenter.java
// Path: AnKey/model/src/main/java/net/qiujuer/powerback/ankey/model/xml/UserModel.java // public class UserModel extends XmlPreference { // private UUID id = AppModel.EMPTY_ID; // private String name; // private String taken; // private String key; // private String salt; // // @Override // protected void refresh(SharedPreferences sp) { // id = UUID.fromString(sp.getString("id", AppModel.EMPTY_ID.toString())); // name = sp.getString("name", name); // taken = sp.getString("taken", taken); // key = sp.getString("key", key); // salt = sp.getString("salt", salt); // } // // @Override // protected String getPreferenceName() { // return SettingModel.class.getName(); // } // // @Override // public void save() { // SharedPreferences sp = getSharedPreferences(); // SharedPreferences.Editor editor = sp.edit(); // // editor.putString("id", id.toString()); // editor.putString("name", name); // editor.putString("taken", taken); // editor.putString("key", key); // editor.putString("salt", salt); // // editor.apply(); // } // // public void setId(UUID id) { // this.id = id; // } // // public void setKey(String key) { // this.key = key; // } // // public void setName(String name) { // this.name = name; // } // // public void setTaken(String taken) { // this.taken = taken; // } // // public UUID getId() { // return id; // } // // public String getKey() { // return key; // } // // public String getName() { // return name; // } // // public String getTaken() { // return taken; // } // // public void setSalt(String salt) { // this.salt = salt; // } // // public String getSalt() { // return salt; // } // } // // Path: AnKey/presenter/src/main/java/net/qiujuer/powerback/ankey/presenter/view/KeyVerifyView.java // public interface KeyVerifyView { // String getKey(); // // void verifyOk(); // // void verifyError(); // // void needCreate(); // // }
import android.text.TextUtils; import net.qiujuer.powerback.ankey.model.xml.UserModel; import net.qiujuer.powerback.ankey.presenter.view.KeyVerifyView;
package net.qiujuer.powerback.ankey.presenter; /** * Created by qiujuer * on 15/10/24. */ public class KeyVerifyPresenter { private KeyVerifyView mView; public KeyVerifyPresenter(KeyVerifyView view) { mView = view; } public void verify() { String key = mView.getKey(); if (!TextUtils.isEmpty(key) && AppPresenter.setKey(key)) { mView.verifyOk(); } else { mView.verifyError(); } } public void checkKeyStatus() {
// Path: AnKey/model/src/main/java/net/qiujuer/powerback/ankey/model/xml/UserModel.java // public class UserModel extends XmlPreference { // private UUID id = AppModel.EMPTY_ID; // private String name; // private String taken; // private String key; // private String salt; // // @Override // protected void refresh(SharedPreferences sp) { // id = UUID.fromString(sp.getString("id", AppModel.EMPTY_ID.toString())); // name = sp.getString("name", name); // taken = sp.getString("taken", taken); // key = sp.getString("key", key); // salt = sp.getString("salt", salt); // } // // @Override // protected String getPreferenceName() { // return SettingModel.class.getName(); // } // // @Override // public void save() { // SharedPreferences sp = getSharedPreferences(); // SharedPreferences.Editor editor = sp.edit(); // // editor.putString("id", id.toString()); // editor.putString("name", name); // editor.putString("taken", taken); // editor.putString("key", key); // editor.putString("salt", salt); // // editor.apply(); // } // // public void setId(UUID id) { // this.id = id; // } // // public void setKey(String key) { // this.key = key; // } // // public void setName(String name) { // this.name = name; // } // // public void setTaken(String taken) { // this.taken = taken; // } // // public UUID getId() { // return id; // } // // public String getKey() { // return key; // } // // public String getName() { // return name; // } // // public String getTaken() { // return taken; // } // // public void setSalt(String salt) { // this.salt = salt; // } // // public String getSalt() { // return salt; // } // } // // Path: AnKey/presenter/src/main/java/net/qiujuer/powerback/ankey/presenter/view/KeyVerifyView.java // public interface KeyVerifyView { // String getKey(); // // void verifyOk(); // // void verifyError(); // // void needCreate(); // // } // Path: AnKey/presenter/src/main/java/net/qiujuer/powerback/ankey/presenter/KeyVerifyPresenter.java import android.text.TextUtils; import net.qiujuer.powerback.ankey.model.xml.UserModel; import net.qiujuer.powerback.ankey.presenter.view.KeyVerifyView; package net.qiujuer.powerback.ankey.presenter; /** * Created by qiujuer * on 15/10/24. */ public class KeyVerifyPresenter { private KeyVerifyView mView; public KeyVerifyPresenter(KeyVerifyView view) { mView = view; } public void verify() { String key = mView.getKey(); if (!TextUtils.isEmpty(key) && AppPresenter.setKey(key)) { mView.verifyOk(); } else { mView.verifyError(); } } public void checkKeyStatus() {
UserModel model = new UserModel();
PowerBack/AnKey
AnKey/model/src/main/java/net/qiujuer/powerback/ankey/model/xml/SettingModel.java
// Path: AnKey/model/src/main/java/net/qiujuer/powerback/ankey/model/AppModel.java // public class AppModel { // public final static UUID EMPTY_ID = new UUID(0, 0); // public static boolean DEBUG = false; // // private static Application APPLICATION; // private static RequestQueue REQUEST_QUEUE; // private static ExecutorService EXECUTORSERVICE; // // public static Application getApplication() { // return APPLICATION; // } // // public static void setApplication(Application application) { // if (application != null && application != APPLICATION) { // APPLICATION = application; // ActiveAndroid.initialize(APPLICATION); // // stopRequestQueue(); // REQUEST_QUEUE = Volley.newRequestQueue(APPLICATION); // } // } // // public static void dispose() { // // ThreadPool // stopThreadPool(); // // // Network // stopRequestQueue(); // // // DataBase // ActiveAndroid.dispose(); // APPLICATION = null; // } // // private static void stopRequestQueue() { // RequestQueue queue = REQUEST_QUEUE; // REQUEST_QUEUE = null; // if (queue != null) { // queue.stop(); // } // } // // private static void stopThreadPool() { // ExecutorService service = EXECUTORSERVICE; // EXECUTORSERVICE = null; // if (service != null && !service.isShutdown()) { // try { // service.shutdownNow(); // service.shutdown(); // } catch (Exception e) { // e.printStackTrace(); // } // } // } // // public static RequestQueue getRequestQueue() { // return REQUEST_QUEUE; // } // // public static ExecutorService getThreadPool() { // // Check and init executor // if (EXECUTORSERVICE == null) { // synchronized (AppModel.class) { // if (EXECUTORSERVICE == null) { // // Init threads executor // int size = Runtime.getRuntime().availableProcessors(); // EXECUTORSERVICE = Executors.newFixedThreadPool(size > 0 ? size : 1); // } // } // } // return EXECUTORSERVICE; // } // }
import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import net.qiujuer.powerback.ankey.model.AppModel;
} public boolean isFirstUse() { int verCode = getVerCode(); if (this.verCode < verCode) { this.verCode = verCode; save(); return true; } else return false; } public static int getVerCode() { PackageInfo info = getPackageInfo(); if (info != null) return info.versionCode; return -1; } public static String getVerName() { PackageInfo info = getPackageInfo(); if (info != null) return info.versionName; return null; } public static PackageInfo getPackageInfo() { try {
// Path: AnKey/model/src/main/java/net/qiujuer/powerback/ankey/model/AppModel.java // public class AppModel { // public final static UUID EMPTY_ID = new UUID(0, 0); // public static boolean DEBUG = false; // // private static Application APPLICATION; // private static RequestQueue REQUEST_QUEUE; // private static ExecutorService EXECUTORSERVICE; // // public static Application getApplication() { // return APPLICATION; // } // // public static void setApplication(Application application) { // if (application != null && application != APPLICATION) { // APPLICATION = application; // ActiveAndroid.initialize(APPLICATION); // // stopRequestQueue(); // REQUEST_QUEUE = Volley.newRequestQueue(APPLICATION); // } // } // // public static void dispose() { // // ThreadPool // stopThreadPool(); // // // Network // stopRequestQueue(); // // // DataBase // ActiveAndroid.dispose(); // APPLICATION = null; // } // // private static void stopRequestQueue() { // RequestQueue queue = REQUEST_QUEUE; // REQUEST_QUEUE = null; // if (queue != null) { // queue.stop(); // } // } // // private static void stopThreadPool() { // ExecutorService service = EXECUTORSERVICE; // EXECUTORSERVICE = null; // if (service != null && !service.isShutdown()) { // try { // service.shutdownNow(); // service.shutdown(); // } catch (Exception e) { // e.printStackTrace(); // } // } // } // // public static RequestQueue getRequestQueue() { // return REQUEST_QUEUE; // } // // public static ExecutorService getThreadPool() { // // Check and init executor // if (EXECUTORSERVICE == null) { // synchronized (AppModel.class) { // if (EXECUTORSERVICE == null) { // // Init threads executor // int size = Runtime.getRuntime().availableProcessors(); // EXECUTORSERVICE = Executors.newFixedThreadPool(size > 0 ? size : 1); // } // } // } // return EXECUTORSERVICE; // } // } // Path: AnKey/model/src/main/java/net/qiujuer/powerback/ankey/model/xml/SettingModel.java import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import net.qiujuer.powerback.ankey.model.AppModel; } public boolean isFirstUse() { int verCode = getVerCode(); if (this.verCode < verCode) { this.verCode = verCode; save(); return true; } else return false; } public static int getVerCode() { PackageInfo info = getPackageInfo(); if (info != null) return info.versionCode; return -1; } public static String getVerName() { PackageInfo info = getPackageInfo(); if (info != null) return info.versionName; return null; } public static PackageInfo getPackageInfo() { try {
PackageManager manager = AppModel.getApplication().getPackageManager();
PowerBack/AnKey
AnKey/app/src/main/java/net/qiujuer/powerback/ankey/ui/adapter/holder/InfoHolder.java
// Path: AnKey/model/src/main/java/net/qiujuer/powerback/ankey/model/view/InfoViewModel.java // public class InfoViewModel { // private UUID id; // private String description; // private int color; // private long lastDate; // // public InfoViewModel() { // // } // // public InfoViewModel(InfoModel model) { // this.id = model.getInfoId(); // this.lastDate = model.getLastDate(); // } // // public UUID getId() { // return id; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // this.color = getStringColor(this.description); // } // // public int getColor() { // return color; // } // // public static int getStringColor(String name) { // int bgColor = Color.TRANSPARENT; // int[] colorArray = Resource.Color.COLORS; // int index = 1; // if (!TextUtils.isEmpty(name)) { // index = Math.abs(name.hashCode()) % (colorArray.length - 1); // index++; // } // if (index < colorArray.length) // bgColor = colorArray[index]; // return bgColor; // } // // public long getLastDate() { // return lastDate; // } // // public void setColor(int color) { // this.color = color; // } // // public void setLastDate(long lastDate) { // this.lastDate = lastDate; // } // }
import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.TextView; import net.qiujuer.powerback.ankey.R; import net.qiujuer.powerback.ankey.model.view.InfoViewModel;
package net.qiujuer.powerback.ankey.ui.adapter.holder; /** * Created by qiujuer * on 15/10/29. */ public class InfoHolder extends RecyclerView.ViewHolder { private TextView mDes; private View mColor; public InfoHolder(View itemView, int type) { super(itemView); mDes = (TextView) itemView.findViewById(R.id.txt_des); mColor = itemView.findViewById(R.id.view_color); }
// Path: AnKey/model/src/main/java/net/qiujuer/powerback/ankey/model/view/InfoViewModel.java // public class InfoViewModel { // private UUID id; // private String description; // private int color; // private long lastDate; // // public InfoViewModel() { // // } // // public InfoViewModel(InfoModel model) { // this.id = model.getInfoId(); // this.lastDate = model.getLastDate(); // } // // public UUID getId() { // return id; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // this.color = getStringColor(this.description); // } // // public int getColor() { // return color; // } // // public static int getStringColor(String name) { // int bgColor = Color.TRANSPARENT; // int[] colorArray = Resource.Color.COLORS; // int index = 1; // if (!TextUtils.isEmpty(name)) { // index = Math.abs(name.hashCode()) % (colorArray.length - 1); // index++; // } // if (index < colorArray.length) // bgColor = colorArray[index]; // return bgColor; // } // // public long getLastDate() { // return lastDate; // } // // public void setColor(int color) { // this.color = color; // } // // public void setLastDate(long lastDate) { // this.lastDate = lastDate; // } // } // Path: AnKey/app/src/main/java/net/qiujuer/powerback/ankey/ui/adapter/holder/InfoHolder.java import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.TextView; import net.qiujuer.powerback.ankey.R; import net.qiujuer.powerback.ankey.model.view.InfoViewModel; package net.qiujuer.powerback.ankey.ui.adapter.holder; /** * Created by qiujuer * on 15/10/29. */ public class InfoHolder extends RecyclerView.ViewHolder { private TextView mDes; private View mColor; public InfoHolder(View itemView, int type) { super(itemView); mDes = (TextView) itemView.findViewById(R.id.txt_des); mColor = itemView.findViewById(R.id.view_color); }
public void setData(InfoViewModel model) {
PowerBack/AnKey
AnKey/app/src/main/java/net/qiujuer/powerback/ankey/AnKeyApplication.java
// Path: AnKey/presenter/src/main/java/net/qiujuer/powerback/ankey/presenter/AppPresenter.java // public class AppPresenter { // private static final Object SERVICE_LOCK = new Object(); // private static KeyTool KEY_TOOL; // private static boolean ALLOW_D_KEY = true; // // // public static void setApplication(Application application) { // AppModel.setApplication(application); // } // // public static void dispose() { // AppModel.dispose(); // } // // public static RequestQueue getRequestQueue() { // return AppModel.getRequestQueue(); // } // // public static boolean isLogin() { // return false; // } // // public static boolean isFirstUse() { // SettingModel model = new SettingModel(); // return model.isFirstUse(); // } // // public static boolean isHaveNetwork() { // final Context context = AppModel.getApplication(); // if (context == null) // return false; // ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); // if (connectivityManager == null) { // return false; // } else { // NetworkInfo[] networkInfo = connectivityManager.getAllNetworkInfo(); // if (networkInfo != null && networkInfo.length > 0) { // for (NetworkInfo aNetworkInfo : networkInfo) { // if (aNetworkInfo.getState() == NetworkInfo.State.CONNECTED) { // return true; // } // } // } // } // return false; // } // // public static boolean createKey(String key) { // UserModel model = new UserModel(); // if (TextUtils.isEmpty(model.getKey()) && TextUtils.isEmpty(model.getSalt())) { // String salt = UUID.randomUUID().toString(); // String keyHash = HashKit.getMD5String(HashKit.getMD5String(key)); // model.setSalt(salt); // model.setKey(keyHash); // model.save(); // return true; // } // return false; // } // // public static boolean setKey(String key) { // UserModel model = new UserModel(); // String keyHash = model.getKey(); // if (keyHash != null) { // key = HashKit.getMD5String(HashKit.getMD5String(key)); // if (key.equals(keyHash)) { // KEY_TOOL = KeyToolHelper.createDefaultKeyTool(key, model.getSalt()); // return true; // } // } // return false; // } // // public static String encrypt(String src) throws NullPointerException { // // Check the string is empty // if (TextUtils.isEmpty(src)) // return null; // // // If tool is null , will throw NullPointerException // KeyTool tool = KEY_TOOL; // if (tool == null) // throw new NullPointerException("The app key tool is null, you should call setKey()"); // else { // return tool.encrypt(src); // } // } // // public static String decrypt(String encrypted) throws NullPointerException { // // Check the string is empty // if (TextUtils.isEmpty(encrypted)) // return null; // // // If tool is null , will throw NullPointerException // KeyTool tool = KEY_TOOL; // if (tool == null) // throw new NullPointerException("The app key tool is null, you should call setKey()"); // else { // return tool.decrypt(encrypted); // } // } // // public static void destroyKey() { // KeyTool tool = KEY_TOOL; // if (tool != null) { // KEY_TOOL = null; // tool.destroyKey(); // } // } // // public static boolean validKey() { // return KEY_TOOL != null; // } // // // public static boolean allowDestroyKey() { // return ALLOW_D_KEY; // } // // public static void setAllowDestroyKey(boolean allowDestroyKey) { // ALLOW_D_KEY = allowDestroyKey; // } // }
import android.widget.Toast; import net.qiujuer.genius.kit.util.UiKit; import net.qiujuer.powerback.ankey.presenter.AppPresenter;
package net.qiujuer.powerback.ankey; /** * Created by qiujuer * on 15/10/24. */ public class AnKeyApplication extends SuperApplication { private Thread mClearKeyThread; public void onCreate() { super.onCreate();
// Path: AnKey/presenter/src/main/java/net/qiujuer/powerback/ankey/presenter/AppPresenter.java // public class AppPresenter { // private static final Object SERVICE_LOCK = new Object(); // private static KeyTool KEY_TOOL; // private static boolean ALLOW_D_KEY = true; // // // public static void setApplication(Application application) { // AppModel.setApplication(application); // } // // public static void dispose() { // AppModel.dispose(); // } // // public static RequestQueue getRequestQueue() { // return AppModel.getRequestQueue(); // } // // public static boolean isLogin() { // return false; // } // // public static boolean isFirstUse() { // SettingModel model = new SettingModel(); // return model.isFirstUse(); // } // // public static boolean isHaveNetwork() { // final Context context = AppModel.getApplication(); // if (context == null) // return false; // ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); // if (connectivityManager == null) { // return false; // } else { // NetworkInfo[] networkInfo = connectivityManager.getAllNetworkInfo(); // if (networkInfo != null && networkInfo.length > 0) { // for (NetworkInfo aNetworkInfo : networkInfo) { // if (aNetworkInfo.getState() == NetworkInfo.State.CONNECTED) { // return true; // } // } // } // } // return false; // } // // public static boolean createKey(String key) { // UserModel model = new UserModel(); // if (TextUtils.isEmpty(model.getKey()) && TextUtils.isEmpty(model.getSalt())) { // String salt = UUID.randomUUID().toString(); // String keyHash = HashKit.getMD5String(HashKit.getMD5String(key)); // model.setSalt(salt); // model.setKey(keyHash); // model.save(); // return true; // } // return false; // } // // public static boolean setKey(String key) { // UserModel model = new UserModel(); // String keyHash = model.getKey(); // if (keyHash != null) { // key = HashKit.getMD5String(HashKit.getMD5String(key)); // if (key.equals(keyHash)) { // KEY_TOOL = KeyToolHelper.createDefaultKeyTool(key, model.getSalt()); // return true; // } // } // return false; // } // // public static String encrypt(String src) throws NullPointerException { // // Check the string is empty // if (TextUtils.isEmpty(src)) // return null; // // // If tool is null , will throw NullPointerException // KeyTool tool = KEY_TOOL; // if (tool == null) // throw new NullPointerException("The app key tool is null, you should call setKey()"); // else { // return tool.encrypt(src); // } // } // // public static String decrypt(String encrypted) throws NullPointerException { // // Check the string is empty // if (TextUtils.isEmpty(encrypted)) // return null; // // // If tool is null , will throw NullPointerException // KeyTool tool = KEY_TOOL; // if (tool == null) // throw new NullPointerException("The app key tool is null, you should call setKey()"); // else { // return tool.decrypt(encrypted); // } // } // // public static void destroyKey() { // KeyTool tool = KEY_TOOL; // if (tool != null) { // KEY_TOOL = null; // tool.destroyKey(); // } // } // // public static boolean validKey() { // return KEY_TOOL != null; // } // // // public static boolean allowDestroyKey() { // return ALLOW_D_KEY; // } // // public static void setAllowDestroyKey(boolean allowDestroyKey) { // ALLOW_D_KEY = allowDestroyKey; // } // } // Path: AnKey/app/src/main/java/net/qiujuer/powerback/ankey/AnKeyApplication.java import android.widget.Toast; import net.qiujuer.genius.kit.util.UiKit; import net.qiujuer.powerback.ankey.presenter.AppPresenter; package net.qiujuer.powerback.ankey; /** * Created by qiujuer * on 15/10/24. */ public class AnKeyApplication extends SuperApplication { private Thread mClearKeyThread; public void onCreate() { super.onCreate();
AppPresenter.setApplication(this);
PowerBack/AnKey
AnKey/model/src/main/java/net/qiujuer/powerback/ankey/model/view/InfoViewModel.java
// Path: AnKey/model/src/main/java/net/qiujuer/powerback/ankey/model/db/InfoModel.java // @Table(name = "Info") // public class InfoModel extends Model implements ModelStatus { // // @Column(name = "InfoId") // private UUID infoId; // // @Column(name = "Description") // private String description; // // @Column(name = "Site") // public SiteModel site; // // @Column(name = "Color") // public int color; // // @Column(name = "UserName") // private FieldModel userName; // // @Column(name = "Email") // private FieldModel email; // // @Column(name = "QQ") // private FieldModel qq; // // @Column(name = "Call") // private FieldModel call; // // @Column(name = "Password") // private String password; // // @Column(name = "Remark") // private String remark; // // @Column(name = "Tag") // private String tag; // // @Column(name = "CreateDate") // private Date createDate; // // @Column(name = "UpdateDate") // private Date updateDate; // // @Column(name = "Encryption") // private int encryption; // // @Expose // @Column(name = "Status") // private transient int status; // // @Expose // @Column(name = "LastDate") // private transient long lastDate; // // public InfoModel() { // super(); // infoId = UUID.randomUUID(); // lastDate = System.currentTimeMillis(); // createDate = new Date(lastDate); // updateDate = createDate; // encryption = KEY_TOOL_VERSION; // } // // public void setCall(FieldModel call) { // this.call = call; // } // // public void setCreateDate(Date createDate) { // this.createDate = createDate; // } // // public void setDescription(String description) { // this.description = description; // } // // public void setEmail(FieldModel email) { // this.email = email; // } // // public void setEncryption(int encryption) { // this.encryption = encryption; // } // // public void setInfoId(UUID infoId) { // this.infoId = infoId; // } // // public void setPassword(String password) { // this.password = password; // } // // public void setQQ(FieldModel qq) { // this.qq = qq; // } // // public void setRemark(String remark) { // this.remark = remark; // } // // public void setSite(SiteModel site) { // this.site = site; // } // // public void setColor(int color) { // this.color = color; // } // // public void setTag(String tag) { // this.tag = tag; // } // // public void setUpdateDate(Date updateDate) { // this.updateDate = updateDate; // } // // public void setUserName(FieldModel userName) { // this.userName = userName; // } // // public void setStatus(int status) { // this.status = status; // } // // public void setLastDate(long lastDate) { // this.lastDate = lastDate; // } // // public FieldModel getCall() { // return call; // } // // public FieldModel getEmail() { // return email; // } // // public FieldModel getQQ() { // return qq; // } // // public FieldModel getUserName() { // return userName; // } // // public int getEncryption() { // return encryption; // } // // public SiteModel getSite() { // return site; // } // // public int getColor() { // return color; // } // // public Date getCreateDate() { // return createDate; // } // // public String getDescription() { // return description; // } // // public String getPassword() { // return password; // } // // public String getRemark() { // return remark; // } // // public String getTag() { // return tag; // } // // public Date getUpdateDate() { // return updateDate; // } // // public UUID getInfoId() { // return infoId; // } // // public int getStatus() { // return status; // } // // public long getLastDate() { // return lastDate; // } // // public static InfoModel get(UUID uuid) { // return new Select() // .from(InfoModel.class) // .where("InfoId = ?", uuid.toString()) // .executeSingle(); // } // // public static InfoModel get(long id) { // return new Select() // .from(InfoModel.class) // .where("id = ?", id) // .executeSingle(); // } // // public static List<InfoModel> getAll() { // return new Select() // .from(InfoModel.class) // .execute(); // } // // public static List<InfoModel> getAll(long date) { // return new Select() // .from(InfoModel.class) // .where("LastDate > ?", date) // .orderBy("LastDate DESC") // .execute(); // } // }
import android.graphics.Color; import android.text.TextUtils; import net.qiujuer.genius.res.Resource; import net.qiujuer.powerback.ankey.model.db.InfoModel; import java.util.UUID;
package net.qiujuer.powerback.ankey.model.view; /** * Created by qiujuer * on 15/10/29. */ public class InfoViewModel { private UUID id; private String description; private int color; private long lastDate; public InfoViewModel() { }
// Path: AnKey/model/src/main/java/net/qiujuer/powerback/ankey/model/db/InfoModel.java // @Table(name = "Info") // public class InfoModel extends Model implements ModelStatus { // // @Column(name = "InfoId") // private UUID infoId; // // @Column(name = "Description") // private String description; // // @Column(name = "Site") // public SiteModel site; // // @Column(name = "Color") // public int color; // // @Column(name = "UserName") // private FieldModel userName; // // @Column(name = "Email") // private FieldModel email; // // @Column(name = "QQ") // private FieldModel qq; // // @Column(name = "Call") // private FieldModel call; // // @Column(name = "Password") // private String password; // // @Column(name = "Remark") // private String remark; // // @Column(name = "Tag") // private String tag; // // @Column(name = "CreateDate") // private Date createDate; // // @Column(name = "UpdateDate") // private Date updateDate; // // @Column(name = "Encryption") // private int encryption; // // @Expose // @Column(name = "Status") // private transient int status; // // @Expose // @Column(name = "LastDate") // private transient long lastDate; // // public InfoModel() { // super(); // infoId = UUID.randomUUID(); // lastDate = System.currentTimeMillis(); // createDate = new Date(lastDate); // updateDate = createDate; // encryption = KEY_TOOL_VERSION; // } // // public void setCall(FieldModel call) { // this.call = call; // } // // public void setCreateDate(Date createDate) { // this.createDate = createDate; // } // // public void setDescription(String description) { // this.description = description; // } // // public void setEmail(FieldModel email) { // this.email = email; // } // // public void setEncryption(int encryption) { // this.encryption = encryption; // } // // public void setInfoId(UUID infoId) { // this.infoId = infoId; // } // // public void setPassword(String password) { // this.password = password; // } // // public void setQQ(FieldModel qq) { // this.qq = qq; // } // // public void setRemark(String remark) { // this.remark = remark; // } // // public void setSite(SiteModel site) { // this.site = site; // } // // public void setColor(int color) { // this.color = color; // } // // public void setTag(String tag) { // this.tag = tag; // } // // public void setUpdateDate(Date updateDate) { // this.updateDate = updateDate; // } // // public void setUserName(FieldModel userName) { // this.userName = userName; // } // // public void setStatus(int status) { // this.status = status; // } // // public void setLastDate(long lastDate) { // this.lastDate = lastDate; // } // // public FieldModel getCall() { // return call; // } // // public FieldModel getEmail() { // return email; // } // // public FieldModel getQQ() { // return qq; // } // // public FieldModel getUserName() { // return userName; // } // // public int getEncryption() { // return encryption; // } // // public SiteModel getSite() { // return site; // } // // public int getColor() { // return color; // } // // public Date getCreateDate() { // return createDate; // } // // public String getDescription() { // return description; // } // // public String getPassword() { // return password; // } // // public String getRemark() { // return remark; // } // // public String getTag() { // return tag; // } // // public Date getUpdateDate() { // return updateDate; // } // // public UUID getInfoId() { // return infoId; // } // // public int getStatus() { // return status; // } // // public long getLastDate() { // return lastDate; // } // // public static InfoModel get(UUID uuid) { // return new Select() // .from(InfoModel.class) // .where("InfoId = ?", uuid.toString()) // .executeSingle(); // } // // public static InfoModel get(long id) { // return new Select() // .from(InfoModel.class) // .where("id = ?", id) // .executeSingle(); // } // // public static List<InfoModel> getAll() { // return new Select() // .from(InfoModel.class) // .execute(); // } // // public static List<InfoModel> getAll(long date) { // return new Select() // .from(InfoModel.class) // .where("LastDate > ?", date) // .orderBy("LastDate DESC") // .execute(); // } // } // Path: AnKey/model/src/main/java/net/qiujuer/powerback/ankey/model/view/InfoViewModel.java import android.graphics.Color; import android.text.TextUtils; import net.qiujuer.genius.res.Resource; import net.qiujuer.powerback.ankey.model.db.InfoModel; import java.util.UUID; package net.qiujuer.powerback.ankey.model.view; /** * Created by qiujuer * on 15/10/29. */ public class InfoViewModel { private UUID id; private String description; private int color; private long lastDate; public InfoViewModel() { }
public InfoViewModel(InfoModel model) {
PowerBack/AnKey
AnKey/model/src/main/java/net/qiujuer/powerback/ankey/model/xml/XmlPreference.java
// Path: AnKey/model/src/main/java/net/qiujuer/powerback/ankey/model/AppModel.java // public class AppModel { // public final static UUID EMPTY_ID = new UUID(0, 0); // public static boolean DEBUG = false; // // private static Application APPLICATION; // private static RequestQueue REQUEST_QUEUE; // private static ExecutorService EXECUTORSERVICE; // // public static Application getApplication() { // return APPLICATION; // } // // public static void setApplication(Application application) { // if (application != null && application != APPLICATION) { // APPLICATION = application; // ActiveAndroid.initialize(APPLICATION); // // stopRequestQueue(); // REQUEST_QUEUE = Volley.newRequestQueue(APPLICATION); // } // } // // public static void dispose() { // // ThreadPool // stopThreadPool(); // // // Network // stopRequestQueue(); // // // DataBase // ActiveAndroid.dispose(); // APPLICATION = null; // } // // private static void stopRequestQueue() { // RequestQueue queue = REQUEST_QUEUE; // REQUEST_QUEUE = null; // if (queue != null) { // queue.stop(); // } // } // // private static void stopThreadPool() { // ExecutorService service = EXECUTORSERVICE; // EXECUTORSERVICE = null; // if (service != null && !service.isShutdown()) { // try { // service.shutdownNow(); // service.shutdown(); // } catch (Exception e) { // e.printStackTrace(); // } // } // } // // public static RequestQueue getRequestQueue() { // return REQUEST_QUEUE; // } // // public static ExecutorService getThreadPool() { // // Check and init executor // if (EXECUTORSERVICE == null) { // synchronized (AppModel.class) { // if (EXECUTORSERVICE == null) { // // Init threads executor // int size = Runtime.getRuntime().availableProcessors(); // EXECUTORSERVICE = Executors.newFixedThreadPool(size > 0 ? size : 1); // } // } // } // return EXECUTORSERVICE; // } // }
import android.content.Context; import android.content.SharedPreferences; import net.qiujuer.powerback.ankey.model.AppModel;
package net.qiujuer.powerback.ankey.model.xml; /** * Created by qiujuer * on 15/10/19. */ public abstract class XmlPreference { public XmlPreference() { refresh(getSharedPreferences()); } protected SharedPreferences getSharedPreferences() {
// Path: AnKey/model/src/main/java/net/qiujuer/powerback/ankey/model/AppModel.java // public class AppModel { // public final static UUID EMPTY_ID = new UUID(0, 0); // public static boolean DEBUG = false; // // private static Application APPLICATION; // private static RequestQueue REQUEST_QUEUE; // private static ExecutorService EXECUTORSERVICE; // // public static Application getApplication() { // return APPLICATION; // } // // public static void setApplication(Application application) { // if (application != null && application != APPLICATION) { // APPLICATION = application; // ActiveAndroid.initialize(APPLICATION); // // stopRequestQueue(); // REQUEST_QUEUE = Volley.newRequestQueue(APPLICATION); // } // } // // public static void dispose() { // // ThreadPool // stopThreadPool(); // // // Network // stopRequestQueue(); // // // DataBase // ActiveAndroid.dispose(); // APPLICATION = null; // } // // private static void stopRequestQueue() { // RequestQueue queue = REQUEST_QUEUE; // REQUEST_QUEUE = null; // if (queue != null) { // queue.stop(); // } // } // // private static void stopThreadPool() { // ExecutorService service = EXECUTORSERVICE; // EXECUTORSERVICE = null; // if (service != null && !service.isShutdown()) { // try { // service.shutdownNow(); // service.shutdown(); // } catch (Exception e) { // e.printStackTrace(); // } // } // } // // public static RequestQueue getRequestQueue() { // return REQUEST_QUEUE; // } // // public static ExecutorService getThreadPool() { // // Check and init executor // if (EXECUTORSERVICE == null) { // synchronized (AppModel.class) { // if (EXECUTORSERVICE == null) { // // Init threads executor // int size = Runtime.getRuntime().availableProcessors(); // EXECUTORSERVICE = Executors.newFixedThreadPool(size > 0 ? size : 1); // } // } // } // return EXECUTORSERVICE; // } // } // Path: AnKey/model/src/main/java/net/qiujuer/powerback/ankey/model/xml/XmlPreference.java import android.content.Context; import android.content.SharedPreferences; import net.qiujuer.powerback.ankey.model.AppModel; package net.qiujuer.powerback.ankey.model.xml; /** * Created by qiujuer * on 15/10/19. */ public abstract class XmlPreference { public XmlPreference() { refresh(getSharedPreferences()); } protected SharedPreferences getSharedPreferences() {
Context context = AppModel.getApplication();
PowerBack/AnKey
AnKey/resource/src/main/java/net/qiujuer/powerback/ankey/widget/drawable/Drawables.java
// Path: AnKey/resource/src/main/java/net/qiujuer/powerback/ankey/widget/drawable/shape/CrossLineShape.java // public class CrossLineShape extends Shape { // private float mCenterX, mCenterY; // private float mHalfLong; // // @Override // public void draw(Canvas canvas, Paint paint) { // float topY = mCenterY - mHalfLong; // float bottomY = mCenterY + mHalfLong; // // canvas.drawLine(mCenterX, topY, mCenterX, bottomY, paint); // // // float leftX = mCenterX - mHalfLong; // float rightX = mCenterX + mHalfLong; // // canvas.drawLine(leftX, mCenterY, rightX, mCenterY, paint); // } // // @Override // protected void onResize(float width, float height) { // mCenterX = width / 2; // mCenterY = height / 2; // // float minLong = Math.min(width, height); // mHalfLong = minLong * 0.2f; // } // } // // Path: AnKey/resource/src/main/java/net/qiujuer/powerback/ankey/widget/drawable/shape/OkLineShape.java // public class OkLineShape extends Shape { // private PointF mStart = new PointF(); // private PointF mCenter = new PointF(); // private PointF mStop = new PointF(); // // @Override // public void draw(Canvas canvas, Paint paint) { // canvas.drawLine(mStart.x, mStart.y, mCenter.x, mCenter.y, paint); // canvas.drawLine(mCenter.x, mCenter.y, mStop.x, mStop.y, paint); // } // // @Override // protected void onResize(float width, float height) { // float tw = width * 0.3f; // float th = height * 0.35f; // // mStart.set(tw, height * 0.5f); // mCenter.set(width * 0.46f, height - th); // mStop.set(width - tw, th * 0.9f); // } // } // // Path: AnKey/resource/src/main/java/net/qiujuer/powerback/ankey/widget/drawable/shape/ShadowShape.java // public class ShadowShape extends Shape { // private int mColor; // private float mShadowLen; // // public ShadowShape(int color, float shadowLen) { // mColor = color; // mShadowLen = shadowLen; // } // // @Override // public void draw(Canvas canvas, Paint paint) { // float w = getWidth(); // float h = getHeight() - 1; // // float sh = h - mShadowLen; // // // draw the background // int sc = canvas.save(); // canvas.clipRect(0, 0, w, sh); // canvas.drawColor(mColor); // canvas.restoreToCount(sc); // // canvas.drawRect(0, sh, w, h, paint); // } // }
import android.content.res.Resources; import android.graphics.LinearGradient; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.Shader; import android.graphics.drawable.Drawable; import android.graphics.drawable.ShapeDrawable; import android.graphics.drawable.shapes.Shape; import net.qiujuer.powerback.ankey.widget.drawable.shape.CrossLineShape; import net.qiujuer.powerback.ankey.widget.drawable.shape.OkLineShape; import net.qiujuer.powerback.ankey.widget.drawable.shape.ShadowShape;
package net.qiujuer.powerback.ankey.widget.drawable; /** * Created by qiujuer * on 15/11/9. */ public class Drawables { private static ShapeDrawable createShapeDrawable(Resources resources, Shape shape, int color, int size, int lineSize) { final float density = resources.getDisplayMetrics().density; ShapeDrawable drawable = new ShapeDrawable(shape); Paint paint = drawable.getPaint(); paint.setStyle(Paint.Style.STROKE); paint.setAntiAlias(true); paint.setDither(true); paint.setColor(color); paint.setStrokeWidth(lineSize * density); paint.setStrokeCap(Paint.Cap.ROUND); drawable.setIntrinsicWidth((int) (size * density)); drawable.setIntrinsicHeight((int) (size * density)); return drawable; } private static Rect convertDPToPX(Rect rect, float density) { if (rect != null) { rect.left *= density; rect.top *= density; rect.right *= density; rect.bottom *= density; } return rect; } public static Drawable getCreateDrawable(Resources resources) {
// Path: AnKey/resource/src/main/java/net/qiujuer/powerback/ankey/widget/drawable/shape/CrossLineShape.java // public class CrossLineShape extends Shape { // private float mCenterX, mCenterY; // private float mHalfLong; // // @Override // public void draw(Canvas canvas, Paint paint) { // float topY = mCenterY - mHalfLong; // float bottomY = mCenterY + mHalfLong; // // canvas.drawLine(mCenterX, topY, mCenterX, bottomY, paint); // // // float leftX = mCenterX - mHalfLong; // float rightX = mCenterX + mHalfLong; // // canvas.drawLine(leftX, mCenterY, rightX, mCenterY, paint); // } // // @Override // protected void onResize(float width, float height) { // mCenterX = width / 2; // mCenterY = height / 2; // // float minLong = Math.min(width, height); // mHalfLong = minLong * 0.2f; // } // } // // Path: AnKey/resource/src/main/java/net/qiujuer/powerback/ankey/widget/drawable/shape/OkLineShape.java // public class OkLineShape extends Shape { // private PointF mStart = new PointF(); // private PointF mCenter = new PointF(); // private PointF mStop = new PointF(); // // @Override // public void draw(Canvas canvas, Paint paint) { // canvas.drawLine(mStart.x, mStart.y, mCenter.x, mCenter.y, paint); // canvas.drawLine(mCenter.x, mCenter.y, mStop.x, mStop.y, paint); // } // // @Override // protected void onResize(float width, float height) { // float tw = width * 0.3f; // float th = height * 0.35f; // // mStart.set(tw, height * 0.5f); // mCenter.set(width * 0.46f, height - th); // mStop.set(width - tw, th * 0.9f); // } // } // // Path: AnKey/resource/src/main/java/net/qiujuer/powerback/ankey/widget/drawable/shape/ShadowShape.java // public class ShadowShape extends Shape { // private int mColor; // private float mShadowLen; // // public ShadowShape(int color, float shadowLen) { // mColor = color; // mShadowLen = shadowLen; // } // // @Override // public void draw(Canvas canvas, Paint paint) { // float w = getWidth(); // float h = getHeight() - 1; // // float sh = h - mShadowLen; // // // draw the background // int sc = canvas.save(); // canvas.clipRect(0, 0, w, sh); // canvas.drawColor(mColor); // canvas.restoreToCount(sc); // // canvas.drawRect(0, sh, w, h, paint); // } // } // Path: AnKey/resource/src/main/java/net/qiujuer/powerback/ankey/widget/drawable/Drawables.java import android.content.res.Resources; import android.graphics.LinearGradient; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.Shader; import android.graphics.drawable.Drawable; import android.graphics.drawable.ShapeDrawable; import android.graphics.drawable.shapes.Shape; import net.qiujuer.powerback.ankey.widget.drawable.shape.CrossLineShape; import net.qiujuer.powerback.ankey.widget.drawable.shape.OkLineShape; import net.qiujuer.powerback.ankey.widget.drawable.shape.ShadowShape; package net.qiujuer.powerback.ankey.widget.drawable; /** * Created by qiujuer * on 15/11/9. */ public class Drawables { private static ShapeDrawable createShapeDrawable(Resources resources, Shape shape, int color, int size, int lineSize) { final float density = resources.getDisplayMetrics().density; ShapeDrawable drawable = new ShapeDrawable(shape); Paint paint = drawable.getPaint(); paint.setStyle(Paint.Style.STROKE); paint.setAntiAlias(true); paint.setDither(true); paint.setColor(color); paint.setStrokeWidth(lineSize * density); paint.setStrokeCap(Paint.Cap.ROUND); drawable.setIntrinsicWidth((int) (size * density)); drawable.setIntrinsicHeight((int) (size * density)); return drawable; } private static Rect convertDPToPX(Rect rect, float density) { if (rect != null) { rect.left *= density; rect.top *= density; rect.right *= density; rect.bottom *= density; } return rect; } public static Drawable getCreateDrawable(Resources resources) {
Shape shape = new CrossLineShape();
PowerBack/AnKey
AnKey/resource/src/main/java/net/qiujuer/powerback/ankey/widget/drawable/Drawables.java
// Path: AnKey/resource/src/main/java/net/qiujuer/powerback/ankey/widget/drawable/shape/CrossLineShape.java // public class CrossLineShape extends Shape { // private float mCenterX, mCenterY; // private float mHalfLong; // // @Override // public void draw(Canvas canvas, Paint paint) { // float topY = mCenterY - mHalfLong; // float bottomY = mCenterY + mHalfLong; // // canvas.drawLine(mCenterX, topY, mCenterX, bottomY, paint); // // // float leftX = mCenterX - mHalfLong; // float rightX = mCenterX + mHalfLong; // // canvas.drawLine(leftX, mCenterY, rightX, mCenterY, paint); // } // // @Override // protected void onResize(float width, float height) { // mCenterX = width / 2; // mCenterY = height / 2; // // float minLong = Math.min(width, height); // mHalfLong = minLong * 0.2f; // } // } // // Path: AnKey/resource/src/main/java/net/qiujuer/powerback/ankey/widget/drawable/shape/OkLineShape.java // public class OkLineShape extends Shape { // private PointF mStart = new PointF(); // private PointF mCenter = new PointF(); // private PointF mStop = new PointF(); // // @Override // public void draw(Canvas canvas, Paint paint) { // canvas.drawLine(mStart.x, mStart.y, mCenter.x, mCenter.y, paint); // canvas.drawLine(mCenter.x, mCenter.y, mStop.x, mStop.y, paint); // } // // @Override // protected void onResize(float width, float height) { // float tw = width * 0.3f; // float th = height * 0.35f; // // mStart.set(tw, height * 0.5f); // mCenter.set(width * 0.46f, height - th); // mStop.set(width - tw, th * 0.9f); // } // } // // Path: AnKey/resource/src/main/java/net/qiujuer/powerback/ankey/widget/drawable/shape/ShadowShape.java // public class ShadowShape extends Shape { // private int mColor; // private float mShadowLen; // // public ShadowShape(int color, float shadowLen) { // mColor = color; // mShadowLen = shadowLen; // } // // @Override // public void draw(Canvas canvas, Paint paint) { // float w = getWidth(); // float h = getHeight() - 1; // // float sh = h - mShadowLen; // // // draw the background // int sc = canvas.save(); // canvas.clipRect(0, 0, w, sh); // canvas.drawColor(mColor); // canvas.restoreToCount(sc); // // canvas.drawRect(0, sh, w, h, paint); // } // }
import android.content.res.Resources; import android.graphics.LinearGradient; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.Shader; import android.graphics.drawable.Drawable; import android.graphics.drawable.ShapeDrawable; import android.graphics.drawable.shapes.Shape; import net.qiujuer.powerback.ankey.widget.drawable.shape.CrossLineShape; import net.qiujuer.powerback.ankey.widget.drawable.shape.OkLineShape; import net.qiujuer.powerback.ankey.widget.drawable.shape.ShadowShape;
package net.qiujuer.powerback.ankey.widget.drawable; /** * Created by qiujuer * on 15/11/9. */ public class Drawables { private static ShapeDrawable createShapeDrawable(Resources resources, Shape shape, int color, int size, int lineSize) { final float density = resources.getDisplayMetrics().density; ShapeDrawable drawable = new ShapeDrawable(shape); Paint paint = drawable.getPaint(); paint.setStyle(Paint.Style.STROKE); paint.setAntiAlias(true); paint.setDither(true); paint.setColor(color); paint.setStrokeWidth(lineSize * density); paint.setStrokeCap(Paint.Cap.ROUND); drawable.setIntrinsicWidth((int) (size * density)); drawable.setIntrinsicHeight((int) (size * density)); return drawable; } private static Rect convertDPToPX(Rect rect, float density) { if (rect != null) { rect.left *= density; rect.top *= density; rect.right *= density; rect.bottom *= density; } return rect; } public static Drawable getCreateDrawable(Resources resources) { Shape shape = new CrossLineShape(); return createShapeDrawable(resources, shape, 0xfffbfbfb, 36, 2); } public static Drawable getOkDrawable(Resources resources) {
// Path: AnKey/resource/src/main/java/net/qiujuer/powerback/ankey/widget/drawable/shape/CrossLineShape.java // public class CrossLineShape extends Shape { // private float mCenterX, mCenterY; // private float mHalfLong; // // @Override // public void draw(Canvas canvas, Paint paint) { // float topY = mCenterY - mHalfLong; // float bottomY = mCenterY + mHalfLong; // // canvas.drawLine(mCenterX, topY, mCenterX, bottomY, paint); // // // float leftX = mCenterX - mHalfLong; // float rightX = mCenterX + mHalfLong; // // canvas.drawLine(leftX, mCenterY, rightX, mCenterY, paint); // } // // @Override // protected void onResize(float width, float height) { // mCenterX = width / 2; // mCenterY = height / 2; // // float minLong = Math.min(width, height); // mHalfLong = minLong * 0.2f; // } // } // // Path: AnKey/resource/src/main/java/net/qiujuer/powerback/ankey/widget/drawable/shape/OkLineShape.java // public class OkLineShape extends Shape { // private PointF mStart = new PointF(); // private PointF mCenter = new PointF(); // private PointF mStop = new PointF(); // // @Override // public void draw(Canvas canvas, Paint paint) { // canvas.drawLine(mStart.x, mStart.y, mCenter.x, mCenter.y, paint); // canvas.drawLine(mCenter.x, mCenter.y, mStop.x, mStop.y, paint); // } // // @Override // protected void onResize(float width, float height) { // float tw = width * 0.3f; // float th = height * 0.35f; // // mStart.set(tw, height * 0.5f); // mCenter.set(width * 0.46f, height - th); // mStop.set(width - tw, th * 0.9f); // } // } // // Path: AnKey/resource/src/main/java/net/qiujuer/powerback/ankey/widget/drawable/shape/ShadowShape.java // public class ShadowShape extends Shape { // private int mColor; // private float mShadowLen; // // public ShadowShape(int color, float shadowLen) { // mColor = color; // mShadowLen = shadowLen; // } // // @Override // public void draw(Canvas canvas, Paint paint) { // float w = getWidth(); // float h = getHeight() - 1; // // float sh = h - mShadowLen; // // // draw the background // int sc = canvas.save(); // canvas.clipRect(0, 0, w, sh); // canvas.drawColor(mColor); // canvas.restoreToCount(sc); // // canvas.drawRect(0, sh, w, h, paint); // } // } // Path: AnKey/resource/src/main/java/net/qiujuer/powerback/ankey/widget/drawable/Drawables.java import android.content.res.Resources; import android.graphics.LinearGradient; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.Shader; import android.graphics.drawable.Drawable; import android.graphics.drawable.ShapeDrawable; import android.graphics.drawable.shapes.Shape; import net.qiujuer.powerback.ankey.widget.drawable.shape.CrossLineShape; import net.qiujuer.powerback.ankey.widget.drawable.shape.OkLineShape; import net.qiujuer.powerback.ankey.widget.drawable.shape.ShadowShape; package net.qiujuer.powerback.ankey.widget.drawable; /** * Created by qiujuer * on 15/11/9. */ public class Drawables { private static ShapeDrawable createShapeDrawable(Resources resources, Shape shape, int color, int size, int lineSize) { final float density = resources.getDisplayMetrics().density; ShapeDrawable drawable = new ShapeDrawable(shape); Paint paint = drawable.getPaint(); paint.setStyle(Paint.Style.STROKE); paint.setAntiAlias(true); paint.setDither(true); paint.setColor(color); paint.setStrokeWidth(lineSize * density); paint.setStrokeCap(Paint.Cap.ROUND); drawable.setIntrinsicWidth((int) (size * density)); drawable.setIntrinsicHeight((int) (size * density)); return drawable; } private static Rect convertDPToPX(Rect rect, float density) { if (rect != null) { rect.left *= density; rect.top *= density; rect.right *= density; rect.bottom *= density; } return rect; } public static Drawable getCreateDrawable(Resources resources) { Shape shape = new CrossLineShape(); return createShapeDrawable(resources, shape, 0xfffbfbfb, 36, 2); } public static Drawable getOkDrawable(Resources resources) {
Shape shape = new OkLineShape();
PowerBack/AnKey
AnKey/resource/src/main/java/net/qiujuer/powerback/ankey/widget/drawable/Drawables.java
// Path: AnKey/resource/src/main/java/net/qiujuer/powerback/ankey/widget/drawable/shape/CrossLineShape.java // public class CrossLineShape extends Shape { // private float mCenterX, mCenterY; // private float mHalfLong; // // @Override // public void draw(Canvas canvas, Paint paint) { // float topY = mCenterY - mHalfLong; // float bottomY = mCenterY + mHalfLong; // // canvas.drawLine(mCenterX, topY, mCenterX, bottomY, paint); // // // float leftX = mCenterX - mHalfLong; // float rightX = mCenterX + mHalfLong; // // canvas.drawLine(leftX, mCenterY, rightX, mCenterY, paint); // } // // @Override // protected void onResize(float width, float height) { // mCenterX = width / 2; // mCenterY = height / 2; // // float minLong = Math.min(width, height); // mHalfLong = minLong * 0.2f; // } // } // // Path: AnKey/resource/src/main/java/net/qiujuer/powerback/ankey/widget/drawable/shape/OkLineShape.java // public class OkLineShape extends Shape { // private PointF mStart = new PointF(); // private PointF mCenter = new PointF(); // private PointF mStop = new PointF(); // // @Override // public void draw(Canvas canvas, Paint paint) { // canvas.drawLine(mStart.x, mStart.y, mCenter.x, mCenter.y, paint); // canvas.drawLine(mCenter.x, mCenter.y, mStop.x, mStop.y, paint); // } // // @Override // protected void onResize(float width, float height) { // float tw = width * 0.3f; // float th = height * 0.35f; // // mStart.set(tw, height * 0.5f); // mCenter.set(width * 0.46f, height - th); // mStop.set(width - tw, th * 0.9f); // } // } // // Path: AnKey/resource/src/main/java/net/qiujuer/powerback/ankey/widget/drawable/shape/ShadowShape.java // public class ShadowShape extends Shape { // private int mColor; // private float mShadowLen; // // public ShadowShape(int color, float shadowLen) { // mColor = color; // mShadowLen = shadowLen; // } // // @Override // public void draw(Canvas canvas, Paint paint) { // float w = getWidth(); // float h = getHeight() - 1; // // float sh = h - mShadowLen; // // // draw the background // int sc = canvas.save(); // canvas.clipRect(0, 0, w, sh); // canvas.drawColor(mColor); // canvas.restoreToCount(sc); // // canvas.drawRect(0, sh, w, h, paint); // } // }
import android.content.res.Resources; import android.graphics.LinearGradient; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.Shader; import android.graphics.drawable.Drawable; import android.graphics.drawable.ShapeDrawable; import android.graphics.drawable.shapes.Shape; import net.qiujuer.powerback.ankey.widget.drawable.shape.CrossLineShape; import net.qiujuer.powerback.ankey.widget.drawable.shape.OkLineShape; import net.qiujuer.powerback.ankey.widget.drawable.shape.ShadowShape;
rect.bottom *= density; } return rect; } public static Drawable getCreateDrawable(Resources resources) { Shape shape = new CrossLineShape(); return createShapeDrawable(resources, shape, 0xfffbfbfb, 36, 2); } public static Drawable getOkDrawable(Resources resources) { Shape shape = new OkLineShape(); return createShapeDrawable(resources, shape, 0xfffbfbfb, 36, 2); } public static Drawable getDirectDrawable(Resources resources, int angle, int direct, Rect padding) { final float density = resources.getDisplayMetrics().density; DirectArrowDrawable directArrowDrawable = new DirectArrowDrawable(angle, direct, density * 2, 0xfffbfbfb); directArrowDrawable.setPadding(convertDPToPX(padding, density)); return directArrowDrawable; } public static Drawable getShadowDrawable(Resources resources, int color) { return getShadowDrawable(resources, color, 0x80000000, 4); } public static Drawable getShadowDrawable(Resources resources, int color, int sColor, int sLen) { final float density = resources.getDisplayMetrics().density; float sLenPx = sLen * density;
// Path: AnKey/resource/src/main/java/net/qiujuer/powerback/ankey/widget/drawable/shape/CrossLineShape.java // public class CrossLineShape extends Shape { // private float mCenterX, mCenterY; // private float mHalfLong; // // @Override // public void draw(Canvas canvas, Paint paint) { // float topY = mCenterY - mHalfLong; // float bottomY = mCenterY + mHalfLong; // // canvas.drawLine(mCenterX, topY, mCenterX, bottomY, paint); // // // float leftX = mCenterX - mHalfLong; // float rightX = mCenterX + mHalfLong; // // canvas.drawLine(leftX, mCenterY, rightX, mCenterY, paint); // } // // @Override // protected void onResize(float width, float height) { // mCenterX = width / 2; // mCenterY = height / 2; // // float minLong = Math.min(width, height); // mHalfLong = minLong * 0.2f; // } // } // // Path: AnKey/resource/src/main/java/net/qiujuer/powerback/ankey/widget/drawable/shape/OkLineShape.java // public class OkLineShape extends Shape { // private PointF mStart = new PointF(); // private PointF mCenter = new PointF(); // private PointF mStop = new PointF(); // // @Override // public void draw(Canvas canvas, Paint paint) { // canvas.drawLine(mStart.x, mStart.y, mCenter.x, mCenter.y, paint); // canvas.drawLine(mCenter.x, mCenter.y, mStop.x, mStop.y, paint); // } // // @Override // protected void onResize(float width, float height) { // float tw = width * 0.3f; // float th = height * 0.35f; // // mStart.set(tw, height * 0.5f); // mCenter.set(width * 0.46f, height - th); // mStop.set(width - tw, th * 0.9f); // } // } // // Path: AnKey/resource/src/main/java/net/qiujuer/powerback/ankey/widget/drawable/shape/ShadowShape.java // public class ShadowShape extends Shape { // private int mColor; // private float mShadowLen; // // public ShadowShape(int color, float shadowLen) { // mColor = color; // mShadowLen = shadowLen; // } // // @Override // public void draw(Canvas canvas, Paint paint) { // float w = getWidth(); // float h = getHeight() - 1; // // float sh = h - mShadowLen; // // // draw the background // int sc = canvas.save(); // canvas.clipRect(0, 0, w, sh); // canvas.drawColor(mColor); // canvas.restoreToCount(sc); // // canvas.drawRect(0, sh, w, h, paint); // } // } // Path: AnKey/resource/src/main/java/net/qiujuer/powerback/ankey/widget/drawable/Drawables.java import android.content.res.Resources; import android.graphics.LinearGradient; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.Shader; import android.graphics.drawable.Drawable; import android.graphics.drawable.ShapeDrawable; import android.graphics.drawable.shapes.Shape; import net.qiujuer.powerback.ankey.widget.drawable.shape.CrossLineShape; import net.qiujuer.powerback.ankey.widget.drawable.shape.OkLineShape; import net.qiujuer.powerback.ankey.widget.drawable.shape.ShadowShape; rect.bottom *= density; } return rect; } public static Drawable getCreateDrawable(Resources resources) { Shape shape = new CrossLineShape(); return createShapeDrawable(resources, shape, 0xfffbfbfb, 36, 2); } public static Drawable getOkDrawable(Resources resources) { Shape shape = new OkLineShape(); return createShapeDrawable(resources, shape, 0xfffbfbfb, 36, 2); } public static Drawable getDirectDrawable(Resources resources, int angle, int direct, Rect padding) { final float density = resources.getDisplayMetrics().density; DirectArrowDrawable directArrowDrawable = new DirectArrowDrawable(angle, direct, density * 2, 0xfffbfbfb); directArrowDrawable.setPadding(convertDPToPX(padding, density)); return directArrowDrawable; } public static Drawable getShadowDrawable(Resources resources, int color) { return getShadowDrawable(resources, color, 0x80000000, 4); } public static Drawable getShadowDrawable(Resources resources, int color, int sColor, int sLen) { final float density = resources.getDisplayMetrics().density; float sLenPx = sLen * density;
ShadowShape shape = new ShadowShape(color, sLenPx);
EatHeat/OmniSnitch
src/tk/eatheat/omnisnitch/showcase/ShowcaseView.java
// Path: src/tk/eatheat/omnisnitch/showcase/AnimationUtils.java // public interface AnimationEndListener { // void onAnimationEnd(); // } // // Path: src/tk/eatheat/omnisnitch/showcase/AnimationUtils.java // public interface AnimationStartListener { // void onAnimationStart(); // }
import java.lang.reflect.Field; import tk.eatheat.omnisnitch.R; import tk.eatheat.omnisnitch.showcase.AnimationUtils.AnimationEndListener; import tk.eatheat.omnisnitch.showcase.AnimationUtils.AnimationStartListener; import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.PixelFormat; import android.graphics.PorterDuff; import android.graphics.PorterDuffXfermode; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.os.Build; import android.text.DynamicLayout; import android.text.Layout; import android.text.TextPaint; import android.text.TextUtils; import android.util.AttributeSet; import android.util.Log; import android.view.Gravity; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.ViewParent; import android.view.WindowManager; import android.widget.Button; import android.widget.RelativeLayout;
*/ private boolean makeVoidedRect() { // This if statement saves resources by not recalculating voidedArea // if the X & Y coordinates haven't changed if (voidedArea == null || (showcaseX != legacyShowcaseX || showcaseY != legacyShowcaseY)) { int cx = (int) showcaseX, cy = (int) showcaseY; int dw = showcase.getIntrinsicWidth(); int dh = showcase.getIntrinsicHeight(); voidedArea = new Rect(cx - dw / 2, cy - dh / 2, cx + dw / 2, cy + dh / 2); legacyShowcaseX = showcaseX; legacyShowcaseY = showcaseY; return true; } return false; } public void animateGesture(float offsetStartX, float offsetStartY, float offsetEndX, float offsetEndY) { mHandy = ((LayoutInflater) getContext().getSystemService( Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.handy, null); addView(mHandy); mHandy.setRotation(mOrientation); moveHand(offsetStartX, offsetStartY, offsetEndX, offsetEndY,
// Path: src/tk/eatheat/omnisnitch/showcase/AnimationUtils.java // public interface AnimationEndListener { // void onAnimationEnd(); // } // // Path: src/tk/eatheat/omnisnitch/showcase/AnimationUtils.java // public interface AnimationStartListener { // void onAnimationStart(); // } // Path: src/tk/eatheat/omnisnitch/showcase/ShowcaseView.java import java.lang.reflect.Field; import tk.eatheat.omnisnitch.R; import tk.eatheat.omnisnitch.showcase.AnimationUtils.AnimationEndListener; import tk.eatheat.omnisnitch.showcase.AnimationUtils.AnimationStartListener; import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.PixelFormat; import android.graphics.PorterDuff; import android.graphics.PorterDuffXfermode; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.os.Build; import android.text.DynamicLayout; import android.text.Layout; import android.text.TextPaint; import android.text.TextUtils; import android.util.AttributeSet; import android.util.Log; import android.view.Gravity; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.ViewParent; import android.view.WindowManager; import android.widget.Button; import android.widget.RelativeLayout; */ private boolean makeVoidedRect() { // This if statement saves resources by not recalculating voidedArea // if the X & Y coordinates haven't changed if (voidedArea == null || (showcaseX != legacyShowcaseX || showcaseY != legacyShowcaseY)) { int cx = (int) showcaseX, cy = (int) showcaseY; int dw = showcase.getIntrinsicWidth(); int dh = showcase.getIntrinsicHeight(); voidedArea = new Rect(cx - dw / 2, cy - dh / 2, cx + dw / 2, cy + dh / 2); legacyShowcaseX = showcaseX; legacyShowcaseY = showcaseY; return true; } return false; } public void animateGesture(float offsetStartX, float offsetStartY, float offsetEndX, float offsetEndY) { mHandy = ((LayoutInflater) getContext().getSystemService( Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.handy, null); addView(mHandy); mHandy.setRotation(mOrientation); moveHand(offsetStartX, offsetStartY, offsetEndX, offsetEndY,
new AnimationEndListener() {
EatHeat/OmniSnitch
src/tk/eatheat/omnisnitch/showcase/ShowcaseView.java
// Path: src/tk/eatheat/omnisnitch/showcase/AnimationUtils.java // public interface AnimationEndListener { // void onAnimationEnd(); // } // // Path: src/tk/eatheat/omnisnitch/showcase/AnimationUtils.java // public interface AnimationStartListener { // void onAnimationStart(); // }
import java.lang.reflect.Field; import tk.eatheat.omnisnitch.R; import tk.eatheat.omnisnitch.showcase.AnimationUtils.AnimationEndListener; import tk.eatheat.omnisnitch.showcase.AnimationUtils.AnimationStartListener; import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.PixelFormat; import android.graphics.PorterDuff; import android.graphics.PorterDuffXfermode; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.os.Build; import android.text.DynamicLayout; import android.text.Layout; import android.text.TextPaint; import android.text.TextUtils; import android.util.AttributeSet; import android.util.Log; import android.view.Gravity; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.ViewParent; import android.view.WindowManager; import android.widget.Button; import android.widget.RelativeLayout;
} if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { fadeOutShowcase(); } else { setVisibility(View.GONE); } } private void fadeOutShowcase() { AnimationUtils.createFadeOutAnimation(this, new AnimationEndListener() { @Override public void onAnimationEnd() { setVisibility(View.GONE); } }).start(); } public void show() { if (mEventListener != null) { mEventListener.onShowcaseViewShow(this); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { fadeInShowcase(); } else { setVisibility(View.VISIBLE); } } private void fadeInShowcase() { AnimationUtils.createFadeInAnimation(this,
// Path: src/tk/eatheat/omnisnitch/showcase/AnimationUtils.java // public interface AnimationEndListener { // void onAnimationEnd(); // } // // Path: src/tk/eatheat/omnisnitch/showcase/AnimationUtils.java // public interface AnimationStartListener { // void onAnimationStart(); // } // Path: src/tk/eatheat/omnisnitch/showcase/ShowcaseView.java import java.lang.reflect.Field; import tk.eatheat.omnisnitch.R; import tk.eatheat.omnisnitch.showcase.AnimationUtils.AnimationEndListener; import tk.eatheat.omnisnitch.showcase.AnimationUtils.AnimationStartListener; import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.PixelFormat; import android.graphics.PorterDuff; import android.graphics.PorterDuffXfermode; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.os.Build; import android.text.DynamicLayout; import android.text.Layout; import android.text.TextPaint; import android.text.TextUtils; import android.util.AttributeSet; import android.util.Log; import android.view.Gravity; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.ViewParent; import android.view.WindowManager; import android.widget.Button; import android.widget.RelativeLayout; } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { fadeOutShowcase(); } else { setVisibility(View.GONE); } } private void fadeOutShowcase() { AnimationUtils.createFadeOutAnimation(this, new AnimationEndListener() { @Override public void onAnimationEnd() { setVisibility(View.GONE); } }).start(); } public void show() { if (mEventListener != null) { mEventListener.onShowcaseViewShow(this); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { fadeInShowcase(); } else { setVisibility(View.VISIBLE); } } private void fadeInShowcase() { AnimationUtils.createFadeInAnimation(this,
new AnimationStartListener() {
EatHeat/OmniSnitch
src/tk/eatheat/omnisnitch/Utils.java
// Path: src/tk/eatheat/omnisnitch/ui/BitmapFilter.java // @SuppressLint("NewApi") // public class BitmapFilter { // private static BitmapFilter mSingleton; // // private Map<String, Bitmap> mGlowCache; // private RenderScript mRS; // private Allocation mBlurInputAllocation; // private Allocation mBlurOutputAllocation; // private ScriptIntrinsicBlur mBlurScript; // // public static BitmapFilter getSingleton() { // if (mSingleton == null) { // mSingleton = new BitmapFilter(); // } // // return mSingleton; // } // // private BitmapFilter() { // mGlowCache = new HashMap<String, Bitmap>(); // } // // /** // * Blurs a bitmap. There's no caching on this one. // * // * @param src The bitmap to blur // * @return A blurred bitmap // */ // public Bitmap getBlur(Context context, Bitmap src, float radius) { // if (android.os.Build.VERSION.SDK_INT >= 17) { // if (mRS == null) { // mRS = RenderScript.create(context); // } // // if (mBlurScript == null) { // mBlurScript = ScriptIntrinsicBlur.create(mRS, Element.U8_4(mRS)); // } // // if (mBlurInputAllocation == null) { // mBlurInputAllocation = Allocation.createFromBitmap(mRS, src, // Allocation.MipmapControl.MIPMAP_NONE, Allocation.USAGE_GRAPHICS_TEXTURE); // mBlurScript.setInput(mBlurInputAllocation); // } else { // mBlurInputAllocation.copyFrom(src); // } // // if (mBlurOutputAllocation == null) { // mBlurOutputAllocation = Allocation.createTyped(mRS, mBlurInputAllocation.getType()); // } // // mBlurScript.setRadius(radius); // mBlurScript.forEach(mBlurOutputAllocation); // mBlurOutputAllocation.copyTo(src); // } // // return src; // } // // /** // * Returns a glowed image of the provided icon. If the // * provided name is already in the cache, the cached image // * will be returned. Otherwise, the bitmap will be glowed and // * cached under the provided name // * // * @param name The name of the bitmap - if name == null dont cache // * @param src The bitmap of the icon itself // * @return Glowed bitmap // */ // public Bitmap getGlow(String name, int glowColor, Bitmap src) { // if (name != null && mGlowCache.containsKey(name)) { // return mGlowCache.get(name); // } else { // // An added margin to the initial image // int margin = 0; // int halfMargin = margin / 2; // // // The glow radius // int glowRadius = 12; // // // Extract the alpha from the source image // Bitmap alpha = src.extractAlpha(); // // // The output bitmap (with the icon + glow) // Bitmap bmp = Bitmap.createBitmap(src.getWidth() + margin, // src.getHeight() + margin, Bitmap.Config.ARGB_8888); // // // The canvas to paint on the image // Canvas canvas = new Canvas(bmp); // // Paint paint = new Paint(); // paint.setColor(glowColor); // // // Outer glow // ColorFilter emphasize = new LightingColorFilter(glowColor, 1); // paint.setColorFilter(emphasize); // canvas.drawBitmap(src, halfMargin, halfMargin, paint); // paint.setColorFilter(null); // paint.setMaskFilter(new BlurMaskFilter(glowRadius, Blur.OUTER)); // canvas.drawBitmap(alpha, halfMargin, halfMargin, paint); // // if(name!=null){ // // Cache icon // mGlowCache.put(name, bmp); // } // // return bmp; // } // } // }
import java.util.Iterator; import java.util.List; import tk.eatheat.omnisnitch.ui.BitmapFilter; import android.content.Intent; import android.content.pm.ActivityInfo; import android.content.pm.PackageManager; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.PorterDuff.Mode; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable;
String[] splitParts = buttonString.split(","); boolean[] buttons = new boolean[splitParts.length]; for(int i = 0; i < splitParts.length; i++){ if (splitParts[i].equals("0")){ buttons[i]=false; } else if (splitParts[i].equals("1")){ buttons[i]=true; } } return buttons; } public static String buttonArrayToString(boolean[] buttons){ String buttonString = ""; for(int i = 0; i < buttons.length; i++){ boolean value = buttons[i]; if (value){ buttonString = buttonString + "1,"; } else { buttonString = buttonString + "0,"; } } if(buttonString.length() > 0){ buttonString = buttonString.substring(0, buttonString.length() - 1); } return buttonString; } public static Bitmap getGlow(Resources resources, String name, int color, Drawable image) { Bitmap b = ((BitmapDrawable) image).getBitmap();
// Path: src/tk/eatheat/omnisnitch/ui/BitmapFilter.java // @SuppressLint("NewApi") // public class BitmapFilter { // private static BitmapFilter mSingleton; // // private Map<String, Bitmap> mGlowCache; // private RenderScript mRS; // private Allocation mBlurInputAllocation; // private Allocation mBlurOutputAllocation; // private ScriptIntrinsicBlur mBlurScript; // // public static BitmapFilter getSingleton() { // if (mSingleton == null) { // mSingleton = new BitmapFilter(); // } // // return mSingleton; // } // // private BitmapFilter() { // mGlowCache = new HashMap<String, Bitmap>(); // } // // /** // * Blurs a bitmap. There's no caching on this one. // * // * @param src The bitmap to blur // * @return A blurred bitmap // */ // public Bitmap getBlur(Context context, Bitmap src, float radius) { // if (android.os.Build.VERSION.SDK_INT >= 17) { // if (mRS == null) { // mRS = RenderScript.create(context); // } // // if (mBlurScript == null) { // mBlurScript = ScriptIntrinsicBlur.create(mRS, Element.U8_4(mRS)); // } // // if (mBlurInputAllocation == null) { // mBlurInputAllocation = Allocation.createFromBitmap(mRS, src, // Allocation.MipmapControl.MIPMAP_NONE, Allocation.USAGE_GRAPHICS_TEXTURE); // mBlurScript.setInput(mBlurInputAllocation); // } else { // mBlurInputAllocation.copyFrom(src); // } // // if (mBlurOutputAllocation == null) { // mBlurOutputAllocation = Allocation.createTyped(mRS, mBlurInputAllocation.getType()); // } // // mBlurScript.setRadius(radius); // mBlurScript.forEach(mBlurOutputAllocation); // mBlurOutputAllocation.copyTo(src); // } // // return src; // } // // /** // * Returns a glowed image of the provided icon. If the // * provided name is already in the cache, the cached image // * will be returned. Otherwise, the bitmap will be glowed and // * cached under the provided name // * // * @param name The name of the bitmap - if name == null dont cache // * @param src The bitmap of the icon itself // * @return Glowed bitmap // */ // public Bitmap getGlow(String name, int glowColor, Bitmap src) { // if (name != null && mGlowCache.containsKey(name)) { // return mGlowCache.get(name); // } else { // // An added margin to the initial image // int margin = 0; // int halfMargin = margin / 2; // // // The glow radius // int glowRadius = 12; // // // Extract the alpha from the source image // Bitmap alpha = src.extractAlpha(); // // // The output bitmap (with the icon + glow) // Bitmap bmp = Bitmap.createBitmap(src.getWidth() + margin, // src.getHeight() + margin, Bitmap.Config.ARGB_8888); // // // The canvas to paint on the image // Canvas canvas = new Canvas(bmp); // // Paint paint = new Paint(); // paint.setColor(glowColor); // // // Outer glow // ColorFilter emphasize = new LightingColorFilter(glowColor, 1); // paint.setColorFilter(emphasize); // canvas.drawBitmap(src, halfMargin, halfMargin, paint); // paint.setColorFilter(null); // paint.setMaskFilter(new BlurMaskFilter(glowRadius, Blur.OUTER)); // canvas.drawBitmap(alpha, halfMargin, halfMargin, paint); // // if(name!=null){ // // Cache icon // mGlowCache.put(name, bmp); // } // // return bmp; // } // } // } // Path: src/tk/eatheat/omnisnitch/Utils.java import java.util.Iterator; import java.util.List; import tk.eatheat.omnisnitch.ui.BitmapFilter; import android.content.Intent; import android.content.pm.ActivityInfo; import android.content.pm.PackageManager; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.PorterDuff.Mode; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; String[] splitParts = buttonString.split(","); boolean[] buttons = new boolean[splitParts.length]; for(int i = 0; i < splitParts.length; i++){ if (splitParts[i].equals("0")){ buttons[i]=false; } else if (splitParts[i].equals("1")){ buttons[i]=true; } } return buttons; } public static String buttonArrayToString(boolean[] buttons){ String buttonString = ""; for(int i = 0; i < buttons.length; i++){ boolean value = buttons[i]; if (value){ buttonString = buttonString + "1,"; } else { buttonString = buttonString + "0,"; } } if(buttonString.length() > 0){ buttonString = buttonString.substring(0, buttonString.length() - 1); } return buttonString; } public static Bitmap getGlow(Resources resources, String name, int color, Drawable image) { Bitmap b = ((BitmapDrawable) image).getBitmap();
return BitmapFilter.getSingleton().getGlow(name, color, b);
neuland/jade4j
src/main/java/de/neuland/jade4j/lexer/Lexer.java
// Path: src/main/java/de/neuland/jade4j/template/TemplateLoader.java // public interface TemplateLoader { // public long getLastModified(String name) throws IOException; // public Reader getReader(String name) throws IOException; // public String getExtension(); // }
import de.neuland.jade4j.exceptions.ExpressionException; import de.neuland.jade4j.exceptions.JadeLexerException; import de.neuland.jade4j.expression.ExpressionHandler; import de.neuland.jade4j.lexer.token.*; import de.neuland.jade4j.template.TemplateLoader; import de.neuland.jade4j.util.CharacterParser; import de.neuland.jade4j.util.Options; import de.neuland.jade4j.util.StringReplacer; import de.neuland.jade4j.util.StringReplacerCallback; import org.apache.commons.io.FilenameUtils; import org.apache.commons.lang3.StringEscapeUtils; import org.apache.commons.lang3.StringUtils; import java.io.IOException; import java.io.Reader; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern;
package de.neuland.jade4j.lexer; public class Lexer { private static final Pattern cleanRe = Pattern.compile("^['\"]|['\"]$"); private static final Pattern doubleQuotedRe = Pattern.compile("^\"[^\"]*\"$"); private static final Pattern quotedRe = Pattern.compile("^'[^']*'$"); @SuppressWarnings("unused") private LinkedList<String> options; Scanner scanner; private LinkedList<Token> deferredTokens; private int lastIndents = -1; private int lineno; private LinkedList<Token> stash; private LinkedList<Integer> indentStack; private String indentRe = null; private boolean pipeless = false; @SuppressWarnings("unused") private boolean attributeMode; private final String filename;
// Path: src/main/java/de/neuland/jade4j/template/TemplateLoader.java // public interface TemplateLoader { // public long getLastModified(String name) throws IOException; // public Reader getReader(String name) throws IOException; // public String getExtension(); // } // Path: src/main/java/de/neuland/jade4j/lexer/Lexer.java import de.neuland.jade4j.exceptions.ExpressionException; import de.neuland.jade4j.exceptions.JadeLexerException; import de.neuland.jade4j.expression.ExpressionHandler; import de.neuland.jade4j.lexer.token.*; import de.neuland.jade4j.template.TemplateLoader; import de.neuland.jade4j.util.CharacterParser; import de.neuland.jade4j.util.Options; import de.neuland.jade4j.util.StringReplacer; import de.neuland.jade4j.util.StringReplacerCallback; import org.apache.commons.io.FilenameUtils; import org.apache.commons.lang3.StringEscapeUtils; import org.apache.commons.lang3.StringUtils; import java.io.IOException; import java.io.Reader; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; package de.neuland.jade4j.lexer; public class Lexer { private static final Pattern cleanRe = Pattern.compile("^['\"]|['\"]$"); private static final Pattern doubleQuotedRe = Pattern.compile("^\"[^\"]*\"$"); private static final Pattern quotedRe = Pattern.compile("^'[^']*'$"); @SuppressWarnings("unused") private LinkedList<String> options; Scanner scanner; private LinkedList<Token> deferredTokens; private int lastIndents = -1; private int lineno; private LinkedList<Token> stash; private LinkedList<Integer> indentStack; private String indentRe = null; private boolean pipeless = false; @SuppressWarnings("unused") private boolean attributeMode; private final String filename;
private final TemplateLoader templateLoader;
neuland/jade4j
src/test/java/de/neuland/jade4j/util/ArgumentSplitterTest.java
// Path: src/main/java/de/neuland/jade4j/util/ArgumentSplitter.java // public static List<String> split(String arguments) { // if(arguments == null) { // return Collections.emptyList(); // } // return new ArgumentSplitter(arguments).splitArguments(); // }
import org.junit.Test; import java.util.List; import static de.neuland.jade4j.util.ArgumentSplitter.split; import static org.junit.Assert.assertEquals;
package de.neuland.jade4j.util; /** * @author dusan.zatkovsky, 2/9/15 */ public class ArgumentSplitterTest { private List<String> parameters; @Test public void testSplit() throws Exception { List<String> args;
// Path: src/main/java/de/neuland/jade4j/util/ArgumentSplitter.java // public static List<String> split(String arguments) { // if(arguments == null) { // return Collections.emptyList(); // } // return new ArgumentSplitter(arguments).splitArguments(); // } // Path: src/test/java/de/neuland/jade4j/util/ArgumentSplitterTest.java import org.junit.Test; import java.util.List; import static de.neuland.jade4j.util.ArgumentSplitter.split; import static org.junit.Assert.assertEquals; package de.neuland.jade4j.util; /** * @author dusan.zatkovsky, 2/9/15 */ public class ArgumentSplitterTest { private List<String> parameters; @Test public void testSplit() throws Exception { List<String> args;
args = split("foo.faa('this is arg1'),'this is arg2'");
neuland/jade4j
src/main/java/de/neuland/jade4j/template/FileTemplateLoader.java
// Path: src/main/java/de/neuland/jade4j/exceptions/JadeTemplateLoaderException.java // public class JadeTemplateLoaderException extends JadeException { // public JadeTemplateLoaderException(String message) { // super(message); // } // }
import de.neuland.jade4j.exceptions.JadeTemplateLoaderException; import org.apache.commons.lang3.StringUtils; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader;
public FileTemplateLoader(String folderPath, String encoding, String extension) { validateFolderPath(folderPath); this.encoding = encoding; this.folderPath = folderPath; this.extension = extension; } private void validateFolderPath(String folderPath) { if(StringUtils.isNotEmpty(folderPath)) { File file = new File(folderPath); if (!file.exists() || !file.isDirectory()) { throw new IllegalArgumentException("The folder path '" + folderPath + "' does not exist"); } } } public long getLastModified(String name) { File templateSource = getFile(name); return templateSource.lastModified(); } @Override public Reader getReader(String name) throws IOException { File templateSource = getFile(name); return new InputStreamReader(new FileInputStream(templateSource), encoding); } private File getFile(String name) { if(name.startsWith("../")){
// Path: src/main/java/de/neuland/jade4j/exceptions/JadeTemplateLoaderException.java // public class JadeTemplateLoaderException extends JadeException { // public JadeTemplateLoaderException(String message) { // super(message); // } // } // Path: src/main/java/de/neuland/jade4j/template/FileTemplateLoader.java import de.neuland.jade4j.exceptions.JadeTemplateLoaderException; import org.apache.commons.lang3.StringUtils; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; public FileTemplateLoader(String folderPath, String encoding, String extension) { validateFolderPath(folderPath); this.encoding = encoding; this.folderPath = folderPath; this.extension = extension; } private void validateFolderPath(String folderPath) { if(StringUtils.isNotEmpty(folderPath)) { File file = new File(folderPath); if (!file.exists() || !file.isDirectory()) { throw new IllegalArgumentException("The folder path '" + folderPath + "' does not exist"); } } } public long getLastModified(String name) { File templateSource = getFile(name); return templateSource.lastModified(); } @Override public Reader getReader(String name) throws IOException { File templateSource = getFile(name); return new InputStreamReader(new FileInputStream(templateSource), encoding); } private File getFile(String name) { if(name.startsWith("../")){
throw new JadeTemplateLoaderException("relative Path is not allowed");
paypal/squbs
squbs-testkit/src/test/java/org/squbs/testkit/japi/junit/CustomRouteTestKitConfigResourcesTest.java
// Path: squbs-testkit/src/test/java/org/squbs/testkit/japi/RouteResultInfo.java // public class RouteResultInfo { // private String webContext; // private String actorPath; // private int result; // // public String getWebContext() { // return webContext; // } // // public void setWebContext(String webContext) { // this.webContext = webContext; // } // // public String getActorPath() { // return actorPath; // } // // public void setActorPath(String actorPath) { // this.actorPath = actorPath; // } // // public int getResult() { // return result; // } // // public void setResult(int result) { // this.result = result; // } // }
import akka.http.javadsl.marshallers.jackson.Jackson; import akka.http.javadsl.model.HttpRequest; import akka.http.javadsl.testkit.TestRoute; import com.typesafe.config.Config; import com.typesafe.config.ConfigFactory; import org.junit.Test; import org.squbs.testkit.japi.InfoRouteWithActor; import org.squbs.testkit.japi.RouteResultInfo; import org.squbs.testkit.japi.JUnitCustomRouteTestKit; import java.util.Arrays; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue;
/* * Copyright 2017 PayPal * * 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.squbs.testkit.japi.junit; public class CustomRouteTestKitConfigResourcesTest extends JUnitCustomRouteTestKit { static List<String> resources = Arrays.asList(CustomRouteTestKitConfigResourcesTest.class.getClassLoader() .getResource("").getPath() + "/CustomTestKitDefaultSpec/META-INF/squbs-meta.conf"); static Config customConfig = ConfigFactory.parseString("CustomRouteTestKitConfigResourcesTest.foobar = baz"); public CustomRouteTestKitConfigResourcesTest() { super(customConfig, resources, false); } @Test public void testSimpleRoute() { TestRoute simpleRoute = testRoute(InfoRouteWithActor.class);
// Path: squbs-testkit/src/test/java/org/squbs/testkit/japi/RouteResultInfo.java // public class RouteResultInfo { // private String webContext; // private String actorPath; // private int result; // // public String getWebContext() { // return webContext; // } // // public void setWebContext(String webContext) { // this.webContext = webContext; // } // // public String getActorPath() { // return actorPath; // } // // public void setActorPath(String actorPath) { // this.actorPath = actorPath; // } // // public int getResult() { // return result; // } // // public void setResult(int result) { // this.result = result; // } // } // Path: squbs-testkit/src/test/java/org/squbs/testkit/japi/junit/CustomRouteTestKitConfigResourcesTest.java import akka.http.javadsl.marshallers.jackson.Jackson; import akka.http.javadsl.model.HttpRequest; import akka.http.javadsl.testkit.TestRoute; import com.typesafe.config.Config; import com.typesafe.config.ConfigFactory; import org.junit.Test; import org.squbs.testkit.japi.InfoRouteWithActor; import org.squbs.testkit.japi.RouteResultInfo; import org.squbs.testkit.japi.JUnitCustomRouteTestKit; import java.util.Arrays; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; /* * Copyright 2017 PayPal * * 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.squbs.testkit.japi.junit; public class CustomRouteTestKitConfigResourcesTest extends JUnitCustomRouteTestKit { static List<String> resources = Arrays.asList(CustomRouteTestKitConfigResourcesTest.class.getClassLoader() .getResource("").getPath() + "/CustomTestKitDefaultSpec/META-INF/squbs-meta.conf"); static Config customConfig = ConfigFactory.parseString("CustomRouteTestKitConfigResourcesTest.foobar = baz"); public CustomRouteTestKitConfigResourcesTest() { super(customConfig, resources, false); } @Test public void testSimpleRoute() { TestRoute simpleRoute = testRoute(InfoRouteWithActor.class);
RouteResultInfo routeInfo = simpleRoute.run(HttpRequest.GET("/decrement/10"))
paypal/squbs
squbs-testkit/src/test/java/org/squbs/testkit/japi/junit/CustomRouteTestKitTest.java
// Path: squbs-testkit/src/test/java/org/squbs/testkit/japi/RouteResultInfo.java // public class RouteResultInfo { // private String webContext; // private String actorPath; // private int result; // // public String getWebContext() { // return webContext; // } // // public void setWebContext(String webContext) { // this.webContext = webContext; // } // // public String getActorPath() { // return actorPath; // } // // public void setActorPath(String actorPath) { // this.actorPath = actorPath; // } // // public int getResult() { // return result; // } // // public void setResult(int result) { // this.result = result; // } // }
import akka.http.javadsl.marshallers.jackson.Jackson; import akka.http.javadsl.model.HttpRequest; import akka.http.javadsl.testkit.TestRoute; import org.junit.Test; import org.squbs.testkit.japi.InfoRouteWithActor; import org.squbs.testkit.japi.RouteResultInfo; import org.squbs.testkit.japi.JUnitCustomRouteTestKit; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue;
/* * Copyright 2017 PayPal * * 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.squbs.testkit.japi.junit; public class CustomRouteTestKitTest extends JUnitCustomRouteTestKit { @Test public void testSimpleRoute() { TestRoute simpleRoute = testRoute(InfoRouteWithActor.class);
// Path: squbs-testkit/src/test/java/org/squbs/testkit/japi/RouteResultInfo.java // public class RouteResultInfo { // private String webContext; // private String actorPath; // private int result; // // public String getWebContext() { // return webContext; // } // // public void setWebContext(String webContext) { // this.webContext = webContext; // } // // public String getActorPath() { // return actorPath; // } // // public void setActorPath(String actorPath) { // this.actorPath = actorPath; // } // // public int getResult() { // return result; // } // // public void setResult(int result) { // this.result = result; // } // } // Path: squbs-testkit/src/test/java/org/squbs/testkit/japi/junit/CustomRouteTestKitTest.java import akka.http.javadsl.marshallers.jackson.Jackson; import akka.http.javadsl.model.HttpRequest; import akka.http.javadsl.testkit.TestRoute; import org.junit.Test; import org.squbs.testkit.japi.InfoRouteWithActor; import org.squbs.testkit.japi.RouteResultInfo; import org.squbs.testkit.japi.JUnitCustomRouteTestKit; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; /* * Copyright 2017 PayPal * * 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.squbs.testkit.japi.junit; public class CustomRouteTestKitTest extends JUnitCustomRouteTestKit { @Test public void testSimpleRoute() { TestRoute simpleRoute = testRoute(InfoRouteWithActor.class);
RouteResultInfo routeInfo = simpleRoute.run(HttpRequest.GET("/increment/10"))
Condroidapp/android
Condroid/src/main/java/cz/quinix/condroid/loader/AProgressedTask.java
// Path: Condroid/src/main/java/cz/quinix/condroid/abstracts/AListenedAsyncTask.java // public abstract class AListenedAsyncTask<Progress, Result> extends RoboAsyncTask<Result> { // // @Inject // private Provider<Context> contextProvider; // // private ITaskListener listener; // // private Result results; // // public AListenedAsyncTask(ITaskListener listener) { // super(listener.getActivity()); // this.listener = listener; // } // // protected CondroidApi getCondroidService() { // Gson gson = new GsonBuilder() // .registerTypeAdapter(Date.class, new DateTypeAdapter()) // .registerTypeAdapter(AnnotationType.class, new AnnotationTypeAdapter()) // .create(); // RestAdapter adapter = new RestAdapter.Builder() // .setEndpoint(CondroidApi.API_ENDPOINT) // .setConverter(new GsonConverter(gson)) // .setRequestInterceptor(new RequestInterceptor() { // @Override // public void intercept(RequestFacade request) { // request.addHeader("X-Device-Info", CondroidActivity.getDeviceInfoString(listener.getActivity())); // } // }) // .build(); // return adapter.create(CondroidApi.class); // } // // protected void onSuccess(Result results) throws Exception { // this.results = results; // this.listener.onTaskCompleted(this); // } // // public Result getResults() { // return this.results; // } // // @Override // protected void onException(Exception e) throws RuntimeException { // if (e instanceof RetrofitError) { // if (((RetrofitError) e).isNetworkError()) { // Toast.makeText(listener.getActivity(), R.string.networkError, Toast.LENGTH_LONG).show(); // //return; // } else if (((RetrofitError) e).getResponse() != null && ((RetrofitError) e).getResponse().getStatus() >= 500) { // Toast.makeText(listener.getActivity(), R.string.serverError, Toast.LENGTH_LONG).show(); // //return; // } // // } // super.onException(e); // listener.onTaskErrored(this); // } // } // // Path: Condroid/src/main/java/cz/quinix/condroid/abstracts/ITaskListener.java // public interface ITaskListener { // // void onTaskCompleted(AListenedAsyncTask<?, ?> task); // // Activity getActivity(); // // void onTaskErrored(AListenedAsyncTask task); // }
import android.app.Activity; import android.app.ProgressDialog; import android.content.DialogInterface; import cz.quinix.condroid.abstracts.AListenedAsyncTask; import cz.quinix.condroid.abstracts.ITaskListener;
package cz.quinix.condroid.loader; public abstract class AProgressedTask<Progress, Result> extends AListenedAsyncTask<Progress, Result> { protected ProgressDialog pd; private Activity parent; protected String pdString;
// Path: Condroid/src/main/java/cz/quinix/condroid/abstracts/AListenedAsyncTask.java // public abstract class AListenedAsyncTask<Progress, Result> extends RoboAsyncTask<Result> { // // @Inject // private Provider<Context> contextProvider; // // private ITaskListener listener; // // private Result results; // // public AListenedAsyncTask(ITaskListener listener) { // super(listener.getActivity()); // this.listener = listener; // } // // protected CondroidApi getCondroidService() { // Gson gson = new GsonBuilder() // .registerTypeAdapter(Date.class, new DateTypeAdapter()) // .registerTypeAdapter(AnnotationType.class, new AnnotationTypeAdapter()) // .create(); // RestAdapter adapter = new RestAdapter.Builder() // .setEndpoint(CondroidApi.API_ENDPOINT) // .setConverter(new GsonConverter(gson)) // .setRequestInterceptor(new RequestInterceptor() { // @Override // public void intercept(RequestFacade request) { // request.addHeader("X-Device-Info", CondroidActivity.getDeviceInfoString(listener.getActivity())); // } // }) // .build(); // return adapter.create(CondroidApi.class); // } // // protected void onSuccess(Result results) throws Exception { // this.results = results; // this.listener.onTaskCompleted(this); // } // // public Result getResults() { // return this.results; // } // // @Override // protected void onException(Exception e) throws RuntimeException { // if (e instanceof RetrofitError) { // if (((RetrofitError) e).isNetworkError()) { // Toast.makeText(listener.getActivity(), R.string.networkError, Toast.LENGTH_LONG).show(); // //return; // } else if (((RetrofitError) e).getResponse() != null && ((RetrofitError) e).getResponse().getStatus() >= 500) { // Toast.makeText(listener.getActivity(), R.string.serverError, Toast.LENGTH_LONG).show(); // //return; // } // // } // super.onException(e); // listener.onTaskErrored(this); // } // } // // Path: Condroid/src/main/java/cz/quinix/condroid/abstracts/ITaskListener.java // public interface ITaskListener { // // void onTaskCompleted(AListenedAsyncTask<?, ?> task); // // Activity getActivity(); // // void onTaskErrored(AListenedAsyncTask task); // } // Path: Condroid/src/main/java/cz/quinix/condroid/loader/AProgressedTask.java import android.app.Activity; import android.app.ProgressDialog; import android.content.DialogInterface; import cz.quinix.condroid.abstracts.AListenedAsyncTask; import cz.quinix.condroid.abstracts.ITaskListener; package cz.quinix.condroid.loader; public abstract class AProgressedTask<Progress, Result> extends AListenedAsyncTask<Progress, Result> { protected ProgressDialog pd; private Activity parent; protected String pdString;
public AProgressedTask(ITaskListener listener, Activity parent) {
BlackCraze/GameResourceBot
src/main/java/de/blackcraze/grb/dao/StockDaoBean.java
// Path: src/main/java/de/blackcraze/grb/model/entity/Mate.java // @Entity // @Table(name = "MATE") // public class Mate extends AbstractNamed { // // private static final long serialVersionUID = 1453233261285704063L; // // @Column(nullable = false, unique = true) // private String discordId; // // @Column // private String language; // // @Enumerated(EnumType.STRING) // @Column // private Device device; // // @OneToMany(mappedBy = "mate", fetch = FetchType.LAZY) // @OnDelete(action = OnDeleteAction.CASCADE) // private Set<Building> buildings; // // @OneToMany(mappedBy = "mate", fetch = FetchType.LAZY) // @OnDelete(action = OnDeleteAction.CASCADE) // private Set<Stock> stocks; // // public Set<Building> getBuildings() { // return buildings; // } // // public Set<Stock> getStocks() { // return stocks; // } // // public String getDiscordId() { // return discordId; // } // // public void setDiscordId(String discordId) { // this.discordId = discordId; // } // // public String getLanguage() { // return language; // } // // public void setLanguage(String language) { // this.language = language; // } // // public Device getDevice() { // return device; // } // // public void setDevice(Device device) { // this.device = device; // } // // }
import java.sql.Date; import java.time.LocalDateTime; import java.time.ZoneId; import java.util.List; import de.blackcraze.grb.model.entity.Mate; import de.blackcraze.grb.model.entity.Stock; import de.blackcraze.grb.model.entity.StockType;
package de.blackcraze.grb.dao; public class StockDaoBean extends BaseDaoBean<Stock> implements IStockDao { @SuppressWarnings("unchecked") @Override
// Path: src/main/java/de/blackcraze/grb/model/entity/Mate.java // @Entity // @Table(name = "MATE") // public class Mate extends AbstractNamed { // // private static final long serialVersionUID = 1453233261285704063L; // // @Column(nullable = false, unique = true) // private String discordId; // // @Column // private String language; // // @Enumerated(EnumType.STRING) // @Column // private Device device; // // @OneToMany(mappedBy = "mate", fetch = FetchType.LAZY) // @OnDelete(action = OnDeleteAction.CASCADE) // private Set<Building> buildings; // // @OneToMany(mappedBy = "mate", fetch = FetchType.LAZY) // @OnDelete(action = OnDeleteAction.CASCADE) // private Set<Stock> stocks; // // public Set<Building> getBuildings() { // return buildings; // } // // public Set<Stock> getStocks() { // return stocks; // } // // public String getDiscordId() { // return discordId; // } // // public void setDiscordId(String discordId) { // this.discordId = discordId; // } // // public String getLanguage() { // return language; // } // // public void setLanguage(String language) { // this.language = language; // } // // public Device getDevice() { // return device; // } // // public void setDevice(Device device) { // this.device = device; // } // // } // Path: src/main/java/de/blackcraze/grb/dao/StockDaoBean.java import java.sql.Date; import java.time.LocalDateTime; import java.time.ZoneId; import java.util.List; import de.blackcraze.grb.model.entity.Mate; import de.blackcraze.grb.model.entity.Stock; import de.blackcraze.grb.model.entity.StockType; package de.blackcraze.grb.dao; public class StockDaoBean extends BaseDaoBean<Stock> implements IStockDao { @SuppressWarnings("unchecked") @Override
public List<Stock> findStocksByMate(Mate mate) {
BlackCraze/GameResourceBot
src/main/java/de/blackcraze/grb/commands/concrete/Config.java
// Path: src/main/java/de/blackcraze/grb/commands/BaseCommand.java // public interface BaseCommand { // // void run(Scanner scanner, Message message); // // default String help(Message message) { // String className = this.getClass().getSimpleName(); // String key = className.toUpperCase(); // return Resource.getHelp(key, getResponseLocale(message), BotConfig.getConfig().PREFIX, // "#" + BotConfig.getConfig().CHANNEL); // } // // static void checkPublic(Message message) { // if (!ChannelType.TEXT.equals(message.getChannelType())) { // Speaker.err(message, // String.format( // Resource.getError("PUBLIC_COMMAND_ONLY", getResponseLocale(message)), // "#" + BotConfig.getConfig().CHANNEL)); // throw new IllegalStateException("Public command only"); // } // } // // static Collection<Class<BaseCommand>> getCommandClasses() { // ClassPath classPath; // try { // classPath = ClassPath.from(ClassLoader.getSystemClassLoader()); // } catch (IOException e) { // e.printStackTrace(); // return Collections.emptyList(); // } // // @SuppressWarnings("unchecked") // Collection<Class<BaseCommand>> classes = // classPath.getTopLevelClassesRecursive("de.blackcraze.grb.commands").stream() // .map(aClassInfo -> ((Class<BaseCommand>) aClassInfo.load())) // .collect(Collectors.toList()); // return classes.stream().filter(BaseCommand.class::isAssignableFrom) // .collect(Collectors.toList()); // } // } // // Path: src/main/java/de/blackcraze/grb/core/BotConfig.java // public class BotConfig { // // static final String[] REQUIRED_ENV_VARS = { "GRB_DISCORD_TOKEN" }; // // static final String DISCORD_TOKEN = System.getenv("GRB_DISCORD_TOKEN"); // public static final String DATABASE_URL = getEnv("DATABASE_URL", "postgres://gbr:gbr@localhost:5432/gbr"); // public static final String USE_SSL = getEnv("USE_SSL", ""); // public static final String TESS_DATA = getEnv("TESS_DATA", "./tessdata"); // // private static ServerConfig config = new ServerConfig(); // // public static class ServerConfig { // public String PREFIX = getEnv("PREFIX", "bot"); // public String CHANNEL = getEnv("CHANNEL", "statistik"); // public String LANGUAGE = getEnv("LANGUAGE", "en"); // public String OCR_RESULT = getEnv("OCR_RESULT", "on"); // public String DELETE_PICTURE_MESSAGE = getEnv("DELETE_PICTURE_MESSAGE", "off"); // } // // private static String getEnv(String envVar, String defaultValue) { // Optional<String> envValue = Optional.ofNullable(System.getenv(envVar)); // return envValue.orElse(defaultValue); // } // // public static ServerConfig getConfig() { // return config; // } // } // // Path: src/main/java/de/blackcraze/grb/core/Speaker.java // public class Speaker { // // public static class Reaction { // public final static String SUCCESS = "✅"; // public final static String FAILURE = "❌"; // } // // public static void say(MessageChannel channel, String text) { // say(channel, text, "", ""); // } // // public static void say(MessageChannel channel, List<String> texts) { // texts.forEach(text -> say(channel, text)); // } // // public static void sayCode(MessageChannel channel, List<String> texts) { // texts.forEach(text -> sayCode(channel, text)); // } // // public static void sayCode(MessageChannel channel, String text) { // say(channel, text, "```dsconfig\n", "\n```"); // } // // private static void say(MessageChannel channel, String text, String prefix, String suffix) { // if (StringUtils.isEmpty(text)) { // return; // } // StringTokenizer t = new StringTokenizer(text, "\n", true); // StringBuffer b = new StringBuffer(prefix); // b.append(suffix); // while (t.hasMoreTokens()) { // String token = t.nextToken(); // if (b.length() + token.length() <= 2000) { // b.insert(b.length() - suffix.length(), token); // } else { // channel.sendMessage(b.toString()).queue(); // b = new StringBuffer(prefix); // b.append(token); // b.append(suffix); // } // } // channel.sendMessage(b.toString()).queue(); // } // // public static void err(Message message, String text) { // message.addReaction(Reaction.FAILURE).queue(); // say(message.getChannel(), text); // } // // }
import de.blackcraze.grb.commands.BaseCommand; import de.blackcraze.grb.core.BotConfig; import de.blackcraze.grb.core.Speaker; import java.lang.reflect.Field; import java.util.Objects; import java.util.Scanner; import net.dv8tion.jda.api.entities.Message;
package de.blackcraze.grb.commands.concrete; public class Config implements BaseCommand { public void run(Scanner scanner, Message message) { BaseCommand.checkPublic(message);
// Path: src/main/java/de/blackcraze/grb/commands/BaseCommand.java // public interface BaseCommand { // // void run(Scanner scanner, Message message); // // default String help(Message message) { // String className = this.getClass().getSimpleName(); // String key = className.toUpperCase(); // return Resource.getHelp(key, getResponseLocale(message), BotConfig.getConfig().PREFIX, // "#" + BotConfig.getConfig().CHANNEL); // } // // static void checkPublic(Message message) { // if (!ChannelType.TEXT.equals(message.getChannelType())) { // Speaker.err(message, // String.format( // Resource.getError("PUBLIC_COMMAND_ONLY", getResponseLocale(message)), // "#" + BotConfig.getConfig().CHANNEL)); // throw new IllegalStateException("Public command only"); // } // } // // static Collection<Class<BaseCommand>> getCommandClasses() { // ClassPath classPath; // try { // classPath = ClassPath.from(ClassLoader.getSystemClassLoader()); // } catch (IOException e) { // e.printStackTrace(); // return Collections.emptyList(); // } // // @SuppressWarnings("unchecked") // Collection<Class<BaseCommand>> classes = // classPath.getTopLevelClassesRecursive("de.blackcraze.grb.commands").stream() // .map(aClassInfo -> ((Class<BaseCommand>) aClassInfo.load())) // .collect(Collectors.toList()); // return classes.stream().filter(BaseCommand.class::isAssignableFrom) // .collect(Collectors.toList()); // } // } // // Path: src/main/java/de/blackcraze/grb/core/BotConfig.java // public class BotConfig { // // static final String[] REQUIRED_ENV_VARS = { "GRB_DISCORD_TOKEN" }; // // static final String DISCORD_TOKEN = System.getenv("GRB_DISCORD_TOKEN"); // public static final String DATABASE_URL = getEnv("DATABASE_URL", "postgres://gbr:gbr@localhost:5432/gbr"); // public static final String USE_SSL = getEnv("USE_SSL", ""); // public static final String TESS_DATA = getEnv("TESS_DATA", "./tessdata"); // // private static ServerConfig config = new ServerConfig(); // // public static class ServerConfig { // public String PREFIX = getEnv("PREFIX", "bot"); // public String CHANNEL = getEnv("CHANNEL", "statistik"); // public String LANGUAGE = getEnv("LANGUAGE", "en"); // public String OCR_RESULT = getEnv("OCR_RESULT", "on"); // public String DELETE_PICTURE_MESSAGE = getEnv("DELETE_PICTURE_MESSAGE", "off"); // } // // private static String getEnv(String envVar, String defaultValue) { // Optional<String> envValue = Optional.ofNullable(System.getenv(envVar)); // return envValue.orElse(defaultValue); // } // // public static ServerConfig getConfig() { // return config; // } // } // // Path: src/main/java/de/blackcraze/grb/core/Speaker.java // public class Speaker { // // public static class Reaction { // public final static String SUCCESS = "✅"; // public final static String FAILURE = "❌"; // } // // public static void say(MessageChannel channel, String text) { // say(channel, text, "", ""); // } // // public static void say(MessageChannel channel, List<String> texts) { // texts.forEach(text -> say(channel, text)); // } // // public static void sayCode(MessageChannel channel, List<String> texts) { // texts.forEach(text -> sayCode(channel, text)); // } // // public static void sayCode(MessageChannel channel, String text) { // say(channel, text, "```dsconfig\n", "\n```"); // } // // private static void say(MessageChannel channel, String text, String prefix, String suffix) { // if (StringUtils.isEmpty(text)) { // return; // } // StringTokenizer t = new StringTokenizer(text, "\n", true); // StringBuffer b = new StringBuffer(prefix); // b.append(suffix); // while (t.hasMoreTokens()) { // String token = t.nextToken(); // if (b.length() + token.length() <= 2000) { // b.insert(b.length() - suffix.length(), token); // } else { // channel.sendMessage(b.toString()).queue(); // b = new StringBuffer(prefix); // b.append(token); // b.append(suffix); // } // } // channel.sendMessage(b.toString()).queue(); // } // // public static void err(Message message, String text) { // message.addReaction(Reaction.FAILURE).queue(); // say(message.getChannel(), text); // } // // } // Path: src/main/java/de/blackcraze/grb/commands/concrete/Config.java import de.blackcraze.grb.commands.BaseCommand; import de.blackcraze.grb.core.BotConfig; import de.blackcraze.grb.core.Speaker; import java.lang.reflect.Field; import java.util.Objects; import java.util.Scanner; import net.dv8tion.jda.api.entities.Message; package de.blackcraze.grb.commands.concrete; public class Config implements BaseCommand { public void run(Scanner scanner, Message message) { BaseCommand.checkPublic(message);
BotConfig.ServerConfig instance = BotConfig.getConfig();
BlackCraze/GameResourceBot
src/main/java/de/blackcraze/grb/commands/concrete/CheckTypes.java
// Path: src/main/java/de/blackcraze/grb/util/CommandUtils.java // public static Optional<String> parseStockName(Scanner scanner) { // if (!scanner.hasNext()) { // return Optional.empty(); // } // StringBuilder stockName = new StringBuilder(); // stockName.append(scanner.next()); // while (scanner.hasNext() && !scanner.hasNextLong()) { // stockName.append(" "); // stockName.append(scanner.next()); // } // return Optional.of(stockName.toString()); // } // // Path: src/main/java/de/blackcraze/grb/util/CommandUtils.java // public static Locale getResponseLocale(Message message) { // Locale channelLocale = getDefaultLocale(); // Mate mate = getMateDao().getOrCreateMate(message, channelLocale); // if (mate != null && !StringUtils.isEmpty(mate.getLanguage())) { // return new Locale(mate.getLanguage()); // } // return channelLocale; // } // // Path: src/main/java/de/blackcraze/grb/util/PrintUtils.java // public static String prettyPrintStockTypes(List<StockType> stockTypes, Locale responseLocale) { // StringBuilder b = new StringBuilder(); // if (stockTypes.isEmpty()) { // b.append(Resource.getError("NO_DATA", responseLocale)); // } // for (StockType type : stockTypes) { // String resourceKey = type.getName(); // String resourceName = Resource.getItem(resourceKey, responseLocale); // b.append(resourceName); // b.append("\n"); // } // return b.toString(); // } // // Path: src/main/java/de/blackcraze/grb/commands/BaseCommand.java // public interface BaseCommand { // // void run(Scanner scanner, Message message); // // default String help(Message message) { // String className = this.getClass().getSimpleName(); // String key = className.toUpperCase(); // return Resource.getHelp(key, getResponseLocale(message), BotConfig.getConfig().PREFIX, // "#" + BotConfig.getConfig().CHANNEL); // } // // static void checkPublic(Message message) { // if (!ChannelType.TEXT.equals(message.getChannelType())) { // Speaker.err(message, // String.format( // Resource.getError("PUBLIC_COMMAND_ONLY", getResponseLocale(message)), // "#" + BotConfig.getConfig().CHANNEL)); // throw new IllegalStateException("Public command only"); // } // } // // static Collection<Class<BaseCommand>> getCommandClasses() { // ClassPath classPath; // try { // classPath = ClassPath.from(ClassLoader.getSystemClassLoader()); // } catch (IOException e) { // e.printStackTrace(); // return Collections.emptyList(); // } // // @SuppressWarnings("unchecked") // Collection<Class<BaseCommand>> classes = // classPath.getTopLevelClassesRecursive("de.blackcraze.grb.commands").stream() // .map(aClassInfo -> ((Class<BaseCommand>) aClassInfo.load())) // .collect(Collectors.toList()); // return classes.stream().filter(BaseCommand.class::isAssignableFrom) // .collect(Collectors.toList()); // } // } // // Path: src/main/java/de/blackcraze/grb/core/Speaker.java // public class Speaker { // // public static class Reaction { // public final static String SUCCESS = "✅"; // public final static String FAILURE = "❌"; // } // // public static void say(MessageChannel channel, String text) { // say(channel, text, "", ""); // } // // public static void say(MessageChannel channel, List<String> texts) { // texts.forEach(text -> say(channel, text)); // } // // public static void sayCode(MessageChannel channel, List<String> texts) { // texts.forEach(text -> sayCode(channel, text)); // } // // public static void sayCode(MessageChannel channel, String text) { // say(channel, text, "```dsconfig\n", "\n```"); // } // // private static void say(MessageChannel channel, String text, String prefix, String suffix) { // if (StringUtils.isEmpty(text)) { // return; // } // StringTokenizer t = new StringTokenizer(text, "\n", true); // StringBuffer b = new StringBuffer(prefix); // b.append(suffix); // while (t.hasMoreTokens()) { // String token = t.nextToken(); // if (b.length() + token.length() <= 2000) { // b.insert(b.length() - suffix.length(), token); // } else { // channel.sendMessage(b.toString()).queue(); // b = new StringBuffer(prefix); // b.append(token); // b.append(suffix); // } // } // channel.sendMessage(b.toString()).queue(); // } // // public static void err(Message message, String text) { // message.addReaction(Reaction.FAILURE).queue(); // say(message.getChannel(), text); // } // // }
import static de.blackcraze.grb.util.CommandUtils.parseStockName; import static de.blackcraze.grb.util.CommandUtils.getResponseLocale; import static de.blackcraze.grb.util.InjectorUtils.getStockTypeDao; import static de.blackcraze.grb.util.PrintUtils.prettyPrintStockTypes; import de.blackcraze.grb.commands.BaseCommand; import de.blackcraze.grb.core.Speaker; import de.blackcraze.grb.model.entity.StockType; import java.util.List; import java.util.Locale; import java.util.Optional; import java.util.Scanner; import net.dv8tion.jda.api.entities.Message;
package de.blackcraze.grb.commands.concrete; public class CheckTypes implements BaseCommand { public void run(Scanner scanner, Message message) {
// Path: src/main/java/de/blackcraze/grb/util/CommandUtils.java // public static Optional<String> parseStockName(Scanner scanner) { // if (!scanner.hasNext()) { // return Optional.empty(); // } // StringBuilder stockName = new StringBuilder(); // stockName.append(scanner.next()); // while (scanner.hasNext() && !scanner.hasNextLong()) { // stockName.append(" "); // stockName.append(scanner.next()); // } // return Optional.of(stockName.toString()); // } // // Path: src/main/java/de/blackcraze/grb/util/CommandUtils.java // public static Locale getResponseLocale(Message message) { // Locale channelLocale = getDefaultLocale(); // Mate mate = getMateDao().getOrCreateMate(message, channelLocale); // if (mate != null && !StringUtils.isEmpty(mate.getLanguage())) { // return new Locale(mate.getLanguage()); // } // return channelLocale; // } // // Path: src/main/java/de/blackcraze/grb/util/PrintUtils.java // public static String prettyPrintStockTypes(List<StockType> stockTypes, Locale responseLocale) { // StringBuilder b = new StringBuilder(); // if (stockTypes.isEmpty()) { // b.append(Resource.getError("NO_DATA", responseLocale)); // } // for (StockType type : stockTypes) { // String resourceKey = type.getName(); // String resourceName = Resource.getItem(resourceKey, responseLocale); // b.append(resourceName); // b.append("\n"); // } // return b.toString(); // } // // Path: src/main/java/de/blackcraze/grb/commands/BaseCommand.java // public interface BaseCommand { // // void run(Scanner scanner, Message message); // // default String help(Message message) { // String className = this.getClass().getSimpleName(); // String key = className.toUpperCase(); // return Resource.getHelp(key, getResponseLocale(message), BotConfig.getConfig().PREFIX, // "#" + BotConfig.getConfig().CHANNEL); // } // // static void checkPublic(Message message) { // if (!ChannelType.TEXT.equals(message.getChannelType())) { // Speaker.err(message, // String.format( // Resource.getError("PUBLIC_COMMAND_ONLY", getResponseLocale(message)), // "#" + BotConfig.getConfig().CHANNEL)); // throw new IllegalStateException("Public command only"); // } // } // // static Collection<Class<BaseCommand>> getCommandClasses() { // ClassPath classPath; // try { // classPath = ClassPath.from(ClassLoader.getSystemClassLoader()); // } catch (IOException e) { // e.printStackTrace(); // return Collections.emptyList(); // } // // @SuppressWarnings("unchecked") // Collection<Class<BaseCommand>> classes = // classPath.getTopLevelClassesRecursive("de.blackcraze.grb.commands").stream() // .map(aClassInfo -> ((Class<BaseCommand>) aClassInfo.load())) // .collect(Collectors.toList()); // return classes.stream().filter(BaseCommand.class::isAssignableFrom) // .collect(Collectors.toList()); // } // } // // Path: src/main/java/de/blackcraze/grb/core/Speaker.java // public class Speaker { // // public static class Reaction { // public final static String SUCCESS = "✅"; // public final static String FAILURE = "❌"; // } // // public static void say(MessageChannel channel, String text) { // say(channel, text, "", ""); // } // // public static void say(MessageChannel channel, List<String> texts) { // texts.forEach(text -> say(channel, text)); // } // // public static void sayCode(MessageChannel channel, List<String> texts) { // texts.forEach(text -> sayCode(channel, text)); // } // // public static void sayCode(MessageChannel channel, String text) { // say(channel, text, "```dsconfig\n", "\n```"); // } // // private static void say(MessageChannel channel, String text, String prefix, String suffix) { // if (StringUtils.isEmpty(text)) { // return; // } // StringTokenizer t = new StringTokenizer(text, "\n", true); // StringBuffer b = new StringBuffer(prefix); // b.append(suffix); // while (t.hasMoreTokens()) { // String token = t.nextToken(); // if (b.length() + token.length() <= 2000) { // b.insert(b.length() - suffix.length(), token); // } else { // channel.sendMessage(b.toString()).queue(); // b = new StringBuffer(prefix); // b.append(token); // b.append(suffix); // } // } // channel.sendMessage(b.toString()).queue(); // } // // public static void err(Message message, String text) { // message.addReaction(Reaction.FAILURE).queue(); // say(message.getChannel(), text); // } // // } // Path: src/main/java/de/blackcraze/grb/commands/concrete/CheckTypes.java import static de.blackcraze.grb.util.CommandUtils.parseStockName; import static de.blackcraze.grb.util.CommandUtils.getResponseLocale; import static de.blackcraze.grb.util.InjectorUtils.getStockTypeDao; import static de.blackcraze.grb.util.PrintUtils.prettyPrintStockTypes; import de.blackcraze.grb.commands.BaseCommand; import de.blackcraze.grb.core.Speaker; import de.blackcraze.grb.model.entity.StockType; import java.util.List; import java.util.Locale; import java.util.Optional; import java.util.Scanner; import net.dv8tion.jda.api.entities.Message; package de.blackcraze.grb.commands.concrete; public class CheckTypes implements BaseCommand { public void run(Scanner scanner, Message message) {
Optional<String> stockNameOptional = parseStockName(scanner);
inloop/AndroidViewModel
sample/src/main/java/eu/inloop/viewmodel/sample/fragment/PagerFragment.java
// Path: library/src/main/java/eu/inloop/viewmodel/base/ViewModelBaseFragment.java // public abstract class ViewModelBaseFragment<T extends IView, R extends AbstractViewModel<T>> extends Fragment implements IView { // // @NonNull // private final ViewModelHelper<T, R> mViewModelHelper = new ViewModelHelper<>(); // // @CallSuper // @Override // public void onCreate(@Nullable final Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // // Class<? extends AbstractViewModel<T>> viewModelClass = getViewModelClass(); // // try to extract the ViewModel class from the implementation // if (viewModelClass == null) { // //noinspection unchecked // viewModelClass = (Class<? extends AbstractViewModel<T>>) ProxyViewHelper.getGenericType(getClass(), AbstractViewModel.class); // } // getViewModelHelper().onCreate(requireActivity(), savedInstanceState, viewModelClass, getArguments()); // } // // @CallSuper // @Override // public void onSaveInstanceState(@NonNull final Bundle outState) { // super.onSaveInstanceState(outState); // getViewModelHelper().onSaveInstanceState(outState); // } // // @CallSuper // @Override // public void onStart() { // super.onStart(); // getViewModelHelper().onStart(); // } // // @CallSuper // @Override // public void onStop() { // super.onStop(); // getViewModelHelper().onStop(); // } // // @CallSuper // @Override // public void onDestroyView() { // getViewModelHelper().onDestroyView(this); // super.onDestroyView(); // } // // @CallSuper // @Override // public void onDestroy() { // getViewModelHelper().onDestroy(this); // super.onDestroy(); // } // // @Nullable // public Class<R> getViewModelClass() { // return null; // } // // /** // * @see ViewModelHelper#getViewModel() // */ // @NonNull // @SuppressWarnings("unused") // public R getViewModel() { // return getViewModelHelper().getViewModel(); // } // // @Nullable // @Override // public ViewModelBindingConfig getViewModelBindingConfig() { // return null; // } // // @NonNull // public ViewModelHelper<T, R> getViewModelHelper() { // return mViewModelHelper; // } // // @Override // public void removeViewModel() { // mViewModelHelper.removeViewModel(requireActivity()); // } // // /** // * Call this after your view is ready - usually on the end of {@link // * Fragment#onViewCreated(View, Bundle)} // * // * @param view view // */ // protected void setModelView(@NonNull final T view) { // getViewModelHelper().setView(view); // } // } // // Path: sample/src/main/java/eu/inloop/viewmodel/sample/SampleApplication.java // public class SampleApplication extends Application { // // private RefWatcher refWatcher; // // @Override // public void onCreate() { // super.onCreate(); // refWatcher = LeakCanary.install(this); // } // // public static RefWatcher getRefWatcher(Context context) { // SampleApplication application = (SampleApplication) context.getApplicationContext(); // return application.refWatcher; // } // // } // // Path: sample/src/main/java/eu/inloop/viewmodel/sample/viewmodel/PageModel.java // public class PageModel extends AbstractViewModel<IPageView> { // // @Override // public void onCreate(@Nullable Bundle arguments, @Nullable Bundle savedInstanceState) { // super.onCreate(arguments, savedInstanceState); // } // } // // Path: sample/src/main/java/eu/inloop/viewmodel/sample/viewmodel/view/IPageView.java // public interface IPageView extends IView { // ViewModelBindingConfig getViewModelBindingConfig(); // }
import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.squareup.leakcanary.RefWatcher; import eu.inloop.viewmodel.base.ViewModelBaseFragment; import eu.inloop.viewmodel.sample.R; import eu.inloop.viewmodel.sample.SampleApplication; import eu.inloop.viewmodel.sample.viewmodel.PageModel; import eu.inloop.viewmodel.sample.viewmodel.view.IPageView;
package eu.inloop.viewmodel.sample.fragment; public class PagerFragment extends ViewModelBaseFragment<IPageView, PageModel> implements IPageView { public static PagerFragment newInstance(int position) { final Bundle bundle = new Bundle(); bundle.putInt("position", position); final PagerFragment fragment = new PagerFragment(); fragment.setArguments(bundle); return fragment; } @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_pager, container, false); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); ((TextView)view.findViewById(R.id.text)).setText(Integer.toString(getArguments().getInt("position"))); setModelView(this); } @Override public void onDestroy() { super.onDestroy(); // watch for memory leaks
// Path: library/src/main/java/eu/inloop/viewmodel/base/ViewModelBaseFragment.java // public abstract class ViewModelBaseFragment<T extends IView, R extends AbstractViewModel<T>> extends Fragment implements IView { // // @NonNull // private final ViewModelHelper<T, R> mViewModelHelper = new ViewModelHelper<>(); // // @CallSuper // @Override // public void onCreate(@Nullable final Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // // Class<? extends AbstractViewModel<T>> viewModelClass = getViewModelClass(); // // try to extract the ViewModel class from the implementation // if (viewModelClass == null) { // //noinspection unchecked // viewModelClass = (Class<? extends AbstractViewModel<T>>) ProxyViewHelper.getGenericType(getClass(), AbstractViewModel.class); // } // getViewModelHelper().onCreate(requireActivity(), savedInstanceState, viewModelClass, getArguments()); // } // // @CallSuper // @Override // public void onSaveInstanceState(@NonNull final Bundle outState) { // super.onSaveInstanceState(outState); // getViewModelHelper().onSaveInstanceState(outState); // } // // @CallSuper // @Override // public void onStart() { // super.onStart(); // getViewModelHelper().onStart(); // } // // @CallSuper // @Override // public void onStop() { // super.onStop(); // getViewModelHelper().onStop(); // } // // @CallSuper // @Override // public void onDestroyView() { // getViewModelHelper().onDestroyView(this); // super.onDestroyView(); // } // // @CallSuper // @Override // public void onDestroy() { // getViewModelHelper().onDestroy(this); // super.onDestroy(); // } // // @Nullable // public Class<R> getViewModelClass() { // return null; // } // // /** // * @see ViewModelHelper#getViewModel() // */ // @NonNull // @SuppressWarnings("unused") // public R getViewModel() { // return getViewModelHelper().getViewModel(); // } // // @Nullable // @Override // public ViewModelBindingConfig getViewModelBindingConfig() { // return null; // } // // @NonNull // public ViewModelHelper<T, R> getViewModelHelper() { // return mViewModelHelper; // } // // @Override // public void removeViewModel() { // mViewModelHelper.removeViewModel(requireActivity()); // } // // /** // * Call this after your view is ready - usually on the end of {@link // * Fragment#onViewCreated(View, Bundle)} // * // * @param view view // */ // protected void setModelView(@NonNull final T view) { // getViewModelHelper().setView(view); // } // } // // Path: sample/src/main/java/eu/inloop/viewmodel/sample/SampleApplication.java // public class SampleApplication extends Application { // // private RefWatcher refWatcher; // // @Override // public void onCreate() { // super.onCreate(); // refWatcher = LeakCanary.install(this); // } // // public static RefWatcher getRefWatcher(Context context) { // SampleApplication application = (SampleApplication) context.getApplicationContext(); // return application.refWatcher; // } // // } // // Path: sample/src/main/java/eu/inloop/viewmodel/sample/viewmodel/PageModel.java // public class PageModel extends AbstractViewModel<IPageView> { // // @Override // public void onCreate(@Nullable Bundle arguments, @Nullable Bundle savedInstanceState) { // super.onCreate(arguments, savedInstanceState); // } // } // // Path: sample/src/main/java/eu/inloop/viewmodel/sample/viewmodel/view/IPageView.java // public interface IPageView extends IView { // ViewModelBindingConfig getViewModelBindingConfig(); // } // Path: sample/src/main/java/eu/inloop/viewmodel/sample/fragment/PagerFragment.java import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.squareup.leakcanary.RefWatcher; import eu.inloop.viewmodel.base.ViewModelBaseFragment; import eu.inloop.viewmodel.sample.R; import eu.inloop.viewmodel.sample.SampleApplication; import eu.inloop.viewmodel.sample.viewmodel.PageModel; import eu.inloop.viewmodel.sample.viewmodel.view.IPageView; package eu.inloop.viewmodel.sample.fragment; public class PagerFragment extends ViewModelBaseFragment<IPageView, PageModel> implements IPageView { public static PagerFragment newInstance(int position) { final Bundle bundle = new Bundle(); bundle.putInt("position", position); final PagerFragment fragment = new PagerFragment(); fragment.setArguments(bundle); return fragment; } @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_pager, container, false); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); ((TextView)view.findViewById(R.id.text)).setText(Integer.toString(getArguments().getInt("position"))); setModelView(this); } @Override public void onDestroy() { super.onDestroy(); // watch for memory leaks
RefWatcher refWatcher = SampleApplication.getRefWatcher(requireActivity());
inloop/AndroidViewModel
sample/src/main/java/eu/inloop/viewmodel/sample/activity/MainActivity.java
// Path: library/src/main/java/eu/inloop/viewmodel/base/ViewModelBaseEmptyActivity.java // public abstract class ViewModelBaseEmptyActivity extends AppCompatActivity implements IViewModelProvider { // // @Nullable // private ViewModelProvider mViewModelProvider; // // @CallSuper // @Override // protected void onCreate(@Nullable final Bundle savedInstanceState) { // //This code must be execute prior to super.onCreate() // mViewModelProvider = ViewModelProvider.newInstance(this); // super.onCreate(savedInstanceState); // } // // @Override // @Nullable // public Object onRetainCustomNonConfigurationInstance() { // return mViewModelProvider; // } // // @CallSuper // @Override // public void onStop() { // super.onStop(); // if (isFinishing()) { // if (null == mViewModelProvider) { // throw new IllegalStateException("ViewModelProvider for activity " + this + " was null."); //NON-NLS // } // mViewModelProvider.removeAllViewModels(); // } // } // // @Nullable // @Override // public ViewModelProvider getViewModelProvider() { // return mViewModelProvider; // } // } // // Path: sample/src/main/java/eu/inloop/viewmodel/sample/fragment/UserListFragment.java // public class UserListFragment extends ViewModelBaseFragment<IUserListView, UserListViewModel> implements IUserListView { // // @BindView(android.R.id.progress) // View mProgressView; // @BindView(R.id.progress_text) // TextView mProgressText; // @BindView(android.R.id.list) // ListView mListview; // @BindView(R.id.open_binding_fragment) // Button mOpenBindingFragment; // // private ArrayAdapter<String> mAdapter; // // @Override // public void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // mAdapter = new ArrayAdapter<>(requireActivity(), android.R.layout.simple_list_item_1, android.R.id.text1, new ArrayList<String>()); // } // // @Override // public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { // final View view = inflater.inflate(R.layout.fragment_userlist, container, false); // ButterKnife.bind(this, view); // // final View headerView = inflater.inflate(R.layout.view_header_info, null, false); // headerView.findViewById(R.id.button1).setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View view) { // requireFragmentManager().beginTransaction().replace(R.id.root_content, SampleBundleFragment.newInstance(1234), "empty-fragment").addToBackStack(null).commit(); // } // }); // headerView.findViewById(R.id.button2).setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View view) { // requireActivity().finish(); // requireActivity().startActivity(requireActivity().getIntent()); // } // }); // headerView.findViewById(R.id.button3).setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View view) { // startActivity(new Intent(requireContext(), ViewPagerActivity.class)); // } // }); // mListview.addHeaderView(headerView, null, false); // mOpenBindingFragment.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // startActivity(SampleBindingActivity.newIntent(requireActivity())); // } // }); // return view; // } // // @Override // public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { // super.onViewCreated(view, savedInstanceState); // mListview.setAdapter(mAdapter); // mListview.setOnItemClickListener(new AdapterView.OnItemClickListener() { // @Override // public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { // getViewModel().deleteUser(i - mListview.getHeaderViewsCount()); // } // }); // setModelView(this); // } // // @Override // public void showUsers(List<String> users) { // mAdapter.setNotifyOnChange(false); // mAdapter.clear(); // mAdapter.addAll(users); // mAdapter.setNotifyOnChange(true); // mAdapter.notifyDataSetChanged(); // } // // @Override // public void showLoading(float progress) { // mProgressView.setVisibility(View.VISIBLE); // mProgressText.setText((int) (progress * 100) + "%"); // } // // @Override // public void hideProgress() { // mProgressView.setVisibility(View.GONE); // } // // @Override // public void onDestroy() { // super.onDestroy(); // // // watch for memory leaks // RefWatcher refWatcher = SampleApplication.getRefWatcher(requireActivity()); // refWatcher.watch(this); // } // }
import android.os.Bundle; import butterknife.ButterKnife; import eu.inloop.viewmodel.base.ViewModelBaseEmptyActivity; import eu.inloop.viewmodel.sample.R; import eu.inloop.viewmodel.sample.fragment.UserListFragment;
package eu.inloop.viewmodel.sample.activity; public class MainActivity extends ViewModelBaseEmptyActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); if (savedInstanceState == null) {
// Path: library/src/main/java/eu/inloop/viewmodel/base/ViewModelBaseEmptyActivity.java // public abstract class ViewModelBaseEmptyActivity extends AppCompatActivity implements IViewModelProvider { // // @Nullable // private ViewModelProvider mViewModelProvider; // // @CallSuper // @Override // protected void onCreate(@Nullable final Bundle savedInstanceState) { // //This code must be execute prior to super.onCreate() // mViewModelProvider = ViewModelProvider.newInstance(this); // super.onCreate(savedInstanceState); // } // // @Override // @Nullable // public Object onRetainCustomNonConfigurationInstance() { // return mViewModelProvider; // } // // @CallSuper // @Override // public void onStop() { // super.onStop(); // if (isFinishing()) { // if (null == mViewModelProvider) { // throw new IllegalStateException("ViewModelProvider for activity " + this + " was null."); //NON-NLS // } // mViewModelProvider.removeAllViewModels(); // } // } // // @Nullable // @Override // public ViewModelProvider getViewModelProvider() { // return mViewModelProvider; // } // } // // Path: sample/src/main/java/eu/inloop/viewmodel/sample/fragment/UserListFragment.java // public class UserListFragment extends ViewModelBaseFragment<IUserListView, UserListViewModel> implements IUserListView { // // @BindView(android.R.id.progress) // View mProgressView; // @BindView(R.id.progress_text) // TextView mProgressText; // @BindView(android.R.id.list) // ListView mListview; // @BindView(R.id.open_binding_fragment) // Button mOpenBindingFragment; // // private ArrayAdapter<String> mAdapter; // // @Override // public void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // mAdapter = new ArrayAdapter<>(requireActivity(), android.R.layout.simple_list_item_1, android.R.id.text1, new ArrayList<String>()); // } // // @Override // public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { // final View view = inflater.inflate(R.layout.fragment_userlist, container, false); // ButterKnife.bind(this, view); // // final View headerView = inflater.inflate(R.layout.view_header_info, null, false); // headerView.findViewById(R.id.button1).setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View view) { // requireFragmentManager().beginTransaction().replace(R.id.root_content, SampleBundleFragment.newInstance(1234), "empty-fragment").addToBackStack(null).commit(); // } // }); // headerView.findViewById(R.id.button2).setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View view) { // requireActivity().finish(); // requireActivity().startActivity(requireActivity().getIntent()); // } // }); // headerView.findViewById(R.id.button3).setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View view) { // startActivity(new Intent(requireContext(), ViewPagerActivity.class)); // } // }); // mListview.addHeaderView(headerView, null, false); // mOpenBindingFragment.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // startActivity(SampleBindingActivity.newIntent(requireActivity())); // } // }); // return view; // } // // @Override // public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { // super.onViewCreated(view, savedInstanceState); // mListview.setAdapter(mAdapter); // mListview.setOnItemClickListener(new AdapterView.OnItemClickListener() { // @Override // public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { // getViewModel().deleteUser(i - mListview.getHeaderViewsCount()); // } // }); // setModelView(this); // } // // @Override // public void showUsers(List<String> users) { // mAdapter.setNotifyOnChange(false); // mAdapter.clear(); // mAdapter.addAll(users); // mAdapter.setNotifyOnChange(true); // mAdapter.notifyDataSetChanged(); // } // // @Override // public void showLoading(float progress) { // mProgressView.setVisibility(View.VISIBLE); // mProgressText.setText((int) (progress * 100) + "%"); // } // // @Override // public void hideProgress() { // mProgressView.setVisibility(View.GONE); // } // // @Override // public void onDestroy() { // super.onDestroy(); // // // watch for memory leaks // RefWatcher refWatcher = SampleApplication.getRefWatcher(requireActivity()); // refWatcher.watch(this); // } // } // Path: sample/src/main/java/eu/inloop/viewmodel/sample/activity/MainActivity.java import android.os.Bundle; import butterknife.ButterKnife; import eu.inloop.viewmodel.base.ViewModelBaseEmptyActivity; import eu.inloop.viewmodel.sample.R; import eu.inloop.viewmodel.sample.fragment.UserListFragment; package eu.inloop.viewmodel.sample.activity; public class MainActivity extends ViewModelBaseEmptyActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction().replace(R.id.root_content, new UserListFragment(), "user-list-fragment").commit();
inloop/AndroidViewModel
library/src/androidTest/java/eu/inloop/viewmodel/fixture/fragment/VMTestFragment.java
// Path: library/src/main/java/eu/inloop/viewmodel/base/ViewModelBaseFragment.java // public abstract class ViewModelBaseFragment<T extends IView, R extends AbstractViewModel<T>> extends Fragment implements IView { // // @NonNull // private final ViewModelHelper<T, R> mViewModelHelper = new ViewModelHelper<>(); // // @CallSuper // @Override // public void onCreate(@Nullable final Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // // Class<? extends AbstractViewModel<T>> viewModelClass = getViewModelClass(); // // try to extract the ViewModel class from the implementation // if (viewModelClass == null) { // //noinspection unchecked // viewModelClass = (Class<? extends AbstractViewModel<T>>) ProxyViewHelper.getGenericType(getClass(), AbstractViewModel.class); // } // getViewModelHelper().onCreate(requireActivity(), savedInstanceState, viewModelClass, getArguments()); // } // // @CallSuper // @Override // public void onSaveInstanceState(@NonNull final Bundle outState) { // super.onSaveInstanceState(outState); // getViewModelHelper().onSaveInstanceState(outState); // } // // @CallSuper // @Override // public void onStart() { // super.onStart(); // getViewModelHelper().onStart(); // } // // @CallSuper // @Override // public void onStop() { // super.onStop(); // getViewModelHelper().onStop(); // } // // @CallSuper // @Override // public void onDestroyView() { // getViewModelHelper().onDestroyView(this); // super.onDestroyView(); // } // // @CallSuper // @Override // public void onDestroy() { // getViewModelHelper().onDestroy(this); // super.onDestroy(); // } // // @Nullable // public Class<R> getViewModelClass() { // return null; // } // // /** // * @see ViewModelHelper#getViewModel() // */ // @NonNull // @SuppressWarnings("unused") // public R getViewModel() { // return getViewModelHelper().getViewModel(); // } // // @Nullable // @Override // public ViewModelBindingConfig getViewModelBindingConfig() { // return null; // } // // @NonNull // public ViewModelHelper<T, R> getViewModelHelper() { // return mViewModelHelper; // } // // @Override // public void removeViewModel() { // mViewModelHelper.removeViewModel(requireActivity()); // } // // /** // * Call this after your view is ready - usually on the end of {@link // * Fragment#onViewCreated(View, Bundle)} // * // * @param view view // */ // protected void setModelView(@NonNull final T view) { // getViewModelHelper().setView(view); // } // } // // Path: library/src/androidTest/java/eu/inloop/viewmodel/fixture/activity/VMTestActivity.java // public class VMTestActivity extends ViewModelBaseActivity<IVMTestActivityView, VMTestActivityViewModel> implements IVMTestActivityView { // // public static final int RESULT_CODE_OK = 1; // public static final String EXTRA_CALL_ON_BIND = "EXTRA_CALL_ON_BIND"; // // @NonNull // public static Intent makeIntent(@NonNull Context context, boolean callOnBindModel) { // Intent intent = new Intent(context, VMTestActivity.class); // intent.putExtra(EXTRA_CALL_ON_BIND, callOnBindModel); // // return intent; // } // // @Override // protected void onCreate(@Nullable Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // // LinearLayout view = new LinearLayout(this); // view.setId(android.R.id.content); // setContentView(view); // // if (savedInstanceState == null) { // addTestFragment(); // } // // setModelView(this); // } // // public void addTestFragment() { // getSupportFragmentManager() // .beginTransaction() // .add(android.R.id.content, new VMTestFragment()) // .commitNow(); // } // // public void removeTestFragment() { // getSupportFragmentManager() // .beginTransaction() // .remove(getTestFragment()) // .commitNow(); // } // // @NonNull // public VMTestFragment getTestFragment() { // for (Fragment fragment : getSupportFragmentManager().getFragments()) { // if (fragment instanceof VMTestFragment) { // return (VMTestFragment) fragment; // } // } // throw new AssertionError("Fragment not found"); // } // // @Override // public void onLoadData(boolean loaded) { // setResult(RESULT_CODE_OK); // finish(); // } // // }
import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import eu.inloop.viewmodel.base.ViewModelBaseFragment; import eu.inloop.viewmodel.fixture.activity.VMTestActivity;
package eu.inloop.viewmodel.fixture.fragment; public class VMTestFragment extends ViewModelBaseFragment<IVMTestFragmentView, VMTestFragmentViewModel> implements IVMTestFragmentView { @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { return new LinearLayout(getContext()); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); setModelView(this); } @Override public void onLoadData(boolean loaded) {
// Path: library/src/main/java/eu/inloop/viewmodel/base/ViewModelBaseFragment.java // public abstract class ViewModelBaseFragment<T extends IView, R extends AbstractViewModel<T>> extends Fragment implements IView { // // @NonNull // private final ViewModelHelper<T, R> mViewModelHelper = new ViewModelHelper<>(); // // @CallSuper // @Override // public void onCreate(@Nullable final Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // // Class<? extends AbstractViewModel<T>> viewModelClass = getViewModelClass(); // // try to extract the ViewModel class from the implementation // if (viewModelClass == null) { // //noinspection unchecked // viewModelClass = (Class<? extends AbstractViewModel<T>>) ProxyViewHelper.getGenericType(getClass(), AbstractViewModel.class); // } // getViewModelHelper().onCreate(requireActivity(), savedInstanceState, viewModelClass, getArguments()); // } // // @CallSuper // @Override // public void onSaveInstanceState(@NonNull final Bundle outState) { // super.onSaveInstanceState(outState); // getViewModelHelper().onSaveInstanceState(outState); // } // // @CallSuper // @Override // public void onStart() { // super.onStart(); // getViewModelHelper().onStart(); // } // // @CallSuper // @Override // public void onStop() { // super.onStop(); // getViewModelHelper().onStop(); // } // // @CallSuper // @Override // public void onDestroyView() { // getViewModelHelper().onDestroyView(this); // super.onDestroyView(); // } // // @CallSuper // @Override // public void onDestroy() { // getViewModelHelper().onDestroy(this); // super.onDestroy(); // } // // @Nullable // public Class<R> getViewModelClass() { // return null; // } // // /** // * @see ViewModelHelper#getViewModel() // */ // @NonNull // @SuppressWarnings("unused") // public R getViewModel() { // return getViewModelHelper().getViewModel(); // } // // @Nullable // @Override // public ViewModelBindingConfig getViewModelBindingConfig() { // return null; // } // // @NonNull // public ViewModelHelper<T, R> getViewModelHelper() { // return mViewModelHelper; // } // // @Override // public void removeViewModel() { // mViewModelHelper.removeViewModel(requireActivity()); // } // // /** // * Call this after your view is ready - usually on the end of {@link // * Fragment#onViewCreated(View, Bundle)} // * // * @param view view // */ // protected void setModelView(@NonNull final T view) { // getViewModelHelper().setView(view); // } // } // // Path: library/src/androidTest/java/eu/inloop/viewmodel/fixture/activity/VMTestActivity.java // public class VMTestActivity extends ViewModelBaseActivity<IVMTestActivityView, VMTestActivityViewModel> implements IVMTestActivityView { // // public static final int RESULT_CODE_OK = 1; // public static final String EXTRA_CALL_ON_BIND = "EXTRA_CALL_ON_BIND"; // // @NonNull // public static Intent makeIntent(@NonNull Context context, boolean callOnBindModel) { // Intent intent = new Intent(context, VMTestActivity.class); // intent.putExtra(EXTRA_CALL_ON_BIND, callOnBindModel); // // return intent; // } // // @Override // protected void onCreate(@Nullable Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // // LinearLayout view = new LinearLayout(this); // view.setId(android.R.id.content); // setContentView(view); // // if (savedInstanceState == null) { // addTestFragment(); // } // // setModelView(this); // } // // public void addTestFragment() { // getSupportFragmentManager() // .beginTransaction() // .add(android.R.id.content, new VMTestFragment()) // .commitNow(); // } // // public void removeTestFragment() { // getSupportFragmentManager() // .beginTransaction() // .remove(getTestFragment()) // .commitNow(); // } // // @NonNull // public VMTestFragment getTestFragment() { // for (Fragment fragment : getSupportFragmentManager().getFragments()) { // if (fragment instanceof VMTestFragment) { // return (VMTestFragment) fragment; // } // } // throw new AssertionError("Fragment not found"); // } // // @Override // public void onLoadData(boolean loaded) { // setResult(RESULT_CODE_OK); // finish(); // } // // } // Path: library/src/androidTest/java/eu/inloop/viewmodel/fixture/fragment/VMTestFragment.java import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import eu.inloop.viewmodel.base.ViewModelBaseFragment; import eu.inloop.viewmodel.fixture.activity.VMTestActivity; package eu.inloop.viewmodel.fixture.fragment; public class VMTestFragment extends ViewModelBaseFragment<IVMTestFragmentView, VMTestFragmentViewModel> implements IVMTestFragmentView { @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { return new LinearLayout(getContext()); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); setModelView(this); } @Override public void onLoadData(boolean loaded) {
requireActivity().setResult(VMTestActivity.RESULT_CODE_OK);
inloop/AndroidViewModel
library/src/androidTest/java/eu/inloop/viewmodel/ViewModelActivityTest.java
// Path: library/src/androidTest/java/eu/inloop/viewmodel/fixture/activity/VMTestActivity.java // public class VMTestActivity extends ViewModelBaseActivity<IVMTestActivityView, VMTestActivityViewModel> implements IVMTestActivityView { // // public static final int RESULT_CODE_OK = 1; // public static final String EXTRA_CALL_ON_BIND = "EXTRA_CALL_ON_BIND"; // // @NonNull // public static Intent makeIntent(@NonNull Context context, boolean callOnBindModel) { // Intent intent = new Intent(context, VMTestActivity.class); // intent.putExtra(EXTRA_CALL_ON_BIND, callOnBindModel); // // return intent; // } // // @Override // protected void onCreate(@Nullable Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // // LinearLayout view = new LinearLayout(this); // view.setId(android.R.id.content); // setContentView(view); // // if (savedInstanceState == null) { // addTestFragment(); // } // // setModelView(this); // } // // public void addTestFragment() { // getSupportFragmentManager() // .beginTransaction() // .add(android.R.id.content, new VMTestFragment()) // .commitNow(); // } // // public void removeTestFragment() { // getSupportFragmentManager() // .beginTransaction() // .remove(getTestFragment()) // .commitNow(); // } // // @NonNull // public VMTestFragment getTestFragment() { // for (Fragment fragment : getSupportFragmentManager().getFragments()) { // if (fragment instanceof VMTestFragment) { // return (VMTestFragment) fragment; // } // } // throw new AssertionError("Fragment not found"); // } // // @Override // public void onLoadData(boolean loaded) { // setResult(RESULT_CODE_OK); // finish(); // } // // }
import android.content.pm.ActivityInfo; import androidx.test.InstrumentationRegistry; import androidx.test.filters.MediumTest; import androidx.test.filters.SmallTest; import androidx.test.rule.ActivityTestRule; import androidx.test.runner.AndroidJUnit4; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import java.util.Map; import eu.inloop.viewmodel.fixture.activity.VMTestActivity; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.notNullValue; import static org.hamcrest.CoreMatchers.nullValue; import static org.hamcrest.MatcherAssert.assertThat;
package eu.inloop.viewmodel; @RunWith(AndroidJUnit4.class) public final class ViewModelActivityTest { @Rule
// Path: library/src/androidTest/java/eu/inloop/viewmodel/fixture/activity/VMTestActivity.java // public class VMTestActivity extends ViewModelBaseActivity<IVMTestActivityView, VMTestActivityViewModel> implements IVMTestActivityView { // // public static final int RESULT_CODE_OK = 1; // public static final String EXTRA_CALL_ON_BIND = "EXTRA_CALL_ON_BIND"; // // @NonNull // public static Intent makeIntent(@NonNull Context context, boolean callOnBindModel) { // Intent intent = new Intent(context, VMTestActivity.class); // intent.putExtra(EXTRA_CALL_ON_BIND, callOnBindModel); // // return intent; // } // // @Override // protected void onCreate(@Nullable Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // // LinearLayout view = new LinearLayout(this); // view.setId(android.R.id.content); // setContentView(view); // // if (savedInstanceState == null) { // addTestFragment(); // } // // setModelView(this); // } // // public void addTestFragment() { // getSupportFragmentManager() // .beginTransaction() // .add(android.R.id.content, new VMTestFragment()) // .commitNow(); // } // // public void removeTestFragment() { // getSupportFragmentManager() // .beginTransaction() // .remove(getTestFragment()) // .commitNow(); // } // // @NonNull // public VMTestFragment getTestFragment() { // for (Fragment fragment : getSupportFragmentManager().getFragments()) { // if (fragment instanceof VMTestFragment) { // return (VMTestFragment) fragment; // } // } // throw new AssertionError("Fragment not found"); // } // // @Override // public void onLoadData(boolean loaded) { // setResult(RESULT_CODE_OK); // finish(); // } // // } // Path: library/src/androidTest/java/eu/inloop/viewmodel/ViewModelActivityTest.java import android.content.pm.ActivityInfo; import androidx.test.InstrumentationRegistry; import androidx.test.filters.MediumTest; import androidx.test.filters.SmallTest; import androidx.test.rule.ActivityTestRule; import androidx.test.runner.AndroidJUnit4; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import java.util.Map; import eu.inloop.viewmodel.fixture.activity.VMTestActivity; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.notNullValue; import static org.hamcrest.CoreMatchers.nullValue; import static org.hamcrest.MatcherAssert.assertThat; package eu.inloop.viewmodel; @RunWith(AndroidJUnit4.class) public final class ViewModelActivityTest { @Rule
public final ActivityTestRule<VMTestActivity> mActivityTestRule =
inloop/AndroidViewModel
library/src/main/java/eu/inloop/viewmodel/base/ViewModelBaseEmptyActivity.java
// Path: library/src/main/java/eu/inloop/viewmodel/IViewModelProvider.java // public interface IViewModelProvider { // // /** // * See {@link eu.inloop.viewmodel.base.ViewModelBaseActivity} on how to implement. // * @return the {@link ViewModelProvider}. // */ // @Nullable // ViewModelProvider getViewModelProvider(); // } // // Path: library/src/main/java/eu/inloop/viewmodel/ViewModelProvider.java // public class ViewModelProvider { // // @NonNull // private final HashMap<String, AbstractViewModel<? extends IView>> mViewModelCache; // // @NonNull // public static ViewModelProvider newInstance(@NonNull final FragmentActivity activity) { // if (activity.getLastCustomNonConfigurationInstance() == null) { // return new ViewModelProvider(); // } else { // return (ViewModelProvider) activity.getLastCustomNonConfigurationInstance(); // } // } // // @SuppressWarnings({"deprecation", "unused"}) // @NonNull // @Deprecated // public static ViewModelProvider newInstance(@NonNull final Activity activity) { // if (activity.getLastNonConfigurationInstance() == null) { // return new ViewModelProvider(); // } else { // return (ViewModelProvider) activity.getLastNonConfigurationInstance(); // } // } // // private ViewModelProvider() { // mViewModelCache = new HashMap<>(); // } // // public synchronized void remove(@Nullable String modeIdentifier) { // mViewModelCache.remove(modeIdentifier); // } // // public synchronized void removeAllViewModels() { // mViewModelCache.clear(); // } // // @VisibleForTesting // @NonNull // Map<String, AbstractViewModel<? extends IView>> getViewModels() { // return Collections.unmodifiableMap(mViewModelCache); // } // // @SuppressWarnings("unchecked") // @NonNull // public synchronized <T extends IView> ViewModelWrapper<T> getViewModel(@NonNull final String modelIdentifier, // @NonNull final Class<? extends AbstractViewModel<T>> viewModelClass) { // AbstractViewModel<T> instance = (AbstractViewModel<T>) mViewModelCache.get(modelIdentifier); // if (instance != null) { // return new ViewModelWrapper<>(instance, false); // } // // try { // instance = viewModelClass.newInstance(); // } catch (final Exception ex) { // throw new RuntimeException(ex); // } // instance.setUniqueIdentifier(modelIdentifier); // mViewModelCache.put(modelIdentifier, instance); // return new ViewModelWrapper<>(instance, true); // } // // final static class ViewModelWrapper<T extends IView> { // @NonNull // final AbstractViewModel<T> viewModel; // final boolean wasCreated; // // private ViewModelWrapper(@NonNull AbstractViewModel<T> mViewModel, final boolean mWasCreated) { // this.viewModel = mViewModel; // this.wasCreated = mWasCreated; // } // } // }
import android.os.Bundle; import androidx.annotation.CallSuper; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import eu.inloop.viewmodel.IViewModelProvider; import eu.inloop.viewmodel.ViewModelProvider;
package eu.inloop.viewmodel.base; /** * All your activities must extend this activity - even in case your activity has no viewmodel. The fragment viewmodels are using the {@link IViewModelProvider} * interface to get the {@link ViewModelProvider} from the current activity. * You can copy this implementation in case you don't want to extend this class. */ public abstract class ViewModelBaseEmptyActivity extends AppCompatActivity implements IViewModelProvider { @Nullable
// Path: library/src/main/java/eu/inloop/viewmodel/IViewModelProvider.java // public interface IViewModelProvider { // // /** // * See {@link eu.inloop.viewmodel.base.ViewModelBaseActivity} on how to implement. // * @return the {@link ViewModelProvider}. // */ // @Nullable // ViewModelProvider getViewModelProvider(); // } // // Path: library/src/main/java/eu/inloop/viewmodel/ViewModelProvider.java // public class ViewModelProvider { // // @NonNull // private final HashMap<String, AbstractViewModel<? extends IView>> mViewModelCache; // // @NonNull // public static ViewModelProvider newInstance(@NonNull final FragmentActivity activity) { // if (activity.getLastCustomNonConfigurationInstance() == null) { // return new ViewModelProvider(); // } else { // return (ViewModelProvider) activity.getLastCustomNonConfigurationInstance(); // } // } // // @SuppressWarnings({"deprecation", "unused"}) // @NonNull // @Deprecated // public static ViewModelProvider newInstance(@NonNull final Activity activity) { // if (activity.getLastNonConfigurationInstance() == null) { // return new ViewModelProvider(); // } else { // return (ViewModelProvider) activity.getLastNonConfigurationInstance(); // } // } // // private ViewModelProvider() { // mViewModelCache = new HashMap<>(); // } // // public synchronized void remove(@Nullable String modeIdentifier) { // mViewModelCache.remove(modeIdentifier); // } // // public synchronized void removeAllViewModels() { // mViewModelCache.clear(); // } // // @VisibleForTesting // @NonNull // Map<String, AbstractViewModel<? extends IView>> getViewModels() { // return Collections.unmodifiableMap(mViewModelCache); // } // // @SuppressWarnings("unchecked") // @NonNull // public synchronized <T extends IView> ViewModelWrapper<T> getViewModel(@NonNull final String modelIdentifier, // @NonNull final Class<? extends AbstractViewModel<T>> viewModelClass) { // AbstractViewModel<T> instance = (AbstractViewModel<T>) mViewModelCache.get(modelIdentifier); // if (instance != null) { // return new ViewModelWrapper<>(instance, false); // } // // try { // instance = viewModelClass.newInstance(); // } catch (final Exception ex) { // throw new RuntimeException(ex); // } // instance.setUniqueIdentifier(modelIdentifier); // mViewModelCache.put(modelIdentifier, instance); // return new ViewModelWrapper<>(instance, true); // } // // final static class ViewModelWrapper<T extends IView> { // @NonNull // final AbstractViewModel<T> viewModel; // final boolean wasCreated; // // private ViewModelWrapper(@NonNull AbstractViewModel<T> mViewModel, final boolean mWasCreated) { // this.viewModel = mViewModel; // this.wasCreated = mWasCreated; // } // } // } // Path: library/src/main/java/eu/inloop/viewmodel/base/ViewModelBaseEmptyActivity.java import android.os.Bundle; import androidx.annotation.CallSuper; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import eu.inloop.viewmodel.IViewModelProvider; import eu.inloop.viewmodel.ViewModelProvider; package eu.inloop.viewmodel.base; /** * All your activities must extend this activity - even in case your activity has no viewmodel. The fragment viewmodels are using the {@link IViewModelProvider} * interface to get the {@link ViewModelProvider} from the current activity. * You can copy this implementation in case you don't want to extend this class. */ public abstract class ViewModelBaseEmptyActivity extends AppCompatActivity implements IViewModelProvider { @Nullable
private ViewModelProvider mViewModelProvider;
inloop/AndroidViewModel
sample/src/main/java/eu/inloop/viewmodel/sample/activity/SampleBindingActivity.java
// Path: library/src/main/java/eu/inloop/viewmodel/base/ViewModelBaseEmptyActivity.java // public abstract class ViewModelBaseEmptyActivity extends AppCompatActivity implements IViewModelProvider { // // @Nullable // private ViewModelProvider mViewModelProvider; // // @CallSuper // @Override // protected void onCreate(@Nullable final Bundle savedInstanceState) { // //This code must be execute prior to super.onCreate() // mViewModelProvider = ViewModelProvider.newInstance(this); // super.onCreate(savedInstanceState); // } // // @Override // @Nullable // public Object onRetainCustomNonConfigurationInstance() { // return mViewModelProvider; // } // // @CallSuper // @Override // public void onStop() { // super.onStop(); // if (isFinishing()) { // if (null == mViewModelProvider) { // throw new IllegalStateException("ViewModelProvider for activity " + this + " was null."); //NON-NLS // } // mViewModelProvider.removeAllViewModels(); // } // } // // @Nullable // @Override // public ViewModelProvider getViewModelProvider() { // return mViewModelProvider; // } // } // // Path: sample/src/main/java/eu/inloop/viewmodel/sample/fragment/SampleBindingFragment.java // public class SampleBindingFragment // extends ViewModelBaseBindingFragment<ISampleBindingView, SampleBindingViewModel, FragmentSampleBindingBinding> // implements ISampleBindingView { // // public SampleBindingFragment() { // // Required empty public constructor // } // // @Override // public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { // super.onViewCreated(view, savedInstanceState); // setModelView(this); // } // // @Override // public ViewModelBindingConfig getViewModelBindingConfig() { // return new ViewModelBindingConfig(R.layout.fragment_sample_binding, requireActivity()); // } // }
import android.content.Context; import android.content.Intent; import android.os.Bundle; import butterknife.ButterKnife; import eu.inloop.viewmodel.base.ViewModelBaseEmptyActivity; import eu.inloop.viewmodel.sample.R; import eu.inloop.viewmodel.sample.fragment.SampleBindingFragment;
package eu.inloop.viewmodel.sample.activity; public class SampleBindingActivity extends ViewModelBaseEmptyActivity { public static Intent newIntent(Context context) { return new Intent(context, SampleBindingActivity.class); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); if (savedInstanceState == null) {
// Path: library/src/main/java/eu/inloop/viewmodel/base/ViewModelBaseEmptyActivity.java // public abstract class ViewModelBaseEmptyActivity extends AppCompatActivity implements IViewModelProvider { // // @Nullable // private ViewModelProvider mViewModelProvider; // // @CallSuper // @Override // protected void onCreate(@Nullable final Bundle savedInstanceState) { // //This code must be execute prior to super.onCreate() // mViewModelProvider = ViewModelProvider.newInstance(this); // super.onCreate(savedInstanceState); // } // // @Override // @Nullable // public Object onRetainCustomNonConfigurationInstance() { // return mViewModelProvider; // } // // @CallSuper // @Override // public void onStop() { // super.onStop(); // if (isFinishing()) { // if (null == mViewModelProvider) { // throw new IllegalStateException("ViewModelProvider for activity " + this + " was null."); //NON-NLS // } // mViewModelProvider.removeAllViewModels(); // } // } // // @Nullable // @Override // public ViewModelProvider getViewModelProvider() { // return mViewModelProvider; // } // } // // Path: sample/src/main/java/eu/inloop/viewmodel/sample/fragment/SampleBindingFragment.java // public class SampleBindingFragment // extends ViewModelBaseBindingFragment<ISampleBindingView, SampleBindingViewModel, FragmentSampleBindingBinding> // implements ISampleBindingView { // // public SampleBindingFragment() { // // Required empty public constructor // } // // @Override // public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { // super.onViewCreated(view, savedInstanceState); // setModelView(this); // } // // @Override // public ViewModelBindingConfig getViewModelBindingConfig() { // return new ViewModelBindingConfig(R.layout.fragment_sample_binding, requireActivity()); // } // } // Path: sample/src/main/java/eu/inloop/viewmodel/sample/activity/SampleBindingActivity.java import android.content.Context; import android.content.Intent; import android.os.Bundle; import butterknife.ButterKnife; import eu.inloop.viewmodel.base.ViewModelBaseEmptyActivity; import eu.inloop.viewmodel.sample.R; import eu.inloop.viewmodel.sample.fragment.SampleBindingFragment; package eu.inloop.viewmodel.sample.activity; public class SampleBindingActivity extends ViewModelBaseEmptyActivity { public static Intent newIntent(Context context) { return new Intent(context, SampleBindingActivity.class); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction().replace(R.id.root_content, new SampleBindingFragment(), "sample-binding-fragment").commit();
inloop/AndroidViewModel
library/src/main/java/eu/inloop/viewmodel/support/ViewModelStatePagerAdapter.java
// Path: library/src/main/java/eu/inloop/viewmodel/IView.java // public interface IView { // /** // * This method is used for Data Binding to bind correct layout and variable automatically // * Can return null value in case that Data Binding is not used. // * // * @return defined ViewModelBinding Config for a specific screen. // */ // @Nullable // ViewModelBindingConfig getViewModelBindingConfig(); // // /** // * Implement this method to remove the ViewModel associated with the Fragment or Activity. // * This is usually implemented by calling {@link ViewModelHelper#removeViewModel(Activity)}, // * see {@link ViewModelBaseActivity#removeViewModel()} and {@link ViewModelBaseFragment#removeViewModel()}. // */ // void removeViewModel(); // }
import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import androidx.fragment.app.FragmentStatePagerAdapter; import android.util.Log; import android.view.ViewGroup; import eu.inloop.viewmodel.BuildConfig; import eu.inloop.viewmodel.IView;
package eu.inloop.viewmodel.support; /** * This class extends {@link FragmentStatePagerAdapter}. It removes the ViewModel once the * pager item is destroyed ({@link #destroyItem(ViewGroup, int, Object)}). The ViewModel state * is stored and then restored once you return back to this pager item and {@link #instantiateItem(ViewGroup, int)} * is called. */ public abstract class ViewModelStatePagerAdapter extends FragmentStatePagerAdapter { public ViewModelStatePagerAdapter(@NonNull final FragmentManager fm) { super(fm); } @Override public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) { super.destroyItem(container, position, object); final Fragment fragment = (Fragment) object;
// Path: library/src/main/java/eu/inloop/viewmodel/IView.java // public interface IView { // /** // * This method is used for Data Binding to bind correct layout and variable automatically // * Can return null value in case that Data Binding is not used. // * // * @return defined ViewModelBinding Config for a specific screen. // */ // @Nullable // ViewModelBindingConfig getViewModelBindingConfig(); // // /** // * Implement this method to remove the ViewModel associated with the Fragment or Activity. // * This is usually implemented by calling {@link ViewModelHelper#removeViewModel(Activity)}, // * see {@link ViewModelBaseActivity#removeViewModel()} and {@link ViewModelBaseFragment#removeViewModel()}. // */ // void removeViewModel(); // } // Path: library/src/main/java/eu/inloop/viewmodel/support/ViewModelStatePagerAdapter.java import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import androidx.fragment.app.FragmentStatePagerAdapter; import android.util.Log; import android.view.ViewGroup; import eu.inloop.viewmodel.BuildConfig; import eu.inloop.viewmodel.IView; package eu.inloop.viewmodel.support; /** * This class extends {@link FragmentStatePagerAdapter}. It removes the ViewModel once the * pager item is destroyed ({@link #destroyItem(ViewGroup, int, Object)}). The ViewModel state * is stored and then restored once you return back to this pager item and {@link #instantiateItem(ViewGroup, int)} * is called. */ public abstract class ViewModelStatePagerAdapter extends FragmentStatePagerAdapter { public ViewModelStatePagerAdapter(@NonNull final FragmentManager fm) { super(fm); } @Override public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) { super.destroyItem(container, position, object); final Fragment fragment = (Fragment) object;
if (fragment instanceof IView) {
inloop/AndroidViewModel
library/src/main/java/eu/inloop/viewmodel/ViewModelHelper.java
// Path: library/src/main/java/eu/inloop/viewmodel/binding/ViewModelBindingConfig.java // public class ViewModelBindingConfig { // // @LayoutRes // private final int mLayoutResource; // private final int mViewModelVariableName; // @NonNull // private final Context mContext; // // /** // * Create a ViewModelBinding Config object for an Activity/Fragment // * This constructor should be used if the binding variable is named differently // * // * @param layoutResource Layout resource ID // * @param viewModelVariableName Data Binding variable name for injecting the ViewModel - use // * generated id (e.g. BR.mViewModel) // */ // public ViewModelBindingConfig(@LayoutRes int layoutResource, int viewModelVariableName, @NonNull Context context) { // mLayoutResource = layoutResource; // mViewModelVariableName = viewModelVariableName; // mContext = context; // } // // /** // * Create a ViewModelBinding Config object for an Activity/Fragment // * Use this constructor if the binding variable is named viewModel // * // * @param layoutResource Layout resource ID // */ // public ViewModelBindingConfig(@LayoutRes int layoutResource, @NonNull Context context) { // this(layoutResource, BR.viewModel, context); // } // // @LayoutRes // public int getLayoutResource() { // return mLayoutResource; // } // // public int getViewModelVariableName() { // return mViewModelVariableName; // } // // @NonNull // public Context getContext() { // return mContext; // } // }
import android.app.Activity; import android.content.Intent; import androidx.databinding.DataBindingUtil; import androidx.databinding.ViewDataBinding; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import java.util.UUID; import eu.inloop.viewmodel.binding.ViewModelBindingConfig;
if (viewModelWrapper.wasCreated) { // detect that the system has killed the app - saved instance is not null, but the model was recreated if (BuildConfig.DEBUG && savedInstanceState != null) { Log.d("model", "Fragment recreated by system or ViewModelStatePagerAdapter - restoring viewmodel"); //NON-NLS } mViewModel.onCreate(arguments, savedInstanceState); } } /** * Call from {@link androidx.core.app.Fragment#onViewCreated(android.view.View, android.os.Bundle)} * or {@link android.app.Activity#onCreate(android.os.Bundle)} * * @param view view */ public void setView(@NonNull final T view) { if (mViewModel == null) { //no viewmodel for this fragment return; } mViewModel.onBindView(view); } public void performBinding(@NonNull final IView bindingView) { // skip if already create if (mBinding != null) { return; } // get ViewModelBinding config
// Path: library/src/main/java/eu/inloop/viewmodel/binding/ViewModelBindingConfig.java // public class ViewModelBindingConfig { // // @LayoutRes // private final int mLayoutResource; // private final int mViewModelVariableName; // @NonNull // private final Context mContext; // // /** // * Create a ViewModelBinding Config object for an Activity/Fragment // * This constructor should be used if the binding variable is named differently // * // * @param layoutResource Layout resource ID // * @param viewModelVariableName Data Binding variable name for injecting the ViewModel - use // * generated id (e.g. BR.mViewModel) // */ // public ViewModelBindingConfig(@LayoutRes int layoutResource, int viewModelVariableName, @NonNull Context context) { // mLayoutResource = layoutResource; // mViewModelVariableName = viewModelVariableName; // mContext = context; // } // // /** // * Create a ViewModelBinding Config object for an Activity/Fragment // * Use this constructor if the binding variable is named viewModel // * // * @param layoutResource Layout resource ID // */ // public ViewModelBindingConfig(@LayoutRes int layoutResource, @NonNull Context context) { // this(layoutResource, BR.viewModel, context); // } // // @LayoutRes // public int getLayoutResource() { // return mLayoutResource; // } // // public int getViewModelVariableName() { // return mViewModelVariableName; // } // // @NonNull // public Context getContext() { // return mContext; // } // } // Path: library/src/main/java/eu/inloop/viewmodel/ViewModelHelper.java import android.app.Activity; import android.content.Intent; import androidx.databinding.DataBindingUtil; import androidx.databinding.ViewDataBinding; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import java.util.UUID; import eu.inloop.viewmodel.binding.ViewModelBindingConfig; if (viewModelWrapper.wasCreated) { // detect that the system has killed the app - saved instance is not null, but the model was recreated if (BuildConfig.DEBUG && savedInstanceState != null) { Log.d("model", "Fragment recreated by system or ViewModelStatePagerAdapter - restoring viewmodel"); //NON-NLS } mViewModel.onCreate(arguments, savedInstanceState); } } /** * Call from {@link androidx.core.app.Fragment#onViewCreated(android.view.View, android.os.Bundle)} * or {@link android.app.Activity#onCreate(android.os.Bundle)} * * @param view view */ public void setView(@NonNull final T view) { if (mViewModel == null) { //no viewmodel for this fragment return; } mViewModel.onBindView(view); } public void performBinding(@NonNull final IView bindingView) { // skip if already create if (mBinding != null) { return; } // get ViewModelBinding config
final ViewModelBindingConfig viewModelConfig = bindingView.getViewModelBindingConfig();
inloop/AndroidViewModel
library/src/androidTest/java/eu/inloop/viewmodel/fixture/activity/VMTestActivity.java
// Path: library/src/main/java/eu/inloop/viewmodel/base/ViewModelBaseActivity.java // public abstract class ViewModelBaseActivity<T extends IView, R extends AbstractViewModel<T>> extends ViewModelBaseEmptyActivity implements IView { // // @NonNull // private final ViewModelHelper<T, R> mViewModeHelper = new ViewModelHelper<>(); // // @CallSuper // @Override // protected void onCreate(@Nullable final Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // // Class<? extends AbstractViewModel<T>> viewModelClass = getViewModelClass(); // // try to extract the ViewModel class from the implementation // if (viewModelClass == null) { // //noinspection unchecked // viewModelClass = (Class<? extends AbstractViewModel<T>>) ProxyViewHelper.getGenericType(getClass(), AbstractViewModel.class); // } // mViewModeHelper.onCreate(this, savedInstanceState, viewModelClass, getIntent().getExtras()); // } // // /** // * Call this after your view is ready - usually on the end of {@link android.app.Activity#onCreate(Bundle)} // * @param view view // */ // @SuppressWarnings("unused") // public void setModelView(@NonNull final T view) { // mViewModeHelper.setView(view); // } // // @Nullable // public Class<R> getViewModelClass() { // return null; // } // // @CallSuper // @Override // public void onSaveInstanceState(@NonNull final Bundle outState) { // super.onSaveInstanceState(outState); // mViewModeHelper.onSaveInstanceState(outState); // } // // @CallSuper // @Override // public void onStart() { // super.onStart(); // mViewModeHelper.onStart(); // } // // @CallSuper // @Override // public void onStop() { // super.onStop(); // mViewModeHelper.onStop(); // } // // @CallSuper // @Override // public void onDestroy() { // mViewModeHelper.onDestroy(this); // super.onDestroy(); // } // // /** // * @see ViewModelHelper#getViewModel() // */ // @SuppressWarnings("unused") // @NonNull // public R getViewModel() { // return mViewModeHelper.getViewModel(); // } // // @Override // public void removeViewModel() { // mViewModeHelper.removeViewModel(this); // } // // @Nullable // @Override // public ViewModelBindingConfig getViewModelBindingConfig() { // return null; // } // } // // Path: library/src/androidTest/java/eu/inloop/viewmodel/fixture/fragment/VMTestFragment.java // public class VMTestFragment extends ViewModelBaseFragment<IVMTestFragmentView, VMTestFragmentViewModel> // implements IVMTestFragmentView { // // @Nullable // @Override // public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { // return new LinearLayout(getContext()); // } // // @Override // public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { // super.onViewCreated(view, savedInstanceState); // setModelView(this); // } // // @Override // public void onLoadData(boolean loaded) { // requireActivity().setResult(VMTestActivity.RESULT_CODE_OK); // requireActivity().finish(); // } // }
import android.content.Context; import android.content.Intent; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import android.widget.LinearLayout; import eu.inloop.viewmodel.base.ViewModelBaseActivity; import eu.inloop.viewmodel.fixture.fragment.VMTestFragment;
package eu.inloop.viewmodel.fixture.activity; public class VMTestActivity extends ViewModelBaseActivity<IVMTestActivityView, VMTestActivityViewModel> implements IVMTestActivityView { public static final int RESULT_CODE_OK = 1; public static final String EXTRA_CALL_ON_BIND = "EXTRA_CALL_ON_BIND"; @NonNull public static Intent makeIntent(@NonNull Context context, boolean callOnBindModel) { Intent intent = new Intent(context, VMTestActivity.class); intent.putExtra(EXTRA_CALL_ON_BIND, callOnBindModel); return intent; } @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); LinearLayout view = new LinearLayout(this); view.setId(android.R.id.content); setContentView(view); if (savedInstanceState == null) { addTestFragment(); } setModelView(this); } public void addTestFragment() { getSupportFragmentManager() .beginTransaction()
// Path: library/src/main/java/eu/inloop/viewmodel/base/ViewModelBaseActivity.java // public abstract class ViewModelBaseActivity<T extends IView, R extends AbstractViewModel<T>> extends ViewModelBaseEmptyActivity implements IView { // // @NonNull // private final ViewModelHelper<T, R> mViewModeHelper = new ViewModelHelper<>(); // // @CallSuper // @Override // protected void onCreate(@Nullable final Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // // Class<? extends AbstractViewModel<T>> viewModelClass = getViewModelClass(); // // try to extract the ViewModel class from the implementation // if (viewModelClass == null) { // //noinspection unchecked // viewModelClass = (Class<? extends AbstractViewModel<T>>) ProxyViewHelper.getGenericType(getClass(), AbstractViewModel.class); // } // mViewModeHelper.onCreate(this, savedInstanceState, viewModelClass, getIntent().getExtras()); // } // // /** // * Call this after your view is ready - usually on the end of {@link android.app.Activity#onCreate(Bundle)} // * @param view view // */ // @SuppressWarnings("unused") // public void setModelView(@NonNull final T view) { // mViewModeHelper.setView(view); // } // // @Nullable // public Class<R> getViewModelClass() { // return null; // } // // @CallSuper // @Override // public void onSaveInstanceState(@NonNull final Bundle outState) { // super.onSaveInstanceState(outState); // mViewModeHelper.onSaveInstanceState(outState); // } // // @CallSuper // @Override // public void onStart() { // super.onStart(); // mViewModeHelper.onStart(); // } // // @CallSuper // @Override // public void onStop() { // super.onStop(); // mViewModeHelper.onStop(); // } // // @CallSuper // @Override // public void onDestroy() { // mViewModeHelper.onDestroy(this); // super.onDestroy(); // } // // /** // * @see ViewModelHelper#getViewModel() // */ // @SuppressWarnings("unused") // @NonNull // public R getViewModel() { // return mViewModeHelper.getViewModel(); // } // // @Override // public void removeViewModel() { // mViewModeHelper.removeViewModel(this); // } // // @Nullable // @Override // public ViewModelBindingConfig getViewModelBindingConfig() { // return null; // } // } // // Path: library/src/androidTest/java/eu/inloop/viewmodel/fixture/fragment/VMTestFragment.java // public class VMTestFragment extends ViewModelBaseFragment<IVMTestFragmentView, VMTestFragmentViewModel> // implements IVMTestFragmentView { // // @Nullable // @Override // public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { // return new LinearLayout(getContext()); // } // // @Override // public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { // super.onViewCreated(view, savedInstanceState); // setModelView(this); // } // // @Override // public void onLoadData(boolean loaded) { // requireActivity().setResult(VMTestActivity.RESULT_CODE_OK); // requireActivity().finish(); // } // } // Path: library/src/androidTest/java/eu/inloop/viewmodel/fixture/activity/VMTestActivity.java import android.content.Context; import android.content.Intent; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import android.widget.LinearLayout; import eu.inloop.viewmodel.base.ViewModelBaseActivity; import eu.inloop.viewmodel.fixture.fragment.VMTestFragment; package eu.inloop.viewmodel.fixture.activity; public class VMTestActivity extends ViewModelBaseActivity<IVMTestActivityView, VMTestActivityViewModel> implements IVMTestActivityView { public static final int RESULT_CODE_OK = 1; public static final String EXTRA_CALL_ON_BIND = "EXTRA_CALL_ON_BIND"; @NonNull public static Intent makeIntent(@NonNull Context context, boolean callOnBindModel) { Intent intent = new Intent(context, VMTestActivity.class); intent.putExtra(EXTRA_CALL_ON_BIND, callOnBindModel); return intent; } @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); LinearLayout view = new LinearLayout(this); view.setId(android.R.id.content); setContentView(view); if (savedInstanceState == null) { addTestFragment(); } setModelView(this); } public void addTestFragment() { getSupportFragmentManager() .beginTransaction()
.add(android.R.id.content, new VMTestFragment())
inloop/AndroidViewModel
sample/src/main/java/eu/inloop/viewmodel/sample/activity/ViewPagerActivity.java
// Path: library/src/main/java/eu/inloop/viewmodel/base/ViewModelBaseEmptyActivity.java // public abstract class ViewModelBaseEmptyActivity extends AppCompatActivity implements IViewModelProvider { // // @Nullable // private ViewModelProvider mViewModelProvider; // // @CallSuper // @Override // protected void onCreate(@Nullable final Bundle savedInstanceState) { // //This code must be execute prior to super.onCreate() // mViewModelProvider = ViewModelProvider.newInstance(this); // super.onCreate(savedInstanceState); // } // // @Override // @Nullable // public Object onRetainCustomNonConfigurationInstance() { // return mViewModelProvider; // } // // @CallSuper // @Override // public void onStop() { // super.onStop(); // if (isFinishing()) { // if (null == mViewModelProvider) { // throw new IllegalStateException("ViewModelProvider for activity " + this + " was null."); //NON-NLS // } // mViewModelProvider.removeAllViewModels(); // } // } // // @Nullable // @Override // public ViewModelProvider getViewModelProvider() { // return mViewModelProvider; // } // } // // Path: sample/src/main/java/eu/inloop/viewmodel/sample/fragment/PagerFragment.java // public class PagerFragment extends ViewModelBaseFragment<IPageView, PageModel> implements IPageView { // // public static PagerFragment newInstance(int position) { // final Bundle bundle = new Bundle(); // bundle.putInt("position", position); // final PagerFragment fragment = new PagerFragment(); // fragment.setArguments(bundle); // return fragment; // } // // @Nullable // @Override // public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // return inflater.inflate(R.layout.fragment_pager, container, false); // } // // @Override // public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { // super.onViewCreated(view, savedInstanceState); // ((TextView)view.findViewById(R.id.text)).setText(Integer.toString(getArguments().getInt("position"))); // setModelView(this); // } // // @Override // public void onDestroy() { // super.onDestroy(); // // // watch for memory leaks // RefWatcher refWatcher = SampleApplication.getRefWatcher(requireActivity()); // refWatcher.watch(this); // } // } // // Path: library/src/main/java/eu/inloop/viewmodel/support/ViewModelStatePagerAdapter.java // public abstract class ViewModelStatePagerAdapter extends FragmentStatePagerAdapter { // // public ViewModelStatePagerAdapter(@NonNull final FragmentManager fm) { // super(fm); // } // // @Override // public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) { // super.destroyItem(container, position, object); // final Fragment fragment = (Fragment) object; // // if (fragment instanceof IView) { // IView viewModelBaseFragment = (IView) fragment; // viewModelBaseFragment.removeViewModel(); // } else { // if (BuildConfig.DEBUG) { // Log.w("model", "Fragment " + fragment + " in FragmentStatePagerAdapter " + this + " doesn't implent IView"); //NON-NLS // } // } // } // }
import android.os.Bundle; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import androidx.viewpager.widget.ViewPager; import butterknife.BindView; import butterknife.ButterKnife; import eu.inloop.viewmodel.base.ViewModelBaseEmptyActivity; import eu.inloop.viewmodel.sample.R; import eu.inloop.viewmodel.sample.fragment.PagerFragment; import eu.inloop.viewmodel.support.ViewModelStatePagerAdapter;
package eu.inloop.viewmodel.sample.activity; public class ViewPagerActivity extends ViewModelBaseEmptyActivity { @BindView(R.id.pager) ViewPager mViewPager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_pager); ButterKnife.bind(this); mViewPager.setAdapter(new TestPagerAdapter(getSupportFragmentManager())); }
// Path: library/src/main/java/eu/inloop/viewmodel/base/ViewModelBaseEmptyActivity.java // public abstract class ViewModelBaseEmptyActivity extends AppCompatActivity implements IViewModelProvider { // // @Nullable // private ViewModelProvider mViewModelProvider; // // @CallSuper // @Override // protected void onCreate(@Nullable final Bundle savedInstanceState) { // //This code must be execute prior to super.onCreate() // mViewModelProvider = ViewModelProvider.newInstance(this); // super.onCreate(savedInstanceState); // } // // @Override // @Nullable // public Object onRetainCustomNonConfigurationInstance() { // return mViewModelProvider; // } // // @CallSuper // @Override // public void onStop() { // super.onStop(); // if (isFinishing()) { // if (null == mViewModelProvider) { // throw new IllegalStateException("ViewModelProvider for activity " + this + " was null."); //NON-NLS // } // mViewModelProvider.removeAllViewModels(); // } // } // // @Nullable // @Override // public ViewModelProvider getViewModelProvider() { // return mViewModelProvider; // } // } // // Path: sample/src/main/java/eu/inloop/viewmodel/sample/fragment/PagerFragment.java // public class PagerFragment extends ViewModelBaseFragment<IPageView, PageModel> implements IPageView { // // public static PagerFragment newInstance(int position) { // final Bundle bundle = new Bundle(); // bundle.putInt("position", position); // final PagerFragment fragment = new PagerFragment(); // fragment.setArguments(bundle); // return fragment; // } // // @Nullable // @Override // public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // return inflater.inflate(R.layout.fragment_pager, container, false); // } // // @Override // public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { // super.onViewCreated(view, savedInstanceState); // ((TextView)view.findViewById(R.id.text)).setText(Integer.toString(getArguments().getInt("position"))); // setModelView(this); // } // // @Override // public void onDestroy() { // super.onDestroy(); // // // watch for memory leaks // RefWatcher refWatcher = SampleApplication.getRefWatcher(requireActivity()); // refWatcher.watch(this); // } // } // // Path: library/src/main/java/eu/inloop/viewmodel/support/ViewModelStatePagerAdapter.java // public abstract class ViewModelStatePagerAdapter extends FragmentStatePagerAdapter { // // public ViewModelStatePagerAdapter(@NonNull final FragmentManager fm) { // super(fm); // } // // @Override // public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) { // super.destroyItem(container, position, object); // final Fragment fragment = (Fragment) object; // // if (fragment instanceof IView) { // IView viewModelBaseFragment = (IView) fragment; // viewModelBaseFragment.removeViewModel(); // } else { // if (BuildConfig.DEBUG) { // Log.w("model", "Fragment " + fragment + " in FragmentStatePagerAdapter " + this + " doesn't implent IView"); //NON-NLS // } // } // } // } // Path: sample/src/main/java/eu/inloop/viewmodel/sample/activity/ViewPagerActivity.java import android.os.Bundle; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import androidx.viewpager.widget.ViewPager; import butterknife.BindView; import butterknife.ButterKnife; import eu.inloop.viewmodel.base.ViewModelBaseEmptyActivity; import eu.inloop.viewmodel.sample.R; import eu.inloop.viewmodel.sample.fragment.PagerFragment; import eu.inloop.viewmodel.support.ViewModelStatePagerAdapter; package eu.inloop.viewmodel.sample.activity; public class ViewPagerActivity extends ViewModelBaseEmptyActivity { @BindView(R.id.pager) ViewPager mViewPager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_pager); ButterKnife.bind(this); mViewPager.setAdapter(new TestPagerAdapter(getSupportFragmentManager())); }
private final static class TestPagerAdapter extends ViewModelStatePagerAdapter {
inloop/AndroidViewModel
sample/src/main/java/eu/inloop/viewmodel/sample/activity/ViewPagerActivity.java
// Path: library/src/main/java/eu/inloop/viewmodel/base/ViewModelBaseEmptyActivity.java // public abstract class ViewModelBaseEmptyActivity extends AppCompatActivity implements IViewModelProvider { // // @Nullable // private ViewModelProvider mViewModelProvider; // // @CallSuper // @Override // protected void onCreate(@Nullable final Bundle savedInstanceState) { // //This code must be execute prior to super.onCreate() // mViewModelProvider = ViewModelProvider.newInstance(this); // super.onCreate(savedInstanceState); // } // // @Override // @Nullable // public Object onRetainCustomNonConfigurationInstance() { // return mViewModelProvider; // } // // @CallSuper // @Override // public void onStop() { // super.onStop(); // if (isFinishing()) { // if (null == mViewModelProvider) { // throw new IllegalStateException("ViewModelProvider for activity " + this + " was null."); //NON-NLS // } // mViewModelProvider.removeAllViewModels(); // } // } // // @Nullable // @Override // public ViewModelProvider getViewModelProvider() { // return mViewModelProvider; // } // } // // Path: sample/src/main/java/eu/inloop/viewmodel/sample/fragment/PagerFragment.java // public class PagerFragment extends ViewModelBaseFragment<IPageView, PageModel> implements IPageView { // // public static PagerFragment newInstance(int position) { // final Bundle bundle = new Bundle(); // bundle.putInt("position", position); // final PagerFragment fragment = new PagerFragment(); // fragment.setArguments(bundle); // return fragment; // } // // @Nullable // @Override // public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // return inflater.inflate(R.layout.fragment_pager, container, false); // } // // @Override // public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { // super.onViewCreated(view, savedInstanceState); // ((TextView)view.findViewById(R.id.text)).setText(Integer.toString(getArguments().getInt("position"))); // setModelView(this); // } // // @Override // public void onDestroy() { // super.onDestroy(); // // // watch for memory leaks // RefWatcher refWatcher = SampleApplication.getRefWatcher(requireActivity()); // refWatcher.watch(this); // } // } // // Path: library/src/main/java/eu/inloop/viewmodel/support/ViewModelStatePagerAdapter.java // public abstract class ViewModelStatePagerAdapter extends FragmentStatePagerAdapter { // // public ViewModelStatePagerAdapter(@NonNull final FragmentManager fm) { // super(fm); // } // // @Override // public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) { // super.destroyItem(container, position, object); // final Fragment fragment = (Fragment) object; // // if (fragment instanceof IView) { // IView viewModelBaseFragment = (IView) fragment; // viewModelBaseFragment.removeViewModel(); // } else { // if (BuildConfig.DEBUG) { // Log.w("model", "Fragment " + fragment + " in FragmentStatePagerAdapter " + this + " doesn't implent IView"); //NON-NLS // } // } // } // }
import android.os.Bundle; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import androidx.viewpager.widget.ViewPager; import butterknife.BindView; import butterknife.ButterKnife; import eu.inloop.viewmodel.base.ViewModelBaseEmptyActivity; import eu.inloop.viewmodel.sample.R; import eu.inloop.viewmodel.sample.fragment.PagerFragment; import eu.inloop.viewmodel.support.ViewModelStatePagerAdapter;
package eu.inloop.viewmodel.sample.activity; public class ViewPagerActivity extends ViewModelBaseEmptyActivity { @BindView(R.id.pager) ViewPager mViewPager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_pager); ButterKnife.bind(this); mViewPager.setAdapter(new TestPagerAdapter(getSupportFragmentManager())); } private final static class TestPagerAdapter extends ViewModelStatePagerAdapter { TestPagerAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int position) {
// Path: library/src/main/java/eu/inloop/viewmodel/base/ViewModelBaseEmptyActivity.java // public abstract class ViewModelBaseEmptyActivity extends AppCompatActivity implements IViewModelProvider { // // @Nullable // private ViewModelProvider mViewModelProvider; // // @CallSuper // @Override // protected void onCreate(@Nullable final Bundle savedInstanceState) { // //This code must be execute prior to super.onCreate() // mViewModelProvider = ViewModelProvider.newInstance(this); // super.onCreate(savedInstanceState); // } // // @Override // @Nullable // public Object onRetainCustomNonConfigurationInstance() { // return mViewModelProvider; // } // // @CallSuper // @Override // public void onStop() { // super.onStop(); // if (isFinishing()) { // if (null == mViewModelProvider) { // throw new IllegalStateException("ViewModelProvider for activity " + this + " was null."); //NON-NLS // } // mViewModelProvider.removeAllViewModels(); // } // } // // @Nullable // @Override // public ViewModelProvider getViewModelProvider() { // return mViewModelProvider; // } // } // // Path: sample/src/main/java/eu/inloop/viewmodel/sample/fragment/PagerFragment.java // public class PagerFragment extends ViewModelBaseFragment<IPageView, PageModel> implements IPageView { // // public static PagerFragment newInstance(int position) { // final Bundle bundle = new Bundle(); // bundle.putInt("position", position); // final PagerFragment fragment = new PagerFragment(); // fragment.setArguments(bundle); // return fragment; // } // // @Nullable // @Override // public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // return inflater.inflate(R.layout.fragment_pager, container, false); // } // // @Override // public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { // super.onViewCreated(view, savedInstanceState); // ((TextView)view.findViewById(R.id.text)).setText(Integer.toString(getArguments().getInt("position"))); // setModelView(this); // } // // @Override // public void onDestroy() { // super.onDestroy(); // // // watch for memory leaks // RefWatcher refWatcher = SampleApplication.getRefWatcher(requireActivity()); // refWatcher.watch(this); // } // } // // Path: library/src/main/java/eu/inloop/viewmodel/support/ViewModelStatePagerAdapter.java // public abstract class ViewModelStatePagerAdapter extends FragmentStatePagerAdapter { // // public ViewModelStatePagerAdapter(@NonNull final FragmentManager fm) { // super(fm); // } // // @Override // public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) { // super.destroyItem(container, position, object); // final Fragment fragment = (Fragment) object; // // if (fragment instanceof IView) { // IView viewModelBaseFragment = (IView) fragment; // viewModelBaseFragment.removeViewModel(); // } else { // if (BuildConfig.DEBUG) { // Log.w("model", "Fragment " + fragment + " in FragmentStatePagerAdapter " + this + " doesn't implent IView"); //NON-NLS // } // } // } // } // Path: sample/src/main/java/eu/inloop/viewmodel/sample/activity/ViewPagerActivity.java import android.os.Bundle; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import androidx.viewpager.widget.ViewPager; import butterknife.BindView; import butterknife.ButterKnife; import eu.inloop.viewmodel.base.ViewModelBaseEmptyActivity; import eu.inloop.viewmodel.sample.R; import eu.inloop.viewmodel.sample.fragment.PagerFragment; import eu.inloop.viewmodel.support.ViewModelStatePagerAdapter; package eu.inloop.viewmodel.sample.activity; public class ViewPagerActivity extends ViewModelBaseEmptyActivity { @BindView(R.id.pager) ViewPager mViewPager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_pager); ButterKnife.bind(this); mViewPager.setAdapter(new TestPagerAdapter(getSupportFragmentManager())); } private final static class TestPagerAdapter extends ViewModelStatePagerAdapter { TestPagerAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int position) {
return PagerFragment.newInstance(position);
inloop/AndroidViewModel
sample/src/main/java/eu/inloop/viewmodel/sample/fragment/SampleBindingFragment.java
// Path: library/src/main/java/eu/inloop/viewmodel/binding/ViewModelBaseBindingFragment.java // public abstract class ViewModelBaseBindingFragment<T extends IView, R extends AbstractViewModel<T>, B extends ViewDataBinding> // extends ViewModelBaseFragment<T, R> // implements IView { // // @Override // public void onCreate(@Nullable Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // getViewModelHelper().performBinding(this); // } // // @Nullable // @Override // public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { // getViewModelHelper().performBinding(this); // final ViewDataBinding binding = getViewModelHelper().getBinding(); // if (binding != null) { // return binding.getRoot(); // } else { // throw new IllegalStateException("Binding cannot be null. Perform binding before calling getBinding()"); // } // } // // @SuppressWarnings("unused") // @Nullable // public B getBinding() { // try { // return (B) getViewModelHelper().getBinding(); // } catch (ClassCastException ex) { // throw new IllegalStateException("Method getViewModelBindingConfig() has to return same " + // "ViewDataBinding type as it is set to base Fragment"); // } // } // } // // Path: library/src/main/java/eu/inloop/viewmodel/binding/ViewModelBindingConfig.java // public class ViewModelBindingConfig { // // @LayoutRes // private final int mLayoutResource; // private final int mViewModelVariableName; // @NonNull // private final Context mContext; // // /** // * Create a ViewModelBinding Config object for an Activity/Fragment // * This constructor should be used if the binding variable is named differently // * // * @param layoutResource Layout resource ID // * @param viewModelVariableName Data Binding variable name for injecting the ViewModel - use // * generated id (e.g. BR.mViewModel) // */ // public ViewModelBindingConfig(@LayoutRes int layoutResource, int viewModelVariableName, @NonNull Context context) { // mLayoutResource = layoutResource; // mViewModelVariableName = viewModelVariableName; // mContext = context; // } // // /** // * Create a ViewModelBinding Config object for an Activity/Fragment // * Use this constructor if the binding variable is named viewModel // * // * @param layoutResource Layout resource ID // */ // public ViewModelBindingConfig(@LayoutRes int layoutResource, @NonNull Context context) { // this(layoutResource, BR.viewModel, context); // } // // @LayoutRes // public int getLayoutResource() { // return mLayoutResource; // } // // public int getViewModelVariableName() { // return mViewModelVariableName; // } // // @NonNull // public Context getContext() { // return mContext; // } // } // // Path: sample/src/main/java/eu/inloop/viewmodel/sample/viewmodel/SampleBindingViewModel.java // public class SampleBindingViewModel extends AbstractViewModel<ISampleBindingView> { // // public final ObservableField<String> text = new ObservableField<>(); // private int mButtonClickedCounter = 0; // // @Override // public void onCreate(@Nullable Bundle arguments, @Nullable Bundle savedInstanceState) { // super.onCreate(arguments, savedInstanceState); // setButtonClickedText(); // } // // public void onButtonClick() { // mButtonClickedCounter++; // setButtonClickedText(); // } // // private void setButtonClickedText() { // text.set("Button Clicked: " + mButtonClickedCounter + " times"); // } // } // // Path: sample/src/main/java/eu/inloop/viewmodel/sample/viewmodel/view/ISampleBindingView.java // public interface ISampleBindingView extends IView { // }
import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import android.view.View; import androidx.fragment.app.Fragment; import eu.inloop.viewmodel.binding.ViewModelBaseBindingFragment; import eu.inloop.viewmodel.binding.ViewModelBindingConfig; import eu.inloop.viewmodel.sample.R; import eu.inloop.viewmodel.sample.databinding.FragmentSampleBindingBinding; import eu.inloop.viewmodel.sample.viewmodel.SampleBindingViewModel; import eu.inloop.viewmodel.sample.viewmodel.view.ISampleBindingView;
package eu.inloop.viewmodel.sample.fragment; /** * A simple {@link Fragment} subclass. */ public class SampleBindingFragment extends ViewModelBaseBindingFragment<ISampleBindingView, SampleBindingViewModel, FragmentSampleBindingBinding> implements ISampleBindingView { public SampleBindingFragment() { // Required empty public constructor } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); setModelView(this); } @Override
// Path: library/src/main/java/eu/inloop/viewmodel/binding/ViewModelBaseBindingFragment.java // public abstract class ViewModelBaseBindingFragment<T extends IView, R extends AbstractViewModel<T>, B extends ViewDataBinding> // extends ViewModelBaseFragment<T, R> // implements IView { // // @Override // public void onCreate(@Nullable Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // getViewModelHelper().performBinding(this); // } // // @Nullable // @Override // public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { // getViewModelHelper().performBinding(this); // final ViewDataBinding binding = getViewModelHelper().getBinding(); // if (binding != null) { // return binding.getRoot(); // } else { // throw new IllegalStateException("Binding cannot be null. Perform binding before calling getBinding()"); // } // } // // @SuppressWarnings("unused") // @Nullable // public B getBinding() { // try { // return (B) getViewModelHelper().getBinding(); // } catch (ClassCastException ex) { // throw new IllegalStateException("Method getViewModelBindingConfig() has to return same " + // "ViewDataBinding type as it is set to base Fragment"); // } // } // } // // Path: library/src/main/java/eu/inloop/viewmodel/binding/ViewModelBindingConfig.java // public class ViewModelBindingConfig { // // @LayoutRes // private final int mLayoutResource; // private final int mViewModelVariableName; // @NonNull // private final Context mContext; // // /** // * Create a ViewModelBinding Config object for an Activity/Fragment // * This constructor should be used if the binding variable is named differently // * // * @param layoutResource Layout resource ID // * @param viewModelVariableName Data Binding variable name for injecting the ViewModel - use // * generated id (e.g. BR.mViewModel) // */ // public ViewModelBindingConfig(@LayoutRes int layoutResource, int viewModelVariableName, @NonNull Context context) { // mLayoutResource = layoutResource; // mViewModelVariableName = viewModelVariableName; // mContext = context; // } // // /** // * Create a ViewModelBinding Config object for an Activity/Fragment // * Use this constructor if the binding variable is named viewModel // * // * @param layoutResource Layout resource ID // */ // public ViewModelBindingConfig(@LayoutRes int layoutResource, @NonNull Context context) { // this(layoutResource, BR.viewModel, context); // } // // @LayoutRes // public int getLayoutResource() { // return mLayoutResource; // } // // public int getViewModelVariableName() { // return mViewModelVariableName; // } // // @NonNull // public Context getContext() { // return mContext; // } // } // // Path: sample/src/main/java/eu/inloop/viewmodel/sample/viewmodel/SampleBindingViewModel.java // public class SampleBindingViewModel extends AbstractViewModel<ISampleBindingView> { // // public final ObservableField<String> text = new ObservableField<>(); // private int mButtonClickedCounter = 0; // // @Override // public void onCreate(@Nullable Bundle arguments, @Nullable Bundle savedInstanceState) { // super.onCreate(arguments, savedInstanceState); // setButtonClickedText(); // } // // public void onButtonClick() { // mButtonClickedCounter++; // setButtonClickedText(); // } // // private void setButtonClickedText() { // text.set("Button Clicked: " + mButtonClickedCounter + " times"); // } // } // // Path: sample/src/main/java/eu/inloop/viewmodel/sample/viewmodel/view/ISampleBindingView.java // public interface ISampleBindingView extends IView { // } // Path: sample/src/main/java/eu/inloop/viewmodel/sample/fragment/SampleBindingFragment.java import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import android.view.View; import androidx.fragment.app.Fragment; import eu.inloop.viewmodel.binding.ViewModelBaseBindingFragment; import eu.inloop.viewmodel.binding.ViewModelBindingConfig; import eu.inloop.viewmodel.sample.R; import eu.inloop.viewmodel.sample.databinding.FragmentSampleBindingBinding; import eu.inloop.viewmodel.sample.viewmodel.SampleBindingViewModel; import eu.inloop.viewmodel.sample.viewmodel.view.ISampleBindingView; package eu.inloop.viewmodel.sample.fragment; /** * A simple {@link Fragment} subclass. */ public class SampleBindingFragment extends ViewModelBaseBindingFragment<ISampleBindingView, SampleBindingViewModel, FragmentSampleBindingBinding> implements ISampleBindingView { public SampleBindingFragment() { // Required empty public constructor } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); setModelView(this); } @Override
public ViewModelBindingConfig getViewModelBindingConfig() {
Earthblood/Toe
app/src/main/java/com/earthblood/tictactoe/strategy/ToeStrategy.java
// Path: app/src/main/java/com/earthblood/tictactoe/util/GameSymbol.java // public enum GameSymbol { // X(1,"X"), // O(2,"O"); // // private int id; // private String value; // // private GameSymbol(int id, String value){ // this.id = id; // this.value = value; // } // // public int getId() { // return id; // } // // public String getValue() { // return value; // } // // public static GameSymbol byId(int id) { // for (GameSymbol gameSymbol : values()) { // if(gameSymbol.getId() == id){ // return gameSymbol; // } // } // return null; // } // }
import com.earthblood.tictactoe.util.GameSymbol;
/** * @author John Piser developer@earthblood.com * * Copyright (C) 2014 EARTHBLOOD, LLC * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.earthblood.tictactoe.strategy; public interface ToeStrategy { public int getBoxId();
// Path: app/src/main/java/com/earthblood/tictactoe/util/GameSymbol.java // public enum GameSymbol { // X(1,"X"), // O(2,"O"); // // private int id; // private String value; // // private GameSymbol(int id, String value){ // this.id = id; // this.value = value; // } // // public int getId() { // return id; // } // // public String getValue() { // return value; // } // // public static GameSymbol byId(int id) { // for (GameSymbol gameSymbol : values()) { // if(gameSymbol.getId() == id){ // return gameSymbol; // } // } // return null; // } // } // Path: app/src/main/java/com/earthblood/tictactoe/strategy/ToeStrategy.java import com.earthblood.tictactoe.util.GameSymbol; /** * @author John Piser developer@earthblood.com * * Copyright (C) 2014 EARTHBLOOD, LLC * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.earthblood.tictactoe.strategy; public interface ToeStrategy { public int getBoxId();
public GameSymbol getSymbol();
Earthblood/Toe
app/src/main/java/com/earthblood/tictactoe/strategy/StrategyItem.java
// Path: app/src/main/java/com/earthblood/tictactoe/application/Toe.java // public class Toe extends Application { // // public static final String TAG = "EARTHBLOOD_TOE"; // private static Context context; // // @Override // public void onCreate() { // super.onCreate(); // // RoboGuice.overrideApplicationInjector(this, new ToeRoboModule()); // // context = this; // } // // public static String getResourceString(int resourceId){ // return context.getString(resourceId); // } // } // // Path: app/src/main/java/com/earthblood/tictactoe/util/GameSymbol.java // public enum GameSymbol { // X(1,"X"), // O(2,"O"); // // private int id; // private String value; // // private GameSymbol(int id, String value){ // this.id = id; // this.value = value; // } // // public int getId() { // return id; // } // // public String getValue() { // return value; // } // // public static GameSymbol byId(int id) { // for (GameSymbol gameSymbol : values()) { // if(gameSymbol.getId() == id){ // return gameSymbol; // } // } // return null; // } // }
import android.util.Log; import com.earthblood.tictactoe.application.Toe; import com.earthblood.tictactoe.util.GameSymbol; import org.apache.commons.lang3.ArrayUtils; import java.util.Random;
/** * @author John Piser developer@earthblood.com * * Copyright (C) 2014 EARTHBLOOD, LLC * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.earthblood.tictactoe.strategy; public class StrategyItem { public static final int[] ALL_BOXES = {1,2,3,4,5,6,7,8,9}; public static final int[] DEFAULT_ZEROS = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; public static final int NOT_FOUND = -1; public static final int MIDDLE_BOX_POSITION = 5; private StrategyItem successor; protected int[] currentlySelectedBoxes; protected int[] availableBoxes; protected Random random = new Random(); public int getRandom(int min, int max){ return random.nextInt(max - min + 1) + min; } public Random getRandomObject(){ return this.random; }
// Path: app/src/main/java/com/earthblood/tictactoe/application/Toe.java // public class Toe extends Application { // // public static final String TAG = "EARTHBLOOD_TOE"; // private static Context context; // // @Override // public void onCreate() { // super.onCreate(); // // RoboGuice.overrideApplicationInjector(this, new ToeRoboModule()); // // context = this; // } // // public static String getResourceString(int resourceId){ // return context.getString(resourceId); // } // } // // Path: app/src/main/java/com/earthblood/tictactoe/util/GameSymbol.java // public enum GameSymbol { // X(1,"X"), // O(2,"O"); // // private int id; // private String value; // // private GameSymbol(int id, String value){ // this.id = id; // this.value = value; // } // // public int getId() { // return id; // } // // public String getValue() { // return value; // } // // public static GameSymbol byId(int id) { // for (GameSymbol gameSymbol : values()) { // if(gameSymbol.getId() == id){ // return gameSymbol; // } // } // return null; // } // } // Path: app/src/main/java/com/earthblood/tictactoe/strategy/StrategyItem.java import android.util.Log; import com.earthblood.tictactoe.application.Toe; import com.earthblood.tictactoe.util.GameSymbol; import org.apache.commons.lang3.ArrayUtils; import java.util.Random; /** * @author John Piser developer@earthblood.com * * Copyright (C) 2014 EARTHBLOOD, LLC * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.earthblood.tictactoe.strategy; public class StrategyItem { public static final int[] ALL_BOXES = {1,2,3,4,5,6,7,8,9}; public static final int[] DEFAULT_ZEROS = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; public static final int NOT_FOUND = -1; public static final int MIDDLE_BOX_POSITION = 5; private StrategyItem successor; protected int[] currentlySelectedBoxes; protected int[] availableBoxes; protected Random random = new Random(); public int getRandom(int min, int max){ return random.nextInt(max - min + 1) + min; } public Random getRandomObject(){ return this.random; }
protected int getBoxId(int[] selectedXBoxIds, int[] selectedOBoxIds, GameSymbol androidSymbol){
Earthblood/Toe
app/src/main/java/com/earthblood/tictactoe/strategy/StrategyItem.java
// Path: app/src/main/java/com/earthblood/tictactoe/application/Toe.java // public class Toe extends Application { // // public static final String TAG = "EARTHBLOOD_TOE"; // private static Context context; // // @Override // public void onCreate() { // super.onCreate(); // // RoboGuice.overrideApplicationInjector(this, new ToeRoboModule()); // // context = this; // } // // public static String getResourceString(int resourceId){ // return context.getString(resourceId); // } // } // // Path: app/src/main/java/com/earthblood/tictactoe/util/GameSymbol.java // public enum GameSymbol { // X(1,"X"), // O(2,"O"); // // private int id; // private String value; // // private GameSymbol(int id, String value){ // this.id = id; // this.value = value; // } // // public int getId() { // return id; // } // // public String getValue() { // return value; // } // // public static GameSymbol byId(int id) { // for (GameSymbol gameSymbol : values()) { // if(gameSymbol.getId() == id){ // return gameSymbol; // } // } // return null; // } // }
import android.util.Log; import com.earthblood.tictactoe.application.Toe; import com.earthblood.tictactoe.util.GameSymbol; import org.apache.commons.lang3.ArrayUtils; import java.util.Random;
/** * @author John Piser developer@earthblood.com * * Copyright (C) 2014 EARTHBLOOD, LLC * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.earthblood.tictactoe.strategy; public class StrategyItem { public static final int[] ALL_BOXES = {1,2,3,4,5,6,7,8,9}; public static final int[] DEFAULT_ZEROS = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; public static final int NOT_FOUND = -1; public static final int MIDDLE_BOX_POSITION = 5; private StrategyItem successor; protected int[] currentlySelectedBoxes; protected int[] availableBoxes; protected Random random = new Random(); public int getRandom(int min, int max){ return random.nextInt(max - min + 1) + min; } public Random getRandomObject(){ return this.random; } protected int getBoxId(int[] selectedXBoxIds, int[] selectedOBoxIds, GameSymbol androidSymbol){ return NOT_FOUND; } public int execute(int[] selectedXBoxIds, int[] selectedOBoxIds, GameSymbol androidSymbol){
// Path: app/src/main/java/com/earthblood/tictactoe/application/Toe.java // public class Toe extends Application { // // public static final String TAG = "EARTHBLOOD_TOE"; // private static Context context; // // @Override // public void onCreate() { // super.onCreate(); // // RoboGuice.overrideApplicationInjector(this, new ToeRoboModule()); // // context = this; // } // // public static String getResourceString(int resourceId){ // return context.getString(resourceId); // } // } // // Path: app/src/main/java/com/earthblood/tictactoe/util/GameSymbol.java // public enum GameSymbol { // X(1,"X"), // O(2,"O"); // // private int id; // private String value; // // private GameSymbol(int id, String value){ // this.id = id; // this.value = value; // } // // public int getId() { // return id; // } // // public String getValue() { // return value; // } // // public static GameSymbol byId(int id) { // for (GameSymbol gameSymbol : values()) { // if(gameSymbol.getId() == id){ // return gameSymbol; // } // } // return null; // } // } // Path: app/src/main/java/com/earthblood/tictactoe/strategy/StrategyItem.java import android.util.Log; import com.earthblood.tictactoe.application.Toe; import com.earthblood.tictactoe.util.GameSymbol; import org.apache.commons.lang3.ArrayUtils; import java.util.Random; /** * @author John Piser developer@earthblood.com * * Copyright (C) 2014 EARTHBLOOD, LLC * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.earthblood.tictactoe.strategy; public class StrategyItem { public static final int[] ALL_BOXES = {1,2,3,4,5,6,7,8,9}; public static final int[] DEFAULT_ZEROS = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; public static final int NOT_FOUND = -1; public static final int MIDDLE_BOX_POSITION = 5; private StrategyItem successor; protected int[] currentlySelectedBoxes; protected int[] availableBoxes; protected Random random = new Random(); public int getRandom(int min, int max){ return random.nextInt(max - min + 1) + min; } public Random getRandomObject(){ return this.random; } protected int getBoxId(int[] selectedXBoxIds, int[] selectedOBoxIds, GameSymbol androidSymbol){ return NOT_FOUND; } public int execute(int[] selectedXBoxIds, int[] selectedOBoxIds, GameSymbol androidSymbol){
Log.i(Toe.TAG, "Inside: " + getClass().getName());
Earthblood/Toe
app/src/test/java/com/earthblood/tictactoe/application/TestToe.java
// Path: app/src/test/java/com/earthblood/tictactoe/guice/TestToeRoboModule.java // public class TestToeRoboModule extends AbstractModule{ // // private final Application application; // // public TestToeRoboModule(Application application) { // this.application = application; // } // // @Override // protected void configure() { // // bind(HapticFeedbackHelper.class).toInstance(Mockito.mock(HapticFeedbackHelper.class)); // bind(ToeGame.class).toInstance(Mockito.mock(ToeGame.class)); // bind(PreferenceHelper.class).toInstance(Mockito.mock(PreferenceHelper.class)); // bind(CoinTossHelper.class).toInstance(Mockito.mock(CoinTossHelper.class)); // bind(HtmlHelper.class).toInstance(Mockito.mock(HtmlHelper.class)); // } // }
import com.earthblood.tictactoe.guice.TestToeRoboModule; import org.robolectric.RuntimeEnvironment; import org.robolectric.TestLifecycleApplication; import java.lang.reflect.Method; import roboguice.RoboGuice;
/** * @author John Piser developer@earthblood.com * * Copyright (C) 2014 EARTHBLOOD, LLC * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.earthblood.tictactoe.application; @SuppressWarnings("UnusedDeclaration") public class TestToe extends Toe implements TestLifecycleApplication { static { //TODO:Disabling roboblender for tests until time to figure out why it wasn't working RoboGuice.setUseAnnotationDatabases(false); } @Override public void onCreate() { super.onCreate(); //RoboGuice.setBaseApplicationInjector(this, RoboGuice.DEFAULT_STAGE, RoboGuice.newDefaultRoboModule(this), new ToeRoboModule()); } @Override public void beforeTest(Method method) { } @Override public void prepareTest(Object test) { TestToe application = (TestToe) RuntimeEnvironment.application;
// Path: app/src/test/java/com/earthblood/tictactoe/guice/TestToeRoboModule.java // public class TestToeRoboModule extends AbstractModule{ // // private final Application application; // // public TestToeRoboModule(Application application) { // this.application = application; // } // // @Override // protected void configure() { // // bind(HapticFeedbackHelper.class).toInstance(Mockito.mock(HapticFeedbackHelper.class)); // bind(ToeGame.class).toInstance(Mockito.mock(ToeGame.class)); // bind(PreferenceHelper.class).toInstance(Mockito.mock(PreferenceHelper.class)); // bind(CoinTossHelper.class).toInstance(Mockito.mock(CoinTossHelper.class)); // bind(HtmlHelper.class).toInstance(Mockito.mock(HtmlHelper.class)); // } // } // Path: app/src/test/java/com/earthblood/tictactoe/application/TestToe.java import com.earthblood.tictactoe.guice.TestToeRoboModule; import org.robolectric.RuntimeEnvironment; import org.robolectric.TestLifecycleApplication; import java.lang.reflect.Method; import roboguice.RoboGuice; /** * @author John Piser developer@earthblood.com * * Copyright (C) 2014 EARTHBLOOD, LLC * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.earthblood.tictactoe.application; @SuppressWarnings("UnusedDeclaration") public class TestToe extends Toe implements TestLifecycleApplication { static { //TODO:Disabling roboblender for tests until time to figure out why it wasn't working RoboGuice.setUseAnnotationDatabases(false); } @Override public void onCreate() { super.onCreate(); //RoboGuice.setBaseApplicationInjector(this, RoboGuice.DEFAULT_STAGE, RoboGuice.newDefaultRoboModule(this), new ToeRoboModule()); } @Override public void beforeTest(Method method) { } @Override public void prepareTest(Object test) { TestToe application = (TestToe) RuntimeEnvironment.application;
RoboGuice.overrideApplicationInjector(this, new TestToeRoboModule(this));
Earthblood/Toe
app/src/main/java/com/earthblood/tictactoe/strategy/StrategyItemPickMiddleBox.java
// Path: app/src/main/java/com/earthblood/tictactoe/util/GameSymbol.java // public enum GameSymbol { // X(1,"X"), // O(2,"O"); // // private int id; // private String value; // // private GameSymbol(int id, String value){ // this.id = id; // this.value = value; // } // // public int getId() { // return id; // } // // public String getValue() { // return value; // } // // public static GameSymbol byId(int id) { // for (GameSymbol gameSymbol : values()) { // if(gameSymbol.getId() == id){ // return gameSymbol; // } // } // return null; // } // }
import com.earthblood.tictactoe.util.GameSymbol; import org.apache.commons.lang3.ArrayUtils;
/** * @author John Piser developer@earthblood.com * * Copyright (C) 2014 EARTHBLOOD, LLC * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** * PICK THE MIDDLE BOX IF AVAILABLE */ package com.earthblood.tictactoe.strategy; public class StrategyItemPickMiddleBox extends StrategyItem { public StrategyItemPickMiddleBox(StrategyItem successor) { this.setSuccessor(successor); }
// Path: app/src/main/java/com/earthblood/tictactoe/util/GameSymbol.java // public enum GameSymbol { // X(1,"X"), // O(2,"O"); // // private int id; // private String value; // // private GameSymbol(int id, String value){ // this.id = id; // this.value = value; // } // // public int getId() { // return id; // } // // public String getValue() { // return value; // } // // public static GameSymbol byId(int id) { // for (GameSymbol gameSymbol : values()) { // if(gameSymbol.getId() == id){ // return gameSymbol; // } // } // return null; // } // } // Path: app/src/main/java/com/earthblood/tictactoe/strategy/StrategyItemPickMiddleBox.java import com.earthblood.tictactoe.util.GameSymbol; import org.apache.commons.lang3.ArrayUtils; /** * @author John Piser developer@earthblood.com * * Copyright (C) 2014 EARTHBLOOD, LLC * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** * PICK THE MIDDLE BOX IF AVAILABLE */ package com.earthblood.tictactoe.strategy; public class StrategyItemPickMiddleBox extends StrategyItem { public StrategyItemPickMiddleBox(StrategyItem successor) { this.setSuccessor(successor); }
public int getBoxId(int[] selectedXBoxIds, int[] selectedOBoxIds, GameSymbol androidSymbol) {
Earthblood/Toe
app/src/main/java/com/earthblood/tictactoe/helper/CoinTossHelper.java
// Path: app/src/main/java/com/earthblood/tictactoe/util/GameSymbol.java // public enum GameSymbol { // X(1,"X"), // O(2,"O"); // // private int id; // private String value; // // private GameSymbol(int id, String value){ // this.id = id; // this.value = value; // } // // public int getId() { // return id; // } // // public String getValue() { // return value; // } // // public static GameSymbol byId(int id) { // for (GameSymbol gameSymbol : values()) { // if(gameSymbol.getId() == id){ // return gameSymbol; // } // } // return null; // } // }
import com.earthblood.tictactoe.util.GameSymbol; import java.util.Random;
/** * @author John Piser developer@earthblood.com * * Copyright (C) 2014 EARTHBLOOD, LLC * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.earthblood.tictactoe.helper; public class CoinTossHelper { private Random random; public CoinTossHelper() { this.random = new Random(); } public int getRandom(int min, int max){ return random.nextInt(max - min + 1) + min; }
// Path: app/src/main/java/com/earthblood/tictactoe/util/GameSymbol.java // public enum GameSymbol { // X(1,"X"), // O(2,"O"); // // private int id; // private String value; // // private GameSymbol(int id, String value){ // this.id = id; // this.value = value; // } // // public int getId() { // return id; // } // // public String getValue() { // return value; // } // // public static GameSymbol byId(int id) { // for (GameSymbol gameSymbol : values()) { // if(gameSymbol.getId() == id){ // return gameSymbol; // } // } // return null; // } // } // Path: app/src/main/java/com/earthblood/tictactoe/helper/CoinTossHelper.java import com.earthblood.tictactoe.util.GameSymbol; import java.util.Random; /** * @author John Piser developer@earthblood.com * * Copyright (C) 2014 EARTHBLOOD, LLC * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.earthblood.tictactoe.helper; public class CoinTossHelper { private Random random; public CoinTossHelper() { this.random = new Random(); } public int getRandom(int min, int max){ return random.nextInt(max - min + 1) + min; }
public GameSymbol coinToss(){
Earthblood/Toe
app/src/main/java/com/earthblood/tictactoe/application/Toe.java
// Path: app/src/main/java/com/earthblood/tictactoe/guice/ToeRoboModule.java // public class ToeRoboModule implements Module { // // @Override // public void configure(Binder binder) { // binder.bind(PreferenceHelper.class).to(PreferenceHelperImpl.class); // } // }
import roboguice.RoboGuice; import android.app.Application; import android.content.Context; import com.earthblood.tictactoe.guice.ToeRoboModule;
/** * @author John Piser developer@earthblood.com * * Copyright (C) 2014 EARTHBLOOD, LLC * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.earthblood.tictactoe.application; public class Toe extends Application { public static final String TAG = "EARTHBLOOD_TOE"; private static Context context; @Override public void onCreate() { super.onCreate();
// Path: app/src/main/java/com/earthblood/tictactoe/guice/ToeRoboModule.java // public class ToeRoboModule implements Module { // // @Override // public void configure(Binder binder) { // binder.bind(PreferenceHelper.class).to(PreferenceHelperImpl.class); // } // } // Path: app/src/main/java/com/earthblood/tictactoe/application/Toe.java import roboguice.RoboGuice; import android.app.Application; import android.content.Context; import com.earthblood.tictactoe.guice.ToeRoboModule; /** * @author John Piser developer@earthblood.com * * Copyright (C) 2014 EARTHBLOOD, LLC * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.earthblood.tictactoe.application; public class Toe extends Application { public static final String TAG = "EARTHBLOOD_TOE"; private static Context context; @Override public void onCreate() { super.onCreate();
RoboGuice.overrideApplicationInjector(this, new ToeRoboModule());
Earthblood/Toe
app/src/main/java/com/earthblood/tictactoe/guice/ToeRoboModule.java
// Path: app/src/main/java/com/earthblood/tictactoe/helper/PreferenceHelper.java // public interface PreferenceHelper { // // public int getPreference(String key, int defaultValue); // public void putPreference(int value, String preferenceName, int mode); // // } // // Path: app/src/main/java/com/earthblood/tictactoe/helper/PreferenceHelperImpl.java // public class PreferenceHelperImpl implements PreferenceHelper { // // public static final String SHARED_PREF_GAME_SETTINGS = "SHARED_PREF_GAME_SETTINGS"; // // @Inject // private Application application; // // // public int getPreference(String key, int defaultValue){ // SharedPreferences prefs = application.getApplicationContext().getSharedPreferences(SHARED_PREF_GAME_SETTINGS, Context.MODE_PRIVATE); // return prefs.getInt(key, defaultValue); // } // // public void putPreference(int value, String preferenceName, int mode) { // SharedPreferences prefs = application.getApplicationContext().getSharedPreferences(SHARED_PREF_GAME_SETTINGS, Context.MODE_PRIVATE); // SharedPreferences.Editor editor = prefs.edit(); // editor.putInt(preferenceName,value); // editor.commit(); // } // }
import com.earthblood.tictactoe.helper.PreferenceHelper; import com.earthblood.tictactoe.helper.PreferenceHelperImpl; import com.google.inject.Binder; import com.google.inject.Module;
/** * @author John Piser developer@earthblood.com * * Copyright (C) 2014 EARTHBLOOD, LLC * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.earthblood.tictactoe.guice; public class ToeRoboModule implements Module { @Override public void configure(Binder binder) {
// Path: app/src/main/java/com/earthblood/tictactoe/helper/PreferenceHelper.java // public interface PreferenceHelper { // // public int getPreference(String key, int defaultValue); // public void putPreference(int value, String preferenceName, int mode); // // } // // Path: app/src/main/java/com/earthblood/tictactoe/helper/PreferenceHelperImpl.java // public class PreferenceHelperImpl implements PreferenceHelper { // // public static final String SHARED_PREF_GAME_SETTINGS = "SHARED_PREF_GAME_SETTINGS"; // // @Inject // private Application application; // // // public int getPreference(String key, int defaultValue){ // SharedPreferences prefs = application.getApplicationContext().getSharedPreferences(SHARED_PREF_GAME_SETTINGS, Context.MODE_PRIVATE); // return prefs.getInt(key, defaultValue); // } // // public void putPreference(int value, String preferenceName, int mode) { // SharedPreferences prefs = application.getApplicationContext().getSharedPreferences(SHARED_PREF_GAME_SETTINGS, Context.MODE_PRIVATE); // SharedPreferences.Editor editor = prefs.edit(); // editor.putInt(preferenceName,value); // editor.commit(); // } // } // Path: app/src/main/java/com/earthblood/tictactoe/guice/ToeRoboModule.java import com.earthblood.tictactoe.helper.PreferenceHelper; import com.earthblood.tictactoe.helper.PreferenceHelperImpl; import com.google.inject.Binder; import com.google.inject.Module; /** * @author John Piser developer@earthblood.com * * Copyright (C) 2014 EARTHBLOOD, LLC * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.earthblood.tictactoe.guice; public class ToeRoboModule implements Module { @Override public void configure(Binder binder) {
binder.bind(PreferenceHelper.class).to(PreferenceHelperImpl.class);
Earthblood/Toe
app/src/main/java/com/earthblood/tictactoe/guice/ToeRoboModule.java
// Path: app/src/main/java/com/earthblood/tictactoe/helper/PreferenceHelper.java // public interface PreferenceHelper { // // public int getPreference(String key, int defaultValue); // public void putPreference(int value, String preferenceName, int mode); // // } // // Path: app/src/main/java/com/earthblood/tictactoe/helper/PreferenceHelperImpl.java // public class PreferenceHelperImpl implements PreferenceHelper { // // public static final String SHARED_PREF_GAME_SETTINGS = "SHARED_PREF_GAME_SETTINGS"; // // @Inject // private Application application; // // // public int getPreference(String key, int defaultValue){ // SharedPreferences prefs = application.getApplicationContext().getSharedPreferences(SHARED_PREF_GAME_SETTINGS, Context.MODE_PRIVATE); // return prefs.getInt(key, defaultValue); // } // // public void putPreference(int value, String preferenceName, int mode) { // SharedPreferences prefs = application.getApplicationContext().getSharedPreferences(SHARED_PREF_GAME_SETTINGS, Context.MODE_PRIVATE); // SharedPreferences.Editor editor = prefs.edit(); // editor.putInt(preferenceName,value); // editor.commit(); // } // }
import com.earthblood.tictactoe.helper.PreferenceHelper; import com.earthblood.tictactoe.helper.PreferenceHelperImpl; import com.google.inject.Binder; import com.google.inject.Module;
/** * @author John Piser developer@earthblood.com * * Copyright (C) 2014 EARTHBLOOD, LLC * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.earthblood.tictactoe.guice; public class ToeRoboModule implements Module { @Override public void configure(Binder binder) {
// Path: app/src/main/java/com/earthblood/tictactoe/helper/PreferenceHelper.java // public interface PreferenceHelper { // // public int getPreference(String key, int defaultValue); // public void putPreference(int value, String preferenceName, int mode); // // } // // Path: app/src/main/java/com/earthblood/tictactoe/helper/PreferenceHelperImpl.java // public class PreferenceHelperImpl implements PreferenceHelper { // // public static final String SHARED_PREF_GAME_SETTINGS = "SHARED_PREF_GAME_SETTINGS"; // // @Inject // private Application application; // // // public int getPreference(String key, int defaultValue){ // SharedPreferences prefs = application.getApplicationContext().getSharedPreferences(SHARED_PREF_GAME_SETTINGS, Context.MODE_PRIVATE); // return prefs.getInt(key, defaultValue); // } // // public void putPreference(int value, String preferenceName, int mode) { // SharedPreferences prefs = application.getApplicationContext().getSharedPreferences(SHARED_PREF_GAME_SETTINGS, Context.MODE_PRIVATE); // SharedPreferences.Editor editor = prefs.edit(); // editor.putInt(preferenceName,value); // editor.commit(); // } // } // Path: app/src/main/java/com/earthblood/tictactoe/guice/ToeRoboModule.java import com.earthblood.tictactoe.helper.PreferenceHelper; import com.earthblood.tictactoe.helper.PreferenceHelperImpl; import com.google.inject.Binder; import com.google.inject.Module; /** * @author John Piser developer@earthblood.com * * Copyright (C) 2014 EARTHBLOOD, LLC * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.earthblood.tictactoe.guice; public class ToeRoboModule implements Module { @Override public void configure(Binder binder) {
binder.bind(PreferenceHelper.class).to(PreferenceHelperImpl.class);
Earthblood/Toe
app/src/main/java/com/earthblood/tictactoe/strategy/ToeStrategyExplicit.java
// Path: app/src/main/java/com/earthblood/tictactoe/util/GameSymbol.java // public enum GameSymbol { // X(1,"X"), // O(2,"O"); // // private int id; // private String value; // // private GameSymbol(int id, String value){ // this.id = id; // this.value = value; // } // // public int getId() { // return id; // } // // public String getValue() { // return value; // } // // public static GameSymbol byId(int id) { // for (GameSymbol gameSymbol : values()) { // if(gameSymbol.getId() == id){ // return gameSymbol; // } // } // return null; // } // }
import com.earthblood.tictactoe.util.GameSymbol;
/** * @author John Piser developer@earthblood.com * * Copyright (C) 2014 EARTHBLOOD, LLC * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.earthblood.tictactoe.strategy; public class ToeStrategyExplicit implements ToeStrategy { private Integer boxId;
// Path: app/src/main/java/com/earthblood/tictactoe/util/GameSymbol.java // public enum GameSymbol { // X(1,"X"), // O(2,"O"); // // private int id; // private String value; // // private GameSymbol(int id, String value){ // this.id = id; // this.value = value; // } // // public int getId() { // return id; // } // // public String getValue() { // return value; // } // // public static GameSymbol byId(int id) { // for (GameSymbol gameSymbol : values()) { // if(gameSymbol.getId() == id){ // return gameSymbol; // } // } // return null; // } // } // Path: app/src/main/java/com/earthblood/tictactoe/strategy/ToeStrategyExplicit.java import com.earthblood.tictactoe.util.GameSymbol; /** * @author John Piser developer@earthblood.com * * Copyright (C) 2014 EARTHBLOOD, LLC * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.earthblood.tictactoe.strategy; public class ToeStrategyExplicit implements ToeStrategy { private Integer boxId;
private GameSymbol gameSymbol;
Earthblood/Toe
app/src/main/java/com/earthblood/tictactoe/strategy/ToeStrategyBase.java
// Path: app/src/main/java/com/earthblood/tictactoe/util/GameSymbol.java // public enum GameSymbol { // X(1,"X"), // O(2,"O"); // // private int id; // private String value; // // private GameSymbol(int id, String value){ // this.id = id; // this.value = value; // } // // public int getId() { // return id; // } // // public String getValue() { // return value; // } // // public static GameSymbol byId(int id) { // for (GameSymbol gameSymbol : values()) { // if(gameSymbol.getId() == id){ // return gameSymbol; // } // } // return null; // } // } // // Path: app/src/main/java/com/earthblood/tictactoe/util/GameWinPattern.java // public enum GameWinPattern { // ONE_ACROSS(1,2,3), // FOUR_ACROSS(4,5,6), // SEVEN_ACROSS(7,8,9), // ONE_DOWN(1,4,7), // TWO_DOWN(2,5,8), // THREE_DOWN(3,6,9), // ONE_DIAGONAL(1,5,9), // THREE_DIAGONAL(3,5,7); // // private int[] boxIds; // // private GameWinPattern(int id1, int id2, int id3){ // this.boxIds = new int[]{id1, id2, id3}; // } // // public int[] getBoxIds() { // return boxIds; // } // // public static GameWinPattern checkForWin(int[] boxIdsForGameSymbol){ // for (GameWinPattern gameWinPattern : values()) { // int count =0; // for (int boxId : gameWinPattern.boxIds) { // for (int id : boxIdsForGameSymbol) { // count += (id == boxId ? 1 : 0 ); // } // } // if(count == 3){ // return gameWinPattern; // } // } // return null; // } // // public boolean containsBoxId(int boxId) { // for (int bId : boxIds) { // if(bId == boxId){ // return true; // } // } // return false; // } // // public int returnFirstMatch(int[] availableBoxes, int notFound) { // for (int boxId : boxIds) { // for (int availableBoxId : availableBoxes) { // if(boxId == availableBoxId){ // return boxId; // } // } // } // return notFound; // } // public static GameWinPattern[] randomBunchOfWinningPatterns(int minNumberOfPatters, Random random){ // // int max = GameWinPattern.values().length; // int numberOfPatterns = max; // // if(minNumberOfPatters < max){ // numberOfPatterns = random.nextInt(max -minNumberOfPatters) + minNumberOfPatters; // } // GameWinPattern[] returnedPatterns = new GameWinPattern[numberOfPatterns]; // int[] ordinalValues = {0,1,2,3,4,5,6,7}; // // int n = max - 1; // for(int i = n; i >= 1; i--){ // int r = random.nextInt(n); // int tmpR = ordinalValues[r]; // int tmpN = ordinalValues[n]; // ordinalValues[r] = tmpN; // ordinalValues[n] = tmpR; // } // // for (int p =0; p < numberOfPatterns; p++) { // returnedPatterns[p] = GameWinPattern.values()[ordinalValues[p]]; // } // return returnedPatterns; // } // }
import com.earthblood.tictactoe.util.GameSymbol; import com.earthblood.tictactoe.util.GameWinPattern;
/** * @author John Piser developer@earthblood.com * * Copyright (C) 2014 EARTHBLOOD, LLC * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.earthblood.tictactoe.strategy; public abstract class ToeStrategyBase { protected int[] selectedXBoxIds; protected int[] selectedOBoxIds;
// Path: app/src/main/java/com/earthblood/tictactoe/util/GameSymbol.java // public enum GameSymbol { // X(1,"X"), // O(2,"O"); // // private int id; // private String value; // // private GameSymbol(int id, String value){ // this.id = id; // this.value = value; // } // // public int getId() { // return id; // } // // public String getValue() { // return value; // } // // public static GameSymbol byId(int id) { // for (GameSymbol gameSymbol : values()) { // if(gameSymbol.getId() == id){ // return gameSymbol; // } // } // return null; // } // } // // Path: app/src/main/java/com/earthblood/tictactoe/util/GameWinPattern.java // public enum GameWinPattern { // ONE_ACROSS(1,2,3), // FOUR_ACROSS(4,5,6), // SEVEN_ACROSS(7,8,9), // ONE_DOWN(1,4,7), // TWO_DOWN(2,5,8), // THREE_DOWN(3,6,9), // ONE_DIAGONAL(1,5,9), // THREE_DIAGONAL(3,5,7); // // private int[] boxIds; // // private GameWinPattern(int id1, int id2, int id3){ // this.boxIds = new int[]{id1, id2, id3}; // } // // public int[] getBoxIds() { // return boxIds; // } // // public static GameWinPattern checkForWin(int[] boxIdsForGameSymbol){ // for (GameWinPattern gameWinPattern : values()) { // int count =0; // for (int boxId : gameWinPattern.boxIds) { // for (int id : boxIdsForGameSymbol) { // count += (id == boxId ? 1 : 0 ); // } // } // if(count == 3){ // return gameWinPattern; // } // } // return null; // } // // public boolean containsBoxId(int boxId) { // for (int bId : boxIds) { // if(bId == boxId){ // return true; // } // } // return false; // } // // public int returnFirstMatch(int[] availableBoxes, int notFound) { // for (int boxId : boxIds) { // for (int availableBoxId : availableBoxes) { // if(boxId == availableBoxId){ // return boxId; // } // } // } // return notFound; // } // public static GameWinPattern[] randomBunchOfWinningPatterns(int minNumberOfPatters, Random random){ // // int max = GameWinPattern.values().length; // int numberOfPatterns = max; // // if(minNumberOfPatters < max){ // numberOfPatterns = random.nextInt(max -minNumberOfPatters) + minNumberOfPatters; // } // GameWinPattern[] returnedPatterns = new GameWinPattern[numberOfPatterns]; // int[] ordinalValues = {0,1,2,3,4,5,6,7}; // // int n = max - 1; // for(int i = n; i >= 1; i--){ // int r = random.nextInt(n); // int tmpR = ordinalValues[r]; // int tmpN = ordinalValues[n]; // ordinalValues[r] = tmpN; // ordinalValues[n] = tmpR; // } // // for (int p =0; p < numberOfPatterns; p++) { // returnedPatterns[p] = GameWinPattern.values()[ordinalValues[p]]; // } // return returnedPatterns; // } // } // Path: app/src/main/java/com/earthblood/tictactoe/strategy/ToeStrategyBase.java import com.earthblood.tictactoe.util.GameSymbol; import com.earthblood.tictactoe.util.GameWinPattern; /** * @author John Piser developer@earthblood.com * * Copyright (C) 2014 EARTHBLOOD, LLC * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.earthblood.tictactoe.strategy; public abstract class ToeStrategyBase { protected int[] selectedXBoxIds; protected int[] selectedOBoxIds;
protected GameSymbol androidSymbol;
Earthblood/Toe
app/src/main/java/com/earthblood/tictactoe/strategy/ToeStrategyBase.java
// Path: app/src/main/java/com/earthblood/tictactoe/util/GameSymbol.java // public enum GameSymbol { // X(1,"X"), // O(2,"O"); // // private int id; // private String value; // // private GameSymbol(int id, String value){ // this.id = id; // this.value = value; // } // // public int getId() { // return id; // } // // public String getValue() { // return value; // } // // public static GameSymbol byId(int id) { // for (GameSymbol gameSymbol : values()) { // if(gameSymbol.getId() == id){ // return gameSymbol; // } // } // return null; // } // } // // Path: app/src/main/java/com/earthblood/tictactoe/util/GameWinPattern.java // public enum GameWinPattern { // ONE_ACROSS(1,2,3), // FOUR_ACROSS(4,5,6), // SEVEN_ACROSS(7,8,9), // ONE_DOWN(1,4,7), // TWO_DOWN(2,5,8), // THREE_DOWN(3,6,9), // ONE_DIAGONAL(1,5,9), // THREE_DIAGONAL(3,5,7); // // private int[] boxIds; // // private GameWinPattern(int id1, int id2, int id3){ // this.boxIds = new int[]{id1, id2, id3}; // } // // public int[] getBoxIds() { // return boxIds; // } // // public static GameWinPattern checkForWin(int[] boxIdsForGameSymbol){ // for (GameWinPattern gameWinPattern : values()) { // int count =0; // for (int boxId : gameWinPattern.boxIds) { // for (int id : boxIdsForGameSymbol) { // count += (id == boxId ? 1 : 0 ); // } // } // if(count == 3){ // return gameWinPattern; // } // } // return null; // } // // public boolean containsBoxId(int boxId) { // for (int bId : boxIds) { // if(bId == boxId){ // return true; // } // } // return false; // } // // public int returnFirstMatch(int[] availableBoxes, int notFound) { // for (int boxId : boxIds) { // for (int availableBoxId : availableBoxes) { // if(boxId == availableBoxId){ // return boxId; // } // } // } // return notFound; // } // public static GameWinPattern[] randomBunchOfWinningPatterns(int minNumberOfPatters, Random random){ // // int max = GameWinPattern.values().length; // int numberOfPatterns = max; // // if(minNumberOfPatters < max){ // numberOfPatterns = random.nextInt(max -minNumberOfPatters) + minNumberOfPatters; // } // GameWinPattern[] returnedPatterns = new GameWinPattern[numberOfPatterns]; // int[] ordinalValues = {0,1,2,3,4,5,6,7}; // // int n = max - 1; // for(int i = n; i >= 1; i--){ // int r = random.nextInt(n); // int tmpR = ordinalValues[r]; // int tmpN = ordinalValues[n]; // ordinalValues[r] = tmpN; // ordinalValues[n] = tmpR; // } // // for (int p =0; p < numberOfPatterns; p++) { // returnedPatterns[p] = GameWinPattern.values()[ordinalValues[p]]; // } // return returnedPatterns; // } // }
import com.earthblood.tictactoe.util.GameSymbol; import com.earthblood.tictactoe.util.GameWinPattern;
/** * @author John Piser developer@earthblood.com * * Copyright (C) 2014 EARTHBLOOD, LLC * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.earthblood.tictactoe.strategy; public abstract class ToeStrategyBase { protected int[] selectedXBoxIds; protected int[] selectedOBoxIds; protected GameSymbol androidSymbol; public GameSymbol androidOpponent(){ return androidSymbol == GameSymbol.O ? GameSymbol.X : GameSymbol.O; } public int totalPatterns(){
// Path: app/src/main/java/com/earthblood/tictactoe/util/GameSymbol.java // public enum GameSymbol { // X(1,"X"), // O(2,"O"); // // private int id; // private String value; // // private GameSymbol(int id, String value){ // this.id = id; // this.value = value; // } // // public int getId() { // return id; // } // // public String getValue() { // return value; // } // // public static GameSymbol byId(int id) { // for (GameSymbol gameSymbol : values()) { // if(gameSymbol.getId() == id){ // return gameSymbol; // } // } // return null; // } // } // // Path: app/src/main/java/com/earthblood/tictactoe/util/GameWinPattern.java // public enum GameWinPattern { // ONE_ACROSS(1,2,3), // FOUR_ACROSS(4,5,6), // SEVEN_ACROSS(7,8,9), // ONE_DOWN(1,4,7), // TWO_DOWN(2,5,8), // THREE_DOWN(3,6,9), // ONE_DIAGONAL(1,5,9), // THREE_DIAGONAL(3,5,7); // // private int[] boxIds; // // private GameWinPattern(int id1, int id2, int id3){ // this.boxIds = new int[]{id1, id2, id3}; // } // // public int[] getBoxIds() { // return boxIds; // } // // public static GameWinPattern checkForWin(int[] boxIdsForGameSymbol){ // for (GameWinPattern gameWinPattern : values()) { // int count =0; // for (int boxId : gameWinPattern.boxIds) { // for (int id : boxIdsForGameSymbol) { // count += (id == boxId ? 1 : 0 ); // } // } // if(count == 3){ // return gameWinPattern; // } // } // return null; // } // // public boolean containsBoxId(int boxId) { // for (int bId : boxIds) { // if(bId == boxId){ // return true; // } // } // return false; // } // // public int returnFirstMatch(int[] availableBoxes, int notFound) { // for (int boxId : boxIds) { // for (int availableBoxId : availableBoxes) { // if(boxId == availableBoxId){ // return boxId; // } // } // } // return notFound; // } // public static GameWinPattern[] randomBunchOfWinningPatterns(int minNumberOfPatters, Random random){ // // int max = GameWinPattern.values().length; // int numberOfPatterns = max; // // if(minNumberOfPatters < max){ // numberOfPatterns = random.nextInt(max -minNumberOfPatters) + minNumberOfPatters; // } // GameWinPattern[] returnedPatterns = new GameWinPattern[numberOfPatterns]; // int[] ordinalValues = {0,1,2,3,4,5,6,7}; // // int n = max - 1; // for(int i = n; i >= 1; i--){ // int r = random.nextInt(n); // int tmpR = ordinalValues[r]; // int tmpN = ordinalValues[n]; // ordinalValues[r] = tmpN; // ordinalValues[n] = tmpR; // } // // for (int p =0; p < numberOfPatterns; p++) { // returnedPatterns[p] = GameWinPattern.values()[ordinalValues[p]]; // } // return returnedPatterns; // } // } // Path: app/src/main/java/com/earthblood/tictactoe/strategy/ToeStrategyBase.java import com.earthblood.tictactoe.util.GameSymbol; import com.earthblood.tictactoe.util.GameWinPattern; /** * @author John Piser developer@earthblood.com * * Copyright (C) 2014 EARTHBLOOD, LLC * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.earthblood.tictactoe.strategy; public abstract class ToeStrategyBase { protected int[] selectedXBoxIds; protected int[] selectedOBoxIds; protected GameSymbol androidSymbol; public GameSymbol androidOpponent(){ return androidSymbol == GameSymbol.O ? GameSymbol.X : GameSymbol.O; } public int totalPatterns(){
return GameWinPattern.values().length;
Earthblood/Toe
app/src/main/java/com/earthblood/tictactoe/strategy/StrategyItemPatternDetector.java
// Path: app/src/main/java/com/earthblood/tictactoe/util/GameSymbol.java // public enum GameSymbol { // X(1,"X"), // O(2,"O"); // // private int id; // private String value; // // private GameSymbol(int id, String value){ // this.id = id; // this.value = value; // } // // public int getId() { // return id; // } // // public String getValue() { // return value; // } // // public static GameSymbol byId(int id) { // for (GameSymbol gameSymbol : values()) { // if(gameSymbol.getId() == id){ // return gameSymbol; // } // } // return null; // } // } // // Path: app/src/main/java/com/earthblood/tictactoe/util/GameWinPattern.java // public enum GameWinPattern { // ONE_ACROSS(1,2,3), // FOUR_ACROSS(4,5,6), // SEVEN_ACROSS(7,8,9), // ONE_DOWN(1,4,7), // TWO_DOWN(2,5,8), // THREE_DOWN(3,6,9), // ONE_DIAGONAL(1,5,9), // THREE_DIAGONAL(3,5,7); // // private int[] boxIds; // // private GameWinPattern(int id1, int id2, int id3){ // this.boxIds = new int[]{id1, id2, id3}; // } // // public int[] getBoxIds() { // return boxIds; // } // // public static GameWinPattern checkForWin(int[] boxIdsForGameSymbol){ // for (GameWinPattern gameWinPattern : values()) { // int count =0; // for (int boxId : gameWinPattern.boxIds) { // for (int id : boxIdsForGameSymbol) { // count += (id == boxId ? 1 : 0 ); // } // } // if(count == 3){ // return gameWinPattern; // } // } // return null; // } // // public boolean containsBoxId(int boxId) { // for (int bId : boxIds) { // if(bId == boxId){ // return true; // } // } // return false; // } // // public int returnFirstMatch(int[] availableBoxes, int notFound) { // for (int boxId : boxIds) { // for (int availableBoxId : availableBoxes) { // if(boxId == availableBoxId){ // return boxId; // } // } // } // return notFound; // } // public static GameWinPattern[] randomBunchOfWinningPatterns(int minNumberOfPatters, Random random){ // // int max = GameWinPattern.values().length; // int numberOfPatterns = max; // // if(minNumberOfPatters < max){ // numberOfPatterns = random.nextInt(max -minNumberOfPatters) + minNumberOfPatters; // } // GameWinPattern[] returnedPatterns = new GameWinPattern[numberOfPatterns]; // int[] ordinalValues = {0,1,2,3,4,5,6,7}; // // int n = max - 1; // for(int i = n; i >= 1; i--){ // int r = random.nextInt(n); // int tmpR = ordinalValues[r]; // int tmpN = ordinalValues[n]; // ordinalValues[r] = tmpN; // ordinalValues[n] = tmpR; // } // // for (int p =0; p < numberOfPatterns; p++) { // returnedPatterns[p] = GameWinPattern.values()[ordinalValues[p]]; // } // return returnedPatterns; // } // }
import com.earthblood.tictactoe.util.GameWinPattern; import com.earthblood.tictactoe.util.GameSymbol;
/** * @author John Piser developer@earthblood.com * * Copyright (C) 2014 EARTHBLOOD, LLC * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /************************************************************************************************** * TRY TO DETECT IF YOU OR YOUR OPPONENT HAS TWO BOXES OF A WINNING PATTERN, * IF THE THIRD WINNING BOX OF THAT PATTERN IS AVAILABLE, SELECT IT EITHER TO BLOCK OR WIN * * THIS STRATEGY CAN BE USED OFFENSIVELY OR DEFENSIVELY * * int numberOfPatternsToDetect: The number of game winning patterns to target. * The higher the number, the greater the degree * of offensive or defensive difficulty. * Cannot be higher than total number of patterns * * GameSymbol symbolToDetect: The symbol whose selected boxes will be inspected * for pattern matching. * When initialized with the Android's symbol, * this strategy will be offensive, else defensive * ************************************************************************************************** */ package com.earthblood.tictactoe.strategy; public class StrategyItemPatternDetector extends StrategyItem { protected int numberOfPatternsToDetect;
// Path: app/src/main/java/com/earthblood/tictactoe/util/GameSymbol.java // public enum GameSymbol { // X(1,"X"), // O(2,"O"); // // private int id; // private String value; // // private GameSymbol(int id, String value){ // this.id = id; // this.value = value; // } // // public int getId() { // return id; // } // // public String getValue() { // return value; // } // // public static GameSymbol byId(int id) { // for (GameSymbol gameSymbol : values()) { // if(gameSymbol.getId() == id){ // return gameSymbol; // } // } // return null; // } // } // // Path: app/src/main/java/com/earthblood/tictactoe/util/GameWinPattern.java // public enum GameWinPattern { // ONE_ACROSS(1,2,3), // FOUR_ACROSS(4,5,6), // SEVEN_ACROSS(7,8,9), // ONE_DOWN(1,4,7), // TWO_DOWN(2,5,8), // THREE_DOWN(3,6,9), // ONE_DIAGONAL(1,5,9), // THREE_DIAGONAL(3,5,7); // // private int[] boxIds; // // private GameWinPattern(int id1, int id2, int id3){ // this.boxIds = new int[]{id1, id2, id3}; // } // // public int[] getBoxIds() { // return boxIds; // } // // public static GameWinPattern checkForWin(int[] boxIdsForGameSymbol){ // for (GameWinPattern gameWinPattern : values()) { // int count =0; // for (int boxId : gameWinPattern.boxIds) { // for (int id : boxIdsForGameSymbol) { // count += (id == boxId ? 1 : 0 ); // } // } // if(count == 3){ // return gameWinPattern; // } // } // return null; // } // // public boolean containsBoxId(int boxId) { // for (int bId : boxIds) { // if(bId == boxId){ // return true; // } // } // return false; // } // // public int returnFirstMatch(int[] availableBoxes, int notFound) { // for (int boxId : boxIds) { // for (int availableBoxId : availableBoxes) { // if(boxId == availableBoxId){ // return boxId; // } // } // } // return notFound; // } // public static GameWinPattern[] randomBunchOfWinningPatterns(int minNumberOfPatters, Random random){ // // int max = GameWinPattern.values().length; // int numberOfPatterns = max; // // if(minNumberOfPatters < max){ // numberOfPatterns = random.nextInt(max -minNumberOfPatters) + minNumberOfPatters; // } // GameWinPattern[] returnedPatterns = new GameWinPattern[numberOfPatterns]; // int[] ordinalValues = {0,1,2,3,4,5,6,7}; // // int n = max - 1; // for(int i = n; i >= 1; i--){ // int r = random.nextInt(n); // int tmpR = ordinalValues[r]; // int tmpN = ordinalValues[n]; // ordinalValues[r] = tmpN; // ordinalValues[n] = tmpR; // } // // for (int p =0; p < numberOfPatterns; p++) { // returnedPatterns[p] = GameWinPattern.values()[ordinalValues[p]]; // } // return returnedPatterns; // } // } // Path: app/src/main/java/com/earthblood/tictactoe/strategy/StrategyItemPatternDetector.java import com.earthblood.tictactoe.util.GameWinPattern; import com.earthblood.tictactoe.util.GameSymbol; /** * @author John Piser developer@earthblood.com * * Copyright (C) 2014 EARTHBLOOD, LLC * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /************************************************************************************************** * TRY TO DETECT IF YOU OR YOUR OPPONENT HAS TWO BOXES OF A WINNING PATTERN, * IF THE THIRD WINNING BOX OF THAT PATTERN IS AVAILABLE, SELECT IT EITHER TO BLOCK OR WIN * * THIS STRATEGY CAN BE USED OFFENSIVELY OR DEFENSIVELY * * int numberOfPatternsToDetect: The number of game winning patterns to target. * The higher the number, the greater the degree * of offensive or defensive difficulty. * Cannot be higher than total number of patterns * * GameSymbol symbolToDetect: The symbol whose selected boxes will be inspected * for pattern matching. * When initialized with the Android's symbol, * this strategy will be offensive, else defensive * ************************************************************************************************** */ package com.earthblood.tictactoe.strategy; public class StrategyItemPatternDetector extends StrategyItem { protected int numberOfPatternsToDetect;
protected GameSymbol symbolToDetect;
Earthblood/Toe
app/src/main/java/com/earthblood/tictactoe/strategy/StrategyItemPatternDetector.java
// Path: app/src/main/java/com/earthblood/tictactoe/util/GameSymbol.java // public enum GameSymbol { // X(1,"X"), // O(2,"O"); // // private int id; // private String value; // // private GameSymbol(int id, String value){ // this.id = id; // this.value = value; // } // // public int getId() { // return id; // } // // public String getValue() { // return value; // } // // public static GameSymbol byId(int id) { // for (GameSymbol gameSymbol : values()) { // if(gameSymbol.getId() == id){ // return gameSymbol; // } // } // return null; // } // } // // Path: app/src/main/java/com/earthblood/tictactoe/util/GameWinPattern.java // public enum GameWinPattern { // ONE_ACROSS(1,2,3), // FOUR_ACROSS(4,5,6), // SEVEN_ACROSS(7,8,9), // ONE_DOWN(1,4,7), // TWO_DOWN(2,5,8), // THREE_DOWN(3,6,9), // ONE_DIAGONAL(1,5,9), // THREE_DIAGONAL(3,5,7); // // private int[] boxIds; // // private GameWinPattern(int id1, int id2, int id3){ // this.boxIds = new int[]{id1, id2, id3}; // } // // public int[] getBoxIds() { // return boxIds; // } // // public static GameWinPattern checkForWin(int[] boxIdsForGameSymbol){ // for (GameWinPattern gameWinPattern : values()) { // int count =0; // for (int boxId : gameWinPattern.boxIds) { // for (int id : boxIdsForGameSymbol) { // count += (id == boxId ? 1 : 0 ); // } // } // if(count == 3){ // return gameWinPattern; // } // } // return null; // } // // public boolean containsBoxId(int boxId) { // for (int bId : boxIds) { // if(bId == boxId){ // return true; // } // } // return false; // } // // public int returnFirstMatch(int[] availableBoxes, int notFound) { // for (int boxId : boxIds) { // for (int availableBoxId : availableBoxes) { // if(boxId == availableBoxId){ // return boxId; // } // } // } // return notFound; // } // public static GameWinPattern[] randomBunchOfWinningPatterns(int minNumberOfPatters, Random random){ // // int max = GameWinPattern.values().length; // int numberOfPatterns = max; // // if(minNumberOfPatters < max){ // numberOfPatterns = random.nextInt(max -minNumberOfPatters) + minNumberOfPatters; // } // GameWinPattern[] returnedPatterns = new GameWinPattern[numberOfPatterns]; // int[] ordinalValues = {0,1,2,3,4,5,6,7}; // // int n = max - 1; // for(int i = n; i >= 1; i--){ // int r = random.nextInt(n); // int tmpR = ordinalValues[r]; // int tmpN = ordinalValues[n]; // ordinalValues[r] = tmpN; // ordinalValues[n] = tmpR; // } // // for (int p =0; p < numberOfPatterns; p++) { // returnedPatterns[p] = GameWinPattern.values()[ordinalValues[p]]; // } // return returnedPatterns; // } // }
import com.earthblood.tictactoe.util.GameWinPattern; import com.earthblood.tictactoe.util.GameSymbol;
/** * @author John Piser developer@earthblood.com * * Copyright (C) 2014 EARTHBLOOD, LLC * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /************************************************************************************************** * TRY TO DETECT IF YOU OR YOUR OPPONENT HAS TWO BOXES OF A WINNING PATTERN, * IF THE THIRD WINNING BOX OF THAT PATTERN IS AVAILABLE, SELECT IT EITHER TO BLOCK OR WIN * * THIS STRATEGY CAN BE USED OFFENSIVELY OR DEFENSIVELY * * int numberOfPatternsToDetect: The number of game winning patterns to target. * The higher the number, the greater the degree * of offensive or defensive difficulty. * Cannot be higher than total number of patterns * * GameSymbol symbolToDetect: The symbol whose selected boxes will be inspected * for pattern matching. * When initialized with the Android's symbol, * this strategy will be offensive, else defensive * ************************************************************************************************** */ package com.earthblood.tictactoe.strategy; public class StrategyItemPatternDetector extends StrategyItem { protected int numberOfPatternsToDetect; protected GameSymbol symbolToDetect; public StrategyItemPatternDetector(StrategyItem successor, int numberOfPatternsToDetect, GameSymbol symbolToDetect) { this.setSuccessor(successor); this.numberOfPatternsToDetect = numberOfPatternsToDetect; this.symbolToDetect = symbolToDetect; } public int getBoxId(int[] selectedXBoxIds, int[] selectedOBoxIds, GameSymbol androidSymbol) { int[] selectedBoxesToInspect = symbolToDetect == GameSymbol.X ? selectedXBoxIds : selectedOBoxIds;
// Path: app/src/main/java/com/earthblood/tictactoe/util/GameSymbol.java // public enum GameSymbol { // X(1,"X"), // O(2,"O"); // // private int id; // private String value; // // private GameSymbol(int id, String value){ // this.id = id; // this.value = value; // } // // public int getId() { // return id; // } // // public String getValue() { // return value; // } // // public static GameSymbol byId(int id) { // for (GameSymbol gameSymbol : values()) { // if(gameSymbol.getId() == id){ // return gameSymbol; // } // } // return null; // } // } // // Path: app/src/main/java/com/earthblood/tictactoe/util/GameWinPattern.java // public enum GameWinPattern { // ONE_ACROSS(1,2,3), // FOUR_ACROSS(4,5,6), // SEVEN_ACROSS(7,8,9), // ONE_DOWN(1,4,7), // TWO_DOWN(2,5,8), // THREE_DOWN(3,6,9), // ONE_DIAGONAL(1,5,9), // THREE_DIAGONAL(3,5,7); // // private int[] boxIds; // // private GameWinPattern(int id1, int id2, int id3){ // this.boxIds = new int[]{id1, id2, id3}; // } // // public int[] getBoxIds() { // return boxIds; // } // // public static GameWinPattern checkForWin(int[] boxIdsForGameSymbol){ // for (GameWinPattern gameWinPattern : values()) { // int count =0; // for (int boxId : gameWinPattern.boxIds) { // for (int id : boxIdsForGameSymbol) { // count += (id == boxId ? 1 : 0 ); // } // } // if(count == 3){ // return gameWinPattern; // } // } // return null; // } // // public boolean containsBoxId(int boxId) { // for (int bId : boxIds) { // if(bId == boxId){ // return true; // } // } // return false; // } // // public int returnFirstMatch(int[] availableBoxes, int notFound) { // for (int boxId : boxIds) { // for (int availableBoxId : availableBoxes) { // if(boxId == availableBoxId){ // return boxId; // } // } // } // return notFound; // } // public static GameWinPattern[] randomBunchOfWinningPatterns(int minNumberOfPatters, Random random){ // // int max = GameWinPattern.values().length; // int numberOfPatterns = max; // // if(minNumberOfPatters < max){ // numberOfPatterns = random.nextInt(max -minNumberOfPatters) + minNumberOfPatters; // } // GameWinPattern[] returnedPatterns = new GameWinPattern[numberOfPatterns]; // int[] ordinalValues = {0,1,2,3,4,5,6,7}; // // int n = max - 1; // for(int i = n; i >= 1; i--){ // int r = random.nextInt(n); // int tmpR = ordinalValues[r]; // int tmpN = ordinalValues[n]; // ordinalValues[r] = tmpN; // ordinalValues[n] = tmpR; // } // // for (int p =0; p < numberOfPatterns; p++) { // returnedPatterns[p] = GameWinPattern.values()[ordinalValues[p]]; // } // return returnedPatterns; // } // } // Path: app/src/main/java/com/earthblood/tictactoe/strategy/StrategyItemPatternDetector.java import com.earthblood.tictactoe.util.GameWinPattern; import com.earthblood.tictactoe.util.GameSymbol; /** * @author John Piser developer@earthblood.com * * Copyright (C) 2014 EARTHBLOOD, LLC * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /************************************************************************************************** * TRY TO DETECT IF YOU OR YOUR OPPONENT HAS TWO BOXES OF A WINNING PATTERN, * IF THE THIRD WINNING BOX OF THAT PATTERN IS AVAILABLE, SELECT IT EITHER TO BLOCK OR WIN * * THIS STRATEGY CAN BE USED OFFENSIVELY OR DEFENSIVELY * * int numberOfPatternsToDetect: The number of game winning patterns to target. * The higher the number, the greater the degree * of offensive or defensive difficulty. * Cannot be higher than total number of patterns * * GameSymbol symbolToDetect: The symbol whose selected boxes will be inspected * for pattern matching. * When initialized with the Android's symbol, * this strategy will be offensive, else defensive * ************************************************************************************************** */ package com.earthblood.tictactoe.strategy; public class StrategyItemPatternDetector extends StrategyItem { protected int numberOfPatternsToDetect; protected GameSymbol symbolToDetect; public StrategyItemPatternDetector(StrategyItem successor, int numberOfPatternsToDetect, GameSymbol symbolToDetect) { this.setSuccessor(successor); this.numberOfPatternsToDetect = numberOfPatternsToDetect; this.symbolToDetect = symbolToDetect; } public int getBoxId(int[] selectedXBoxIds, int[] selectedOBoxIds, GameSymbol androidSymbol) { int[] selectedBoxesToInspect = symbolToDetect == GameSymbol.X ? selectedXBoxIds : selectedOBoxIds;
numberOfPatternsToDetect = numberOfPatternsToDetect > GameWinPattern.values().length ?
kefik/MsPacMan-vs-Ghosts-AI
Exercises/E4/src/game/controllers/pacman/exercises/e4/path/Path.java
// Path: Exercises/E4/src/game/controllers/pacman/exercises/e4/graph/Link.java // public class Link { // // public final Node n1; // public final Node n2; // // public final MazeNode[] mazeNodes; // // public final int distance; // // public Link(Node n1, Node n2, MazeNode... mazeNodes) { // this.n1 = n1; // this.n2 = n2; // this.mazeNodes = mazeNodes; // distance = mazeNodes.length+1; // } // // public Node getOtherEnd(Node node) { // if (node == n1) return n2; // if (node == n2) return n1; // return null; // } // // public void debugDrawLink(Game game, Color linkColor, Color nodeColor, boolean drawDistance) { // GameView.addLines(game, linkColor, n1.index, mazeNodes[0].index); // int i = 0; // int step = 4; // for (i = step; i < mazeNodes.length-1; i += step) { // GameView.addLines(game, linkColor, mazeNodes[i-step].index, mazeNodes[i].index); // } // if (i >= mazeNodes.length) { // GameView.addLines(game, linkColor, mazeNodes[i-step].index, mazeNodes[mazeNodes.length-1].index); // } // GameView.addLines(game, linkColor, mazeNodes[mazeNodes.length-1].index, n2.index); // if (drawDistance) { // GameView.addText(game, mazeNodes[mazeNodes.length/2].index, Color.YELLOW, String.valueOf(distance)); // } // GameView.addPoints(game, nodeColor, n1.index, n2.index); // } // // } // // Path: Exercises/E4/src/game/controllers/pacman/exercises/e4/graph/Node.java // public class Node { // // /** // * Unique index of the node. // */ // public final int index; // // /** // * Type of sub-node within the Pac-Man maze. // */ // public final NodeType type; // // /** // * Direction -> Link // * // * Node that link is never stored for {@link Direction#NONE}. // */ // public Map<Direction, Link> links = new HashMap<Direction, Link>(); // // public Node(int index, NodeType type) { // this.index = index; // this.type = type; // } // // public Node(MazeNode node) { // this.index = node.index; // this.type = node.nodeType(); // } // // @Override // public String toString() { // return "Node[index=" + index + ",type=" + type + "]"; // } // // }
import java.util.Collection; import game.controllers.pacman.exercises.e4.graph.Link; import game.controllers.pacman.exercises.e4.graph.Node;
package game.controllers.pacman.exercises.e4.path; public class Path { public Node[] path; public Path(Node... path) { this.path = path; } public Path(Collection<Node> path) { this.path = path.toArray(new Node[path.size()]); } public void reverse() { Node[] pathReverse = new Node[path.length]; for (int i = path.length - 1; i >= 0; --i) { pathReverse[path.length - 1 - i] = path[i]; } this.path = pathReverse; } public int computeCost() { int result = 0; for (int i = 1; i < path.length; ++i) { Node n1 = path[i-1]; Node n2 = path[i];
// Path: Exercises/E4/src/game/controllers/pacman/exercises/e4/graph/Link.java // public class Link { // // public final Node n1; // public final Node n2; // // public final MazeNode[] mazeNodes; // // public final int distance; // // public Link(Node n1, Node n2, MazeNode... mazeNodes) { // this.n1 = n1; // this.n2 = n2; // this.mazeNodes = mazeNodes; // distance = mazeNodes.length+1; // } // // public Node getOtherEnd(Node node) { // if (node == n1) return n2; // if (node == n2) return n1; // return null; // } // // public void debugDrawLink(Game game, Color linkColor, Color nodeColor, boolean drawDistance) { // GameView.addLines(game, linkColor, n1.index, mazeNodes[0].index); // int i = 0; // int step = 4; // for (i = step; i < mazeNodes.length-1; i += step) { // GameView.addLines(game, linkColor, mazeNodes[i-step].index, mazeNodes[i].index); // } // if (i >= mazeNodes.length) { // GameView.addLines(game, linkColor, mazeNodes[i-step].index, mazeNodes[mazeNodes.length-1].index); // } // GameView.addLines(game, linkColor, mazeNodes[mazeNodes.length-1].index, n2.index); // if (drawDistance) { // GameView.addText(game, mazeNodes[mazeNodes.length/2].index, Color.YELLOW, String.valueOf(distance)); // } // GameView.addPoints(game, nodeColor, n1.index, n2.index); // } // // } // // Path: Exercises/E4/src/game/controllers/pacman/exercises/e4/graph/Node.java // public class Node { // // /** // * Unique index of the node. // */ // public final int index; // // /** // * Type of sub-node within the Pac-Man maze. // */ // public final NodeType type; // // /** // * Direction -> Link // * // * Node that link is never stored for {@link Direction#NONE}. // */ // public Map<Direction, Link> links = new HashMap<Direction, Link>(); // // public Node(int index, NodeType type) { // this.index = index; // this.type = type; // } // // public Node(MazeNode node) { // this.index = node.index; // this.type = node.nodeType(); // } // // @Override // public String toString() { // return "Node[index=" + index + ",type=" + type + "]"; // } // // } // Path: Exercises/E4/src/game/controllers/pacman/exercises/e4/path/Path.java import java.util.Collection; import game.controllers.pacman.exercises.e4.graph.Link; import game.controllers.pacman.exercises.e4.graph.Node; package game.controllers.pacman.exercises.e4.path; public class Path { public Node[] path; public Path(Node... path) { this.path = path; } public Path(Collection<Node> path) { this.path = path.toArray(new Node[path.size()]); } public void reverse() { Node[] pathReverse = new Node[path.length]; for (int i = path.length - 1; i >= 0; --i) { pathReverse[path.length - 1 - i] = path[i]; } this.path = pathReverse; } public int computeCost() { int result = 0; for (int i = 1; i < path.length; ++i) { Node n1 = path[i-1]; Node n2 = path[i];
for (Link link : n1.links.values()) {
kefik/MsPacMan-vs-Ghosts-AI
PacMan-vs-Ghosts/src/game/core/_G_.java
// Path: PacMan-vs-Ghosts/src/game/PacManSimulator.java // public static class GameConfig { // // public int seed = -1; // // /** // * Whether POWER PILLS should be present within the environment. // */ // public boolean powerPillsEnabled = true; // // /** // * Total percentage of PILLS present within the level. If < 1, some (random) pills will be taken away. // */ // public double totalPills = 1; // // /** // * How many levels Ms PacMan may play (-1 => unbound). // */ // public int levelsToPlay = -1; // // public GameConfig clone() { // GameConfig result = new GameConfig(); // // result.seed = seed; // result.powerPillsEnabled = powerPillsEnabled; // result.totalPills = totalPills; // result.levelsToPlay = levelsToPlay; // // return result; // } // // public String asString() { // return "" + seed + ";" + powerPillsEnabled + ";" + totalPills + ";" + levelsToPlay; // } // // public void fromString(String line) { // String[] all = line.split(";"); // seed = Integer.parseInt(all[0]); // powerPillsEnabled = Boolean.parseBoolean(all[1]); // totalPills = Double.parseDouble(all[2]); // levelsToPlay = Integer.parseInt(all[3]); // } // // public String getCSVHeader() { // return "seed;powerPillsEnabled;totalPills;levelsToPlay"; // } // // public String getCSV() { // return "" + seed + ";" + powerPillsEnabled + ";" + totalPills + ";" + levelsToPlay; // } // // } // // Path: PacMan-vs-Ghosts/src/game/controllers/Direction.java // public enum Direction { // // NONE(-1, 0, 0), UP(Game.UP, 0, -1), RIGHT(Game.RIGHT, 1, 0), DOWN(Game.DOWN, 0, 1), LEFT(Game.LEFT, -1, 0); // // private static Direction[] arrows = new Direction[]{UP, RIGHT, DOWN, LEFT}; // // private static List<Direction> arrowsList = null; // // private static Map<Integer, Direction> indices = null; // // public final int index; // public final int dX; // public final int dY; // // private Direction(int directionIndex, int dX, int dY) { // this.index = directionIndex; // this.dX = dX; // this.dY = dY; // } // // public Direction opposite() { // switch(this) { // case NONE: return NONE; // case DOWN: return UP; // case LEFT: return RIGHT; // case RIGHT: return LEFT; // case UP: return DOWN; // } // return null; // } // // public Direction cw() { // switch(this) { // case NONE: return NONE; // case DOWN: return LEFT; // case LEFT: return UP; // case RIGHT: return DOWN; // case UP: return RIGHT; // } // return null; // } // // public Direction ccw() { // switch(this) { // case NONE: return NONE; // case DOWN: return RIGHT; // case LEFT: return DOWN; // case RIGHT: return UP; // case UP: return LEFT; // } // return null; // } // // public static Direction forIndex(int directionIndex) { // if (indices == null) { // indices = new HashMap<Integer, Direction>(); // for (Direction dir : values()) { // indices.put(dir.index, dir); // } // } // Direction dir = indices.get(directionIndex); // if (dir == null) return NONE; // return dir; // } // // /** // * UP, RIGHT, DOWN, LEFT // * @return // */ // public static Direction[] arrows() { // return arrows; // } // // /** // * UP, RIGHT, DOWN, LEFT // * @return // */ // public static List<Direction> arrowsList() { // if (arrowsList == null) { // arrowsList = new ArrayList<Direction>(4); // for (Direction d : arrows) { // arrowsList.add(d); // } // } // return arrowsList; // } // // // }
import game.PacManSimulator.GameConfig; import game.controllers.Direction; import java.util.ArrayList; import java.util.BitSet; import java.util.HashSet; import java.util.List; import java.util.Set;
/* * Implementation of "Ms Pac-Man" for the "Ms Pac-Man versus Ghost Team Competition", brought * to you by Philipp Rohlfshagen, David Robles and Simon Lucas of the University of Essex. * * www.pacman-vs-ghosts.net * * Code written by Philipp Rohlfshagen, based on earlier implementations of the game by * Simon Lucas and David Robles. * * You may use and distribute this code freely for non-commercial purposes. This notice * needs to be included in all distributions. Deviations from the original should be * clearly documented. We welcome any comments and suggestions regarding the code. */ package game.core; public class _G_ extends G { public static final int EDIBLE_ALERT=30; //for display only (ghosts turning blue) //to save replays private int pacManDir=G.INITIAL_PAC_DIR; private StringBuilder sb; public _G_(){} //Instantiates everything to start a new game
// Path: PacMan-vs-Ghosts/src/game/PacManSimulator.java // public static class GameConfig { // // public int seed = -1; // // /** // * Whether POWER PILLS should be present within the environment. // */ // public boolean powerPillsEnabled = true; // // /** // * Total percentage of PILLS present within the level. If < 1, some (random) pills will be taken away. // */ // public double totalPills = 1; // // /** // * How many levels Ms PacMan may play (-1 => unbound). // */ // public int levelsToPlay = -1; // // public GameConfig clone() { // GameConfig result = new GameConfig(); // // result.seed = seed; // result.powerPillsEnabled = powerPillsEnabled; // result.totalPills = totalPills; // result.levelsToPlay = levelsToPlay; // // return result; // } // // public String asString() { // return "" + seed + ";" + powerPillsEnabled + ";" + totalPills + ";" + levelsToPlay; // } // // public void fromString(String line) { // String[] all = line.split(";"); // seed = Integer.parseInt(all[0]); // powerPillsEnabled = Boolean.parseBoolean(all[1]); // totalPills = Double.parseDouble(all[2]); // levelsToPlay = Integer.parseInt(all[3]); // } // // public String getCSVHeader() { // return "seed;powerPillsEnabled;totalPills;levelsToPlay"; // } // // public String getCSV() { // return "" + seed + ";" + powerPillsEnabled + ";" + totalPills + ";" + levelsToPlay; // } // // } // // Path: PacMan-vs-Ghosts/src/game/controllers/Direction.java // public enum Direction { // // NONE(-1, 0, 0), UP(Game.UP, 0, -1), RIGHT(Game.RIGHT, 1, 0), DOWN(Game.DOWN, 0, 1), LEFT(Game.LEFT, -1, 0); // // private static Direction[] arrows = new Direction[]{UP, RIGHT, DOWN, LEFT}; // // private static List<Direction> arrowsList = null; // // private static Map<Integer, Direction> indices = null; // // public final int index; // public final int dX; // public final int dY; // // private Direction(int directionIndex, int dX, int dY) { // this.index = directionIndex; // this.dX = dX; // this.dY = dY; // } // // public Direction opposite() { // switch(this) { // case NONE: return NONE; // case DOWN: return UP; // case LEFT: return RIGHT; // case RIGHT: return LEFT; // case UP: return DOWN; // } // return null; // } // // public Direction cw() { // switch(this) { // case NONE: return NONE; // case DOWN: return LEFT; // case LEFT: return UP; // case RIGHT: return DOWN; // case UP: return RIGHT; // } // return null; // } // // public Direction ccw() { // switch(this) { // case NONE: return NONE; // case DOWN: return RIGHT; // case LEFT: return DOWN; // case RIGHT: return UP; // case UP: return LEFT; // } // return null; // } // // public static Direction forIndex(int directionIndex) { // if (indices == null) { // indices = new HashMap<Integer, Direction>(); // for (Direction dir : values()) { // indices.put(dir.index, dir); // } // } // Direction dir = indices.get(directionIndex); // if (dir == null) return NONE; // return dir; // } // // /** // * UP, RIGHT, DOWN, LEFT // * @return // */ // public static Direction[] arrows() { // return arrows; // } // // /** // * UP, RIGHT, DOWN, LEFT // * @return // */ // public static List<Direction> arrowsList() { // if (arrowsList == null) { // arrowsList = new ArrayList<Direction>(4); // for (Direction d : arrows) { // arrowsList.add(d); // } // } // return arrowsList; // } // // // } // Path: PacMan-vs-Ghosts/src/game/core/_G_.java import game.PacManSimulator.GameConfig; import game.controllers.Direction; import java.util.ArrayList; import java.util.BitSet; import java.util.HashSet; import java.util.List; import java.util.Set; /* * Implementation of "Ms Pac-Man" for the "Ms Pac-Man versus Ghost Team Competition", brought * to you by Philipp Rohlfshagen, David Robles and Simon Lucas of the University of Essex. * * www.pacman-vs-ghosts.net * * Code written by Philipp Rohlfshagen, based on earlier implementations of the game by * Simon Lucas and David Robles. * * You may use and distribute this code freely for non-commercial purposes. This notice * needs to be included in all distributions. Deviations from the original should be * clearly documented. We welcome any comments and suggestions regarding the code. */ package game.core; public class _G_ extends G { public static final int EDIBLE_ALERT=30; //for display only (ghosts turning blue) //to save replays private int pacManDir=G.INITIAL_PAC_DIR; private StringBuilder sb; public _G_(){} //Instantiates everything to start a new game
public void newGame(GameConfig config)
kefik/MsPacMan-vs-Ghosts-AI
PacMan-vs-Ghosts/src/game/core/_RG_.java
// Path: PacMan-vs-Ghosts/src/game/controllers/ghosts/GhostsActions.java // public final class GhostsActions { // // private static GhostAction NONE; // // public GhostAction[] actions = new GhostAction[4]; // // public final int ghostCount; // // public boolean pauseSimulation; // public boolean nextFrame; // // public GhostsActions(int ghostCount) { // this.ghostCount = ghostCount; // for (int i = 0; i < actions.length; ++i) { // actions[i] = new GhostAction(); // } // } // // public GhostAction ghost(int index) { // if (index < 0 || index > actions.length) return NONE; // return actions[index]; // } // // public void set(int[] directions) { // for (int i = 0; i < directions.length && i < actions.length; ++i) { // actions[i].set(directions[i]); // } // } // // public GhostAction blinky() { // return actions[GhostType.BLINKY.index]; // } // // public GhostAction pinky() { // return actions[GhostType.PINKY.index]; // } // // public GhostAction clyde() { // return actions[GhostType.CLYDE.index]; // } // // public GhostAction inky() { // return actions[GhostType.INKY.index]; // } // // public void pause() { // pauseSimulation = true; // } // // public void resume() { // pauseSimulation = false; // } // // public void togglePause() { // pauseSimulation = !pauseSimulation; // } // // public void reset() { // for (int i = 0; i < actions.length; ++i) { // actions[i].reset(); // } // pauseSimulation = false; // nextFrame = false; // } // // public GhostsActions clone() { // GhostsActions result = new GhostsActions(ghostCount); // // for (int i = 0; i < actions.length; ++i) { // result.actions[i] = actions[i].clone(); // } // result.pauseSimulation = pauseSimulation; // result.nextFrame = nextFrame; // // return result; // } // // // // }
import java.util.Arrays; import game.controllers.ghosts.GhostsActions;
package game.core; /** * This class is to replay games that were recorded using Replay. The only differences are: * 1. Ghost reversals are removed * 2. Directions are not checked (since they are necessarily valid) * This class should only be used in conjunction with stored directions, not to play the game itself. */ public final class _RG_ extends _G_ { //Updates the locations of the ghosts without reversals
// Path: PacMan-vs-Ghosts/src/game/controllers/ghosts/GhostsActions.java // public final class GhostsActions { // // private static GhostAction NONE; // // public GhostAction[] actions = new GhostAction[4]; // // public final int ghostCount; // // public boolean pauseSimulation; // public boolean nextFrame; // // public GhostsActions(int ghostCount) { // this.ghostCount = ghostCount; // for (int i = 0; i < actions.length; ++i) { // actions[i] = new GhostAction(); // } // } // // public GhostAction ghost(int index) { // if (index < 0 || index > actions.length) return NONE; // return actions[index]; // } // // public void set(int[] directions) { // for (int i = 0; i < directions.length && i < actions.length; ++i) { // actions[i].set(directions[i]); // } // } // // public GhostAction blinky() { // return actions[GhostType.BLINKY.index]; // } // // public GhostAction pinky() { // return actions[GhostType.PINKY.index]; // } // // public GhostAction clyde() { // return actions[GhostType.CLYDE.index]; // } // // public GhostAction inky() { // return actions[GhostType.INKY.index]; // } // // public void pause() { // pauseSimulation = true; // } // // public void resume() { // pauseSimulation = false; // } // // public void togglePause() { // pauseSimulation = !pauseSimulation; // } // // public void reset() { // for (int i = 0; i < actions.length; ++i) { // actions[i].reset(); // } // pauseSimulation = false; // nextFrame = false; // } // // public GhostsActions clone() { // GhostsActions result = new GhostsActions(ghostCount); // // for (int i = 0; i < actions.length; ++i) { // result.actions[i] = actions[i].clone(); // } // result.pauseSimulation = pauseSimulation; // result.nextFrame = nextFrame; // // return result; // } // // // // } // Path: PacMan-vs-Ghosts/src/game/core/_RG_.java import java.util.Arrays; import game.controllers.ghosts.GhostsActions; package game.core; /** * This class is to replay games that were recorded using Replay. The only differences are: * 1. Ghost reversals are removed * 2. Directions are not checked (since they are necessarily valid) * This class should only be used in conjunction with stored directions, not to play the game itself. */ public final class _RG_ extends _G_ { //Updates the locations of the ghosts without reversals
protected void updateGhosts(GhostsActions ghosts, boolean reverse)
HiveKa/HiveKa
src/main/java/org/apache/hadoop/hive/kafka/camus/KafkaAvroMessageDecoder.java
// Path: src/main/java/org/apache/hadoop/hive/kafka/AvroSchemaGenerator.java // public class AvroSchemaGenerator { // private TypeInfoToSchema typeInfoToSchema; // // public AvroSchemaGenerator() { // this.typeInfoToSchema = new TypeInfoToSchema(); // } // // public Schema getSchema(String columnNamesStr, String columnTypesStr, // String columnCommentsStr, String namespace, String name, // String doc) { // List<String> columnNames = Arrays.asList(columnNamesStr.split(",")); // List<TypeInfo> columnTypes = TypeInfoUtils.getTypeInfosFromTypeString(columnTypesStr); // List<String> columnComments; // if (columnCommentsStr.isEmpty()) { // columnComments = new ArrayList<String>(); // } else { // columnComments = Arrays.asList(columnCommentsStr.split(",")); // } // // return typeInfoToSchema.convert(columnNames, columnTypes, columnComments, namespace, name, doc); // } // } // // Path: src/main/java/org/apache/hadoop/hive/kafka/KafkaBackedTableProperties.java // public class KafkaBackedTableProperties { // private static final Logger LOG = Logger.getLogger(KafkaBackedTableProperties.class); // public static final String KAFKA_URI = "kafka.service.uri"; // public static final String KAFKA_URL = "kafka.service.url"; // public static final String KAFKA_PORT = "kafka.service.port"; // public static final String KAFKA_WHITELIST_TOPICS = "kafka.whitelist.topics"; // public static final String KAFKA_AVRO_SCHEMA_FILE = "kafka.avro.schema.file"; // public static final String COLUMN_NAMES = "columns"; // public static final String COLUMN_TYPES = "columns.types"; // public static final String COLUMN_COMMENTS = "columns.comments"; // // /* // * This method initializes properties of the external table and populates // * the jobProperties map with them so that they can be used throughout the job. // */ // public void initialize(Properties tableProperties, Map<String,String> jobProperties, // TableDesc tableDesc) { // // // Set kafka.whitelist.topics in the jobProperty // String kafkaWhitelistTopics = tableProperties.getProperty(KAFKA_WHITELIST_TOPICS); // LOG.debug("Kafka whitelist topics : " + kafkaWhitelistTopics); // jobProperties.put(KAFKA_WHITELIST_TOPICS, kafkaWhitelistTopics); // // // Set kafka.avro.schema.file in the jobProperty // String kafkaAvroSchemaFile = tableProperties.getProperty(KAFKA_AVRO_SCHEMA_FILE, null); // if (kafkaAvroSchemaFile != null) { // LOG.debug("Kafka avro schema file : " + kafkaAvroSchemaFile); // jobProperties.put(KAFKA_AVRO_SCHEMA_FILE, kafkaAvroSchemaFile); // } // // // Set kafka.url and kafka.port in the jobProperty // String kafkaUri = tableProperties.getProperty(KAFKA_URI); // LOG.debug("Kafka URI : " + kafkaUri); // jobProperties.put(KAFKA_URI, kafkaUri); // final String[] uriSplits = kafkaUri.split(":"); // String kafkaUrl = uriSplits[0]; // String kafkaPort = uriSplits[1]; // LOG.debug("Kafka URL : " + kafkaUrl); // jobProperties.put(KAFKA_URL, kafkaUrl); // LOG.debug("Kafka PORT : " + kafkaPort); // jobProperties.put(KAFKA_PORT, kafkaPort); // // // Set column names in the jobProperty // String columnNames = tableProperties.getProperty(COLUMN_NAMES); // LOG.debug("Column Names : " + columnNames); // jobProperties.put(COLUMN_NAMES, columnNames); // // // Set column types in the jobProperty // String columnTypes = tableProperties.getProperty(COLUMN_TYPES); // LOG.debug("Column Types : " + columnTypes); // jobProperties.put(COLUMN_TYPES, columnTypes); // // // Set column types in the jobProperty // String columnComments = tableProperties.getProperty(COLUMN_COMMENTS); // LOG.debug("Column Comments : " + columnComments); // jobProperties.put(COLUMN_COMMENTS, columnComments); // } // }
import org.apache.avro.Schema; import org.apache.avro.generic.GenericData.Record; import org.apache.avro.generic.GenericDatumReader; import org.apache.avro.generic.GenericRecord; import org.apache.avro.io.DatumReader; import org.apache.avro.io.DecoderFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hive.kafka.AvroSchemaGenerator; import org.apache.hadoop.hive.kafka.KafkaBackedTableProperties; import org.apache.hadoop.hive.serde2.avro.AvroGenericRecordWritable; import org.apache.hadoop.io.Text; import org.apache.log4j.Logger; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.nio.ByteBuffer; import java.util.Properties;
package org.apache.hadoop.hive.kafka.camus; public class KafkaAvroMessageDecoder extends MessageDecoder<byte[], Record> { protected DecoderFactory decoderFactory; protected SchemaRegistry<Schema> registry; private Schema latestSchema; private static Logger log = null; @Override public void init(Properties props, String topicName) { super.init(props, topicName); if (log == null) { log = Logger.getLogger(getClass()); } try { SchemaRegistry<Schema> registry = (SchemaRegistry<Schema>) Class .forName("org.apache.hadoop.hive.kafka.camus" + ".MemorySchemaRegistry").newInstance(); registry.init(props); this.registry = new CachedSchemaRegistry<Schema>(registry); Schema.Parser parser = new Schema.Parser(); Schema schema;
// Path: src/main/java/org/apache/hadoop/hive/kafka/AvroSchemaGenerator.java // public class AvroSchemaGenerator { // private TypeInfoToSchema typeInfoToSchema; // // public AvroSchemaGenerator() { // this.typeInfoToSchema = new TypeInfoToSchema(); // } // // public Schema getSchema(String columnNamesStr, String columnTypesStr, // String columnCommentsStr, String namespace, String name, // String doc) { // List<String> columnNames = Arrays.asList(columnNamesStr.split(",")); // List<TypeInfo> columnTypes = TypeInfoUtils.getTypeInfosFromTypeString(columnTypesStr); // List<String> columnComments; // if (columnCommentsStr.isEmpty()) { // columnComments = new ArrayList<String>(); // } else { // columnComments = Arrays.asList(columnCommentsStr.split(",")); // } // // return typeInfoToSchema.convert(columnNames, columnTypes, columnComments, namespace, name, doc); // } // } // // Path: src/main/java/org/apache/hadoop/hive/kafka/KafkaBackedTableProperties.java // public class KafkaBackedTableProperties { // private static final Logger LOG = Logger.getLogger(KafkaBackedTableProperties.class); // public static final String KAFKA_URI = "kafka.service.uri"; // public static final String KAFKA_URL = "kafka.service.url"; // public static final String KAFKA_PORT = "kafka.service.port"; // public static final String KAFKA_WHITELIST_TOPICS = "kafka.whitelist.topics"; // public static final String KAFKA_AVRO_SCHEMA_FILE = "kafka.avro.schema.file"; // public static final String COLUMN_NAMES = "columns"; // public static final String COLUMN_TYPES = "columns.types"; // public static final String COLUMN_COMMENTS = "columns.comments"; // // /* // * This method initializes properties of the external table and populates // * the jobProperties map with them so that they can be used throughout the job. // */ // public void initialize(Properties tableProperties, Map<String,String> jobProperties, // TableDesc tableDesc) { // // // Set kafka.whitelist.topics in the jobProperty // String kafkaWhitelistTopics = tableProperties.getProperty(KAFKA_WHITELIST_TOPICS); // LOG.debug("Kafka whitelist topics : " + kafkaWhitelistTopics); // jobProperties.put(KAFKA_WHITELIST_TOPICS, kafkaWhitelistTopics); // // // Set kafka.avro.schema.file in the jobProperty // String kafkaAvroSchemaFile = tableProperties.getProperty(KAFKA_AVRO_SCHEMA_FILE, null); // if (kafkaAvroSchemaFile != null) { // LOG.debug("Kafka avro schema file : " + kafkaAvroSchemaFile); // jobProperties.put(KAFKA_AVRO_SCHEMA_FILE, kafkaAvroSchemaFile); // } // // // Set kafka.url and kafka.port in the jobProperty // String kafkaUri = tableProperties.getProperty(KAFKA_URI); // LOG.debug("Kafka URI : " + kafkaUri); // jobProperties.put(KAFKA_URI, kafkaUri); // final String[] uriSplits = kafkaUri.split(":"); // String kafkaUrl = uriSplits[0]; // String kafkaPort = uriSplits[1]; // LOG.debug("Kafka URL : " + kafkaUrl); // jobProperties.put(KAFKA_URL, kafkaUrl); // LOG.debug("Kafka PORT : " + kafkaPort); // jobProperties.put(KAFKA_PORT, kafkaPort); // // // Set column names in the jobProperty // String columnNames = tableProperties.getProperty(COLUMN_NAMES); // LOG.debug("Column Names : " + columnNames); // jobProperties.put(COLUMN_NAMES, columnNames); // // // Set column types in the jobProperty // String columnTypes = tableProperties.getProperty(COLUMN_TYPES); // LOG.debug("Column Types : " + columnTypes); // jobProperties.put(COLUMN_TYPES, columnTypes); // // // Set column types in the jobProperty // String columnComments = tableProperties.getProperty(COLUMN_COMMENTS); // LOG.debug("Column Comments : " + columnComments); // jobProperties.put(COLUMN_COMMENTS, columnComments); // } // } // Path: src/main/java/org/apache/hadoop/hive/kafka/camus/KafkaAvroMessageDecoder.java import org.apache.avro.Schema; import org.apache.avro.generic.GenericData.Record; import org.apache.avro.generic.GenericDatumReader; import org.apache.avro.generic.GenericRecord; import org.apache.avro.io.DatumReader; import org.apache.avro.io.DecoderFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hive.kafka.AvroSchemaGenerator; import org.apache.hadoop.hive.kafka.KafkaBackedTableProperties; import org.apache.hadoop.hive.serde2.avro.AvroGenericRecordWritable; import org.apache.hadoop.io.Text; import org.apache.log4j.Logger; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.nio.ByteBuffer; import java.util.Properties; package org.apache.hadoop.hive.kafka.camus; public class KafkaAvroMessageDecoder extends MessageDecoder<byte[], Record> { protected DecoderFactory decoderFactory; protected SchemaRegistry<Schema> registry; private Schema latestSchema; private static Logger log = null; @Override public void init(Properties props, String topicName) { super.init(props, topicName); if (log == null) { log = Logger.getLogger(getClass()); } try { SchemaRegistry<Schema> registry = (SchemaRegistry<Schema>) Class .forName("org.apache.hadoop.hive.kafka.camus" + ".MemorySchemaRegistry").newInstance(); registry.init(props); this.registry = new CachedSchemaRegistry<Schema>(registry); Schema.Parser parser = new Schema.Parser(); Schema schema;
final String schemaFile = props.getProperty(KafkaBackedTableProperties
davidmoten/rxjava2-extras
src/main/java/com/github/davidmoten/rx2/Bytes.java
// Path: src/main/java/com/github/davidmoten/rx2/util/ZippedEntry.java // public final class ZippedEntry { // // final String name; // entry name // final long time; // last modification time // // final FileTime mtime; // last modification time, from extra field data // // final FileTime atime; // last access time, from extra field data // // final FileTime ctime; // creation time, from extra field data // final long crc; // crc-32 of entry data // final long size; // uncompressed size of entry data // final long csize; // compressed size of entry data // final int method; // compression method // final byte[] extra; // optional extra field data for entry // final String comment; // optional comment string for entry // private final InputStream is; // // public ZippedEntry(ZipEntry e, InputStream is) { // this.name = e.getName(); // this.time = e.getTime(); // // this.mtime = e.getLastModifiedTime(); // // this.atime = e.getLastAccessTime(); // // this.ctime = e.getCreationTime(); // this.crc = e.getCrc(); // this.size = e.getSize(); // this.csize = e.getCompressedSize(); // this.method = e.getMethod(); // this.extra = e.getExtra(); // this.comment = e.getComment(); // this.is = is; // } // // public InputStream getInputStream() { // return is; // } // // public String getName() { // return name; // } // // public long getTime() { // return time; // } // // // public FileTime getLastModifiedTime() { // // return mtime; // // } // // // public FileTime getLastAccessTime() { // // return atime; // // } // // // public FileTime getCreatedtime() { // // return ctime; // // } // // public long getCrc() { // return crc; // } // // public long getSize() { // return size; // } // // public long getCompressedSize() { // return csize; // } // // public int getMethod() { // return method; // } // // public byte[] getExtra() { // return extra; // } // // public String getComment() { // return comment; // } // // }
import java.io.BufferedInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.concurrent.Callable; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import com.github.davidmoten.rx2.util.ZippedEntry; import io.reactivex.Emitter; import io.reactivex.Flowable; import io.reactivex.Single; import io.reactivex.functions.BiConsumer; import io.reactivex.functions.Consumer; import io.reactivex.functions.Function;
public Flowable<byte[]> apply(InputStream is) { return from(is, size); } }; return Flowable.using(resourceFactory, observableFactory, InputStreamCloseHolder.INSTANCE, true); } private static final class InputStreamCloseHolder { static final Consumer<InputStream> INSTANCE = new Consumer<InputStream>() { @Override public void accept(InputStream is) throws IOException { is.close(); } }; } /** * Returns a Flowable stream of byte arrays from the given * {@link InputStream} of {@code 8192} bytes. The final byte array may be * less than {@code 8192} bytes. * * @param is * input stream of bytes * @return a stream of byte arrays */ public static Flowable<byte[]> from(InputStream is) { return from(is, DEFAULT_BUFFER_SIZE); }
// Path: src/main/java/com/github/davidmoten/rx2/util/ZippedEntry.java // public final class ZippedEntry { // // final String name; // entry name // final long time; // last modification time // // final FileTime mtime; // last modification time, from extra field data // // final FileTime atime; // last access time, from extra field data // // final FileTime ctime; // creation time, from extra field data // final long crc; // crc-32 of entry data // final long size; // uncompressed size of entry data // final long csize; // compressed size of entry data // final int method; // compression method // final byte[] extra; // optional extra field data for entry // final String comment; // optional comment string for entry // private final InputStream is; // // public ZippedEntry(ZipEntry e, InputStream is) { // this.name = e.getName(); // this.time = e.getTime(); // // this.mtime = e.getLastModifiedTime(); // // this.atime = e.getLastAccessTime(); // // this.ctime = e.getCreationTime(); // this.crc = e.getCrc(); // this.size = e.getSize(); // this.csize = e.getCompressedSize(); // this.method = e.getMethod(); // this.extra = e.getExtra(); // this.comment = e.getComment(); // this.is = is; // } // // public InputStream getInputStream() { // return is; // } // // public String getName() { // return name; // } // // public long getTime() { // return time; // } // // // public FileTime getLastModifiedTime() { // // return mtime; // // } // // // public FileTime getLastAccessTime() { // // return atime; // // } // // // public FileTime getCreatedtime() { // // return ctime; // // } // // public long getCrc() { // return crc; // } // // public long getSize() { // return size; // } // // public long getCompressedSize() { // return csize; // } // // public int getMethod() { // return method; // } // // public byte[] getExtra() { // return extra; // } // // public String getComment() { // return comment; // } // // } // Path: src/main/java/com/github/davidmoten/rx2/Bytes.java import java.io.BufferedInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.concurrent.Callable; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import com.github.davidmoten.rx2.util.ZippedEntry; import io.reactivex.Emitter; import io.reactivex.Flowable; import io.reactivex.Single; import io.reactivex.functions.BiConsumer; import io.reactivex.functions.Consumer; import io.reactivex.functions.Function; public Flowable<byte[]> apply(InputStream is) { return from(is, size); } }; return Flowable.using(resourceFactory, observableFactory, InputStreamCloseHolder.INSTANCE, true); } private static final class InputStreamCloseHolder { static final Consumer<InputStream> INSTANCE = new Consumer<InputStream>() { @Override public void accept(InputStream is) throws IOException { is.close(); } }; } /** * Returns a Flowable stream of byte arrays from the given * {@link InputStream} of {@code 8192} bytes. The final byte array may be * less than {@code 8192} bytes. * * @param is * input stream of bytes * @return a stream of byte arrays */ public static Flowable<byte[]> from(InputStream is) { return from(is, DEFAULT_BUFFER_SIZE); }
public static Flowable<ZippedEntry> unzip(final File file) {
davidmoten/rxjava2-extras
src/main/java/com/github/davidmoten/rx2/IO.java
// Path: src/main/java/com/github/davidmoten/rx2/internal/flowable/FlowableServerSocket.java // public final class FlowableServerSocket { // // private FlowableServerSocket() { // // prevent instantiation // } // // public static Flowable<Flowable<byte[]>> create(final Callable<? extends ServerSocket> serverSocketFactory, // final int timeoutMs, final int bufferSize, Action preAcceptAction, int acceptTimeoutMs, // Predicate<? super Socket> acceptSocket) { // Function<ServerSocket, Flowable<Flowable<byte[]>>> FlowableFactory = createFlowableFactory(timeoutMs, // bufferSize, preAcceptAction, acceptSocket); // return Flowable.<Flowable<byte[]>, ServerSocket>using( // // createServerSocketFactory(serverSocketFactory, acceptTimeoutMs), // // FlowableFactory, // // new Consumer<ServerSocket>() { // // Note that in java 1.6, ServerSocket does not implement // // Closeable // @Override // public void accept(ServerSocket ss) throws Exception { // ss.close(); // } // }, // // true); // } // // private static Callable<ServerSocket> createServerSocketFactory( // final Callable<? extends ServerSocket> serverSocketFactory, final int acceptTimeoutMs) { // return new Callable<ServerSocket>() { // @Override // public ServerSocket call() throws Exception { // return createServerSocket(serverSocketFactory, acceptTimeoutMs); // } // }; // } // // private static ServerSocket createServerSocket(Callable<? extends ServerSocket> serverSocketCreator, long timeoutMs) // throws Exception { // ServerSocket s = serverSocketCreator.call(); // s.setSoTimeout((int) timeoutMs); // return s; // } // // private static Function<ServerSocket, Flowable<Flowable<byte[]>>> createFlowableFactory(final int timeoutMs, // final int bufferSize, final Action preAcceptAction, final Predicate<? super Socket> acceptSocket) { // return new Function<ServerSocket, Flowable<Flowable<byte[]>>>() { // @Override // public Flowable<Flowable<byte[]>> apply(ServerSocket serverSocket) { // return createServerSocketFlowable(serverSocket, timeoutMs, bufferSize, preAcceptAction, acceptSocket); // } // }; // } // // private static Flowable<Flowable<byte[]>> createServerSocketFlowable(final ServerSocket serverSocket, // final long timeoutMs, final int bufferSize, final Action preAcceptAction, // final Predicate<? super Socket> acceptSocket) { // return Flowable.generate( // // new Consumer<Emitter<Flowable<byte[]>>>() { // @Override // public void accept(Emitter<Flowable<byte[]>> emitter) throws Exception { // acceptConnection(timeoutMs, bufferSize, serverSocket, emitter, preAcceptAction, acceptSocket); // } // }); // } // // private static void acceptConnection(long timeoutMs, int bufferSize, ServerSocket ss, // Emitter<Flowable<byte[]>> emitter, Action preAcceptAction, Predicate<? super Socket> acceptSocket) { // Socket socket; // while (true) { // try { // preAcceptAction.run(); // socket = ss.accept(); // if (!acceptSocket.test(socket)) { // closeQuietly(socket); // } else { // emitter.onNext(createSocketFlowable(socket, timeoutMs, bufferSize)); // break; // } // } catch (SocketTimeoutException e) { // // timed out so will loop around again // } catch (Throwable e) { // // if the server socket has been closed then this is most likely // // an unsubscribe so we don't try to report an error which would // // just end up in RxJavaPlugins.onError as a stack trace in the // // console. // if (e instanceof SocketException && ("Socket closed".equals(e.getMessage()) // || "Socket operation on nonsocket: configureBlocking".equals(e.getMessage()))) { // break; // } else { // // unknown problem // emitter.onError(e); // break; // } // } // } // } // // @VisibleForTesting // static void closeQuietly(Socket socket) { // try { // socket.close(); // } catch (IOException e) { // // ignore exception // } // } // // private static Flowable<byte[]> createSocketFlowable(final Socket socket, long timeoutMs, final int bufferSize) { // setTimeout(socket, timeoutMs); // return Flowable.using( // // new Callable<InputStream>() { // @Override // public InputStream call() throws Exception { // return socket.getInputStream(); // } // }, // // new Function<InputStream, Flowable<byte[]>>() { // @Override // public Flowable<byte[]> apply(InputStream is) { // return Bytes.from(is, bufferSize); // } // }, // // Consumers.close(), // // true); // } // // private static void setTimeout(Socket socket, long timeoutMs) { // try { // socket.setSoTimeout((int) timeoutMs); // } catch (SocketException e) { // throw new RuntimeException(e); // } // } // // }
import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.util.concurrent.Callable; import com.github.davidmoten.rx2.internal.flowable.FlowableServerSocket; import io.reactivex.Flowable; import io.reactivex.functions.Action; import io.reactivex.functions.Consumer; import io.reactivex.functions.Predicate; import io.reactivex.internal.functions.Functions;
public ServerSocketBuilder(final Callable<? extends ServerSocket> serverSocketFactory) { this.serverSocketFactory = serverSocketFactory; } public ServerSocketBuilder readTimeoutMs(int readTimeoutMs) { this.readTimeoutMs = readTimeoutMs; return this; } public ServerSocketBuilder bufferSize(int bufferSize) { this.bufferSize = bufferSize; return this; } public ServerSocketBuilder preAcceptAction(Action action) { this.preAcceptAction = action; return this; } public ServerSocketBuilder acceptTimeoutMs(int acceptTimeoutMs) { this.acceptTimeoutMs = acceptTimeoutMs; return this; } public ServerSocketBuilder acceptSocketIf(Predicate<? super Socket> acceptSocket) { this.acceptSocket = acceptSocket; return this; } public Flowable<Flowable<byte[]>> create() {
// Path: src/main/java/com/github/davidmoten/rx2/internal/flowable/FlowableServerSocket.java // public final class FlowableServerSocket { // // private FlowableServerSocket() { // // prevent instantiation // } // // public static Flowable<Flowable<byte[]>> create(final Callable<? extends ServerSocket> serverSocketFactory, // final int timeoutMs, final int bufferSize, Action preAcceptAction, int acceptTimeoutMs, // Predicate<? super Socket> acceptSocket) { // Function<ServerSocket, Flowable<Flowable<byte[]>>> FlowableFactory = createFlowableFactory(timeoutMs, // bufferSize, preAcceptAction, acceptSocket); // return Flowable.<Flowable<byte[]>, ServerSocket>using( // // createServerSocketFactory(serverSocketFactory, acceptTimeoutMs), // // FlowableFactory, // // new Consumer<ServerSocket>() { // // Note that in java 1.6, ServerSocket does not implement // // Closeable // @Override // public void accept(ServerSocket ss) throws Exception { // ss.close(); // } // }, // // true); // } // // private static Callable<ServerSocket> createServerSocketFactory( // final Callable<? extends ServerSocket> serverSocketFactory, final int acceptTimeoutMs) { // return new Callable<ServerSocket>() { // @Override // public ServerSocket call() throws Exception { // return createServerSocket(serverSocketFactory, acceptTimeoutMs); // } // }; // } // // private static ServerSocket createServerSocket(Callable<? extends ServerSocket> serverSocketCreator, long timeoutMs) // throws Exception { // ServerSocket s = serverSocketCreator.call(); // s.setSoTimeout((int) timeoutMs); // return s; // } // // private static Function<ServerSocket, Flowable<Flowable<byte[]>>> createFlowableFactory(final int timeoutMs, // final int bufferSize, final Action preAcceptAction, final Predicate<? super Socket> acceptSocket) { // return new Function<ServerSocket, Flowable<Flowable<byte[]>>>() { // @Override // public Flowable<Flowable<byte[]>> apply(ServerSocket serverSocket) { // return createServerSocketFlowable(serverSocket, timeoutMs, bufferSize, preAcceptAction, acceptSocket); // } // }; // } // // private static Flowable<Flowable<byte[]>> createServerSocketFlowable(final ServerSocket serverSocket, // final long timeoutMs, final int bufferSize, final Action preAcceptAction, // final Predicate<? super Socket> acceptSocket) { // return Flowable.generate( // // new Consumer<Emitter<Flowable<byte[]>>>() { // @Override // public void accept(Emitter<Flowable<byte[]>> emitter) throws Exception { // acceptConnection(timeoutMs, bufferSize, serverSocket, emitter, preAcceptAction, acceptSocket); // } // }); // } // // private static void acceptConnection(long timeoutMs, int bufferSize, ServerSocket ss, // Emitter<Flowable<byte[]>> emitter, Action preAcceptAction, Predicate<? super Socket> acceptSocket) { // Socket socket; // while (true) { // try { // preAcceptAction.run(); // socket = ss.accept(); // if (!acceptSocket.test(socket)) { // closeQuietly(socket); // } else { // emitter.onNext(createSocketFlowable(socket, timeoutMs, bufferSize)); // break; // } // } catch (SocketTimeoutException e) { // // timed out so will loop around again // } catch (Throwable e) { // // if the server socket has been closed then this is most likely // // an unsubscribe so we don't try to report an error which would // // just end up in RxJavaPlugins.onError as a stack trace in the // // console. // if (e instanceof SocketException && ("Socket closed".equals(e.getMessage()) // || "Socket operation on nonsocket: configureBlocking".equals(e.getMessage()))) { // break; // } else { // // unknown problem // emitter.onError(e); // break; // } // } // } // } // // @VisibleForTesting // static void closeQuietly(Socket socket) { // try { // socket.close(); // } catch (IOException e) { // // ignore exception // } // } // // private static Flowable<byte[]> createSocketFlowable(final Socket socket, long timeoutMs, final int bufferSize) { // setTimeout(socket, timeoutMs); // return Flowable.using( // // new Callable<InputStream>() { // @Override // public InputStream call() throws Exception { // return socket.getInputStream(); // } // }, // // new Function<InputStream, Flowable<byte[]>>() { // @Override // public Flowable<byte[]> apply(InputStream is) { // return Bytes.from(is, bufferSize); // } // }, // // Consumers.close(), // // true); // } // // private static void setTimeout(Socket socket, long timeoutMs) { // try { // socket.setSoTimeout((int) timeoutMs); // } catch (SocketException e) { // throw new RuntimeException(e); // } // } // // } // Path: src/main/java/com/github/davidmoten/rx2/IO.java import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.util.concurrent.Callable; import com.github.davidmoten.rx2.internal.flowable.FlowableServerSocket; import io.reactivex.Flowable; import io.reactivex.functions.Action; import io.reactivex.functions.Consumer; import io.reactivex.functions.Predicate; import io.reactivex.internal.functions.Functions; public ServerSocketBuilder(final Callable<? extends ServerSocket> serverSocketFactory) { this.serverSocketFactory = serverSocketFactory; } public ServerSocketBuilder readTimeoutMs(int readTimeoutMs) { this.readTimeoutMs = readTimeoutMs; return this; } public ServerSocketBuilder bufferSize(int bufferSize) { this.bufferSize = bufferSize; return this; } public ServerSocketBuilder preAcceptAction(Action action) { this.preAcceptAction = action; return this; } public ServerSocketBuilder acceptTimeoutMs(int acceptTimeoutMs) { this.acceptTimeoutMs = acceptTimeoutMs; return this; } public ServerSocketBuilder acceptSocketIf(Predicate<? super Socket> acceptSocket) { this.acceptSocket = acceptSocket; return this; } public Flowable<Flowable<byte[]>> create() {
return FlowableServerSocket.create(serverSocketFactory, readTimeoutMs, bufferSize, preAcceptAction,
davidmoten/rxjava2-extras
src/test/java/com/github/davidmoten/rx2/internal/flowable/SerializerJavaIOTest.java
// Path: src/main/java/com/github/davidmoten/rx2/buffertofile/Serializers.java // public final class Serializers { // // private static final Charset UTF_8 = Charset.forName("UTF-8"); // // private Serializers() { // // prevent initialization // } // // public static <T extends Serializable> Serializer<T> javaIO() { // // TODO use holder // return new SerializerJavaIO<T>(); // } // // public static Serializer<byte[]> bytes() { // // TODO use holder // return new SerializerBytes(); // } // // public static Serializer<String> utf8() { // // TODO use holder // return string(UTF_8); // } // // public static Serializer<String> string(Charset charset) { // return new SerializerString(charset); // } // // public static <T> Serializer<T> from(DataSerializer<T> ds) { // return new WrappedDataSerializer<T>(ds); // } // // private static final class WrappedDataSerializer<T> implements Serializer<T> { // // private final DataSerializer<T> ds; // // WrappedDataSerializer(DataSerializer<T> ds) { // this.ds = ds; // } // // @Override // public byte[] serialize(T t) throws IOException { // ByteArrayOutputStream bytes; // int cap = ds.sizeHint(); // if (cap > 0) // bytes = new ByteArrayOutputStream(ds.sizeHint()); // else // bytes = new ByteArrayOutputStream(); // DataOutputStream out = new DataOutputStream(bytes); // ds.serialize(t, out); // out.close(); // return bytes.toByteArray(); // } // // @Override // public T deserialize(byte[] bytes) throws IOException, ClassNotFoundException { // ByteArrayInputStream is = new ByteArrayInputStream(bytes); // DataInputStream in = new DataInputStream(is); // T t = ds.deserialize(in); // in.close(); // return t; // } // // } // // }
import java.io.IOException; import java.util.Arrays; import org.junit.Test; import com.github.davidmoten.rx2.buffertofile.Serializers;
package com.github.davidmoten.rx2.internal.flowable; public class SerializerJavaIOTest { @Test(expected = IOException.class) public void testNoHeader() throws IOException, ClassNotFoundException {
// Path: src/main/java/com/github/davidmoten/rx2/buffertofile/Serializers.java // public final class Serializers { // // private static final Charset UTF_8 = Charset.forName("UTF-8"); // // private Serializers() { // // prevent initialization // } // // public static <T extends Serializable> Serializer<T> javaIO() { // // TODO use holder // return new SerializerJavaIO<T>(); // } // // public static Serializer<byte[]> bytes() { // // TODO use holder // return new SerializerBytes(); // } // // public static Serializer<String> utf8() { // // TODO use holder // return string(UTF_8); // } // // public static Serializer<String> string(Charset charset) { // return new SerializerString(charset); // } // // public static <T> Serializer<T> from(DataSerializer<T> ds) { // return new WrappedDataSerializer<T>(ds); // } // // private static final class WrappedDataSerializer<T> implements Serializer<T> { // // private final DataSerializer<T> ds; // // WrappedDataSerializer(DataSerializer<T> ds) { // this.ds = ds; // } // // @Override // public byte[] serialize(T t) throws IOException { // ByteArrayOutputStream bytes; // int cap = ds.sizeHint(); // if (cap > 0) // bytes = new ByteArrayOutputStream(ds.sizeHint()); // else // bytes = new ByteArrayOutputStream(); // DataOutputStream out = new DataOutputStream(bytes); // ds.serialize(t, out); // out.close(); // return bytes.toByteArray(); // } // // @Override // public T deserialize(byte[] bytes) throws IOException, ClassNotFoundException { // ByteArrayInputStream is = new ByteArrayInputStream(bytes); // DataInputStream in = new DataInputStream(is); // T t = ds.deserialize(in); // in.close(); // return t; // } // // } // // } // Path: src/test/java/com/github/davidmoten/rx2/internal/flowable/SerializerJavaIOTest.java import java.io.IOException; import java.util.Arrays; import org.junit.Test; import com.github.davidmoten.rx2.buffertofile.Serializers; package com.github.davidmoten.rx2.internal.flowable; public class SerializerJavaIOTest { @Test(expected = IOException.class) public void testNoHeader() throws IOException, ClassNotFoundException {
Serializers.javaIO().deserialize(new byte[] {});
davidmoten/rxjava2-extras
src/main/java/com/github/davidmoten/rx2/Consumers.java
// Path: src/main/java/com/github/davidmoten/rx2/exceptions/AssertionException.java // public class AssertionException extends RuntimeException { // // private static final long serialVersionUID = -349922011349921601L; // // public AssertionException(String message) { // super(message); // } // // }
import java.io.Closeable; import java.util.Arrays; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import com.github.davidmoten.rx2.exceptions.AssertionException; import io.reactivex.functions.Consumer; import io.reactivex.functions.LongConsumer;
@Override public void accept(T t) throws Exception { list.add(t); } }; } @SuppressWarnings("unchecked") public static <T> Consumer<T> println() { return (Consumer<T>) PrintlnHolder.INSTANCE; } private static final class PrintlnHolder { static final Consumer<Object> INSTANCE = new Consumer<Object>() { @Override public void accept(Object t) throws Exception { System.out.println(t); } }; } public static Consumer<byte[]> assertBytesEquals(final byte[] expected) { // TODO make holder return new Consumer<byte[]>() { @Override public void accept(byte[] array) throws Exception { if (!Arrays.equals(expected, array)) { // TODO use custom exception
// Path: src/main/java/com/github/davidmoten/rx2/exceptions/AssertionException.java // public class AssertionException extends RuntimeException { // // private static final long serialVersionUID = -349922011349921601L; // // public AssertionException(String message) { // super(message); // } // // } // Path: src/main/java/com/github/davidmoten/rx2/Consumers.java import java.io.Closeable; import java.util.Arrays; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import com.github.davidmoten.rx2.exceptions.AssertionException; import io.reactivex.functions.Consumer; import io.reactivex.functions.LongConsumer; @Override public void accept(T t) throws Exception { list.add(t); } }; } @SuppressWarnings("unchecked") public static <T> Consumer<T> println() { return (Consumer<T>) PrintlnHolder.INSTANCE; } private static final class PrintlnHolder { static final Consumer<Object> INSTANCE = new Consumer<Object>() { @Override public void accept(Object t) throws Exception { System.out.println(t); } }; } public static Consumer<byte[]> assertBytesEquals(final byte[] expected) { // TODO make holder return new Consumer<byte[]>() { @Override public void accept(byte[] array) throws Exception { if (!Arrays.equals(expected, array)) { // TODO use custom exception
throw new AssertionException("arrays not equal: expected=" + Arrays.toString(expected) + ",actual="
davidmoten/rxjava2-extras
src/main/java/com/github/davidmoten/rx2/Functions.java
// Path: src/main/java/com/github/davidmoten/rx2/exceptions/ThrowingException.java // public final class ThrowingException extends RuntimeException { // // private static final long serialVersionUID = 8336479045139136638L; // // }
import com.github.davidmoten.rx2.exceptions.ThrowingException; import io.reactivex.functions.Function;
package com.github.davidmoten.rx2; public final class Functions { private Functions() { // prevent instantiation } public static <T> Function<Object, T> constant(final T value) { return new Function<Object, T>() { @Override public T apply(Object t) throws Exception { return value; } }; } @SuppressWarnings("unchecked") public static <T> Function<T, T> identity() { return (Function<T, T>) IdentityHolder.INSTANCE; } private static final class IdentityHolder { static final Function<Object, Object> INSTANCE = new Function<Object, Object>() { @Override public Object apply(Object t) throws Exception { return t; } }; } public static <T, R> Function<T, R> throwing() { // TODO make holder return new Function<T, R>() { @Override public R apply(T t) {
// Path: src/main/java/com/github/davidmoten/rx2/exceptions/ThrowingException.java // public final class ThrowingException extends RuntimeException { // // private static final long serialVersionUID = 8336479045139136638L; // // } // Path: src/main/java/com/github/davidmoten/rx2/Functions.java import com.github.davidmoten.rx2.exceptions.ThrowingException; import io.reactivex.functions.Function; package com.github.davidmoten.rx2; public final class Functions { private Functions() { // prevent instantiation } public static <T> Function<Object, T> constant(final T value) { return new Function<Object, T>() { @Override public T apply(Object t) throws Exception { return value; } }; } @SuppressWarnings("unchecked") public static <T> Function<T, T> identity() { return (Function<T, T>) IdentityHolder.INSTANCE; } private static final class IdentityHolder { static final Function<Object, Object> INSTANCE = new Function<Object, Object>() { @Override public Object apply(Object t) throws Exception { return t; } }; } public static <T, R> Function<T, R> throwing() { // TODO make holder return new Function<T, R>() { @Override public R apply(T t) {
throw new ThrowingException();
davidmoten/rxjava2-extras
src/main/java/com/github/davidmoten/rx2/internal/flowable/FlowableStateMachine.java
// Path: src/main/java/com/github/davidmoten/rx2/StateMachine.java // public static interface Emitter<T> { // void onNext_(T t); // // void onError_(Throwable e); // // void onComplete_(); // // void cancel_(); // } // // Path: src/main/java/com/github/davidmoten/rx2/functions/Consumer3.java // public interface Consumer3<A, B, C> { // // void accept(A a, B b, C c); // // }
import java.util.concurrent.Callable; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import com.github.davidmoten.guavamini.Preconditions; import com.github.davidmoten.rx2.StateMachine.Emitter; import com.github.davidmoten.rx2.functions.Consumer3; import io.reactivex.BackpressureStrategy; import io.reactivex.Flowable; import io.reactivex.FlowableSubscriber; import io.reactivex.exceptions.Exceptions; import io.reactivex.functions.BiConsumer; import io.reactivex.functions.Function3; import io.reactivex.internal.functions.ObjectHelper; import io.reactivex.internal.fuseable.SimplePlainQueue; import io.reactivex.internal.queue.SpscLinkedArrayQueue; import io.reactivex.internal.subscriptions.SubscriptionHelper; import io.reactivex.internal.util.BackpressureHelper; import io.reactivex.plugins.RxJavaPlugins;
package com.github.davidmoten.rx2.internal.flowable; public final class FlowableStateMachine<State, In, Out> extends Flowable<Out> { private final Flowable<In> source; private final Callable<? extends State> initialState;
// Path: src/main/java/com/github/davidmoten/rx2/StateMachine.java // public static interface Emitter<T> { // void onNext_(T t); // // void onError_(Throwable e); // // void onComplete_(); // // void cancel_(); // } // // Path: src/main/java/com/github/davidmoten/rx2/functions/Consumer3.java // public interface Consumer3<A, B, C> { // // void accept(A a, B b, C c); // // } // Path: src/main/java/com/github/davidmoten/rx2/internal/flowable/FlowableStateMachine.java import java.util.concurrent.Callable; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import com.github.davidmoten.guavamini.Preconditions; import com.github.davidmoten.rx2.StateMachine.Emitter; import com.github.davidmoten.rx2.functions.Consumer3; import io.reactivex.BackpressureStrategy; import io.reactivex.Flowable; import io.reactivex.FlowableSubscriber; import io.reactivex.exceptions.Exceptions; import io.reactivex.functions.BiConsumer; import io.reactivex.functions.Function3; import io.reactivex.internal.functions.ObjectHelper; import io.reactivex.internal.fuseable.SimplePlainQueue; import io.reactivex.internal.queue.SpscLinkedArrayQueue; import io.reactivex.internal.subscriptions.SubscriptionHelper; import io.reactivex.internal.util.BackpressureHelper; import io.reactivex.plugins.RxJavaPlugins; package com.github.davidmoten.rx2.internal.flowable; public final class FlowableStateMachine<State, In, Out> extends Flowable<Out> { private final Flowable<In> source; private final Callable<? extends State> initialState;
private final Function3<? super State, ? super In, ? super Emitter<Out>, ? extends State> transition;
davidmoten/rxjava2-extras
src/main/java/com/github/davidmoten/rx2/internal/flowable/FlowableStateMachine.java
// Path: src/main/java/com/github/davidmoten/rx2/StateMachine.java // public static interface Emitter<T> { // void onNext_(T t); // // void onError_(Throwable e); // // void onComplete_(); // // void cancel_(); // } // // Path: src/main/java/com/github/davidmoten/rx2/functions/Consumer3.java // public interface Consumer3<A, B, C> { // // void accept(A a, B b, C c); // // }
import java.util.concurrent.Callable; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import com.github.davidmoten.guavamini.Preconditions; import com.github.davidmoten.rx2.StateMachine.Emitter; import com.github.davidmoten.rx2.functions.Consumer3; import io.reactivex.BackpressureStrategy; import io.reactivex.Flowable; import io.reactivex.FlowableSubscriber; import io.reactivex.exceptions.Exceptions; import io.reactivex.functions.BiConsumer; import io.reactivex.functions.Function3; import io.reactivex.internal.functions.ObjectHelper; import io.reactivex.internal.fuseable.SimplePlainQueue; import io.reactivex.internal.queue.SpscLinkedArrayQueue; import io.reactivex.internal.subscriptions.SubscriptionHelper; import io.reactivex.internal.util.BackpressureHelper; import io.reactivex.plugins.RxJavaPlugins;
package com.github.davidmoten.rx2.internal.flowable; public final class FlowableStateMachine<State, In, Out> extends Flowable<Out> { private final Flowable<In> source; private final Callable<? extends State> initialState; private final Function3<? super State, ? super In, ? super Emitter<Out>, ? extends State> transition; private final BiConsumer<? super State, ? super Emitter<Out>> completionAction;
// Path: src/main/java/com/github/davidmoten/rx2/StateMachine.java // public static interface Emitter<T> { // void onNext_(T t); // // void onError_(Throwable e); // // void onComplete_(); // // void cancel_(); // } // // Path: src/main/java/com/github/davidmoten/rx2/functions/Consumer3.java // public interface Consumer3<A, B, C> { // // void accept(A a, B b, C c); // // } // Path: src/main/java/com/github/davidmoten/rx2/internal/flowable/FlowableStateMachine.java import java.util.concurrent.Callable; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import com.github.davidmoten.guavamini.Preconditions; import com.github.davidmoten.rx2.StateMachine.Emitter; import com.github.davidmoten.rx2.functions.Consumer3; import io.reactivex.BackpressureStrategy; import io.reactivex.Flowable; import io.reactivex.FlowableSubscriber; import io.reactivex.exceptions.Exceptions; import io.reactivex.functions.BiConsumer; import io.reactivex.functions.Function3; import io.reactivex.internal.functions.ObjectHelper; import io.reactivex.internal.fuseable.SimplePlainQueue; import io.reactivex.internal.queue.SpscLinkedArrayQueue; import io.reactivex.internal.subscriptions.SubscriptionHelper; import io.reactivex.internal.util.BackpressureHelper; import io.reactivex.plugins.RxJavaPlugins; package com.github.davidmoten.rx2.internal.flowable; public final class FlowableStateMachine<State, In, Out> extends Flowable<Out> { private final Flowable<In> source; private final Callable<? extends State> initialState; private final Function3<? super State, ? super In, ? super Emitter<Out>, ? extends State> transition; private final BiConsumer<? super State, ? super Emitter<Out>> completionAction;
private final Consumer3<? super State, ? super Throwable, ? super Emitter<Out>> errorAction;
davidmoten/rxjava2-extras
src/test/java/com/github/davidmoten/rx2/RetryWhenTest.java
// Path: src/main/java/com/github/davidmoten/rx2/RetryWhen.java // public static final class ErrorAndDuration { // // private final Throwable throwable; // private final long durationMs; // // public ErrorAndDuration(Throwable throwable, long durationMs) { // this.throwable = throwable; // this.durationMs = durationMs; // } // // public Throwable throwable() { // return throwable; // } // // public long durationMs() { // return durationMs; // } // // }
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import java.sql.SQLException; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import org.junit.Test; import org.reactivestreams.Subscription; import com.github.davidmoten.junit.Asserts; import com.github.davidmoten.rx2.RetryWhen.ErrorAndDuration; import io.reactivex.Flowable; import io.reactivex.functions.Consumer; import io.reactivex.functions.Predicate; import io.reactivex.schedulers.Schedulers; import io.reactivex.schedulers.TestScheduler; import io.reactivex.subscribers.TestSubscriber;
package com.github.davidmoten.rx2; public class RetryWhenTest { @Test public void isUtilityClass() { Asserts.assertIsUtilityClass(RetryWhen.class); } @Test public void testExponentialBackoff() { Exception ex = new IllegalArgumentException("boo"); TestSubscriber<Integer> ts = TestSubscriber.create(); final AtomicInteger logCalls = new AtomicInteger();
// Path: src/main/java/com/github/davidmoten/rx2/RetryWhen.java // public static final class ErrorAndDuration { // // private final Throwable throwable; // private final long durationMs; // // public ErrorAndDuration(Throwable throwable, long durationMs) { // this.throwable = throwable; // this.durationMs = durationMs; // } // // public Throwable throwable() { // return throwable; // } // // public long durationMs() { // return durationMs; // } // // } // Path: src/test/java/com/github/davidmoten/rx2/RetryWhenTest.java import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import java.sql.SQLException; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import org.junit.Test; import org.reactivestreams.Subscription; import com.github.davidmoten.junit.Asserts; import com.github.davidmoten.rx2.RetryWhen.ErrorAndDuration; import io.reactivex.Flowable; import io.reactivex.functions.Consumer; import io.reactivex.functions.Predicate; import io.reactivex.schedulers.Schedulers; import io.reactivex.schedulers.TestScheduler; import io.reactivex.subscribers.TestSubscriber; package com.github.davidmoten.rx2; public class RetryWhenTest { @Test public void isUtilityClass() { Asserts.assertIsUtilityClass(RetryWhen.class); } @Test public void testExponentialBackoff() { Exception ex = new IllegalArgumentException("boo"); TestSubscriber<Integer> ts = TestSubscriber.create(); final AtomicInteger logCalls = new AtomicInteger();
Consumer<ErrorAndDuration> log = new Consumer<ErrorAndDuration>() {
davidmoten/rxjava2-extras
src/test/java/com/github/davidmoten/rx2/BytesTest.java
// Path: src/main/java/com/github/davidmoten/rx2/util/ZippedEntry.java // public final class ZippedEntry { // // final String name; // entry name // final long time; // last modification time // // final FileTime mtime; // last modification time, from extra field data // // final FileTime atime; // last access time, from extra field data // // final FileTime ctime; // creation time, from extra field data // final long crc; // crc-32 of entry data // final long size; // uncompressed size of entry data // final long csize; // compressed size of entry data // final int method; // compression method // final byte[] extra; // optional extra field data for entry // final String comment; // optional comment string for entry // private final InputStream is; // // public ZippedEntry(ZipEntry e, InputStream is) { // this.name = e.getName(); // this.time = e.getTime(); // // this.mtime = e.getLastModifiedTime(); // // this.atime = e.getLastAccessTime(); // // this.ctime = e.getCreationTime(); // this.crc = e.getCrc(); // this.size = e.getSize(); // this.csize = e.getCompressedSize(); // this.method = e.getMethod(); // this.extra = e.getExtra(); // this.comment = e.getComment(); // this.is = is; // } // // public InputStream getInputStream() { // return is; // } // // public String getName() { // return name; // } // // public long getTime() { // return time; // } // // // public FileTime getLastModifiedTime() { // // return mtime; // // } // // // public FileTime getLastAccessTime() { // // return atime; // // } // // // public FileTime getCreatedtime() { // // return ctime; // // } // // public long getCrc() { // return crc; // } // // public long getSize() { // return size; // } // // public long getCompressedSize() { // return csize; // } // // public int getMethod() { // return method; // } // // public byte[] getExtra() { // return extra; // } // // public String getComment() { // return comment; // } // // }
import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.List; import java.util.UUID; import org.junit.Test; import com.github.davidmoten.junit.Asserts; import com.github.davidmoten.rx2.util.ZippedEntry; import io.reactivex.Flowable; import io.reactivex.functions.Consumer; import io.reactivex.functions.Function; import io.reactivex.functions.Predicate;
package com.github.davidmoten.rx2; public class BytesTest { @Test public void testUnzip() { List<String> list = Bytes.unzip(new File("src/test/resources/test.zip"))
// Path: src/main/java/com/github/davidmoten/rx2/util/ZippedEntry.java // public final class ZippedEntry { // // final String name; // entry name // final long time; // last modification time // // final FileTime mtime; // last modification time, from extra field data // // final FileTime atime; // last access time, from extra field data // // final FileTime ctime; // creation time, from extra field data // final long crc; // crc-32 of entry data // final long size; // uncompressed size of entry data // final long csize; // compressed size of entry data // final int method; // compression method // final byte[] extra; // optional extra field data for entry // final String comment; // optional comment string for entry // private final InputStream is; // // public ZippedEntry(ZipEntry e, InputStream is) { // this.name = e.getName(); // this.time = e.getTime(); // // this.mtime = e.getLastModifiedTime(); // // this.atime = e.getLastAccessTime(); // // this.ctime = e.getCreationTime(); // this.crc = e.getCrc(); // this.size = e.getSize(); // this.csize = e.getCompressedSize(); // this.method = e.getMethod(); // this.extra = e.getExtra(); // this.comment = e.getComment(); // this.is = is; // } // // public InputStream getInputStream() { // return is; // } // // public String getName() { // return name; // } // // public long getTime() { // return time; // } // // // public FileTime getLastModifiedTime() { // // return mtime; // // } // // // public FileTime getLastAccessTime() { // // return atime; // // } // // // public FileTime getCreatedtime() { // // return ctime; // // } // // public long getCrc() { // return crc; // } // // public long getSize() { // return size; // } // // public long getCompressedSize() { // return csize; // } // // public int getMethod() { // return method; // } // // public byte[] getExtra() { // return extra; // } // // public String getComment() { // return comment; // } // // } // Path: src/test/java/com/github/davidmoten/rx2/BytesTest.java import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.List; import java.util.UUID; import org.junit.Test; import com.github.davidmoten.junit.Asserts; import com.github.davidmoten.rx2.util.ZippedEntry; import io.reactivex.Flowable; import io.reactivex.functions.Consumer; import io.reactivex.functions.Function; import io.reactivex.functions.Predicate; package com.github.davidmoten.rx2; public class BytesTest { @Test public void testUnzip() { List<String> list = Bytes.unzip(new File("src/test/resources/test.zip"))
.concatMap(new Function<ZippedEntry, Flowable<String>>() {
davidmoten/rxjava2-extras
src/main/java/com/github/davidmoten/rx2/flowable/Serialized.java
// Path: src/main/java/com/github/davidmoten/rx2/Consumers.java // public final class Consumers { // // private Consumers() { // // prevent instantiation // } // // public static LongConsumer addLongTo(final List<Long> list) { // return new LongConsumer() { // // @Override // public void accept(long t) throws Exception { // list.add(t); // } // // }; // } // // @SuppressWarnings("unchecked") // public static <T extends Closeable> Consumer<T> close() { // return (Consumer<T>) CloseHolder.INSTANCE; // } // // private static final class CloseHolder { // final static Consumer<Closeable> INSTANCE = new Consumer<Closeable>() { // @Override // public void accept(Closeable t) throws Exception { // t.close(); // } // // }; // } // // public static Consumer<Object> increment(final AtomicInteger value) { // return new Consumer<Object>() { // @Override // public void accept(Object t) throws Exception { // value.incrementAndGet(); // } // }; // } // // public static Consumer<Throwable> printStackTrace() { // // TODO make holder // return new Consumer<Throwable>() { // @Override // public void accept(Throwable e) throws Exception { // e.printStackTrace(); // } // }; // } // // @SuppressWarnings("unchecked") // public static <T> Consumer<T> doNothing() { // return (Consumer<T>) DoNothingHolder.INSTANCE; // } // // private static final class DoNothingHolder { // static final Consumer<Object> INSTANCE = new Consumer<Object>() { // // @Override // public void accept(Object t) throws Exception { // // do nothing // } // }; // } // // public static <T> Consumer<T> set(final AtomicReference<T> value) { // return new Consumer<T>() { // // @Override // public void accept(T t) throws Exception { // value.set(t); // } // }; // } // // public static Consumer<Integer> set(final AtomicInteger value) { // return new Consumer<Integer>() { // @Override // public void accept(Integer t) throws Exception { // value.set(t); // } // }; // } // // public static Consumer<Object> decrement(final AtomicInteger value) { // return new Consumer<Object>() { // // @Override // public void accept(Object t) throws Exception { // value.decrementAndGet(); // } // // }; // } // // @SuppressWarnings("unchecked") // public static <T> Consumer<T> setToTrue(final AtomicBoolean value) { // return (Consumer<T>) new Consumer<Object>() { // // @Override // public void accept(Object t) throws Exception { // value.set(true); // } // }; // } // // public static <T> Consumer<T> addTo(final List<T> list) { // return new Consumer<T>() { // // @Override // public void accept(T t) throws Exception { // list.add(t); // } // }; // } // // @SuppressWarnings("unchecked") // public static <T> Consumer<T> println() { // return (Consumer<T>) PrintlnHolder.INSTANCE; // } // // private static final class PrintlnHolder { // static final Consumer<Object> INSTANCE = new Consumer<Object>() { // @Override // public void accept(Object t) throws Exception { // System.out.println(t); // } // }; // } // // public static Consumer<byte[]> assertBytesEquals(final byte[] expected) { // // TODO make holder // return new Consumer<byte[]>() { // // @Override // public void accept(byte[] array) throws Exception { // if (!Arrays.equals(expected, array)) { // // TODO use custom exception // throw new AssertionException("arrays not equal: expected=" + Arrays.toString(expected) + ",actual=" // + Arrays.toString(array)); // } // } // // }; // } // // public static LongConsumer printLong(final String prefix) { // return new LongConsumer() { // @Override // public void accept(long t) throws Exception { // System.out.println(prefix + t); // } // }; // } // }
import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.EOFException; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.concurrent.Callable; import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.io.Input; import com.esotericsoftware.kryo.io.Output; import com.github.davidmoten.rx2.Consumers; import io.reactivex.Emitter; import io.reactivex.Flowable; import io.reactivex.functions.Consumer; import io.reactivex.functions.Function;
emitter.onError(e); } } }); } /** * Returns the deserialized objects from the given {@link File} as a * {@link Flowable} stream. Uses buffer of size <code>bufferSize</code> * buffer reads from the File. * * @param file * the input file * @param bufferSize * the buffer size for reading bytes from the file. * @param <T> * the generic type of the deserialized objects returned in the * stream * @return the stream of deserialized objects from the {@link InputStream} * as a {@link Flowable}. */ public static <T extends Serializable> Flowable<T> read(final File file, final int bufferSize) { Callable<ObjectInputStream> resourceFactory = new Callable<ObjectInputStream>() { @Override public ObjectInputStream call() throws IOException { return new ObjectInputStream(new BufferedInputStream(new FileInputStream(file), bufferSize)); } }; @SuppressWarnings("unchecked") Function<ObjectInputStream, Flowable<T>> flowableFactory = (Function<ObjectInputStream, Flowable<T>>) (Function<?, ?>) ObjectInputStreamFlowableFactoryHolder.INSTANCE;
// Path: src/main/java/com/github/davidmoten/rx2/Consumers.java // public final class Consumers { // // private Consumers() { // // prevent instantiation // } // // public static LongConsumer addLongTo(final List<Long> list) { // return new LongConsumer() { // // @Override // public void accept(long t) throws Exception { // list.add(t); // } // // }; // } // // @SuppressWarnings("unchecked") // public static <T extends Closeable> Consumer<T> close() { // return (Consumer<T>) CloseHolder.INSTANCE; // } // // private static final class CloseHolder { // final static Consumer<Closeable> INSTANCE = new Consumer<Closeable>() { // @Override // public void accept(Closeable t) throws Exception { // t.close(); // } // // }; // } // // public static Consumer<Object> increment(final AtomicInteger value) { // return new Consumer<Object>() { // @Override // public void accept(Object t) throws Exception { // value.incrementAndGet(); // } // }; // } // // public static Consumer<Throwable> printStackTrace() { // // TODO make holder // return new Consumer<Throwable>() { // @Override // public void accept(Throwable e) throws Exception { // e.printStackTrace(); // } // }; // } // // @SuppressWarnings("unchecked") // public static <T> Consumer<T> doNothing() { // return (Consumer<T>) DoNothingHolder.INSTANCE; // } // // private static final class DoNothingHolder { // static final Consumer<Object> INSTANCE = new Consumer<Object>() { // // @Override // public void accept(Object t) throws Exception { // // do nothing // } // }; // } // // public static <T> Consumer<T> set(final AtomicReference<T> value) { // return new Consumer<T>() { // // @Override // public void accept(T t) throws Exception { // value.set(t); // } // }; // } // // public static Consumer<Integer> set(final AtomicInteger value) { // return new Consumer<Integer>() { // @Override // public void accept(Integer t) throws Exception { // value.set(t); // } // }; // } // // public static Consumer<Object> decrement(final AtomicInteger value) { // return new Consumer<Object>() { // // @Override // public void accept(Object t) throws Exception { // value.decrementAndGet(); // } // // }; // } // // @SuppressWarnings("unchecked") // public static <T> Consumer<T> setToTrue(final AtomicBoolean value) { // return (Consumer<T>) new Consumer<Object>() { // // @Override // public void accept(Object t) throws Exception { // value.set(true); // } // }; // } // // public static <T> Consumer<T> addTo(final List<T> list) { // return new Consumer<T>() { // // @Override // public void accept(T t) throws Exception { // list.add(t); // } // }; // } // // @SuppressWarnings("unchecked") // public static <T> Consumer<T> println() { // return (Consumer<T>) PrintlnHolder.INSTANCE; // } // // private static final class PrintlnHolder { // static final Consumer<Object> INSTANCE = new Consumer<Object>() { // @Override // public void accept(Object t) throws Exception { // System.out.println(t); // } // }; // } // // public static Consumer<byte[]> assertBytesEquals(final byte[] expected) { // // TODO make holder // return new Consumer<byte[]>() { // // @Override // public void accept(byte[] array) throws Exception { // if (!Arrays.equals(expected, array)) { // // TODO use custom exception // throw new AssertionException("arrays not equal: expected=" + Arrays.toString(expected) + ",actual=" // + Arrays.toString(array)); // } // } // // }; // } // // public static LongConsumer printLong(final String prefix) { // return new LongConsumer() { // @Override // public void accept(long t) throws Exception { // System.out.println(prefix + t); // } // }; // } // } // Path: src/main/java/com/github/davidmoten/rx2/flowable/Serialized.java import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.EOFException; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.concurrent.Callable; import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.io.Input; import com.esotericsoftware.kryo.io.Output; import com.github.davidmoten.rx2.Consumers; import io.reactivex.Emitter; import io.reactivex.Flowable; import io.reactivex.functions.Consumer; import io.reactivex.functions.Function; emitter.onError(e); } } }); } /** * Returns the deserialized objects from the given {@link File} as a * {@link Flowable} stream. Uses buffer of size <code>bufferSize</code> * buffer reads from the File. * * @param file * the input file * @param bufferSize * the buffer size for reading bytes from the file. * @param <T> * the generic type of the deserialized objects returned in the * stream * @return the stream of deserialized objects from the {@link InputStream} * as a {@link Flowable}. */ public static <T extends Serializable> Flowable<T> read(final File file, final int bufferSize) { Callable<ObjectInputStream> resourceFactory = new Callable<ObjectInputStream>() { @Override public ObjectInputStream call() throws IOException { return new ObjectInputStream(new BufferedInputStream(new FileInputStream(file), bufferSize)); } }; @SuppressWarnings("unchecked") Function<ObjectInputStream, Flowable<T>> flowableFactory = (Function<ObjectInputStream, Flowable<T>>) (Function<?, ?>) ObjectInputStreamFlowableFactoryHolder.INSTANCE;
Consumer<ObjectInputStream> disposeAction = Consumers.close();
davidmoten/rxjava2-extras
src/test/java/com/github/davidmoten/rx2/StringsTest.java
// Path: src/main/java/com/github/davidmoten/rx2/Strings.java // public static FlowableTransformer<byte[], String> decode(CharsetDecoder decoder) { // return decode(decoder, BackpressureStrategy.BUFFER, DEFAULT_REQUEST_SIZE); // }
import static com.github.davidmoten.rx2.Strings.decode; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.fail; import java.io.File; import java.io.IOException; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import org.junit.Test; import com.github.davidmoten.guavamini.Lists; import com.github.davidmoten.junit.Asserts; import io.reactivex.Flowable; import io.reactivex.functions.BiFunction;
package com.github.davidmoten.rx2; public class StringsTest { @Test public void testMultibyteSpanningTwoBuffers() { Flowable<byte[]> src = Flowable.just(new byte[] { (byte) 0xc2 }, new byte[] { (byte) 0xa1 });
// Path: src/main/java/com/github/davidmoten/rx2/Strings.java // public static FlowableTransformer<byte[], String> decode(CharsetDecoder decoder) { // return decode(decoder, BackpressureStrategy.BUFFER, DEFAULT_REQUEST_SIZE); // } // Path: src/test/java/com/github/davidmoten/rx2/StringsTest.java import static com.github.davidmoten.rx2.Strings.decode; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.fail; import java.io.File; import java.io.IOException; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import org.junit.Test; import com.github.davidmoten.guavamini.Lists; import com.github.davidmoten.junit.Asserts; import io.reactivex.Flowable; import io.reactivex.functions.BiFunction; package com.github.davidmoten.rx2; public class StringsTest { @Test public void testMultibyteSpanningTwoBuffers() { Flowable<byte[]> src = Flowable.just(new byte[] { (byte) 0xc2 }, new byte[] { (byte) 0xa1 });
String out = decode(src, "UTF-8").blockingSingle();
davidmoten/rxjava2-extras
src/main/java/com/github/davidmoten/rx2/internal/flowable/FlowableMergeInterleave.java
// Path: src/main/java/com/github/davidmoten/util/RingBuffer.java // public class RingBuffer<T> implements Queue<T> { // // private final T[] list; // private int start; // private int finish; // // @SuppressWarnings("unchecked") // private RingBuffer(int size) { // list = (T[]) new Object[size + 1]; // } // // public static <T> RingBuffer<T> create(int size) { // return new RingBuffer<T>(size); // } // // @Override // public void clear() { // finish = start; // } // // @Override // public Iterator<T> iterator() { // final int _start = start; // final int _finish = finish; // return new Iterator<T>() { // int i = _start; // // @Override // public boolean hasNext() { // return i != _finish; // } // // @Override // public T next() { // T value = list[i]; // i = (i + 1) % list.length; // return value; // } // }; // } // // @Override // public T peek() { // if (start == finish) // return null; // else // return list[start]; // } // // public boolean isEmpty() { // return start == finish; // } // // public int size() { // if (start <= finish) // return finish - start; // else // return finish - start + list.length; // } // // public int maxSize() { // return list.length - 1; // } // // @Override // public boolean contains(Object o) { // return notImplemented(); // } // // @Override // public Object[] toArray() { // return notImplemented(); // } // // @Override // public <S> S[] toArray(S[] a) { // return notImplemented(); // } // // @Override // public boolean remove(Object o) { // return notImplemented(); // } // // @Override // public boolean containsAll(Collection<?> c) { // return notImplemented(); // } // // private static <T> T notImplemented() { // throw new RuntimeException("Not implemented"); // } // // @Override // public boolean addAll(Collection<? extends T> c) { // for (T t : c) // add(t); // return true; // } // // @Override // public boolean removeAll(Collection<?> c) { // return notImplemented(); // } // // @Override // public boolean retainAll(Collection<?> c) { // return notImplemented(); // } // // @Override // public boolean add(T t) { // if (offer(t)) // return true; // else // throw new IllegalStateException("Cannot add to queue because is full"); // } // // @Override // public boolean offer(T t) { // if (t == null) // throw new NullPointerException(); // int currentFinish = finish; // finish = (finish + 1) % list.length; // if (finish == start) { // return false; // } else { // list[currentFinish] = t; // return true; // } // } // // @Override // public T remove() { // T t = poll(); // if (t == null) // throw new NoSuchElementException(); // else // return t; // } // // @Override // public T poll() { // if (start == finish) { // return null; // } else { // T value = list[start]; // // don't hold a reference to a popped value // list[start] = null; // start = (start + 1) % list.length; // return value; // } // } // // @Override // public T element() { // return notImplemented(); // } // // @Override // public String toString() { // StringBuilder s = new StringBuilder(); // s.append("RingBuffer["); // boolean first = true; // for (T value: this) { // if (!first) { // s.append(", "); // } else { // first = false; // } // s.append(String.valueOf(value)); // } // s.append("]"); // return s.toString(); // } // }
import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; import org.reactivestreams.Publisher; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import com.github.davidmoten.guavamini.Preconditions; import com.github.davidmoten.util.RingBuffer; import io.reactivex.Flowable; import io.reactivex.internal.fuseable.SimplePlainQueue; import io.reactivex.internal.queue.MpscLinkedQueue; import io.reactivex.internal.subscriptions.SubscriptionHelper; import io.reactivex.internal.util.BackpressureHelper;
this.sources = sources; this.maxConcurrent = maxConcurrent; this.batchSize = batchSize; this.delayErrors = delayErrors; } @Override protected void subscribeActual(Subscriber<? super T> s) { MergeInterleaveSubscription<T> subscription = new MergeInterleaveSubscription<T>(sources, maxConcurrent, batchSize, delayErrors, s); s.onSubscribe(subscription); } private static final class MergeInterleaveSubscription<T> extends AtomicInteger implements Subscription, Subscriber<Publisher<? extends T>> { private static final long serialVersionUID = -6416801556759306113L; private static final Object SOURCES_COMPLETE = new Object(); private final AtomicBoolean once = new AtomicBoolean(); private final Publisher<? extends Publisher<? extends T>> sources; private final int maxConcurrent; private final int batchSize; private final boolean delayErrors; private Subscriber<? super T> subscriber; private Subscription subscription; private volatile boolean cancelled; private Throwable error; private volatile boolean finished; private final AtomicLong requested = new AtomicLong(); private long emitted;
// Path: src/main/java/com/github/davidmoten/util/RingBuffer.java // public class RingBuffer<T> implements Queue<T> { // // private final T[] list; // private int start; // private int finish; // // @SuppressWarnings("unchecked") // private RingBuffer(int size) { // list = (T[]) new Object[size + 1]; // } // // public static <T> RingBuffer<T> create(int size) { // return new RingBuffer<T>(size); // } // // @Override // public void clear() { // finish = start; // } // // @Override // public Iterator<T> iterator() { // final int _start = start; // final int _finish = finish; // return new Iterator<T>() { // int i = _start; // // @Override // public boolean hasNext() { // return i != _finish; // } // // @Override // public T next() { // T value = list[i]; // i = (i + 1) % list.length; // return value; // } // }; // } // // @Override // public T peek() { // if (start == finish) // return null; // else // return list[start]; // } // // public boolean isEmpty() { // return start == finish; // } // // public int size() { // if (start <= finish) // return finish - start; // else // return finish - start + list.length; // } // // public int maxSize() { // return list.length - 1; // } // // @Override // public boolean contains(Object o) { // return notImplemented(); // } // // @Override // public Object[] toArray() { // return notImplemented(); // } // // @Override // public <S> S[] toArray(S[] a) { // return notImplemented(); // } // // @Override // public boolean remove(Object o) { // return notImplemented(); // } // // @Override // public boolean containsAll(Collection<?> c) { // return notImplemented(); // } // // private static <T> T notImplemented() { // throw new RuntimeException("Not implemented"); // } // // @Override // public boolean addAll(Collection<? extends T> c) { // for (T t : c) // add(t); // return true; // } // // @Override // public boolean removeAll(Collection<?> c) { // return notImplemented(); // } // // @Override // public boolean retainAll(Collection<?> c) { // return notImplemented(); // } // // @Override // public boolean add(T t) { // if (offer(t)) // return true; // else // throw new IllegalStateException("Cannot add to queue because is full"); // } // // @Override // public boolean offer(T t) { // if (t == null) // throw new NullPointerException(); // int currentFinish = finish; // finish = (finish + 1) % list.length; // if (finish == start) { // return false; // } else { // list[currentFinish] = t; // return true; // } // } // // @Override // public T remove() { // T t = poll(); // if (t == null) // throw new NoSuchElementException(); // else // return t; // } // // @Override // public T poll() { // if (start == finish) { // return null; // } else { // T value = list[start]; // // don't hold a reference to a popped value // list[start] = null; // start = (start + 1) % list.length; // return value; // } // } // // @Override // public T element() { // return notImplemented(); // } // // @Override // public String toString() { // StringBuilder s = new StringBuilder(); // s.append("RingBuffer["); // boolean first = true; // for (T value: this) { // if (!first) { // s.append(", "); // } else { // first = false; // } // s.append(String.valueOf(value)); // } // s.append("]"); // return s.toString(); // } // } // Path: src/main/java/com/github/davidmoten/rx2/internal/flowable/FlowableMergeInterleave.java import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; import org.reactivestreams.Publisher; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import com.github.davidmoten.guavamini.Preconditions; import com.github.davidmoten.util.RingBuffer; import io.reactivex.Flowable; import io.reactivex.internal.fuseable.SimplePlainQueue; import io.reactivex.internal.queue.MpscLinkedQueue; import io.reactivex.internal.subscriptions.SubscriptionHelper; import io.reactivex.internal.util.BackpressureHelper; this.sources = sources; this.maxConcurrent = maxConcurrent; this.batchSize = batchSize; this.delayErrors = delayErrors; } @Override protected void subscribeActual(Subscriber<? super T> s) { MergeInterleaveSubscription<T> subscription = new MergeInterleaveSubscription<T>(sources, maxConcurrent, batchSize, delayErrors, s); s.onSubscribe(subscription); } private static final class MergeInterleaveSubscription<T> extends AtomicInteger implements Subscription, Subscriber<Publisher<? extends T>> { private static final long serialVersionUID = -6416801556759306113L; private static final Object SOURCES_COMPLETE = new Object(); private final AtomicBoolean once = new AtomicBoolean(); private final Publisher<? extends Publisher<? extends T>> sources; private final int maxConcurrent; private final int batchSize; private final boolean delayErrors; private Subscriber<? super T> subscriber; private Subscription subscription; private volatile boolean cancelled; private Throwable error; private volatile boolean finished; private final AtomicLong requested = new AtomicLong(); private long emitted;
private final RingBuffer<BatchFinished> batchFinished;
davidmoten/rxjava2-extras
src/main/java/com/github/davidmoten/rx2/BiFunctions.java
// Path: src/main/java/com/github/davidmoten/rx2/exceptions/ThrowingException.java // public final class ThrowingException extends RuntimeException { // // private static final long serialVersionUID = 8336479045139136638L; // // }
import com.github.davidmoten.rx2.exceptions.ThrowingException; import io.reactivex.functions.BiFunction;
package com.github.davidmoten.rx2; public final class BiFunctions { private BiFunctions() { // prevent instantiation } @SuppressWarnings("unchecked") public static <A, B, C> BiFunction<A, B, C> throwing() { return (BiFunction<A, B, C>) ThrowingHolder.INSTANCE; } private static final class ThrowingHolder { static BiFunction<Object, Object, Object> INSTANCE = new BiFunction<Object, Object, Object>() { @Override public Object apply(Object t1, Object t2) throws Exception {
// Path: src/main/java/com/github/davidmoten/rx2/exceptions/ThrowingException.java // public final class ThrowingException extends RuntimeException { // // private static final long serialVersionUID = 8336479045139136638L; // // } // Path: src/main/java/com/github/davidmoten/rx2/BiFunctions.java import com.github.davidmoten.rx2.exceptions.ThrowingException; import io.reactivex.functions.BiFunction; package com.github.davidmoten.rx2; public final class BiFunctions { private BiFunctions() { // prevent instantiation } @SuppressWarnings("unchecked") public static <A, B, C> BiFunction<A, B, C> throwing() { return (BiFunction<A, B, C>) ThrowingHolder.INSTANCE; } private static final class ThrowingHolder { static BiFunction<Object, Object, Object> INSTANCE = new BiFunction<Object, Object, Object>() { @Override public Object apply(Object t1, Object t2) throws Exception {
throw new ThrowingException();
davidmoten/rxjava2-extras
src/main/java/com/github/davidmoten/rx2/Observables.java
// Path: src/main/java/com/github/davidmoten/rx2/flowable/CachedFlowable.java // public final class CachedFlowable<T> extends Flowable<T> { // // private final OnSubscribeCacheResettable<T> cache; // // public CachedFlowable(Flowable<T> source) { // this(new OnSubscribeCacheResettable<T>(source)); // } // // CachedFlowable(OnSubscribeCacheResettable<T> cache) { // this.cache = cache; // } // // public CachedFlowable<T> reset() { // cache.reset(); // return this; // } // // @Override // protected void subscribeActual(Subscriber<? super T> subscriber) { // cache.subscribe(subscriber); // } // } // // Path: src/main/java/com/github/davidmoten/rx2/observable/CachedObservable.java // public final class CachedObservable<T> extends Observable<T> { // // private final OnSubscribeCacheResetable<T> cache; // // public CachedObservable(Observable<T> source) { // this(new OnSubscribeCacheResetable<T>(source)); // } // // CachedObservable(OnSubscribeCacheResetable<T> cache) { // this.cache = cache; // } // // public CachedObservable<T> reset() { // cache.reset(); // return this; // } // // @Override // protected void subscribeActual(Observer<? super T> observer) { // cache.subscribe(observer); // } // // } // // Path: src/main/java/com/github/davidmoten/rx2/observable/CloseableObservableWithReset.java // public final class CloseableObservableWithReset<T> { // // private final Observable<T> observable; // private final Runnable closeAction; // private final Runnable resetAction; // // public CloseableObservableWithReset(Observable<T> observable, Runnable closeAction, Runnable resetAction) { // this.observable = observable; // this.closeAction = closeAction; // this.resetAction = resetAction; // } // // public Observable<T> observable() { // return observable; // } // // public void reset() { // resetAction.run(); // } // // public void close() { // closeAction.run(); // } // // }
import com.github.davidmoten.guavamini.Optional; import com.github.davidmoten.rx2.flowable.CachedFlowable; import com.github.davidmoten.rx2.observable.CachedObservable; import com.github.davidmoten.rx2.observable.CloseableObservableWithReset; import io.reactivex.Flowable; import io.reactivex.Observable; import io.reactivex.Scheduler; import io.reactivex.disposables.Disposable; import io.reactivex.functions.Consumer; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference;
package com.github.davidmoten.rx2; public final class Observables { private Observables() { // prevent instantiation } /** * Returns a cached {@link Flowable} like {@link Flowable#cache()} * except that the cache can be reset by calling * {@link CachedFlowable#reset()}. * * @param source * the observable to be cached. * @param <T> * the generic type of the source * @return a cached observable whose cache can be reset. */
// Path: src/main/java/com/github/davidmoten/rx2/flowable/CachedFlowable.java // public final class CachedFlowable<T> extends Flowable<T> { // // private final OnSubscribeCacheResettable<T> cache; // // public CachedFlowable(Flowable<T> source) { // this(new OnSubscribeCacheResettable<T>(source)); // } // // CachedFlowable(OnSubscribeCacheResettable<T> cache) { // this.cache = cache; // } // // public CachedFlowable<T> reset() { // cache.reset(); // return this; // } // // @Override // protected void subscribeActual(Subscriber<? super T> subscriber) { // cache.subscribe(subscriber); // } // } // // Path: src/main/java/com/github/davidmoten/rx2/observable/CachedObservable.java // public final class CachedObservable<T> extends Observable<T> { // // private final OnSubscribeCacheResetable<T> cache; // // public CachedObservable(Observable<T> source) { // this(new OnSubscribeCacheResetable<T>(source)); // } // // CachedObservable(OnSubscribeCacheResetable<T> cache) { // this.cache = cache; // } // // public CachedObservable<T> reset() { // cache.reset(); // return this; // } // // @Override // protected void subscribeActual(Observer<? super T> observer) { // cache.subscribe(observer); // } // // } // // Path: src/main/java/com/github/davidmoten/rx2/observable/CloseableObservableWithReset.java // public final class CloseableObservableWithReset<T> { // // private final Observable<T> observable; // private final Runnable closeAction; // private final Runnable resetAction; // // public CloseableObservableWithReset(Observable<T> observable, Runnable closeAction, Runnable resetAction) { // this.observable = observable; // this.closeAction = closeAction; // this.resetAction = resetAction; // } // // public Observable<T> observable() { // return observable; // } // // public void reset() { // resetAction.run(); // } // // public void close() { // closeAction.run(); // } // // } // Path: src/main/java/com/github/davidmoten/rx2/Observables.java import com.github.davidmoten.guavamini.Optional; import com.github.davidmoten.rx2.flowable.CachedFlowable; import com.github.davidmoten.rx2.observable.CachedObservable; import com.github.davidmoten.rx2.observable.CloseableObservableWithReset; import io.reactivex.Flowable; import io.reactivex.Observable; import io.reactivex.Scheduler; import io.reactivex.disposables.Disposable; import io.reactivex.functions.Consumer; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; package com.github.davidmoten.rx2; public final class Observables { private Observables() { // prevent instantiation } /** * Returns a cached {@link Flowable} like {@link Flowable#cache()} * except that the cache can be reset by calling * {@link CachedFlowable#reset()}. * * @param source * the observable to be cached. * @param <T> * the generic type of the source * @return a cached observable whose cache can be reset. */
public static <T> CachedObservable<T> cache(Observable<T> source) {
davidmoten/rxjava2-extras
src/main/java/com/github/davidmoten/rx2/Observables.java
// Path: src/main/java/com/github/davidmoten/rx2/flowable/CachedFlowable.java // public final class CachedFlowable<T> extends Flowable<T> { // // private final OnSubscribeCacheResettable<T> cache; // // public CachedFlowable(Flowable<T> source) { // this(new OnSubscribeCacheResettable<T>(source)); // } // // CachedFlowable(OnSubscribeCacheResettable<T> cache) { // this.cache = cache; // } // // public CachedFlowable<T> reset() { // cache.reset(); // return this; // } // // @Override // protected void subscribeActual(Subscriber<? super T> subscriber) { // cache.subscribe(subscriber); // } // } // // Path: src/main/java/com/github/davidmoten/rx2/observable/CachedObservable.java // public final class CachedObservable<T> extends Observable<T> { // // private final OnSubscribeCacheResetable<T> cache; // // public CachedObservable(Observable<T> source) { // this(new OnSubscribeCacheResetable<T>(source)); // } // // CachedObservable(OnSubscribeCacheResetable<T> cache) { // this.cache = cache; // } // // public CachedObservable<T> reset() { // cache.reset(); // return this; // } // // @Override // protected void subscribeActual(Observer<? super T> observer) { // cache.subscribe(observer); // } // // } // // Path: src/main/java/com/github/davidmoten/rx2/observable/CloseableObservableWithReset.java // public final class CloseableObservableWithReset<T> { // // private final Observable<T> observable; // private final Runnable closeAction; // private final Runnable resetAction; // // public CloseableObservableWithReset(Observable<T> observable, Runnable closeAction, Runnable resetAction) { // this.observable = observable; // this.closeAction = closeAction; // this.resetAction = resetAction; // } // // public Observable<T> observable() { // return observable; // } // // public void reset() { // resetAction.run(); // } // // public void close() { // closeAction.run(); // } // // }
import com.github.davidmoten.guavamini.Optional; import com.github.davidmoten.rx2.flowable.CachedFlowable; import com.github.davidmoten.rx2.observable.CachedObservable; import com.github.davidmoten.rx2.observable.CloseableObservableWithReset; import io.reactivex.Flowable; import io.reactivex.Observable; import io.reactivex.Scheduler; import io.reactivex.disposables.Disposable; import io.reactivex.functions.Consumer; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference;
package com.github.davidmoten.rx2; public final class Observables { private Observables() { // prevent instantiation } /** * Returns a cached {@link Flowable} like {@link Flowable#cache()} * except that the cache can be reset by calling * {@link CachedFlowable#reset()}. * * @param source * the observable to be cached. * @param <T> * the generic type of the source * @return a cached observable whose cache can be reset. */ public static <T> CachedObservable<T> cache(Observable<T> source) { return new CachedObservable<T>(source); } /** * Returns a cached {@link Observable} like {@link Observable#cache()} * except that the cache can be reset by calling * {@link CachedObservable#reset()} and the cache will be automatically * reset an interval after first subscription (or first subscription after * reset). The interval is defined by {@code duration} and {@code unit} . * * @param source * the source observable * @param duration * duration till next reset * @param unit * units corresponding to the duration * @param worker * worker to use for scheduling reset. Don't forget to * unsubscribe the worker when no longer required. * @param <T> * the generic type of the source * @return cached observable that resets regularly on a time interval */ public static <T> Observable<T> cache(final Observable<T> source, final long duration, final TimeUnit unit, final Scheduler.Worker worker) { final AtomicReference<CachedObservable<T>> cacheRef = new AtomicReference<CachedObservable<T>>(); CachedObservable<T> cache = new CachedObservable<T>(source); cacheRef.set(cache); return cache.doOnSubscribe(new Consumer<Disposable>() { @Override public void accept(Disposable d) { Runnable action = new Runnable() { @Override public void run() { cacheRef.get().reset(); } }; worker.schedule(action, duration, unit); } }); } /** * Returns a cached {@link Observable} like {@link Observable#cache()} * except that the cache may be reset by the user calling * {@link CloseableObservableWithReset#reset}. * * @param source * the source observable * @param duration * duration till next reset * @param unit * units corresponding to the duration * @param scheduler * scheduler to use for scheduling reset. * @param <T> * generic type of source observable * @return {@link CloseableObservableWithReset} that should be closed once * finished to prevent worker memory leak. */
// Path: src/main/java/com/github/davidmoten/rx2/flowable/CachedFlowable.java // public final class CachedFlowable<T> extends Flowable<T> { // // private final OnSubscribeCacheResettable<T> cache; // // public CachedFlowable(Flowable<T> source) { // this(new OnSubscribeCacheResettable<T>(source)); // } // // CachedFlowable(OnSubscribeCacheResettable<T> cache) { // this.cache = cache; // } // // public CachedFlowable<T> reset() { // cache.reset(); // return this; // } // // @Override // protected void subscribeActual(Subscriber<? super T> subscriber) { // cache.subscribe(subscriber); // } // } // // Path: src/main/java/com/github/davidmoten/rx2/observable/CachedObservable.java // public final class CachedObservable<T> extends Observable<T> { // // private final OnSubscribeCacheResetable<T> cache; // // public CachedObservable(Observable<T> source) { // this(new OnSubscribeCacheResetable<T>(source)); // } // // CachedObservable(OnSubscribeCacheResetable<T> cache) { // this.cache = cache; // } // // public CachedObservable<T> reset() { // cache.reset(); // return this; // } // // @Override // protected void subscribeActual(Observer<? super T> observer) { // cache.subscribe(observer); // } // // } // // Path: src/main/java/com/github/davidmoten/rx2/observable/CloseableObservableWithReset.java // public final class CloseableObservableWithReset<T> { // // private final Observable<T> observable; // private final Runnable closeAction; // private final Runnable resetAction; // // public CloseableObservableWithReset(Observable<T> observable, Runnable closeAction, Runnable resetAction) { // this.observable = observable; // this.closeAction = closeAction; // this.resetAction = resetAction; // } // // public Observable<T> observable() { // return observable; // } // // public void reset() { // resetAction.run(); // } // // public void close() { // closeAction.run(); // } // // } // Path: src/main/java/com/github/davidmoten/rx2/Observables.java import com.github.davidmoten.guavamini.Optional; import com.github.davidmoten.rx2.flowable.CachedFlowable; import com.github.davidmoten.rx2.observable.CachedObservable; import com.github.davidmoten.rx2.observable.CloseableObservableWithReset; import io.reactivex.Flowable; import io.reactivex.Observable; import io.reactivex.Scheduler; import io.reactivex.disposables.Disposable; import io.reactivex.functions.Consumer; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; package com.github.davidmoten.rx2; public final class Observables { private Observables() { // prevent instantiation } /** * Returns a cached {@link Flowable} like {@link Flowable#cache()} * except that the cache can be reset by calling * {@link CachedFlowable#reset()}. * * @param source * the observable to be cached. * @param <T> * the generic type of the source * @return a cached observable whose cache can be reset. */ public static <T> CachedObservable<T> cache(Observable<T> source) { return new CachedObservable<T>(source); } /** * Returns a cached {@link Observable} like {@link Observable#cache()} * except that the cache can be reset by calling * {@link CachedObservable#reset()} and the cache will be automatically * reset an interval after first subscription (or first subscription after * reset). The interval is defined by {@code duration} and {@code unit} . * * @param source * the source observable * @param duration * duration till next reset * @param unit * units corresponding to the duration * @param worker * worker to use for scheduling reset. Don't forget to * unsubscribe the worker when no longer required. * @param <T> * the generic type of the source * @return cached observable that resets regularly on a time interval */ public static <T> Observable<T> cache(final Observable<T> source, final long duration, final TimeUnit unit, final Scheduler.Worker worker) { final AtomicReference<CachedObservable<T>> cacheRef = new AtomicReference<CachedObservable<T>>(); CachedObservable<T> cache = new CachedObservable<T>(source); cacheRef.set(cache); return cache.doOnSubscribe(new Consumer<Disposable>() { @Override public void accept(Disposable d) { Runnable action = new Runnable() { @Override public void run() { cacheRef.get().reset(); } }; worker.schedule(action, duration, unit); } }); } /** * Returns a cached {@link Observable} like {@link Observable#cache()} * except that the cache may be reset by the user calling * {@link CloseableObservableWithReset#reset}. * * @param source * the source observable * @param duration * duration till next reset * @param unit * units corresponding to the duration * @param scheduler * scheduler to use for scheduling reset. * @param <T> * generic type of source observable * @return {@link CloseableObservableWithReset} that should be closed once * finished to prevent worker memory leak. */
public static <T> CloseableObservableWithReset<T> cache(final Observable<T> source,
davidmoten/rxjava2-extras
src/test/java/com/github/davidmoten/rx2/observable/TransformersTest.java
// Path: src/main/java/com/github/davidmoten/rx2/observable/Transformers.java // public final class Transformers { // // private Transformers() { // // prevent instantiation // } // // public static Options.BuilderObservable onBackpressureBufferToFile() { // return Options.builderObservable(); // } // }
import org.junit.Test; import com.github.davidmoten.junit.Asserts; import com.github.davidmoten.rx2.observable.Transformers;
package com.github.davidmoten.rx2.observable; public class TransformersTest { @Test public void isUtilityClass() {
// Path: src/main/java/com/github/davidmoten/rx2/observable/Transformers.java // public final class Transformers { // // private Transformers() { // // prevent instantiation // } // // public static Options.BuilderObservable onBackpressureBufferToFile() { // return Options.builderObservable(); // } // } // Path: src/test/java/com/github/davidmoten/rx2/observable/TransformersTest.java import org.junit.Test; import com.github.davidmoten.junit.Asserts; import com.github.davidmoten.rx2.observable.Transformers; package com.github.davidmoten.rx2.observable; public class TransformersTest { @Test public void isUtilityClass() {
Asserts.assertIsUtilityClass(Transformers.class);
davidmoten/rxjava2-extras
src/test/java/com/github/davidmoten/rx2/ObservablesTest.java
// Path: src/main/java/com/github/davidmoten/rx2/observable/CloseableObservableWithReset.java // public final class CloseableObservableWithReset<T> { // // private final Observable<T> observable; // private final Runnable closeAction; // private final Runnable resetAction; // // public CloseableObservableWithReset(Observable<T> observable, Runnable closeAction, Runnable resetAction) { // this.observable = observable; // this.closeAction = closeAction; // this.resetAction = resetAction; // } // // public Observable<T> observable() { // return observable; // } // // public void reset() { // resetAction.run(); // } // // public void close() { // closeAction.run(); // } // // }
import com.github.davidmoten.junit.Asserts; import com.github.davidmoten.rx2.observable.CloseableObservableWithReset; import io.reactivex.Flowable; import io.reactivex.Observable; import io.reactivex.annotations.NonNull; import io.reactivex.functions.Consumer; import io.reactivex.schedulers.Schedulers; import org.junit.Test; import org.reactivestreams.Subscription; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import static org.junit.Assert.assertTrue;
package com.github.davidmoten.rx2; public class ObservablesTest { @Test public void isUtilityClass() { Asserts.assertIsUtilityClass(Observables.class); } @Test public void testCache() { final AtomicInteger subscriptionCount = new AtomicInteger(0); Flowable<String> source = Flowable.just("Alpha", "Beta", "Gamma", "Delta", "Epsilon");
// Path: src/main/java/com/github/davidmoten/rx2/observable/CloseableObservableWithReset.java // public final class CloseableObservableWithReset<T> { // // private final Observable<T> observable; // private final Runnable closeAction; // private final Runnable resetAction; // // public CloseableObservableWithReset(Observable<T> observable, Runnable closeAction, Runnable resetAction) { // this.observable = observable; // this.closeAction = closeAction; // this.resetAction = resetAction; // } // // public Observable<T> observable() { // return observable; // } // // public void reset() { // resetAction.run(); // } // // public void close() { // closeAction.run(); // } // // } // Path: src/test/java/com/github/davidmoten/rx2/ObservablesTest.java import com.github.davidmoten.junit.Asserts; import com.github.davidmoten.rx2.observable.CloseableObservableWithReset; import io.reactivex.Flowable; import io.reactivex.Observable; import io.reactivex.annotations.NonNull; import io.reactivex.functions.Consumer; import io.reactivex.schedulers.Schedulers; import org.junit.Test; import org.reactivestreams.Subscription; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import static org.junit.Assert.assertTrue; package com.github.davidmoten.rx2; public class ObservablesTest { @Test public void isUtilityClass() { Asserts.assertIsUtilityClass(Observables.class); } @Test public void testCache() { final AtomicInteger subscriptionCount = new AtomicInteger(0); Flowable<String> source = Flowable.just("Alpha", "Beta", "Gamma", "Delta", "Epsilon");
final CloseableObservableWithReset<List<String>> closeable = Observables
davidmoten/rxjava2-extras
src/main/java/com/github/davidmoten/rx2/BiPredicates.java
// Path: src/main/java/com/github/davidmoten/rx2/exceptions/ThrowingException.java // public final class ThrowingException extends RuntimeException { // // private static final long serialVersionUID = 8336479045139136638L; // // }
import com.github.davidmoten.rx2.exceptions.ThrowingException; import io.reactivex.functions.BiPredicate;
package com.github.davidmoten.rx2; public final class BiPredicates { private BiPredicates() { // prevent instantiation } public static <T, R> BiPredicate<T, R> alwaysTrue() { // TODO make holder return new BiPredicate<T, R>() { @Override public boolean test(T t1, R t2) throws Exception { return true; } }; } public static <T, R> BiPredicate<T, R> alwaysFalse() { // TODO make holder return new BiPredicate<T, R>() { @Override public boolean test(T t1, R t2) throws Exception { return false; } }; } public static <T, R> BiPredicate<T, R> throwing() { // TODO make holder return new BiPredicate<T, R>() { @Override public boolean test(T t1, R t2) throws Exception {
// Path: src/main/java/com/github/davidmoten/rx2/exceptions/ThrowingException.java // public final class ThrowingException extends RuntimeException { // // private static final long serialVersionUID = 8336479045139136638L; // // } // Path: src/main/java/com/github/davidmoten/rx2/BiPredicates.java import com.github.davidmoten.rx2.exceptions.ThrowingException; import io.reactivex.functions.BiPredicate; package com.github.davidmoten.rx2; public final class BiPredicates { private BiPredicates() { // prevent instantiation } public static <T, R> BiPredicate<T, R> alwaysTrue() { // TODO make holder return new BiPredicate<T, R>() { @Override public boolean test(T t1, R t2) throws Exception { return true; } }; } public static <T, R> BiPredicate<T, R> alwaysFalse() { // TODO make holder return new BiPredicate<T, R>() { @Override public boolean test(T t1, R t2) throws Exception { return false; } }; } public static <T, R> BiPredicate<T, R> throwing() { // TODO make holder return new BiPredicate<T, R>() { @Override public boolean test(T t1, R t2) throws Exception {
throw new ThrowingException();
davidmoten/rxjava2-extras
src/test/java/com/github/davidmoten/rx2/FlowablesTest.java
// Path: src/main/java/com/github/davidmoten/rx2/flowable/CloseableFlowableWithReset.java // public final class CloseableFlowableWithReset<T> { // // private final Flowable<T> flowable; // private final Runnable closeAction; // private final Runnable resetAction; // // public CloseableFlowableWithReset(Flowable<T> flowable, Runnable closeAction, Runnable resetAction) { // this.flowable = flowable; // this.closeAction = closeAction; // this.resetAction = resetAction; // } // // public Flowable<T> flowable() { // return flowable; // } // // public void reset() { // resetAction.run(); // } // // public void close() { // closeAction.run(); // } // // }
import io.reactivex.Flowable; import io.reactivex.annotations.NonNull; import io.reactivex.functions.Consumer; import io.reactivex.schedulers.Schedulers; import org.junit.Test; import com.github.davidmoten.junit.Asserts; import com.github.davidmoten.rx2.flowable.CloseableFlowableWithReset; import org.reactivestreams.Subscription; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import static org.junit.Assert.assertTrue;
package com.github.davidmoten.rx2; public class FlowablesTest { @Test public void isUtilityClass() { Asserts.assertIsUtilityClass(Flowables.class); } @Test public void testCache() { final AtomicInteger subscriptionCount = new AtomicInteger(0); Flowable<String> source = Flowable.just("Alpha", "Beta", "Gamma", "Delta", "Epsilon");
// Path: src/main/java/com/github/davidmoten/rx2/flowable/CloseableFlowableWithReset.java // public final class CloseableFlowableWithReset<T> { // // private final Flowable<T> flowable; // private final Runnable closeAction; // private final Runnable resetAction; // // public CloseableFlowableWithReset(Flowable<T> flowable, Runnable closeAction, Runnable resetAction) { // this.flowable = flowable; // this.closeAction = closeAction; // this.resetAction = resetAction; // } // // public Flowable<T> flowable() { // return flowable; // } // // public void reset() { // resetAction.run(); // } // // public void close() { // closeAction.run(); // } // // } // Path: src/test/java/com/github/davidmoten/rx2/FlowablesTest.java import io.reactivex.Flowable; import io.reactivex.annotations.NonNull; import io.reactivex.functions.Consumer; import io.reactivex.schedulers.Schedulers; import org.junit.Test; import com.github.davidmoten.junit.Asserts; import com.github.davidmoten.rx2.flowable.CloseableFlowableWithReset; import org.reactivestreams.Subscription; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import static org.junit.Assert.assertTrue; package com.github.davidmoten.rx2; public class FlowablesTest { @Test public void isUtilityClass() { Asserts.assertIsUtilityClass(Flowables.class); } @Test public void testCache() { final AtomicInteger subscriptionCount = new AtomicInteger(0); Flowable<String> source = Flowable.just("Alpha", "Beta", "Gamma", "Delta", "Epsilon");
final CloseableFlowableWithReset<List<String>> closeable = Flowables.cache(
davidmoten/rxjava2-extras
src/main/java/com/github/davidmoten/rx2/buffertofile/Serializers.java
// Path: src/main/java/com/github/davidmoten/rx2/internal/flowable/buffertofile/SerializerBytes.java // public final class SerializerBytes implements Serializer<byte[]> { // // @Override // public byte[] serialize(byte[] t) throws IOException { // return t; // } // // @Override // public byte[] deserialize(byte[] bytes) throws ClassNotFoundException, IOException { // return bytes; // } // // } // // Path: src/main/java/com/github/davidmoten/rx2/internal/flowable/buffertofile/SerializerJavaIO.java // public final class SerializerJavaIO<T extends Serializable> implements Serializer<T> { // // @Override // public byte[] serialize(Serializable t) throws IOException { // ByteArrayOutputStream bos = new ByteArrayOutputStream(); // ObjectOutputStream oos = new ObjectOutputStream(bos); // oos.writeObject(t); // bos.close(); // return bos.toByteArray(); // } // // @Override // public T deserialize(byte[] bytes) throws ClassNotFoundException, IOException { // ByteArrayInputStream bis = new ByteArrayInputStream(bytes); // ObjectInputStream ois = null; // try { // ois = new ObjectInputStream(bis); // @SuppressWarnings("unchecked") // T t = (T) ois.readObject(); // return t; // } finally { // if (ois != null) { // ois.close(); // } // } // } // // }
import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.Serializable; import java.nio.charset.Charset; import com.github.davidmoten.rx2.internal.flowable.buffertofile.SerializerBytes; import com.github.davidmoten.rx2.internal.flowable.buffertofile.SerializerJavaIO;
package com.github.davidmoten.rx2.buffertofile; public final class Serializers { private static final Charset UTF_8 = Charset.forName("UTF-8"); private Serializers() { // prevent initialization } public static <T extends Serializable> Serializer<T> javaIO() { // TODO use holder
// Path: src/main/java/com/github/davidmoten/rx2/internal/flowable/buffertofile/SerializerBytes.java // public final class SerializerBytes implements Serializer<byte[]> { // // @Override // public byte[] serialize(byte[] t) throws IOException { // return t; // } // // @Override // public byte[] deserialize(byte[] bytes) throws ClassNotFoundException, IOException { // return bytes; // } // // } // // Path: src/main/java/com/github/davidmoten/rx2/internal/flowable/buffertofile/SerializerJavaIO.java // public final class SerializerJavaIO<T extends Serializable> implements Serializer<T> { // // @Override // public byte[] serialize(Serializable t) throws IOException { // ByteArrayOutputStream bos = new ByteArrayOutputStream(); // ObjectOutputStream oos = new ObjectOutputStream(bos); // oos.writeObject(t); // bos.close(); // return bos.toByteArray(); // } // // @Override // public T deserialize(byte[] bytes) throws ClassNotFoundException, IOException { // ByteArrayInputStream bis = new ByteArrayInputStream(bytes); // ObjectInputStream ois = null; // try { // ois = new ObjectInputStream(bis); // @SuppressWarnings("unchecked") // T t = (T) ois.readObject(); // return t; // } finally { // if (ois != null) { // ois.close(); // } // } // } // // } // Path: src/main/java/com/github/davidmoten/rx2/buffertofile/Serializers.java import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.Serializable; import java.nio.charset.Charset; import com.github.davidmoten.rx2.internal.flowable.buffertofile.SerializerBytes; import com.github.davidmoten.rx2.internal.flowable.buffertofile.SerializerJavaIO; package com.github.davidmoten.rx2.buffertofile; public final class Serializers { private static final Charset UTF_8 = Charset.forName("UTF-8"); private Serializers() { // prevent initialization } public static <T extends Serializable> Serializer<T> javaIO() { // TODO use holder
return new SerializerJavaIO<T>();
davidmoten/rxjava2-extras
src/main/java/com/github/davidmoten/rx2/buffertofile/Serializers.java
// Path: src/main/java/com/github/davidmoten/rx2/internal/flowable/buffertofile/SerializerBytes.java // public final class SerializerBytes implements Serializer<byte[]> { // // @Override // public byte[] serialize(byte[] t) throws IOException { // return t; // } // // @Override // public byte[] deserialize(byte[] bytes) throws ClassNotFoundException, IOException { // return bytes; // } // // } // // Path: src/main/java/com/github/davidmoten/rx2/internal/flowable/buffertofile/SerializerJavaIO.java // public final class SerializerJavaIO<T extends Serializable> implements Serializer<T> { // // @Override // public byte[] serialize(Serializable t) throws IOException { // ByteArrayOutputStream bos = new ByteArrayOutputStream(); // ObjectOutputStream oos = new ObjectOutputStream(bos); // oos.writeObject(t); // bos.close(); // return bos.toByteArray(); // } // // @Override // public T deserialize(byte[] bytes) throws ClassNotFoundException, IOException { // ByteArrayInputStream bis = new ByteArrayInputStream(bytes); // ObjectInputStream ois = null; // try { // ois = new ObjectInputStream(bis); // @SuppressWarnings("unchecked") // T t = (T) ois.readObject(); // return t; // } finally { // if (ois != null) { // ois.close(); // } // } // } // // }
import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.Serializable; import java.nio.charset.Charset; import com.github.davidmoten.rx2.internal.flowable.buffertofile.SerializerBytes; import com.github.davidmoten.rx2.internal.flowable.buffertofile.SerializerJavaIO;
package com.github.davidmoten.rx2.buffertofile; public final class Serializers { private static final Charset UTF_8 = Charset.forName("UTF-8"); private Serializers() { // prevent initialization } public static <T extends Serializable> Serializer<T> javaIO() { // TODO use holder return new SerializerJavaIO<T>(); } public static Serializer<byte[]> bytes() { // TODO use holder
// Path: src/main/java/com/github/davidmoten/rx2/internal/flowable/buffertofile/SerializerBytes.java // public final class SerializerBytes implements Serializer<byte[]> { // // @Override // public byte[] serialize(byte[] t) throws IOException { // return t; // } // // @Override // public byte[] deserialize(byte[] bytes) throws ClassNotFoundException, IOException { // return bytes; // } // // } // // Path: src/main/java/com/github/davidmoten/rx2/internal/flowable/buffertofile/SerializerJavaIO.java // public final class SerializerJavaIO<T extends Serializable> implements Serializer<T> { // // @Override // public byte[] serialize(Serializable t) throws IOException { // ByteArrayOutputStream bos = new ByteArrayOutputStream(); // ObjectOutputStream oos = new ObjectOutputStream(bos); // oos.writeObject(t); // bos.close(); // return bos.toByteArray(); // } // // @Override // public T deserialize(byte[] bytes) throws ClassNotFoundException, IOException { // ByteArrayInputStream bis = new ByteArrayInputStream(bytes); // ObjectInputStream ois = null; // try { // ois = new ObjectInputStream(bis); // @SuppressWarnings("unchecked") // T t = (T) ois.readObject(); // return t; // } finally { // if (ois != null) { // ois.close(); // } // } // } // // } // Path: src/main/java/com/github/davidmoten/rx2/buffertofile/Serializers.java import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.Serializable; import java.nio.charset.Charset; import com.github.davidmoten.rx2.internal.flowable.buffertofile.SerializerBytes; import com.github.davidmoten.rx2.internal.flowable.buffertofile.SerializerJavaIO; package com.github.davidmoten.rx2.buffertofile; public final class Serializers { private static final Charset UTF_8 = Charset.forName("UTF-8"); private Serializers() { // prevent initialization } public static <T extends Serializable> Serializer<T> javaIO() { // TODO use holder return new SerializerJavaIO<T>(); } public static Serializer<byte[]> bytes() { // TODO use holder
return new SerializerBytes();
davidmoten/rxjava2-extras
src/main/java/com/github/davidmoten/rx2/SchedulerHelper.java
// Path: src/main/java/com/github/davidmoten/rx2/internal/SchedulerWithId.java // public final class SchedulerWithId extends Scheduler { // // private final Scheduler scheduler; // private final String id; // private final static Pattern pattern = Pattern.compile("\\bschedId=\\[[^\\]]+\\]+\\b"); // // public SchedulerWithId(Scheduler scheduler, String id) { // this.scheduler = scheduler; // this.id = "[" + id + "]"; // } // // @Override // public Worker createWorker() { // // final Worker worker = scheduler.createWorker(); // Worker w = new Worker() { // // @Override // public Disposable schedule(final Runnable action, long delayTime, TimeUnit unit) { // Runnable a = new Runnable() { // @Override // public void run() { // String name = null; // try { // name = setThreadName(); // action.run(); // } finally { // if (name != null) { // Thread.currentThread().setName(name); // } // } // } // }; // return worker.schedule(a, delayTime, unit); // } // // @Override // public void dispose() { // worker.dispose(); // } // // @Override // public boolean isDisposed() { // return worker.isDisposed(); // } // // }; // return w; // // } // // private String setThreadName() { // String name = Thread.currentThread().getName(); // String newName = updateNameWithId(name, id); // Thread.currentThread().setName(newName); // return name; // } // // private static String updateNameWithId(String name, String id) { // final String newName; // if (name == null) { // newName = id; // } else { // Matcher matcher = pattern.matcher(name); // if (matcher.find()) { // newName = name.replace(matcher.group(), "schedId=" + id); // } else { // newName = name + "|schedId=" + id; // } // } // return newName; // } // // }
import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import com.github.davidmoten.rx2.internal.SchedulerWithId; import io.reactivex.Scheduler; import io.reactivex.Scheduler.Worker;
package com.github.davidmoten.rx2; public final class SchedulerHelper { private SchedulerHelper() { // prevent instantiation } public static Scheduler withThreadIdFromCallSite(Scheduler scheduler) {
// Path: src/main/java/com/github/davidmoten/rx2/internal/SchedulerWithId.java // public final class SchedulerWithId extends Scheduler { // // private final Scheduler scheduler; // private final String id; // private final static Pattern pattern = Pattern.compile("\\bschedId=\\[[^\\]]+\\]+\\b"); // // public SchedulerWithId(Scheduler scheduler, String id) { // this.scheduler = scheduler; // this.id = "[" + id + "]"; // } // // @Override // public Worker createWorker() { // // final Worker worker = scheduler.createWorker(); // Worker w = new Worker() { // // @Override // public Disposable schedule(final Runnable action, long delayTime, TimeUnit unit) { // Runnable a = new Runnable() { // @Override // public void run() { // String name = null; // try { // name = setThreadName(); // action.run(); // } finally { // if (name != null) { // Thread.currentThread().setName(name); // } // } // } // }; // return worker.schedule(a, delayTime, unit); // } // // @Override // public void dispose() { // worker.dispose(); // } // // @Override // public boolean isDisposed() { // return worker.isDisposed(); // } // // }; // return w; // // } // // private String setThreadName() { // String name = Thread.currentThread().getName(); // String newName = updateNameWithId(name, id); // Thread.currentThread().setName(newName); // return name; // } // // private static String updateNameWithId(String name, String id) { // final String newName; // if (name == null) { // newName = id; // } else { // Matcher matcher = pattern.matcher(name); // if (matcher.find()) { // newName = name.replace(matcher.group(), "schedId=" + id); // } else { // newName = name + "|schedId=" + id; // } // } // return newName; // } // // } // Path: src/main/java/com/github/davidmoten/rx2/SchedulerHelper.java import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import com.github.davidmoten.rx2.internal.SchedulerWithId; import io.reactivex.Scheduler; import io.reactivex.Scheduler.Worker; package com.github.davidmoten.rx2; public final class SchedulerHelper { private SchedulerHelper() { // prevent instantiation } public static Scheduler withThreadIdFromCallSite(Scheduler scheduler) {
return new SchedulerWithId(scheduler, describeCallSite());
jimdowling/nat-traverser
stun/upnp/src/main/java/org/cybergarage/upnp/Service.java
// Path: stun/upnp/src/main/java/org/cybergarage/xml/Parser.java // public abstract class Parser // { // //////////////////////////////////////////////// // // Constructor // //////////////////////////////////////////////// // // public Parser() // { // } // // //////////////////////////////////////////////// // // parse // //////////////////////////////////////////////// // // public abstract Node parse(InputStream inStream) throws ParserException; // // //////////////////////////////////////////////// // // parse (URL) // //////////////////////////////////////////////// // // public Node parse(URL locationURL) throws ParserException // { // String host = locationURL.getHost(); // int port = locationURL.getPort(); // String uri = locationURL.getPath(); // // try { // HttpURLConnection urlCon = (HttpURLConnection)locationURL.openConnection(); // urlCon.setRequestMethod("GET"); // urlCon.setRequestProperty(HTTP.CONTENT_LENGTH,"0"); // if (host != null) // urlCon.setRequestProperty(HTTP.HOST, host); // // InputStream urlIn = urlCon.getInputStream(); // // Node rootElem = parse(urlIn); // // urlIn.close(); // urlCon.disconnect(); // // return rootElem; // // } catch (Exception e) { // //throw new ParserException(e); // } // // HTTPRequest httpReq = new HTTPRequest(); // httpReq.setMethod(HTTP.GET); // httpReq.setURI(uri); // HTTPResponse httpRes = httpReq.post(host, port); // if (httpRes.isSuccessful() == false) // throw new ParserException("HTTP comunication failed: no answer from peer." + // "Unable to retrive resoure -> "+locationURL.toString()); // String content = new String(httpRes.getContent()); // ByteArrayInputStream strBuf = new ByteArrayInputStream(content.getBytes()); // return parse(strBuf); // } // // //////////////////////////////////////////////// // // parse (File) // //////////////////////////////////////////////// // // public Node parse(File descriptionFile) throws ParserException // { // try { // InputStream fileIn = new FileInputStream(descriptionFile); // Node root = parse(fileIn); // fileIn.close(); // return root; // // } catch (Exception e) { // throw new ParserException(e); // } // } // // //////////////////////////////////////////////// // // parse (Memory) // //////////////////////////////////////////////// // // public Node parse(String descr) throws ParserException // { // try { // InputStream decrIn = new ByteArrayInputStream(descr.getBytes()); // Node root = parse(decrIn); // return root; // } catch (Exception e) { // throw new ParserException(e); // } // } // // }
import java.io.File; import java.io.InputStream; import java.net.URL; import java.util.Iterator; import org.cybergarage.http.HTTP; import org.cybergarage.http.HTTPResponse; import org.cybergarage.upnp.control.ActionListener; import org.cybergarage.upnp.control.QueryListener; import org.cybergarage.upnp.device.InvalidDescriptionException; import org.cybergarage.upnp.device.NTS; import org.cybergarage.upnp.device.ST; import org.cybergarage.upnp.event.NotifyRequest; import org.cybergarage.upnp.event.Subscriber; import org.cybergarage.upnp.event.SubscriberList; import org.cybergarage.upnp.ssdp.SSDPNotifyRequest; import org.cybergarage.upnp.ssdp.SSDPNotifySocket; import org.cybergarage.upnp.ssdp.SSDPPacket; import org.cybergarage.upnp.xml.ServiceData; import org.cybergarage.util.Debug; import org.cybergarage.util.Mutex; import org.cybergarage.util.StringUtil; import org.cybergarage.xml.Node; import org.cybergarage.xml.Parser; import org.cybergarage.xml.ParserException;
} //////////////////////////////////////////////// // eventSubURL //////////////////////////////////////////////// private final static String EVENT_SUB_URL = "eventSubURL"; public void setEventSubURL(String value) { getServiceNode().setNode(EVENT_SUB_URL, value); } public String getEventSubURL() { return getServiceNode().getNodeValue(EVENT_SUB_URL); } public boolean isEventSubURL(String url) { return isURL(getEventSubURL(), url); } //////////////////////////////////////////////// // SCPD node //////////////////////////////////////////////// public boolean loadSCPD(String scpdStr) throws InvalidDescriptionException { try {
// Path: stun/upnp/src/main/java/org/cybergarage/xml/Parser.java // public abstract class Parser // { // //////////////////////////////////////////////// // // Constructor // //////////////////////////////////////////////// // // public Parser() // { // } // // //////////////////////////////////////////////// // // parse // //////////////////////////////////////////////// // // public abstract Node parse(InputStream inStream) throws ParserException; // // //////////////////////////////////////////////// // // parse (URL) // //////////////////////////////////////////////// // // public Node parse(URL locationURL) throws ParserException // { // String host = locationURL.getHost(); // int port = locationURL.getPort(); // String uri = locationURL.getPath(); // // try { // HttpURLConnection urlCon = (HttpURLConnection)locationURL.openConnection(); // urlCon.setRequestMethod("GET"); // urlCon.setRequestProperty(HTTP.CONTENT_LENGTH,"0"); // if (host != null) // urlCon.setRequestProperty(HTTP.HOST, host); // // InputStream urlIn = urlCon.getInputStream(); // // Node rootElem = parse(urlIn); // // urlIn.close(); // urlCon.disconnect(); // // return rootElem; // // } catch (Exception e) { // //throw new ParserException(e); // } // // HTTPRequest httpReq = new HTTPRequest(); // httpReq.setMethod(HTTP.GET); // httpReq.setURI(uri); // HTTPResponse httpRes = httpReq.post(host, port); // if (httpRes.isSuccessful() == false) // throw new ParserException("HTTP comunication failed: no answer from peer." + // "Unable to retrive resoure -> "+locationURL.toString()); // String content = new String(httpRes.getContent()); // ByteArrayInputStream strBuf = new ByteArrayInputStream(content.getBytes()); // return parse(strBuf); // } // // //////////////////////////////////////////////// // // parse (File) // //////////////////////////////////////////////// // // public Node parse(File descriptionFile) throws ParserException // { // try { // InputStream fileIn = new FileInputStream(descriptionFile); // Node root = parse(fileIn); // fileIn.close(); // return root; // // } catch (Exception e) { // throw new ParserException(e); // } // } // // //////////////////////////////////////////////// // // parse (Memory) // //////////////////////////////////////////////// // // public Node parse(String descr) throws ParserException // { // try { // InputStream decrIn = new ByteArrayInputStream(descr.getBytes()); // Node root = parse(decrIn); // return root; // } catch (Exception e) { // throw new ParserException(e); // } // } // // } // Path: stun/upnp/src/main/java/org/cybergarage/upnp/Service.java import java.io.File; import java.io.InputStream; import java.net.URL; import java.util.Iterator; import org.cybergarage.http.HTTP; import org.cybergarage.http.HTTPResponse; import org.cybergarage.upnp.control.ActionListener; import org.cybergarage.upnp.control.QueryListener; import org.cybergarage.upnp.device.InvalidDescriptionException; import org.cybergarage.upnp.device.NTS; import org.cybergarage.upnp.device.ST; import org.cybergarage.upnp.event.NotifyRequest; import org.cybergarage.upnp.event.Subscriber; import org.cybergarage.upnp.event.SubscriberList; import org.cybergarage.upnp.ssdp.SSDPNotifyRequest; import org.cybergarage.upnp.ssdp.SSDPNotifySocket; import org.cybergarage.upnp.ssdp.SSDPPacket; import org.cybergarage.upnp.xml.ServiceData; import org.cybergarage.util.Debug; import org.cybergarage.util.Mutex; import org.cybergarage.util.StringUtil; import org.cybergarage.xml.Node; import org.cybergarage.xml.Parser; import org.cybergarage.xml.ParserException; } //////////////////////////////////////////////// // eventSubURL //////////////////////////////////////////////// private final static String EVENT_SUB_URL = "eventSubURL"; public void setEventSubURL(String value) { getServiceNode().setNode(EVENT_SUB_URL, value); } public String getEventSubURL() { return getServiceNode().getNodeValue(EVENT_SUB_URL); } public boolean isEventSubURL(String url) { return isURL(getEventSubURL(), url); } //////////////////////////////////////////////// // SCPD node //////////////////////////////////////////////// public boolean loadSCPD(String scpdStr) throws InvalidDescriptionException { try {
Parser parser = UPnP.getXMLParser();
jimdowling/nat-traverser
simulators/src/main/java/se/sics/gvod/simulator/nattraverser/NatTraverserSimulatorInit.java
// Path: hole-punching/hp-client/src/main/java/se/sics/gvod/config/HpClientConfiguration.java // public class HpClientConfiguration extends AbstractConfiguration<HpClientConfiguration> { // // /** // * Fields cannot be private. Package protected, ok. // */ // int sessionExpirationTime; // int scanRetries; // boolean scanningEnabled; // int rto; // int rtoRetries; // double rtoScale; // // /** // * Default constructor comes first. // */ // public HpClientConfiguration() { // this( // VodConfig.HP_SESSION_EXPIRATION, // VodConfig.HP_SCANNING_RETRIES, // true, // VodConfig.DEFAULT_RTO, // VodConfig.DEFAULT_RTO_RETRIES, // VodConfig.DEFAULT_RTO_SCALE // ); // } // // /** // * Full argument constructor comes second. // */ // public HpClientConfiguration(int sessionExpirationTime, // int scanRetries, boolean scanningEnabled, // int rto, // int rtoRetries, // double rtoScale) { // this.scanRetries = scanRetries; // this.sessionExpirationTime = sessionExpirationTime; // this.scanningEnabled = scanningEnabled; // this.rto = rto; // this.rtoRetries = rtoRetries; // this.rtoScale = rtoScale; // } // // public static HpClientConfiguration build() { // return new HpClientConfiguration(); // } // // public int getRtoRetries() { // return rtoRetries; // } // // public double getRtoScale() { // return rtoScale; // } // // public int getRto() { // return rto; // } // // public int getScanRetries() { // return scanRetries; // } // // public boolean isScanningEnabled() { // return scanningEnabled; // } // // public int getSessionExpirationTime() { // return sessionExpirationTime; // } // // public HpClientConfiguration setRto(int rto) { // this.rto = rto; // return this; // } // // public HpClientConfiguration setRtoRetries(int rtoRetries) { // this.rtoRetries = rtoRetries; // return this; // } // // public HpClientConfiguration setRtoScale(double rtoScale) { // this.rtoScale = rtoScale; // return this; // } // // public HpClientConfiguration setScanRetries(int scanRetries) { // this.scanRetries = scanRetries; // return this; // } // // public HpClientConfiguration setScanningEnabled(boolean scanningEnabled) { // this.scanningEnabled = scanningEnabled; // return this; // } // // public HpClientConfiguration setSessionExpirationTime(int sessionExpirationTime) { // this.sessionExpirationTime = sessionExpirationTime; // return this; // } // }
import se.sics.gvod.config.CroupierConfiguration; import se.sics.gvod.config.HpClientConfiguration; import se.sics.gvod.config.NatConfiguration; import se.sics.gvod.config.RendezvousServerConfiguration; import se.sics.gvod.config.NatTraverserConfiguration; import se.sics.gvod.config.ParentMakerConfiguration; import se.sics.gvod.config.StunClientConfiguration; import se.sics.gvod.config.StunServerConfiguration; import se.sics.kompics.Init;
package se.sics.gvod.simulator.nattraverser; public final class NatTraverserSimulatorInit extends Init { private final NatTraverserConfiguration natTraverserConfig; private final ParentMakerConfiguration parentMakerConfig;
// Path: hole-punching/hp-client/src/main/java/se/sics/gvod/config/HpClientConfiguration.java // public class HpClientConfiguration extends AbstractConfiguration<HpClientConfiguration> { // // /** // * Fields cannot be private. Package protected, ok. // */ // int sessionExpirationTime; // int scanRetries; // boolean scanningEnabled; // int rto; // int rtoRetries; // double rtoScale; // // /** // * Default constructor comes first. // */ // public HpClientConfiguration() { // this( // VodConfig.HP_SESSION_EXPIRATION, // VodConfig.HP_SCANNING_RETRIES, // true, // VodConfig.DEFAULT_RTO, // VodConfig.DEFAULT_RTO_RETRIES, // VodConfig.DEFAULT_RTO_SCALE // ); // } // // /** // * Full argument constructor comes second. // */ // public HpClientConfiguration(int sessionExpirationTime, // int scanRetries, boolean scanningEnabled, // int rto, // int rtoRetries, // double rtoScale) { // this.scanRetries = scanRetries; // this.sessionExpirationTime = sessionExpirationTime; // this.scanningEnabled = scanningEnabled; // this.rto = rto; // this.rtoRetries = rtoRetries; // this.rtoScale = rtoScale; // } // // public static HpClientConfiguration build() { // return new HpClientConfiguration(); // } // // public int getRtoRetries() { // return rtoRetries; // } // // public double getRtoScale() { // return rtoScale; // } // // public int getRto() { // return rto; // } // // public int getScanRetries() { // return scanRetries; // } // // public boolean isScanningEnabled() { // return scanningEnabled; // } // // public int getSessionExpirationTime() { // return sessionExpirationTime; // } // // public HpClientConfiguration setRto(int rto) { // this.rto = rto; // return this; // } // // public HpClientConfiguration setRtoRetries(int rtoRetries) { // this.rtoRetries = rtoRetries; // return this; // } // // public HpClientConfiguration setRtoScale(double rtoScale) { // this.rtoScale = rtoScale; // return this; // } // // public HpClientConfiguration setScanRetries(int scanRetries) { // this.scanRetries = scanRetries; // return this; // } // // public HpClientConfiguration setScanningEnabled(boolean scanningEnabled) { // this.scanningEnabled = scanningEnabled; // return this; // } // // public HpClientConfiguration setSessionExpirationTime(int sessionExpirationTime) { // this.sessionExpirationTime = sessionExpirationTime; // return this; // } // } // Path: simulators/src/main/java/se/sics/gvod/simulator/nattraverser/NatTraverserSimulatorInit.java import se.sics.gvod.config.CroupierConfiguration; import se.sics.gvod.config.HpClientConfiguration; import se.sics.gvod.config.NatConfiguration; import se.sics.gvod.config.RendezvousServerConfiguration; import se.sics.gvod.config.NatTraverserConfiguration; import se.sics.gvod.config.ParentMakerConfiguration; import se.sics.gvod.config.StunClientConfiguration; import se.sics.gvod.config.StunServerConfiguration; import se.sics.kompics.Init; package se.sics.gvod.simulator.nattraverser; public final class NatTraverserSimulatorInit extends Init { private final NatTraverserConfiguration natTraverserConfig; private final ParentMakerConfiguration parentMakerConfig;
private final HpClientConfiguration hpClientConfig;
jimdowling/nat-traverser
stun/upnp/src/main/java/org/cybergarage/upnp/Device.java
// Path: stun/upnp/src/main/java/org/cybergarage/xml/Parser.java // public abstract class Parser // { // //////////////////////////////////////////////// // // Constructor // //////////////////////////////////////////////// // // public Parser() // { // } // // //////////////////////////////////////////////// // // parse // //////////////////////////////////////////////// // // public abstract Node parse(InputStream inStream) throws ParserException; // // //////////////////////////////////////////////// // // parse (URL) // //////////////////////////////////////////////// // // public Node parse(URL locationURL) throws ParserException // { // String host = locationURL.getHost(); // int port = locationURL.getPort(); // String uri = locationURL.getPath(); // // try { // HttpURLConnection urlCon = (HttpURLConnection)locationURL.openConnection(); // urlCon.setRequestMethod("GET"); // urlCon.setRequestProperty(HTTP.CONTENT_LENGTH,"0"); // if (host != null) // urlCon.setRequestProperty(HTTP.HOST, host); // // InputStream urlIn = urlCon.getInputStream(); // // Node rootElem = parse(urlIn); // // urlIn.close(); // urlCon.disconnect(); // // return rootElem; // // } catch (Exception e) { // //throw new ParserException(e); // } // // HTTPRequest httpReq = new HTTPRequest(); // httpReq.setMethod(HTTP.GET); // httpReq.setURI(uri); // HTTPResponse httpRes = httpReq.post(host, port); // if (httpRes.isSuccessful() == false) // throw new ParserException("HTTP comunication failed: no answer from peer." + // "Unable to retrive resoure -> "+locationURL.toString()); // String content = new String(httpRes.getContent()); // ByteArrayInputStream strBuf = new ByteArrayInputStream(content.getBytes()); // return parse(strBuf); // } // // //////////////////////////////////////////////// // // parse (File) // //////////////////////////////////////////////// // // public Node parse(File descriptionFile) throws ParserException // { // try { // InputStream fileIn = new FileInputStream(descriptionFile); // Node root = parse(fileIn); // fileIn.close(); // return root; // // } catch (Exception e) { // throw new ParserException(e); // } // } // // //////////////////////////////////////////////// // // parse (Memory) // //////////////////////////////////////////////// // // public Node parse(String descr) throws ParserException // { // try { // InputStream decrIn = new ByteArrayInputStream(descr.getBytes()); // Node root = parse(decrIn); // return root; // } catch (Exception e) { // throw new ParserException(e); // } // } // // }
import org.cybergarage.upnp.event.SubscriptionResponse; import org.cybergarage.upnp.ssdp.SSDPNotifyRequest; import org.cybergarage.upnp.ssdp.SSDPNotifySocket; import org.cybergarage.upnp.ssdp.SSDPPacket; import org.cybergarage.upnp.ssdp.SSDPSearchResponse; import org.cybergarage.upnp.ssdp.SSDPSearchResponseSocket; import org.cybergarage.upnp.ssdp.SSDPSearchSocketList; import org.cybergarage.upnp.xml.DeviceData; import org.cybergarage.upnp.xml.ServiceData; import org.cybergarage.util.Debug; import org.cybergarage.util.FileUtil; import org.cybergarage.util.Mutex; import org.cybergarage.util.TimerUtil; import org.cybergarage.xml.Node; import org.cybergarage.xml.Parser; import org.cybergarage.xml.ParserException; import org.cybergarage.xml.XML; import org.cybergarage.http.HTTP; import java.io.File; import java.io.InputStream; import java.net.InetAddress; import java.net.URL; import java.util.Calendar; import org.cybergarage.http.HTTP; import org.cybergarage.http.HTTPRequest; import org.cybergarage.http.HTTPResponse; import org.cybergarage.http.HTTPServerList; import org.cybergarage.http.HTTPStatus; import org.cybergarage.net.HostInterface; import org.cybergarage.soap.SOAPResponse; import org.cybergarage.upnp.control.ActionListener; import org.cybergarage.upnp.control.ActionRequest; import org.cybergarage.upnp.control.ActionResponse; import org.cybergarage.upnp.control.ControlRequest; import org.cybergarage.upnp.control.ControlResponse; import org.cybergarage.upnp.control.QueryListener; import org.cybergarage.upnp.control.QueryRequest; import org.cybergarage.upnp.device.Advertiser; import org.cybergarage.upnp.device.Description; import org.cybergarage.upnp.device.InvalidDescriptionException; import org.cybergarage.upnp.device.NTS; import org.cybergarage.upnp.device.ST; import org.cybergarage.upnp.device.SearchListener; import org.cybergarage.upnp.device.USN; import org.cybergarage.upnp.event.Subscriber; import org.cybergarage.upnp.event.Subscription; import org.cybergarage.upnp.event.SubscriptionRequest;
getDeviceData().setDescriptionURI(uri); } private String getDescriptionURI() { return getDeviceData().getDescriptionURI(); } private boolean isDescriptionURI(String uri) { String descriptionURI = getDescriptionURI(); if (uri == null || descriptionURI == null) return false; return descriptionURI.equals(uri); } public String getDescriptionFilePath() { File descriptionFile = getDescriptionFile(); if (descriptionFile == null) return ""; return descriptionFile.getAbsoluteFile().getParent(); } /** * @since 1.8.0 */ public boolean loadDescription(InputStream input) throws InvalidDescriptionException { try {
// Path: stun/upnp/src/main/java/org/cybergarage/xml/Parser.java // public abstract class Parser // { // //////////////////////////////////////////////// // // Constructor // //////////////////////////////////////////////// // // public Parser() // { // } // // //////////////////////////////////////////////// // // parse // //////////////////////////////////////////////// // // public abstract Node parse(InputStream inStream) throws ParserException; // // //////////////////////////////////////////////// // // parse (URL) // //////////////////////////////////////////////// // // public Node parse(URL locationURL) throws ParserException // { // String host = locationURL.getHost(); // int port = locationURL.getPort(); // String uri = locationURL.getPath(); // // try { // HttpURLConnection urlCon = (HttpURLConnection)locationURL.openConnection(); // urlCon.setRequestMethod("GET"); // urlCon.setRequestProperty(HTTP.CONTENT_LENGTH,"0"); // if (host != null) // urlCon.setRequestProperty(HTTP.HOST, host); // // InputStream urlIn = urlCon.getInputStream(); // // Node rootElem = parse(urlIn); // // urlIn.close(); // urlCon.disconnect(); // // return rootElem; // // } catch (Exception e) { // //throw new ParserException(e); // } // // HTTPRequest httpReq = new HTTPRequest(); // httpReq.setMethod(HTTP.GET); // httpReq.setURI(uri); // HTTPResponse httpRes = httpReq.post(host, port); // if (httpRes.isSuccessful() == false) // throw new ParserException("HTTP comunication failed: no answer from peer." + // "Unable to retrive resoure -> "+locationURL.toString()); // String content = new String(httpRes.getContent()); // ByteArrayInputStream strBuf = new ByteArrayInputStream(content.getBytes()); // return parse(strBuf); // } // // //////////////////////////////////////////////// // // parse (File) // //////////////////////////////////////////////// // // public Node parse(File descriptionFile) throws ParserException // { // try { // InputStream fileIn = new FileInputStream(descriptionFile); // Node root = parse(fileIn); // fileIn.close(); // return root; // // } catch (Exception e) { // throw new ParserException(e); // } // } // // //////////////////////////////////////////////// // // parse (Memory) // //////////////////////////////////////////////// // // public Node parse(String descr) throws ParserException // { // try { // InputStream decrIn = new ByteArrayInputStream(descr.getBytes()); // Node root = parse(decrIn); // return root; // } catch (Exception e) { // throw new ParserException(e); // } // } // // } // Path: stun/upnp/src/main/java/org/cybergarage/upnp/Device.java import org.cybergarage.upnp.event.SubscriptionResponse; import org.cybergarage.upnp.ssdp.SSDPNotifyRequest; import org.cybergarage.upnp.ssdp.SSDPNotifySocket; import org.cybergarage.upnp.ssdp.SSDPPacket; import org.cybergarage.upnp.ssdp.SSDPSearchResponse; import org.cybergarage.upnp.ssdp.SSDPSearchResponseSocket; import org.cybergarage.upnp.ssdp.SSDPSearchSocketList; import org.cybergarage.upnp.xml.DeviceData; import org.cybergarage.upnp.xml.ServiceData; import org.cybergarage.util.Debug; import org.cybergarage.util.FileUtil; import org.cybergarage.util.Mutex; import org.cybergarage.util.TimerUtil; import org.cybergarage.xml.Node; import org.cybergarage.xml.Parser; import org.cybergarage.xml.ParserException; import org.cybergarage.xml.XML; import org.cybergarage.http.HTTP; import java.io.File; import java.io.InputStream; import java.net.InetAddress; import java.net.URL; import java.util.Calendar; import org.cybergarage.http.HTTP; import org.cybergarage.http.HTTPRequest; import org.cybergarage.http.HTTPResponse; import org.cybergarage.http.HTTPServerList; import org.cybergarage.http.HTTPStatus; import org.cybergarage.net.HostInterface; import org.cybergarage.soap.SOAPResponse; import org.cybergarage.upnp.control.ActionListener; import org.cybergarage.upnp.control.ActionRequest; import org.cybergarage.upnp.control.ActionResponse; import org.cybergarage.upnp.control.ControlRequest; import org.cybergarage.upnp.control.ControlResponse; import org.cybergarage.upnp.control.QueryListener; import org.cybergarage.upnp.control.QueryRequest; import org.cybergarage.upnp.device.Advertiser; import org.cybergarage.upnp.device.Description; import org.cybergarage.upnp.device.InvalidDescriptionException; import org.cybergarage.upnp.device.NTS; import org.cybergarage.upnp.device.ST; import org.cybergarage.upnp.device.SearchListener; import org.cybergarage.upnp.device.USN; import org.cybergarage.upnp.event.Subscriber; import org.cybergarage.upnp.event.Subscription; import org.cybergarage.upnp.event.SubscriptionRequest; getDeviceData().setDescriptionURI(uri); } private String getDescriptionURI() { return getDeviceData().getDescriptionURI(); } private boolean isDescriptionURI(String uri) { String descriptionURI = getDescriptionURI(); if (uri == null || descriptionURI == null) return false; return descriptionURI.equals(uri); } public String getDescriptionFilePath() { File descriptionFile = getDescriptionFile(); if (descriptionFile == null) return ""; return descriptionFile.getAbsoluteFile().getParent(); } /** * @since 1.8.0 */ public boolean loadDescription(InputStream input) throws InvalidDescriptionException { try {
Parser parser = UPnP.getXMLParser();
jimdowling/nat-traverser
network/netty/src/main/java/se/sics/gvod/hp/msgs/HpFinishedMsg.java
// Path: network/netty/src/main/java/se/sics/gvod/common/msgs/MessageEncodingException.java // public class MessageEncodingException extends Exception { // // private static final long serialVersionUID = -3078825718180083408L; // // public MessageEncodingException(String mesg) { // super(mesg); // } // // }
import io.netty.buffer.ByteBuf; import se.sics.gvod.common.msgs.MessageEncodingException; import se.sics.gvod.net.BaseMsgFrameDecoder; import se.sics.gvod.net.VodAddress; import se.sics.gvod.net.msgs.RewriteableMsg; import se.sics.gvod.net.util.UserTypesEncoderFactory; import se.sics.gvod.timer.TimeoutId;
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package se.sics.gvod.hp.msgs; /** * * @author Jim * * message send by the client to zServer */ public class HpFinishedMsg extends HpMsg.Oneway { static final long serialVersionUID = 1L; private final boolean hpSuccessful; public HpFinishedMsg(VodAddress src, VodAddress dest, int remoteClientId, boolean hpSuccessful, TimeoutId msgTimeoutId) { super(src, dest, remoteClientId, msgTimeoutId); this.hpSuccessful = hpSuccessful; } public boolean isHPSuccessful() { return hpSuccessful; } @Override public int getSize() { return super.getHeaderSize() + 1 /* hpsuccessful */; } @Override public byte getOpcode() { return BaseMsgFrameDecoder.HP_FINISHED; } @Override
// Path: network/netty/src/main/java/se/sics/gvod/common/msgs/MessageEncodingException.java // public class MessageEncodingException extends Exception { // // private static final long serialVersionUID = -3078825718180083408L; // // public MessageEncodingException(String mesg) { // super(mesg); // } // // } // Path: network/netty/src/main/java/se/sics/gvod/hp/msgs/HpFinishedMsg.java import io.netty.buffer.ByteBuf; import se.sics.gvod.common.msgs.MessageEncodingException; import se.sics.gvod.net.BaseMsgFrameDecoder; import se.sics.gvod.net.VodAddress; import se.sics.gvod.net.msgs.RewriteableMsg; import se.sics.gvod.net.util.UserTypesEncoderFactory; import se.sics.gvod.timer.TimeoutId; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package se.sics.gvod.hp.msgs; /** * * @author Jim * * message send by the client to zServer */ public class HpFinishedMsg extends HpMsg.Oneway { static final long serialVersionUID = 1L; private final boolean hpSuccessful; public HpFinishedMsg(VodAddress src, VodAddress dest, int remoteClientId, boolean hpSuccessful, TimeoutId msgTimeoutId) { super(src, dest, remoteClientId, msgTimeoutId); this.hpSuccessful = hpSuccessful; } public boolean isHPSuccessful() { return hpSuccessful; } @Override public int getSize() { return super.getHeaderSize() + 1 /* hpsuccessful */; } @Override public byte getOpcode() { return BaseMsgFrameDecoder.HP_FINISHED; } @Override
public ByteBuf toByteArray() throws MessageEncodingException {
jimdowling/nat-traverser
network/netty/src/main/java/se/sics/gvod/hp/msgs/TConnectionMsg.java
// Path: network/netty/src/main/java/se/sics/gvod/common/msgs/MessageEncodingException.java // public class MessageEncodingException extends Exception { // // private static final long serialVersionUID = -3078825718180083408L; // // public MessageEncodingException(String mesg) { // super(mesg); // } // // }
import io.netty.buffer.ByteBuf; import se.sics.gvod.common.msgs.DirectMsgNetty; import se.sics.gvod.common.msgs.MessageEncodingException; import se.sics.gvod.net.BaseMsgFrameDecoder; import se.sics.gvod.net.Transport; import se.sics.gvod.net.VodAddress; import se.sics.gvod.net.msgs.RewriteableMsg; import se.sics.gvod.net.msgs.RewriteableRetryTimeout; import se.sics.gvod.net.msgs.ScheduleRetryTimeout; import se.sics.gvod.net.util.UserTypesEncoderFactory; import se.sics.gvod.timer.TimeoutId;
; } public Ping(VodAddress src, VodAddress dest, Transport protocol, TimeoutId timeoutId) { super(src, dest, protocol, timeoutId); } public Ping(VodAddress src, VodAddress dest, TimeoutId timeoutId) { super(src, dest, timeoutId); } private Ping(Ping msg, VodAddress src) { super(src, msg.getVodDestination()); } private Ping(VodAddress dest, Ping msg) { super(msg.getVodSource(), dest); } @Override public RewriteableMsg copy() { TConnectionMsg.Ping copy = new TConnectionMsg.Ping(vodSrc, vodDest, timeoutId); copy.setTimeoutId(timeoutId); return copy; } @Override
// Path: network/netty/src/main/java/se/sics/gvod/common/msgs/MessageEncodingException.java // public class MessageEncodingException extends Exception { // // private static final long serialVersionUID = -3078825718180083408L; // // public MessageEncodingException(String mesg) { // super(mesg); // } // // } // Path: network/netty/src/main/java/se/sics/gvod/hp/msgs/TConnectionMsg.java import io.netty.buffer.ByteBuf; import se.sics.gvod.common.msgs.DirectMsgNetty; import se.sics.gvod.common.msgs.MessageEncodingException; import se.sics.gvod.net.BaseMsgFrameDecoder; import se.sics.gvod.net.Transport; import se.sics.gvod.net.VodAddress; import se.sics.gvod.net.msgs.RewriteableMsg; import se.sics.gvod.net.msgs.RewriteableRetryTimeout; import se.sics.gvod.net.msgs.ScheduleRetryTimeout; import se.sics.gvod.net.util.UserTypesEncoderFactory; import se.sics.gvod.timer.TimeoutId; ; } public Ping(VodAddress src, VodAddress dest, Transport protocol, TimeoutId timeoutId) { super(src, dest, protocol, timeoutId); } public Ping(VodAddress src, VodAddress dest, TimeoutId timeoutId) { super(src, dest, timeoutId); } private Ping(Ping msg, VodAddress src) { super(src, msg.getVodDestination()); } private Ping(VodAddress dest, Ping msg) { super(msg.getVodSource(), dest); } @Override public RewriteableMsg copy() { TConnectionMsg.Ping copy = new TConnectionMsg.Ping(vodSrc, vodDest, timeoutId); copy.setTimeoutId(timeoutId); return copy; } @Override
public ByteBuf toByteArray() throws MessageEncodingException {
jimdowling/nat-traverser
network/netty/src/main/java/se/sics/gvod/stun/msgs/EchoMsg.java
// Path: network/netty/src/main/java/se/sics/gvod/common/msgs/MessageEncodingException.java // public class MessageEncodingException extends Exception { // // private static final long serialVersionUID = -3078825718180083408L; // // public MessageEncodingException(String mesg) { // super(mesg); // } // // }
import io.netty.buffer.ByteBuf; import java.util.Set; import se.sics.gvod.address.Address; import se.sics.gvod.common.msgs.MessageEncodingException; import se.sics.gvod.net.BaseMsgFrameDecoder; import se.sics.gvod.net.VodAddress; import se.sics.gvod.net.msgs.RewriteableMsg; import se.sics.gvod.net.msgs.RewriteableRetryTimeout; import se.sics.gvod.net.msgs.ScheduleRetryTimeout; import se.sics.gvod.net.util.UserTypesEncoderFactory; import se.sics.gvod.timer.TimeoutId;
return replyTo; } public void setTryId(int tryId) { this.tryId = tryId; } public int getTryId() { return tryId; } public Test getTestType() { return testType; } @Override public String toString() { return "Echo.RequestMessage. Type " + testType + " tryId " + tryId; } @Override public int getSize() { return super.getHeaderSize() + 1 /*test type*/ + 1 /*try id*/ + UserTypesEncoderFactory.ADDRESS_LEN // replyTo ; } @Override
// Path: network/netty/src/main/java/se/sics/gvod/common/msgs/MessageEncodingException.java // public class MessageEncodingException extends Exception { // // private static final long serialVersionUID = -3078825718180083408L; // // public MessageEncodingException(String mesg) { // super(mesg); // } // // } // Path: network/netty/src/main/java/se/sics/gvod/stun/msgs/EchoMsg.java import io.netty.buffer.ByteBuf; import java.util.Set; import se.sics.gvod.address.Address; import se.sics.gvod.common.msgs.MessageEncodingException; import se.sics.gvod.net.BaseMsgFrameDecoder; import se.sics.gvod.net.VodAddress; import se.sics.gvod.net.msgs.RewriteableMsg; import se.sics.gvod.net.msgs.RewriteableRetryTimeout; import se.sics.gvod.net.msgs.ScheduleRetryTimeout; import se.sics.gvod.net.util.UserTypesEncoderFactory; import se.sics.gvod.timer.TimeoutId; return replyTo; } public void setTryId(int tryId) { this.tryId = tryId; } public int getTryId() { return tryId; } public Test getTestType() { return testType; } @Override public String toString() { return "Echo.RequestMessage. Type " + testType + " tryId " + tryId; } @Override public int getSize() { return super.getHeaderSize() + 1 /*test type*/ + 1 /*try id*/ + UserTypesEncoderFactory.ADDRESS_LEN // replyTo ; } @Override
public ByteBuf toByteArray() throws MessageEncodingException {