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
teocci/YouTube-In-Background
app/src/main/java/com/teocci/ytinbg/model/YouTubeVideo.java
// Path: app/src/main/java/com/teocci/ytinbg/utils/LogHelper.java // public class LogHelper // { // private static final int LOG_PREFIX_LENGTH = LOG_PREFIX.length(); // private static final int MAX_LOG_TAG_LENGTH = 23; // private static final int RESERVED_LENGTH = MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH - 2; // // public static String makeLogTag(String str) // { // return LOG_PREFIX // + '[' // + (str.length() > RESERVED_LENGTH ? str.substring(0, RESERVED_LENGTH - 1) : str) // + ']'; // } // // /** // * Don't use this when obfuscating class names! // */ // public static String makeLogTag(Class cls) // { // return makeLogTag(cls.getSimpleName()); // } // // // public static void v(String tag, Object... messages) // { // // Only log VERBOSE if build type is DEBUG // if (BuildConfig.DEBUG) { // log(tag, Log.VERBOSE, null, messages); // } // } // // public static void d(String tag, Object... messages) // { // // Only log DEBUG if build type is DEBUG // if (BuildConfig.DEBUG) { // log(tag, Log.DEBUG, null, messages); // } // } // // public static void i(String tag, Object... messages) // { // log(tag, Log.INFO, null, messages); // } // // public static void w(String tag, Object... messages) // { // log(tag, Log.WARN, null, messages); // } // // public static void w(String tag, Throwable t, Object... messages) // { // log(tag, Log.WARN, t, messages); // } // // public static void e(String tag, Object... messages) // { // log(tag, Log.ERROR, null, messages); // } // // public static void e(String tag, Throwable t, Object... messages) // { // log(tag, Log.ERROR, t, messages); // } // // public static void log(String tag, int level, Throwable t, Object... messages) // { // if (Log.isLoggable(tag, level)) { // String message; // if (t == null && messages != null && messages.length == 1) { // // Handle this common case without the extra cost of creating a StringBuffer: // message = messages[0].toString(); // } else { // StringBuilder sb = new StringBuilder(); // if (messages != null) for (Object m : messages) { // sb.append(m); // } // if (t != null) { // sb.append("\n").append(Log.getStackTraceString(t)); // } // message = sb.toString(); // } // // Log.println(level, tag, message); // } // } // }
import com.teocci.ytinbg.utils.LogHelper; import java.io.Serializable;
package com.teocci.ytinbg.model; /** * YouTube video class * Created by Teocci * * @author teocci@yandex.com on 2016-Aug-18 */ public class YouTubeVideo implements Serializable {
// Path: app/src/main/java/com/teocci/ytinbg/utils/LogHelper.java // public class LogHelper // { // private static final int LOG_PREFIX_LENGTH = LOG_PREFIX.length(); // private static final int MAX_LOG_TAG_LENGTH = 23; // private static final int RESERVED_LENGTH = MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH - 2; // // public static String makeLogTag(String str) // { // return LOG_PREFIX // + '[' // + (str.length() > RESERVED_LENGTH ? str.substring(0, RESERVED_LENGTH - 1) : str) // + ']'; // } // // /** // * Don't use this when obfuscating class names! // */ // public static String makeLogTag(Class cls) // { // return makeLogTag(cls.getSimpleName()); // } // // // public static void v(String tag, Object... messages) // { // // Only log VERBOSE if build type is DEBUG // if (BuildConfig.DEBUG) { // log(tag, Log.VERBOSE, null, messages); // } // } // // public static void d(String tag, Object... messages) // { // // Only log DEBUG if build type is DEBUG // if (BuildConfig.DEBUG) { // log(tag, Log.DEBUG, null, messages); // } // } // // public static void i(String tag, Object... messages) // { // log(tag, Log.INFO, null, messages); // } // // public static void w(String tag, Object... messages) // { // log(tag, Log.WARN, null, messages); // } // // public static void w(String tag, Throwable t, Object... messages) // { // log(tag, Log.WARN, t, messages); // } // // public static void e(String tag, Object... messages) // { // log(tag, Log.ERROR, null, messages); // } // // public static void e(String tag, Throwable t, Object... messages) // { // log(tag, Log.ERROR, t, messages); // } // // public static void log(String tag, int level, Throwable t, Object... messages) // { // if (Log.isLoggable(tag, level)) { // String message; // if (t == null && messages != null && messages.length == 1) { // // Handle this common case without the extra cost of creating a StringBuffer: // message = messages[0].toString(); // } else { // StringBuilder sb = new StringBuilder(); // if (messages != null) for (Object m : messages) { // sb.append(m); // } // if (t != null) { // sb.append("\n").append(Log.getStackTraceString(t)); // } // message = sb.toString(); // } // // Log.println(level, tag, message); // } // } // } // Path: app/src/main/java/com/teocci/ytinbg/model/YouTubeVideo.java import com.teocci.ytinbg.utils.LogHelper; import java.io.Serializable; package com.teocci.ytinbg.model; /** * YouTube video class * Created by Teocci * * @author teocci@yandex.com on 2016-Aug-18 */ public class YouTubeVideo implements Serializable {
private static final String TAG = LogHelper.makeLogTag(YouTubeVideo.class);
teocci/YouTube-In-Background
app/src/main/java/com/teocci/ytinbg/receivers/MediaButtonIntentReceiver.java
// Path: app/src/main/java/com/teocci/ytinbg/utils/LogHelper.java // public class LogHelper // { // private static final int LOG_PREFIX_LENGTH = LOG_PREFIX.length(); // private static final int MAX_LOG_TAG_LENGTH = 23; // private static final int RESERVED_LENGTH = MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH - 2; // // public static String makeLogTag(String str) // { // return LOG_PREFIX // + '[' // + (str.length() > RESERVED_LENGTH ? str.substring(0, RESERVED_LENGTH - 1) : str) // + ']'; // } // // /** // * Don't use this when obfuscating class names! // */ // public static String makeLogTag(Class cls) // { // return makeLogTag(cls.getSimpleName()); // } // // // public static void v(String tag, Object... messages) // { // // Only log VERBOSE if build type is DEBUG // if (BuildConfig.DEBUG) { // log(tag, Log.VERBOSE, null, messages); // } // } // // public static void d(String tag, Object... messages) // { // // Only log DEBUG if build type is DEBUG // if (BuildConfig.DEBUG) { // log(tag, Log.DEBUG, null, messages); // } // } // // public static void i(String tag, Object... messages) // { // log(tag, Log.INFO, null, messages); // } // // public static void w(String tag, Object... messages) // { // log(tag, Log.WARN, null, messages); // } // // public static void w(String tag, Throwable t, Object... messages) // { // log(tag, Log.WARN, t, messages); // } // // public static void e(String tag, Object... messages) // { // log(tag, Log.ERROR, null, messages); // } // // public static void e(String tag, Throwable t, Object... messages) // { // log(tag, Log.ERROR, t, messages); // } // // public static void log(String tag, int level, Throwable t, Object... messages) // { // if (Log.isLoggable(tag, level)) { // String message; // if (t == null && messages != null && messages.length == 1) { // // Handle this common case without the extra cost of creating a StringBuffer: // message = messages[0].toString(); // } else { // StringBuilder sb = new StringBuilder(); // if (messages != null) for (Object m : messages) { // sb.append(m); // } // if (t != null) { // sb.append("\n").append(Log.getStackTraceString(t)); // } // message = sb.toString(); // } // // Log.println(level, tag, message); // } // } // }
import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import com.teocci.ytinbg.utils.LogHelper;
package com.teocci.ytinbg.receivers; /** * Created by teocci. * * @author teocci@yandex.com on 2016-Mar-23 */ public class MediaButtonIntentReceiver extends BroadcastReceiver {
// Path: app/src/main/java/com/teocci/ytinbg/utils/LogHelper.java // public class LogHelper // { // private static final int LOG_PREFIX_LENGTH = LOG_PREFIX.length(); // private static final int MAX_LOG_TAG_LENGTH = 23; // private static final int RESERVED_LENGTH = MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH - 2; // // public static String makeLogTag(String str) // { // return LOG_PREFIX // + '[' // + (str.length() > RESERVED_LENGTH ? str.substring(0, RESERVED_LENGTH - 1) : str) // + ']'; // } // // /** // * Don't use this when obfuscating class names! // */ // public static String makeLogTag(Class cls) // { // return makeLogTag(cls.getSimpleName()); // } // // // public static void v(String tag, Object... messages) // { // // Only log VERBOSE if build type is DEBUG // if (BuildConfig.DEBUG) { // log(tag, Log.VERBOSE, null, messages); // } // } // // public static void d(String tag, Object... messages) // { // // Only log DEBUG if build type is DEBUG // if (BuildConfig.DEBUG) { // log(tag, Log.DEBUG, null, messages); // } // } // // public static void i(String tag, Object... messages) // { // log(tag, Log.INFO, null, messages); // } // // public static void w(String tag, Object... messages) // { // log(tag, Log.WARN, null, messages); // } // // public static void w(String tag, Throwable t, Object... messages) // { // log(tag, Log.WARN, t, messages); // } // // public static void e(String tag, Object... messages) // { // log(tag, Log.ERROR, null, messages); // } // // public static void e(String tag, Throwable t, Object... messages) // { // log(tag, Log.ERROR, t, messages); // } // // public static void log(String tag, int level, Throwable t, Object... messages) // { // if (Log.isLoggable(tag, level)) { // String message; // if (t == null && messages != null && messages.length == 1) { // // Handle this common case without the extra cost of creating a StringBuffer: // message = messages[0].toString(); // } else { // StringBuilder sb = new StringBuilder(); // if (messages != null) for (Object m : messages) { // sb.append(m); // } // if (t != null) { // sb.append("\n").append(Log.getStackTraceString(t)); // } // message = sb.toString(); // } // // Log.println(level, tag, message); // } // } // } // Path: app/src/main/java/com/teocci/ytinbg/receivers/MediaButtonIntentReceiver.java import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import com.teocci.ytinbg.utils.LogHelper; package com.teocci.ytinbg.receivers; /** * Created by teocci. * * @author teocci@yandex.com on 2016-Mar-23 */ public class MediaButtonIntentReceiver extends BroadcastReceiver {
private static final String TAG = LogHelper.makeLogTag(MediaButtonIntentReceiver.class);
teocci/YouTube-In-Background
app/src/main/java/com/teocci/ytinbg/interfaces/YouTubeVideoUpdateListener.java
// Path: app/src/main/java/com/teocci/ytinbg/model/YouTubeVideo.java // public class YouTubeVideo implements Serializable // { // private static final String TAG = LogHelper.makeLogTag(YouTubeVideo.class); // private static final long serialVersionUID = 1L; // private String id; // private String title; // private String thumbnailURL; // private String duration; // private String viewCount; // // public YouTubeVideo() // { // this.id = ""; // this.title = ""; // this.thumbnailURL = ""; // this.duration = ""; // this.viewCount = ""; // } // // public YouTubeVideo(YouTubeVideo newVideo) { // this.id = newVideo.id; // this.title = newVideo.title; // this.thumbnailURL = newVideo.thumbnailURL; // this.duration = newVideo.duration; // this.viewCount = newVideo.viewCount; // } // public YouTubeVideo(String id, String title, String thumbnailURL, String duration, String // viewCount) // { // this.id = id; // this.title = title; // this.thumbnailURL = thumbnailURL; // this.duration = duration; // this.viewCount = viewCount; // } // // public String getId() // { // return id; // } // // public void setId(String id) // { // this.id = id; // } // // public String getDuration() // { // return duration; // } // // public void setDuration(String duration) // { // this.duration = duration; // } // // public String getTitle() // { // return title; // } // // public void setTitle(String title) // { // this.title = title; // } // // public String getThumbnailURL() // { // return thumbnailURL; // } // // public void setThumbnailURL(String thumbnail) // { // this.thumbnailURL = thumbnail; // } // // public String getViewCount() // { // return viewCount; // } // // public void setViewCount(String viewCount) // { // this.viewCount = viewCount; // } // // @Override // public String toString() // { // return "YouTubeVideo {" + // "id='" + id + '\'' + // ", title='" + title + '\'' + // '}'; // } // }
import com.teocci.ytinbg.model.YouTubeVideo; import java.util.List;
package com.teocci.ytinbg.interfaces; /** * Created by teocci. * * @author teocci@yandex.com on 2017-Jun-13 */ public interface YouTubeVideoUpdateListener {
// Path: app/src/main/java/com/teocci/ytinbg/model/YouTubeVideo.java // public class YouTubeVideo implements Serializable // { // private static final String TAG = LogHelper.makeLogTag(YouTubeVideo.class); // private static final long serialVersionUID = 1L; // private String id; // private String title; // private String thumbnailURL; // private String duration; // private String viewCount; // // public YouTubeVideo() // { // this.id = ""; // this.title = ""; // this.thumbnailURL = ""; // this.duration = ""; // this.viewCount = ""; // } // // public YouTubeVideo(YouTubeVideo newVideo) { // this.id = newVideo.id; // this.title = newVideo.title; // this.thumbnailURL = newVideo.thumbnailURL; // this.duration = newVideo.duration; // this.viewCount = newVideo.viewCount; // } // public YouTubeVideo(String id, String title, String thumbnailURL, String duration, String // viewCount) // { // this.id = id; // this.title = title; // this.thumbnailURL = thumbnailURL; // this.duration = duration; // this.viewCount = viewCount; // } // // public String getId() // { // return id; // } // // public void setId(String id) // { // this.id = id; // } // // public String getDuration() // { // return duration; // } // // public void setDuration(String duration) // { // this.duration = duration; // } // // public String getTitle() // { // return title; // } // // public void setTitle(String title) // { // this.title = title; // } // // public String getThumbnailURL() // { // return thumbnailURL; // } // // public void setThumbnailURL(String thumbnail) // { // this.thumbnailURL = thumbnail; // } // // public String getViewCount() // { // return viewCount; // } // // public void setViewCount(String viewCount) // { // this.viewCount = viewCount; // } // // @Override // public String toString() // { // return "YouTubeVideo {" + // "id='" + id + '\'' + // ", title='" + title + '\'' + // '}'; // } // } // Path: app/src/main/java/com/teocci/ytinbg/interfaces/YouTubeVideoUpdateListener.java import com.teocci.ytinbg.model.YouTubeVideo; import java.util.List; package com.teocci.ytinbg.interfaces; /** * Created by teocci. * * @author teocci@yandex.com on 2017-Jun-13 */ public interface YouTubeVideoUpdateListener {
void onYouTubeVideoChanged(YouTubeVideo youTubeVideo);
teocci/YouTube-In-Background
app/src/main/java/com/teocci/ytinbg/interfaces/YouTubeVideoReceiver.java
// Path: app/src/main/java/com/teocci/ytinbg/model/YouTubeVideo.java // public class YouTubeVideo implements Serializable // { // private static final String TAG = LogHelper.makeLogTag(YouTubeVideo.class); // private static final long serialVersionUID = 1L; // private String id; // private String title; // private String thumbnailURL; // private String duration; // private String viewCount; // // public YouTubeVideo() // { // this.id = ""; // this.title = ""; // this.thumbnailURL = ""; // this.duration = ""; // this.viewCount = ""; // } // // public YouTubeVideo(YouTubeVideo newVideo) { // this.id = newVideo.id; // this.title = newVideo.title; // this.thumbnailURL = newVideo.thumbnailURL; // this.duration = newVideo.duration; // this.viewCount = newVideo.viewCount; // } // public YouTubeVideo(String id, String title, String thumbnailURL, String duration, String // viewCount) // { // this.id = id; // this.title = title; // this.thumbnailURL = thumbnailURL; // this.duration = duration; // this.viewCount = viewCount; // } // // public String getId() // { // return id; // } // // public void setId(String id) // { // this.id = id; // } // // public String getDuration() // { // return duration; // } // // public void setDuration(String duration) // { // this.duration = duration; // } // // public String getTitle() // { // return title; // } // // public void setTitle(String title) // { // this.title = title; // } // // public String getThumbnailURL() // { // return thumbnailURL; // } // // public void setThumbnailURL(String thumbnail) // { // this.thumbnailURL = thumbnail; // } // // public String getViewCount() // { // return viewCount; // } // // public void setViewCount(String viewCount) // { // this.viewCount = viewCount; // } // // @Override // public String toString() // { // return "YouTubeVideo {" + // "id='" + id + '\'' + // ", title='" + title + '\'' + // '}'; // } // }
import com.teocci.ytinbg.model.YouTubeVideo; import java.util.List;
package com.teocci.ytinbg.interfaces; /** * Interface which enables passing videos to the fragments * Created by Teocci on 10.3.16.. */ public interface YouTubeVideoReceiver {
// Path: app/src/main/java/com/teocci/ytinbg/model/YouTubeVideo.java // public class YouTubeVideo implements Serializable // { // private static final String TAG = LogHelper.makeLogTag(YouTubeVideo.class); // private static final long serialVersionUID = 1L; // private String id; // private String title; // private String thumbnailURL; // private String duration; // private String viewCount; // // public YouTubeVideo() // { // this.id = ""; // this.title = ""; // this.thumbnailURL = ""; // this.duration = ""; // this.viewCount = ""; // } // // public YouTubeVideo(YouTubeVideo newVideo) { // this.id = newVideo.id; // this.title = newVideo.title; // this.thumbnailURL = newVideo.thumbnailURL; // this.duration = newVideo.duration; // this.viewCount = newVideo.viewCount; // } // public YouTubeVideo(String id, String title, String thumbnailURL, String duration, String // viewCount) // { // this.id = id; // this.title = title; // this.thumbnailURL = thumbnailURL; // this.duration = duration; // this.viewCount = viewCount; // } // // public String getId() // { // return id; // } // // public void setId(String id) // { // this.id = id; // } // // public String getDuration() // { // return duration; // } // // public void setDuration(String duration) // { // this.duration = duration; // } // // public String getTitle() // { // return title; // } // // public void setTitle(String title) // { // this.title = title; // } // // public String getThumbnailURL() // { // return thumbnailURL; // } // // public void setThumbnailURL(String thumbnail) // { // this.thumbnailURL = thumbnail; // } // // public String getViewCount() // { // return viewCount; // } // // public void setViewCount(String viewCount) // { // this.viewCount = viewCount; // } // // @Override // public String toString() // { // return "YouTubeVideo {" + // "id='" + id + '\'' + // ", title='" + title + '\'' + // '}'; // } // } // Path: app/src/main/java/com/teocci/ytinbg/interfaces/YouTubeVideoReceiver.java import com.teocci.ytinbg.model.YouTubeVideo; import java.util.List; package com.teocci.ytinbg.interfaces; /** * Interface which enables passing videos to the fragments * Created by Teocci on 10.3.16.. */ public interface YouTubeVideoReceiver {
void onVideosReceived(List<YouTubeVideo> youTubeVideos, String currentPageToken, String nextPageToken);
teocci/YouTube-In-Background
app/src/main/java/com/teocci/ytinbg/utils/QueueHelper.java
// Path: app/src/main/java/com/teocci/ytinbg/model/YouTubeVideo.java // public class YouTubeVideo implements Serializable // { // private static final String TAG = LogHelper.makeLogTag(YouTubeVideo.class); // private static final long serialVersionUID = 1L; // private String id; // private String title; // private String thumbnailURL; // private String duration; // private String viewCount; // // public YouTubeVideo() // { // this.id = ""; // this.title = ""; // this.thumbnailURL = ""; // this.duration = ""; // this.viewCount = ""; // } // // public YouTubeVideo(YouTubeVideo newVideo) { // this.id = newVideo.id; // this.title = newVideo.title; // this.thumbnailURL = newVideo.thumbnailURL; // this.duration = newVideo.duration; // this.viewCount = newVideo.viewCount; // } // public YouTubeVideo(String id, String title, String thumbnailURL, String duration, String // viewCount) // { // this.id = id; // this.title = title; // this.thumbnailURL = thumbnailURL; // this.duration = duration; // this.viewCount = viewCount; // } // // public String getId() // { // return id; // } // // public void setId(String id) // { // this.id = id; // } // // public String getDuration() // { // return duration; // } // // public void setDuration(String duration) // { // this.duration = duration; // } // // public String getTitle() // { // return title; // } // // public void setTitle(String title) // { // this.title = title; // } // // public String getThumbnailURL() // { // return thumbnailURL; // } // // public void setThumbnailURL(String thumbnail) // { // this.thumbnailURL = thumbnail; // } // // public String getViewCount() // { // return viewCount; // } // // public void setViewCount(String viewCount) // { // this.viewCount = viewCount; // } // // @Override // public String toString() // { // return "YouTubeVideo {" + // "id='" + id + '\'' + // ", title='" + title + '\'' + // '}'; // } // }
import android.content.Context; import android.support.v4.media.session.MediaControllerCompat; import android.text.TextUtils; import com.teocci.ytinbg.model.YouTubeVideo; import java.util.List;
package com.teocci.ytinbg.utils; /** * Created by teocci. * * @author teocci@yandex.com on 2017-Jun-10 */ public class QueueHelper { private static final String TAG = QueueHelper.class.getSimpleName();
// Path: app/src/main/java/com/teocci/ytinbg/model/YouTubeVideo.java // public class YouTubeVideo implements Serializable // { // private static final String TAG = LogHelper.makeLogTag(YouTubeVideo.class); // private static final long serialVersionUID = 1L; // private String id; // private String title; // private String thumbnailURL; // private String duration; // private String viewCount; // // public YouTubeVideo() // { // this.id = ""; // this.title = ""; // this.thumbnailURL = ""; // this.duration = ""; // this.viewCount = ""; // } // // public YouTubeVideo(YouTubeVideo newVideo) { // this.id = newVideo.id; // this.title = newVideo.title; // this.thumbnailURL = newVideo.thumbnailURL; // this.duration = newVideo.duration; // this.viewCount = newVideo.viewCount; // } // public YouTubeVideo(String id, String title, String thumbnailURL, String duration, String // viewCount) // { // this.id = id; // this.title = title; // this.thumbnailURL = thumbnailURL; // this.duration = duration; // this.viewCount = viewCount; // } // // public String getId() // { // return id; // } // // public void setId(String id) // { // this.id = id; // } // // public String getDuration() // { // return duration; // } // // public void setDuration(String duration) // { // this.duration = duration; // } // // public String getTitle() // { // return title; // } // // public void setTitle(String title) // { // this.title = title; // } // // public String getThumbnailURL() // { // return thumbnailURL; // } // // public void setThumbnailURL(String thumbnail) // { // this.thumbnailURL = thumbnail; // } // // public String getViewCount() // { // return viewCount; // } // // public void setViewCount(String viewCount) // { // this.viewCount = viewCount; // } // // @Override // public String toString() // { // return "YouTubeVideo {" + // "id='" + id + '\'' + // ", title='" + title + '\'' + // '}'; // } // } // Path: app/src/main/java/com/teocci/ytinbg/utils/QueueHelper.java import android.content.Context; import android.support.v4.media.session.MediaControllerCompat; import android.text.TextUtils; import com.teocci.ytinbg.model.YouTubeVideo; import java.util.List; package com.teocci.ytinbg.utils; /** * Created by teocci. * * @author teocci@yandex.com on 2017-Jun-10 */ public class QueueHelper { private static final String TAG = QueueHelper.class.getSimpleName();
public static int getYouTubeVideoIndexOnQueue(Iterable<YouTubeVideo> queue,
teocci/YouTube-In-Background
app/src/main/java/com/teocci/ytinbg/notification/NotificationBuilder.java
// Path: app/src/main/java/com/teocci/ytinbg/utils/LogHelper.java // public class LogHelper // { // private static final int LOG_PREFIX_LENGTH = LOG_PREFIX.length(); // private static final int MAX_LOG_TAG_LENGTH = 23; // private static final int RESERVED_LENGTH = MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH - 2; // // public static String makeLogTag(String str) // { // return LOG_PREFIX // + '[' // + (str.length() > RESERVED_LENGTH ? str.substring(0, RESERVED_LENGTH - 1) : str) // + ']'; // } // // /** // * Don't use this when obfuscating class names! // */ // public static String makeLogTag(Class cls) // { // return makeLogTag(cls.getSimpleName()); // } // // // public static void v(String tag, Object... messages) // { // // Only log VERBOSE if build type is DEBUG // if (BuildConfig.DEBUG) { // log(tag, Log.VERBOSE, null, messages); // } // } // // public static void d(String tag, Object... messages) // { // // Only log DEBUG if build type is DEBUG // if (BuildConfig.DEBUG) { // log(tag, Log.DEBUG, null, messages); // } // } // // public static void i(String tag, Object... messages) // { // log(tag, Log.INFO, null, messages); // } // // public static void w(String tag, Object... messages) // { // log(tag, Log.WARN, null, messages); // } // // public static void w(String tag, Throwable t, Object... messages) // { // log(tag, Log.WARN, t, messages); // } // // public static void e(String tag, Object... messages) // { // log(tag, Log.ERROR, null, messages); // } // // public static void e(String tag, Throwable t, Object... messages) // { // log(tag, Log.ERROR, t, messages); // } // // public static void log(String tag, int level, Throwable t, Object... messages) // { // if (Log.isLoggable(tag, level)) { // String message; // if (t == null && messages != null && messages.length == 1) { // // Handle this common case without the extra cost of creating a StringBuffer: // message = messages[0].toString(); // } else { // StringBuilder sb = new StringBuilder(); // if (messages != null) for (Object m : messages) { // sb.append(m); // } // if (t != null) { // sb.append("\n").append(Log.getStackTraceString(t)); // } // message = sb.toString(); // } // // Log.println(level, tag, message); // } // } // } // // Path: app/src/main/java/com/teocci/ytinbg/utils/BuildUtil.java // public static boolean minAPI26() // { // return Build.VERSION.SDK_INT >= Build.VERSION_CODES.O; // }
import android.app.Notification; import android.app.NotificationChannel; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.os.Build; import android.os.RemoteException; import android.support.v4.media.MediaDescriptionCompat; import android.support.v4.media.MediaMetadataCompat; import android.support.v4.media.session.MediaControllerCompat; import android.support.v4.media.session.MediaSessionCompat; import android.support.v4.media.session.PlaybackStateCompat; import com.teocci.ytinbg.R; import com.teocci.ytinbg.utils.LogHelper; import androidx.annotation.RequiresApi; import androidx.core.app.NotificationCompat; import androidx.core.app.NotificationCompat.Action; import androidx.media.app.NotificationCompat.MediaStyle; import androidx.media.session.MediaButtonReceiver; import static android.support.v4.media.session.PlaybackStateCompat.ACTION_PAUSE; import static android.support.v4.media.session.PlaybackStateCompat.ACTION_PLAY; import static android.support.v4.media.session.PlaybackStateCompat.ACTION_SKIP_TO_NEXT; import static android.support.v4.media.session.PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS; import static android.support.v4.media.session.PlaybackStateCompat.ACTION_STOP; import static com.teocci.ytinbg.utils.BuildUtil.minAPI26;
package com.teocci.ytinbg.notification; /** * Created by teocci. * * @author teocci@yandex.com on 2019-Jun-28 */ public class NotificationBuilder {
// Path: app/src/main/java/com/teocci/ytinbg/utils/LogHelper.java // public class LogHelper // { // private static final int LOG_PREFIX_LENGTH = LOG_PREFIX.length(); // private static final int MAX_LOG_TAG_LENGTH = 23; // private static final int RESERVED_LENGTH = MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH - 2; // // public static String makeLogTag(String str) // { // return LOG_PREFIX // + '[' // + (str.length() > RESERVED_LENGTH ? str.substring(0, RESERVED_LENGTH - 1) : str) // + ']'; // } // // /** // * Don't use this when obfuscating class names! // */ // public static String makeLogTag(Class cls) // { // return makeLogTag(cls.getSimpleName()); // } // // // public static void v(String tag, Object... messages) // { // // Only log VERBOSE if build type is DEBUG // if (BuildConfig.DEBUG) { // log(tag, Log.VERBOSE, null, messages); // } // } // // public static void d(String tag, Object... messages) // { // // Only log DEBUG if build type is DEBUG // if (BuildConfig.DEBUG) { // log(tag, Log.DEBUG, null, messages); // } // } // // public static void i(String tag, Object... messages) // { // log(tag, Log.INFO, null, messages); // } // // public static void w(String tag, Object... messages) // { // log(tag, Log.WARN, null, messages); // } // // public static void w(String tag, Throwable t, Object... messages) // { // log(tag, Log.WARN, t, messages); // } // // public static void e(String tag, Object... messages) // { // log(tag, Log.ERROR, null, messages); // } // // public static void e(String tag, Throwable t, Object... messages) // { // log(tag, Log.ERROR, t, messages); // } // // public static void log(String tag, int level, Throwable t, Object... messages) // { // if (Log.isLoggable(tag, level)) { // String message; // if (t == null && messages != null && messages.length == 1) { // // Handle this common case without the extra cost of creating a StringBuffer: // message = messages[0].toString(); // } else { // StringBuilder sb = new StringBuilder(); // if (messages != null) for (Object m : messages) { // sb.append(m); // } // if (t != null) { // sb.append("\n").append(Log.getStackTraceString(t)); // } // message = sb.toString(); // } // // Log.println(level, tag, message); // } // } // } // // Path: app/src/main/java/com/teocci/ytinbg/utils/BuildUtil.java // public static boolean minAPI26() // { // return Build.VERSION.SDK_INT >= Build.VERSION_CODES.O; // } // Path: app/src/main/java/com/teocci/ytinbg/notification/NotificationBuilder.java import android.app.Notification; import android.app.NotificationChannel; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.os.Build; import android.os.RemoteException; import android.support.v4.media.MediaDescriptionCompat; import android.support.v4.media.MediaMetadataCompat; import android.support.v4.media.session.MediaControllerCompat; import android.support.v4.media.session.MediaSessionCompat; import android.support.v4.media.session.PlaybackStateCompat; import com.teocci.ytinbg.R; import com.teocci.ytinbg.utils.LogHelper; import androidx.annotation.RequiresApi; import androidx.core.app.NotificationCompat; import androidx.core.app.NotificationCompat.Action; import androidx.media.app.NotificationCompat.MediaStyle; import androidx.media.session.MediaButtonReceiver; import static android.support.v4.media.session.PlaybackStateCompat.ACTION_PAUSE; import static android.support.v4.media.session.PlaybackStateCompat.ACTION_PLAY; import static android.support.v4.media.session.PlaybackStateCompat.ACTION_SKIP_TO_NEXT; import static android.support.v4.media.session.PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS; import static android.support.v4.media.session.PlaybackStateCompat.ACTION_STOP; import static com.teocci.ytinbg.utils.BuildUtil.minAPI26; package com.teocci.ytinbg.notification; /** * Created by teocci. * * @author teocci@yandex.com on 2019-Jun-28 */ public class NotificationBuilder {
private static final String TAG = LogHelper.makeLogTag(NotificationBuilder.class);
teocci/YouTube-In-Background
app/src/main/java/com/teocci/ytinbg/notification/NotificationBuilder.java
// Path: app/src/main/java/com/teocci/ytinbg/utils/LogHelper.java // public class LogHelper // { // private static final int LOG_PREFIX_LENGTH = LOG_PREFIX.length(); // private static final int MAX_LOG_TAG_LENGTH = 23; // private static final int RESERVED_LENGTH = MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH - 2; // // public static String makeLogTag(String str) // { // return LOG_PREFIX // + '[' // + (str.length() > RESERVED_LENGTH ? str.substring(0, RESERVED_LENGTH - 1) : str) // + ']'; // } // // /** // * Don't use this when obfuscating class names! // */ // public static String makeLogTag(Class cls) // { // return makeLogTag(cls.getSimpleName()); // } // // // public static void v(String tag, Object... messages) // { // // Only log VERBOSE if build type is DEBUG // if (BuildConfig.DEBUG) { // log(tag, Log.VERBOSE, null, messages); // } // } // // public static void d(String tag, Object... messages) // { // // Only log DEBUG if build type is DEBUG // if (BuildConfig.DEBUG) { // log(tag, Log.DEBUG, null, messages); // } // } // // public static void i(String tag, Object... messages) // { // log(tag, Log.INFO, null, messages); // } // // public static void w(String tag, Object... messages) // { // log(tag, Log.WARN, null, messages); // } // // public static void w(String tag, Throwable t, Object... messages) // { // log(tag, Log.WARN, t, messages); // } // // public static void e(String tag, Object... messages) // { // log(tag, Log.ERROR, null, messages); // } // // public static void e(String tag, Throwable t, Object... messages) // { // log(tag, Log.ERROR, t, messages); // } // // public static void log(String tag, int level, Throwable t, Object... messages) // { // if (Log.isLoggable(tag, level)) { // String message; // if (t == null && messages != null && messages.length == 1) { // // Handle this common case without the extra cost of creating a StringBuffer: // message = messages[0].toString(); // } else { // StringBuilder sb = new StringBuilder(); // if (messages != null) for (Object m : messages) { // sb.append(m); // } // if (t != null) { // sb.append("\n").append(Log.getStackTraceString(t)); // } // message = sb.toString(); // } // // Log.println(level, tag, message); // } // } // } // // Path: app/src/main/java/com/teocci/ytinbg/utils/BuildUtil.java // public static boolean minAPI26() // { // return Build.VERSION.SDK_INT >= Build.VERSION_CODES.O; // }
import android.app.Notification; import android.app.NotificationChannel; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.os.Build; import android.os.RemoteException; import android.support.v4.media.MediaDescriptionCompat; import android.support.v4.media.MediaMetadataCompat; import android.support.v4.media.session.MediaControllerCompat; import android.support.v4.media.session.MediaSessionCompat; import android.support.v4.media.session.PlaybackStateCompat; import com.teocci.ytinbg.R; import com.teocci.ytinbg.utils.LogHelper; import androidx.annotation.RequiresApi; import androidx.core.app.NotificationCompat; import androidx.core.app.NotificationCompat.Action; import androidx.media.app.NotificationCompat.MediaStyle; import androidx.media.session.MediaButtonReceiver; import static android.support.v4.media.session.PlaybackStateCompat.ACTION_PAUSE; import static android.support.v4.media.session.PlaybackStateCompat.ACTION_PLAY; import static android.support.v4.media.session.PlaybackStateCompat.ACTION_SKIP_TO_NEXT; import static android.support.v4.media.session.PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS; import static android.support.v4.media.session.PlaybackStateCompat.ACTION_STOP; import static com.teocci.ytinbg.utils.BuildUtil.minAPI26;
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC) .build(); } /** * Creates Notification Channel. This is required in Android O+ to display notifications. */ @RequiresApi(Build.VERSION_CODES.O) private void createNotificationChannel() { if (notificationManager.getNotificationChannel(CHANNEL_ID) == null) { NotificationChannel notificationChannel = new NotificationChannel( CHANNEL_ID, context.getString(R.string.notification_channel), NotificationManager.IMPORTANCE_LOW ); notificationChannel.setDescription(context.getString(R.string.notification_channel_description)); notificationManager.createNotificationChannel(notificationChannel); } } /** * @return true if if the minimum API is Oreo and if the notification channel does not exist. */ private boolean shouldCreateNowRunningChannel() {
// Path: app/src/main/java/com/teocci/ytinbg/utils/LogHelper.java // public class LogHelper // { // private static final int LOG_PREFIX_LENGTH = LOG_PREFIX.length(); // private static final int MAX_LOG_TAG_LENGTH = 23; // private static final int RESERVED_LENGTH = MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH - 2; // // public static String makeLogTag(String str) // { // return LOG_PREFIX // + '[' // + (str.length() > RESERVED_LENGTH ? str.substring(0, RESERVED_LENGTH - 1) : str) // + ']'; // } // // /** // * Don't use this when obfuscating class names! // */ // public static String makeLogTag(Class cls) // { // return makeLogTag(cls.getSimpleName()); // } // // // public static void v(String tag, Object... messages) // { // // Only log VERBOSE if build type is DEBUG // if (BuildConfig.DEBUG) { // log(tag, Log.VERBOSE, null, messages); // } // } // // public static void d(String tag, Object... messages) // { // // Only log DEBUG if build type is DEBUG // if (BuildConfig.DEBUG) { // log(tag, Log.DEBUG, null, messages); // } // } // // public static void i(String tag, Object... messages) // { // log(tag, Log.INFO, null, messages); // } // // public static void w(String tag, Object... messages) // { // log(tag, Log.WARN, null, messages); // } // // public static void w(String tag, Throwable t, Object... messages) // { // log(tag, Log.WARN, t, messages); // } // // public static void e(String tag, Object... messages) // { // log(tag, Log.ERROR, null, messages); // } // // public static void e(String tag, Throwable t, Object... messages) // { // log(tag, Log.ERROR, t, messages); // } // // public static void log(String tag, int level, Throwable t, Object... messages) // { // if (Log.isLoggable(tag, level)) { // String message; // if (t == null && messages != null && messages.length == 1) { // // Handle this common case without the extra cost of creating a StringBuffer: // message = messages[0].toString(); // } else { // StringBuilder sb = new StringBuilder(); // if (messages != null) for (Object m : messages) { // sb.append(m); // } // if (t != null) { // sb.append("\n").append(Log.getStackTraceString(t)); // } // message = sb.toString(); // } // // Log.println(level, tag, message); // } // } // } // // Path: app/src/main/java/com/teocci/ytinbg/utils/BuildUtil.java // public static boolean minAPI26() // { // return Build.VERSION.SDK_INT >= Build.VERSION_CODES.O; // } // Path: app/src/main/java/com/teocci/ytinbg/notification/NotificationBuilder.java import android.app.Notification; import android.app.NotificationChannel; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.os.Build; import android.os.RemoteException; import android.support.v4.media.MediaDescriptionCompat; import android.support.v4.media.MediaMetadataCompat; import android.support.v4.media.session.MediaControllerCompat; import android.support.v4.media.session.MediaSessionCompat; import android.support.v4.media.session.PlaybackStateCompat; import com.teocci.ytinbg.R; import com.teocci.ytinbg.utils.LogHelper; import androidx.annotation.RequiresApi; import androidx.core.app.NotificationCompat; import androidx.core.app.NotificationCompat.Action; import androidx.media.app.NotificationCompat.MediaStyle; import androidx.media.session.MediaButtonReceiver; import static android.support.v4.media.session.PlaybackStateCompat.ACTION_PAUSE; import static android.support.v4.media.session.PlaybackStateCompat.ACTION_PLAY; import static android.support.v4.media.session.PlaybackStateCompat.ACTION_SKIP_TO_NEXT; import static android.support.v4.media.session.PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS; import static android.support.v4.media.session.PlaybackStateCompat.ACTION_STOP; import static com.teocci.ytinbg.utils.BuildUtil.minAPI26; .setVisibility(NotificationCompat.VISIBILITY_PUBLIC) .build(); } /** * Creates Notification Channel. This is required in Android O+ to display notifications. */ @RequiresApi(Build.VERSION_CODES.O) private void createNotificationChannel() { if (notificationManager.getNotificationChannel(CHANNEL_ID) == null) { NotificationChannel notificationChannel = new NotificationChannel( CHANNEL_ID, context.getString(R.string.notification_channel), NotificationManager.IMPORTANCE_LOW ); notificationChannel.setDescription(context.getString(R.string.notification_channel_description)); notificationManager.createNotificationChannel(notificationChannel); } } /** * @return true if if the minimum API is Oreo and if the notification channel does not exist. */ private boolean shouldCreateNowRunningChannel() {
return minAPI26() && !nowRunningChannelExist();
teocci/YouTube-In-Background
app/src/main/java/com/teocci/ytinbg/youtube/YouTubeSingleton.java
// Path: app/src/main/java/com/teocci/ytinbg/utils/LogHelper.java // public class LogHelper // { // private static final int LOG_PREFIX_LENGTH = LOG_PREFIX.length(); // private static final int MAX_LOG_TAG_LENGTH = 23; // private static final int RESERVED_LENGTH = MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH - 2; // // public static String makeLogTag(String str) // { // return LOG_PREFIX // + '[' // + (str.length() > RESERVED_LENGTH ? str.substring(0, RESERVED_LENGTH - 1) : str) // + ']'; // } // // /** // * Don't use this when obfuscating class names! // */ // public static String makeLogTag(Class cls) // { // return makeLogTag(cls.getSimpleName()); // } // // // public static void v(String tag, Object... messages) // { // // Only log VERBOSE if build type is DEBUG // if (BuildConfig.DEBUG) { // log(tag, Log.VERBOSE, null, messages); // } // } // // public static void d(String tag, Object... messages) // { // // Only log DEBUG if build type is DEBUG // if (BuildConfig.DEBUG) { // log(tag, Log.DEBUG, null, messages); // } // } // // public static void i(String tag, Object... messages) // { // log(tag, Log.INFO, null, messages); // } // // public static void w(String tag, Object... messages) // { // log(tag, Log.WARN, null, messages); // } // // public static void w(String tag, Throwable t, Object... messages) // { // log(tag, Log.WARN, t, messages); // } // // public static void e(String tag, Object... messages) // { // log(tag, Log.ERROR, null, messages); // } // // public static void e(String tag, Throwable t, Object... messages) // { // log(tag, Log.ERROR, t, messages); // } // // public static void log(String tag, int level, Throwable t, Object... messages) // { // if (Log.isLoggable(tag, level)) { // String message; // if (t == null && messages != null && messages.length == 1) { // // Handle this common case without the extra cost of creating a StringBuffer: // message = messages[0].toString(); // } else { // StringBuilder sb = new StringBuilder(); // if (messages != null) for (Object m : messages) { // sb.append(m); // } // if (t != null) { // sb.append("\n").append(Log.getStackTraceString(t)); // } // message = sb.toString(); // } // // Log.println(level, tag, message); // } // } // } // // Path: app/src/main/java/com/teocci/ytinbg/utils/Auth.java // public static final String[] SCOPES = {YouTubeScopes.YOUTUBE};
import android.content.Context; import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential; import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.json.jackson2.JacksonFactory; import com.google.api.client.util.ExponentialBackOff; import com.google.api.services.youtube.YouTube; import com.teocci.ytinbg.R; import com.teocci.ytinbg.utils.LogHelper; import java.util.Arrays; import static com.teocci.ytinbg.utils.Auth.SCOPES;
package com.teocci.ytinbg.youtube; /** * Created by teocci. * * @author teocci@yandex.com on 2017-Jun-09 */ public class YouTubeSingleton {
// Path: app/src/main/java/com/teocci/ytinbg/utils/LogHelper.java // public class LogHelper // { // private static final int LOG_PREFIX_LENGTH = LOG_PREFIX.length(); // private static final int MAX_LOG_TAG_LENGTH = 23; // private static final int RESERVED_LENGTH = MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH - 2; // // public static String makeLogTag(String str) // { // return LOG_PREFIX // + '[' // + (str.length() > RESERVED_LENGTH ? str.substring(0, RESERVED_LENGTH - 1) : str) // + ']'; // } // // /** // * Don't use this when obfuscating class names! // */ // public static String makeLogTag(Class cls) // { // return makeLogTag(cls.getSimpleName()); // } // // // public static void v(String tag, Object... messages) // { // // Only log VERBOSE if build type is DEBUG // if (BuildConfig.DEBUG) { // log(tag, Log.VERBOSE, null, messages); // } // } // // public static void d(String tag, Object... messages) // { // // Only log DEBUG if build type is DEBUG // if (BuildConfig.DEBUG) { // log(tag, Log.DEBUG, null, messages); // } // } // // public static void i(String tag, Object... messages) // { // log(tag, Log.INFO, null, messages); // } // // public static void w(String tag, Object... messages) // { // log(tag, Log.WARN, null, messages); // } // // public static void w(String tag, Throwable t, Object... messages) // { // log(tag, Log.WARN, t, messages); // } // // public static void e(String tag, Object... messages) // { // log(tag, Log.ERROR, null, messages); // } // // public static void e(String tag, Throwable t, Object... messages) // { // log(tag, Log.ERROR, t, messages); // } // // public static void log(String tag, int level, Throwable t, Object... messages) // { // if (Log.isLoggable(tag, level)) { // String message; // if (t == null && messages != null && messages.length == 1) { // // Handle this common case without the extra cost of creating a StringBuffer: // message = messages[0].toString(); // } else { // StringBuilder sb = new StringBuilder(); // if (messages != null) for (Object m : messages) { // sb.append(m); // } // if (t != null) { // sb.append("\n").append(Log.getStackTraceString(t)); // } // message = sb.toString(); // } // // Log.println(level, tag, message); // } // } // } // // Path: app/src/main/java/com/teocci/ytinbg/utils/Auth.java // public static final String[] SCOPES = {YouTubeScopes.YOUTUBE}; // Path: app/src/main/java/com/teocci/ytinbg/youtube/YouTubeSingleton.java import android.content.Context; import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential; import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.json.jackson2.JacksonFactory; import com.google.api.client.util.ExponentialBackOff; import com.google.api.services.youtube.YouTube; import com.teocci.ytinbg.R; import com.teocci.ytinbg.utils.LogHelper; import java.util.Arrays; import static com.teocci.ytinbg.utils.Auth.SCOPES; package com.teocci.ytinbg.youtube; /** * Created by teocci. * * @author teocci@yandex.com on 2017-Jun-09 */ public class YouTubeSingleton {
private static String TAG = LogHelper.makeLogTag(YouTubeSingleton.class);
teocci/YouTube-In-Background
app/src/main/java/com/teocci/ytinbg/youtube/YouTubeSingleton.java
// Path: app/src/main/java/com/teocci/ytinbg/utils/LogHelper.java // public class LogHelper // { // private static final int LOG_PREFIX_LENGTH = LOG_PREFIX.length(); // private static final int MAX_LOG_TAG_LENGTH = 23; // private static final int RESERVED_LENGTH = MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH - 2; // // public static String makeLogTag(String str) // { // return LOG_PREFIX // + '[' // + (str.length() > RESERVED_LENGTH ? str.substring(0, RESERVED_LENGTH - 1) : str) // + ']'; // } // // /** // * Don't use this when obfuscating class names! // */ // public static String makeLogTag(Class cls) // { // return makeLogTag(cls.getSimpleName()); // } // // // public static void v(String tag, Object... messages) // { // // Only log VERBOSE if build type is DEBUG // if (BuildConfig.DEBUG) { // log(tag, Log.VERBOSE, null, messages); // } // } // // public static void d(String tag, Object... messages) // { // // Only log DEBUG if build type is DEBUG // if (BuildConfig.DEBUG) { // log(tag, Log.DEBUG, null, messages); // } // } // // public static void i(String tag, Object... messages) // { // log(tag, Log.INFO, null, messages); // } // // public static void w(String tag, Object... messages) // { // log(tag, Log.WARN, null, messages); // } // // public static void w(String tag, Throwable t, Object... messages) // { // log(tag, Log.WARN, t, messages); // } // // public static void e(String tag, Object... messages) // { // log(tag, Log.ERROR, null, messages); // } // // public static void e(String tag, Throwable t, Object... messages) // { // log(tag, Log.ERROR, t, messages); // } // // public static void log(String tag, int level, Throwable t, Object... messages) // { // if (Log.isLoggable(tag, level)) { // String message; // if (t == null && messages != null && messages.length == 1) { // // Handle this common case without the extra cost of creating a StringBuffer: // message = messages[0].toString(); // } else { // StringBuilder sb = new StringBuilder(); // if (messages != null) for (Object m : messages) { // sb.append(m); // } // if (t != null) { // sb.append("\n").append(Log.getStackTraceString(t)); // } // message = sb.toString(); // } // // Log.println(level, tag, message); // } // } // } // // Path: app/src/main/java/com/teocci/ytinbg/utils/Auth.java // public static final String[] SCOPES = {YouTubeScopes.YOUTUBE};
import android.content.Context; import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential; import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.json.jackson2.JacksonFactory; import com.google.api.client.util.ExponentialBackOff; import com.google.api.services.youtube.YouTube; import com.teocci.ytinbg.R; import com.teocci.ytinbg.utils.LogHelper; import java.util.Arrays; import static com.teocci.ytinbg.utils.Auth.SCOPES;
package com.teocci.ytinbg.youtube; /** * Created by teocci. * * @author teocci@yandex.com on 2017-Jun-09 */ public class YouTubeSingleton { private static String TAG = LogHelper.makeLogTag(YouTubeSingleton.class); private static YouTube youTube; private static YouTube youTubeWithCredentials; private static GoogleAccountCredential credential; // Create the instance private static YouTubeSingleton instance = null; private static final Object mutex = new Object(); public static YouTubeSingleton getInstance(Context context) { if (instance == null) { synchronized (mutex) { if (instance == null) instance = new YouTubeSingleton(context); } } // Return the instance return instance; } private YouTubeSingleton(Context context) { String appName = context.getString(R.string.app_name); credential = GoogleAccountCredential
// Path: app/src/main/java/com/teocci/ytinbg/utils/LogHelper.java // public class LogHelper // { // private static final int LOG_PREFIX_LENGTH = LOG_PREFIX.length(); // private static final int MAX_LOG_TAG_LENGTH = 23; // private static final int RESERVED_LENGTH = MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH - 2; // // public static String makeLogTag(String str) // { // return LOG_PREFIX // + '[' // + (str.length() > RESERVED_LENGTH ? str.substring(0, RESERVED_LENGTH - 1) : str) // + ']'; // } // // /** // * Don't use this when obfuscating class names! // */ // public static String makeLogTag(Class cls) // { // return makeLogTag(cls.getSimpleName()); // } // // // public static void v(String tag, Object... messages) // { // // Only log VERBOSE if build type is DEBUG // if (BuildConfig.DEBUG) { // log(tag, Log.VERBOSE, null, messages); // } // } // // public static void d(String tag, Object... messages) // { // // Only log DEBUG if build type is DEBUG // if (BuildConfig.DEBUG) { // log(tag, Log.DEBUG, null, messages); // } // } // // public static void i(String tag, Object... messages) // { // log(tag, Log.INFO, null, messages); // } // // public static void w(String tag, Object... messages) // { // log(tag, Log.WARN, null, messages); // } // // public static void w(String tag, Throwable t, Object... messages) // { // log(tag, Log.WARN, t, messages); // } // // public static void e(String tag, Object... messages) // { // log(tag, Log.ERROR, null, messages); // } // // public static void e(String tag, Throwable t, Object... messages) // { // log(tag, Log.ERROR, t, messages); // } // // public static void log(String tag, int level, Throwable t, Object... messages) // { // if (Log.isLoggable(tag, level)) { // String message; // if (t == null && messages != null && messages.length == 1) { // // Handle this common case without the extra cost of creating a StringBuffer: // message = messages[0].toString(); // } else { // StringBuilder sb = new StringBuilder(); // if (messages != null) for (Object m : messages) { // sb.append(m); // } // if (t != null) { // sb.append("\n").append(Log.getStackTraceString(t)); // } // message = sb.toString(); // } // // Log.println(level, tag, message); // } // } // } // // Path: app/src/main/java/com/teocci/ytinbg/utils/Auth.java // public static final String[] SCOPES = {YouTubeScopes.YOUTUBE}; // Path: app/src/main/java/com/teocci/ytinbg/youtube/YouTubeSingleton.java import android.content.Context; import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential; import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.json.jackson2.JacksonFactory; import com.google.api.client.util.ExponentialBackOff; import com.google.api.services.youtube.YouTube; import com.teocci.ytinbg.R; import com.teocci.ytinbg.utils.LogHelper; import java.util.Arrays; import static com.teocci.ytinbg.utils.Auth.SCOPES; package com.teocci.ytinbg.youtube; /** * Created by teocci. * * @author teocci@yandex.com on 2017-Jun-09 */ public class YouTubeSingleton { private static String TAG = LogHelper.makeLogTag(YouTubeSingleton.class); private static YouTube youTube; private static YouTube youTubeWithCredentials; private static GoogleAccountCredential credential; // Create the instance private static YouTubeSingleton instance = null; private static final Object mutex = new Object(); public static YouTubeSingleton getInstance(Context context) { if (instance == null) { synchronized (mutex) { if (instance == null) instance = new YouTubeSingleton(context); } } // Return the instance return instance; } private YouTubeSingleton(Context context) { String appName = context.getString(R.string.app_name); credential = GoogleAccountCredential
.usingOAuth2(context, Arrays.asList(SCOPES))
teocci/YouTube-In-Background
app/src/main/java/com/teocci/ytinbg/interfaces/YouTubePlaylistReceiver.java
// Path: app/src/main/java/com/teocci/ytinbg/model/YouTubePlaylist.java // public class YouTubePlaylist implements Serializable // { // private static final String TAG = LogHelper.makeLogTag(YouTubePlaylist.class); // private String title; // private String thumbnailURL; // private String id; // private long numberOfVideos; // private String privacy; // // // public YouTubePlaylist() // { // this.title = ""; // this.thumbnailURL = ""; // this.id = ""; // this.numberOfVideos = 0; // this.privacy = ""; // } // // public YouTubePlaylist(String title, String thumbnailURL, String id, long numberOfVideos, // String privacy) // { // this.title = title; // this.thumbnailURL = thumbnailURL; // this.id = id; // this.numberOfVideos = numberOfVideos; // this.privacy = privacy; // } // // public long getNumberOfVideos() // { // return numberOfVideos; // } // // public void setNumberOfVideos(long numberOfVideos) // { // this.numberOfVideos = numberOfVideos; // } // // public String getId() // { // return id; // } // // public void setId(String id) // { // this.id = id; // } // // public String getTitle() // { // return title; // } // // public void setTitle(String title) // { // this.title = title; // } // // public String getThumbnailURL() // { // return thumbnailURL; // } // // public void setThumbnailURL(String thumbnail) // { // this.thumbnailURL = thumbnail; // } // // public String getPrivacy() // { // return privacy; // } // // public void setPrivacy(String status) // { // this.privacy = status; // } // // @Override // public String toString() // { // return "YouTubePlaylist {" + // "id='" + id + '\'' + // ", title='" + title + '\'' + // ", number of videos=" + numberOfVideos + // ", " + privacy + // '}'; // } // } // // Path: app/src/main/java/com/teocci/ytinbg/model/YouTubeVideo.java // public class YouTubeVideo implements Serializable // { // private static final String TAG = LogHelper.makeLogTag(YouTubeVideo.class); // private static final long serialVersionUID = 1L; // private String id; // private String title; // private String thumbnailURL; // private String duration; // private String viewCount; // // public YouTubeVideo() // { // this.id = ""; // this.title = ""; // this.thumbnailURL = ""; // this.duration = ""; // this.viewCount = ""; // } // // public YouTubeVideo(YouTubeVideo newVideo) { // this.id = newVideo.id; // this.title = newVideo.title; // this.thumbnailURL = newVideo.thumbnailURL; // this.duration = newVideo.duration; // this.viewCount = newVideo.viewCount; // } // public YouTubeVideo(String id, String title, String thumbnailURL, String duration, String // viewCount) // { // this.id = id; // this.title = title; // this.thumbnailURL = thumbnailURL; // this.duration = duration; // this.viewCount = viewCount; // } // // public String getId() // { // return id; // } // // public void setId(String id) // { // this.id = id; // } // // public String getDuration() // { // return duration; // } // // public void setDuration(String duration) // { // this.duration = duration; // } // // public String getTitle() // { // return title; // } // // public void setTitle(String title) // { // this.title = title; // } // // public String getThumbnailURL() // { // return thumbnailURL; // } // // public void setThumbnailURL(String thumbnail) // { // this.thumbnailURL = thumbnail; // } // // public String getViewCount() // { // return viewCount; // } // // public void setViewCount(String viewCount) // { // this.viewCount = viewCount; // } // // @Override // public String toString() // { // return "YouTubeVideo {" + // "id='" + id + '\'' + // ", title='" + title + '\'' + // '}'; // } // }
import com.teocci.ytinbg.model.YouTubePlaylist; import com.teocci.ytinbg.model.YouTubeVideo; import java.util.List;
package com.teocci.ytinbg.interfaces; /** * Interface which enables passing playlist to the fragments * Created by Teocci on 15.3.16.. */ public interface YouTubePlaylistReceiver {
// Path: app/src/main/java/com/teocci/ytinbg/model/YouTubePlaylist.java // public class YouTubePlaylist implements Serializable // { // private static final String TAG = LogHelper.makeLogTag(YouTubePlaylist.class); // private String title; // private String thumbnailURL; // private String id; // private long numberOfVideos; // private String privacy; // // // public YouTubePlaylist() // { // this.title = ""; // this.thumbnailURL = ""; // this.id = ""; // this.numberOfVideos = 0; // this.privacy = ""; // } // // public YouTubePlaylist(String title, String thumbnailURL, String id, long numberOfVideos, // String privacy) // { // this.title = title; // this.thumbnailURL = thumbnailURL; // this.id = id; // this.numberOfVideos = numberOfVideos; // this.privacy = privacy; // } // // public long getNumberOfVideos() // { // return numberOfVideos; // } // // public void setNumberOfVideos(long numberOfVideos) // { // this.numberOfVideos = numberOfVideos; // } // // public String getId() // { // return id; // } // // public void setId(String id) // { // this.id = id; // } // // public String getTitle() // { // return title; // } // // public void setTitle(String title) // { // this.title = title; // } // // public String getThumbnailURL() // { // return thumbnailURL; // } // // public void setThumbnailURL(String thumbnail) // { // this.thumbnailURL = thumbnail; // } // // public String getPrivacy() // { // return privacy; // } // // public void setPrivacy(String status) // { // this.privacy = status; // } // // @Override // public String toString() // { // return "YouTubePlaylist {" + // "id='" + id + '\'' + // ", title='" + title + '\'' + // ", number of videos=" + numberOfVideos + // ", " + privacy + // '}'; // } // } // // Path: app/src/main/java/com/teocci/ytinbg/model/YouTubeVideo.java // public class YouTubeVideo implements Serializable // { // private static final String TAG = LogHelper.makeLogTag(YouTubeVideo.class); // private static final long serialVersionUID = 1L; // private String id; // private String title; // private String thumbnailURL; // private String duration; // private String viewCount; // // public YouTubeVideo() // { // this.id = ""; // this.title = ""; // this.thumbnailURL = ""; // this.duration = ""; // this.viewCount = ""; // } // // public YouTubeVideo(YouTubeVideo newVideo) { // this.id = newVideo.id; // this.title = newVideo.title; // this.thumbnailURL = newVideo.thumbnailURL; // this.duration = newVideo.duration; // this.viewCount = newVideo.viewCount; // } // public YouTubeVideo(String id, String title, String thumbnailURL, String duration, String // viewCount) // { // this.id = id; // this.title = title; // this.thumbnailURL = thumbnailURL; // this.duration = duration; // this.viewCount = viewCount; // } // // public String getId() // { // return id; // } // // public void setId(String id) // { // this.id = id; // } // // public String getDuration() // { // return duration; // } // // public void setDuration(String duration) // { // this.duration = duration; // } // // public String getTitle() // { // return title; // } // // public void setTitle(String title) // { // this.title = title; // } // // public String getThumbnailURL() // { // return thumbnailURL; // } // // public void setThumbnailURL(String thumbnail) // { // this.thumbnailURL = thumbnail; // } // // public String getViewCount() // { // return viewCount; // } // // public void setViewCount(String viewCount) // { // this.viewCount = viewCount; // } // // @Override // public String toString() // { // return "YouTubeVideo {" + // "id='" + id + '\'' + // ", title='" + title + '\'' + // '}'; // } // } // Path: app/src/main/java/com/teocci/ytinbg/interfaces/YouTubePlaylistReceiver.java import com.teocci.ytinbg.model.YouTubePlaylist; import com.teocci.ytinbg.model.YouTubeVideo; import java.util.List; package com.teocci.ytinbg.interfaces; /** * Interface which enables passing playlist to the fragments * Created by Teocci on 15.3.16.. */ public interface YouTubePlaylistReceiver {
void onPlaylistReceived(List<YouTubePlaylist> youTubePlaylistList);
teocci/YouTube-In-Background
app/src/main/java/com/teocci/ytinbg/interfaces/YouTubePlaylistReceiver.java
// Path: app/src/main/java/com/teocci/ytinbg/model/YouTubePlaylist.java // public class YouTubePlaylist implements Serializable // { // private static final String TAG = LogHelper.makeLogTag(YouTubePlaylist.class); // private String title; // private String thumbnailURL; // private String id; // private long numberOfVideos; // private String privacy; // // // public YouTubePlaylist() // { // this.title = ""; // this.thumbnailURL = ""; // this.id = ""; // this.numberOfVideos = 0; // this.privacy = ""; // } // // public YouTubePlaylist(String title, String thumbnailURL, String id, long numberOfVideos, // String privacy) // { // this.title = title; // this.thumbnailURL = thumbnailURL; // this.id = id; // this.numberOfVideos = numberOfVideos; // this.privacy = privacy; // } // // public long getNumberOfVideos() // { // return numberOfVideos; // } // // public void setNumberOfVideos(long numberOfVideos) // { // this.numberOfVideos = numberOfVideos; // } // // public String getId() // { // return id; // } // // public void setId(String id) // { // this.id = id; // } // // public String getTitle() // { // return title; // } // // public void setTitle(String title) // { // this.title = title; // } // // public String getThumbnailURL() // { // return thumbnailURL; // } // // public void setThumbnailURL(String thumbnail) // { // this.thumbnailURL = thumbnail; // } // // public String getPrivacy() // { // return privacy; // } // // public void setPrivacy(String status) // { // this.privacy = status; // } // // @Override // public String toString() // { // return "YouTubePlaylist {" + // "id='" + id + '\'' + // ", title='" + title + '\'' + // ", number of videos=" + numberOfVideos + // ", " + privacy + // '}'; // } // } // // Path: app/src/main/java/com/teocci/ytinbg/model/YouTubeVideo.java // public class YouTubeVideo implements Serializable // { // private static final String TAG = LogHelper.makeLogTag(YouTubeVideo.class); // private static final long serialVersionUID = 1L; // private String id; // private String title; // private String thumbnailURL; // private String duration; // private String viewCount; // // public YouTubeVideo() // { // this.id = ""; // this.title = ""; // this.thumbnailURL = ""; // this.duration = ""; // this.viewCount = ""; // } // // public YouTubeVideo(YouTubeVideo newVideo) { // this.id = newVideo.id; // this.title = newVideo.title; // this.thumbnailURL = newVideo.thumbnailURL; // this.duration = newVideo.duration; // this.viewCount = newVideo.viewCount; // } // public YouTubeVideo(String id, String title, String thumbnailURL, String duration, String // viewCount) // { // this.id = id; // this.title = title; // this.thumbnailURL = thumbnailURL; // this.duration = duration; // this.viewCount = viewCount; // } // // public String getId() // { // return id; // } // // public void setId(String id) // { // this.id = id; // } // // public String getDuration() // { // return duration; // } // // public void setDuration(String duration) // { // this.duration = duration; // } // // public String getTitle() // { // return title; // } // // public void setTitle(String title) // { // this.title = title; // } // // public String getThumbnailURL() // { // return thumbnailURL; // } // // public void setThumbnailURL(String thumbnail) // { // this.thumbnailURL = thumbnail; // } // // public String getViewCount() // { // return viewCount; // } // // public void setViewCount(String viewCount) // { // this.viewCount = viewCount; // } // // @Override // public String toString() // { // return "YouTubeVideo {" + // "id='" + id + '\'' + // ", title='" + title + '\'' + // '}'; // } // }
import com.teocci.ytinbg.model.YouTubePlaylist; import com.teocci.ytinbg.model.YouTubeVideo; import java.util.List;
package com.teocci.ytinbg.interfaces; /** * Interface which enables passing playlist to the fragments * Created by Teocci on 15.3.16.. */ public interface YouTubePlaylistReceiver { void onPlaylistReceived(List<YouTubePlaylist> youTubePlaylistList); void onPlaylistNotFound(String playlistId, int errorCode);
// Path: app/src/main/java/com/teocci/ytinbg/model/YouTubePlaylist.java // public class YouTubePlaylist implements Serializable // { // private static final String TAG = LogHelper.makeLogTag(YouTubePlaylist.class); // private String title; // private String thumbnailURL; // private String id; // private long numberOfVideos; // private String privacy; // // // public YouTubePlaylist() // { // this.title = ""; // this.thumbnailURL = ""; // this.id = ""; // this.numberOfVideos = 0; // this.privacy = ""; // } // // public YouTubePlaylist(String title, String thumbnailURL, String id, long numberOfVideos, // String privacy) // { // this.title = title; // this.thumbnailURL = thumbnailURL; // this.id = id; // this.numberOfVideos = numberOfVideos; // this.privacy = privacy; // } // // public long getNumberOfVideos() // { // return numberOfVideos; // } // // public void setNumberOfVideos(long numberOfVideos) // { // this.numberOfVideos = numberOfVideos; // } // // public String getId() // { // return id; // } // // public void setId(String id) // { // this.id = id; // } // // public String getTitle() // { // return title; // } // // public void setTitle(String title) // { // this.title = title; // } // // public String getThumbnailURL() // { // return thumbnailURL; // } // // public void setThumbnailURL(String thumbnail) // { // this.thumbnailURL = thumbnail; // } // // public String getPrivacy() // { // return privacy; // } // // public void setPrivacy(String status) // { // this.privacy = status; // } // // @Override // public String toString() // { // return "YouTubePlaylist {" + // "id='" + id + '\'' + // ", title='" + title + '\'' + // ", number of videos=" + numberOfVideos + // ", " + privacy + // '}'; // } // } // // Path: app/src/main/java/com/teocci/ytinbg/model/YouTubeVideo.java // public class YouTubeVideo implements Serializable // { // private static final String TAG = LogHelper.makeLogTag(YouTubeVideo.class); // private static final long serialVersionUID = 1L; // private String id; // private String title; // private String thumbnailURL; // private String duration; // private String viewCount; // // public YouTubeVideo() // { // this.id = ""; // this.title = ""; // this.thumbnailURL = ""; // this.duration = ""; // this.viewCount = ""; // } // // public YouTubeVideo(YouTubeVideo newVideo) { // this.id = newVideo.id; // this.title = newVideo.title; // this.thumbnailURL = newVideo.thumbnailURL; // this.duration = newVideo.duration; // this.viewCount = newVideo.viewCount; // } // public YouTubeVideo(String id, String title, String thumbnailURL, String duration, String // viewCount) // { // this.id = id; // this.title = title; // this.thumbnailURL = thumbnailURL; // this.duration = duration; // this.viewCount = viewCount; // } // // public String getId() // { // return id; // } // // public void setId(String id) // { // this.id = id; // } // // public String getDuration() // { // return duration; // } // // public void setDuration(String duration) // { // this.duration = duration; // } // // public String getTitle() // { // return title; // } // // public void setTitle(String title) // { // this.title = title; // } // // public String getThumbnailURL() // { // return thumbnailURL; // } // // public void setThumbnailURL(String thumbnail) // { // this.thumbnailURL = thumbnail; // } // // public String getViewCount() // { // return viewCount; // } // // public void setViewCount(String viewCount) // { // this.viewCount = viewCount; // } // // @Override // public String toString() // { // return "YouTubeVideo {" + // "id='" + id + '\'' + // ", title='" + title + '\'' + // '}'; // } // } // Path: app/src/main/java/com/teocci/ytinbg/interfaces/YouTubePlaylistReceiver.java import com.teocci.ytinbg.model.YouTubePlaylist; import com.teocci.ytinbg.model.YouTubeVideo; import java.util.List; package com.teocci.ytinbg.interfaces; /** * Interface which enables passing playlist to the fragments * Created by Teocci on 15.3.16.. */ public interface YouTubePlaylistReceiver { void onPlaylistReceived(List<YouTubePlaylist> youTubePlaylistList); void onPlaylistNotFound(String playlistId, int errorCode);
void onPlaylistVideoReceived(List<YouTubeVideo> youTubeVideos);
teocci/YouTube-In-Background
app/src/main/java/com/teocci/ytinbg/utils/LogHelper.java
// Path: app/src/main/java/com/teocci/ytinbg/utils/Config.java // public static final String LOG_PREFIX = "[" + APP_NAME + "]";
import android.util.Log; import com.teocci.ytinbg.BuildConfig; import static com.teocci.ytinbg.utils.Config.LOG_PREFIX;
package com.teocci.ytinbg.utils; /** * Created by teocci. * * @author teocci@yandex.com on 2016-Dec-23 */ public class LogHelper {
// Path: app/src/main/java/com/teocci/ytinbg/utils/Config.java // public static final String LOG_PREFIX = "[" + APP_NAME + "]"; // Path: app/src/main/java/com/teocci/ytinbg/utils/LogHelper.java import android.util.Log; import com.teocci.ytinbg.BuildConfig; import static com.teocci.ytinbg.utils.Config.LOG_PREFIX; package com.teocci.ytinbg.utils; /** * Created by teocci. * * @author teocci@yandex.com on 2016-Dec-23 */ public class LogHelper {
private static final int LOG_PREFIX_LENGTH = LOG_PREFIX.length();
teocci/YouTube-In-Background
app/src/main/java/com/teocci/ytinbg/ui/fragments/PlaybackControlsFragment.java
// Path: app/src/main/java/com/teocci/ytinbg/utils/LogHelper.java // public class LogHelper // { // private static final int LOG_PREFIX_LENGTH = LOG_PREFIX.length(); // private static final int MAX_LOG_TAG_LENGTH = 23; // private static final int RESERVED_LENGTH = MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH - 2; // // public static String makeLogTag(String str) // { // return LOG_PREFIX // + '[' // + (str.length() > RESERVED_LENGTH ? str.substring(0, RESERVED_LENGTH - 1) : str) // + ']'; // } // // /** // * Don't use this when obfuscating class names! // */ // public static String makeLogTag(Class cls) // { // return makeLogTag(cls.getSimpleName()); // } // // // public static void v(String tag, Object... messages) // { // // Only log VERBOSE if build type is DEBUG // if (BuildConfig.DEBUG) { // log(tag, Log.VERBOSE, null, messages); // } // } // // public static void d(String tag, Object... messages) // { // // Only log DEBUG if build type is DEBUG // if (BuildConfig.DEBUG) { // log(tag, Log.DEBUG, null, messages); // } // } // // public static void i(String tag, Object... messages) // { // log(tag, Log.INFO, null, messages); // } // // public static void w(String tag, Object... messages) // { // log(tag, Log.WARN, null, messages); // } // // public static void w(String tag, Throwable t, Object... messages) // { // log(tag, Log.WARN, t, messages); // } // // public static void e(String tag, Object... messages) // { // log(tag, Log.ERROR, null, messages); // } // // public static void e(String tag, Throwable t, Object... messages) // { // log(tag, Log.ERROR, t, messages); // } // // public static void log(String tag, int level, Throwable t, Object... messages) // { // if (Log.isLoggable(tag, level)) { // String message; // if (t == null && messages != null && messages.length == 1) { // // Handle this common case without the extra cost of creating a StringBuffer: // message = messages[0].toString(); // } else { // StringBuilder sb = new StringBuilder(); // if (messages != null) for (Object m : messages) { // sb.append(m); // } // if (t != null) { // sb.append("\n").append(Log.getStackTraceString(t)); // } // message = sb.toString(); // } // // Log.println(level, tag, message); // } // } // }
import android.graphics.Color; import android.graphics.PorterDuff; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.os.Handler; import android.os.SystemClock; import android.support.v4.media.MediaBrowserCompat; import android.support.v4.media.MediaDescriptionCompat; import android.support.v4.media.MediaMetadataCompat; import android.support.v4.media.session.MediaControllerCompat; import android.support.v4.media.session.PlaybackStateCompat; import android.text.TextUtils; import android.text.format.DateUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.SeekBar; import android.widget.TextView; import com.squareup.picasso.Picasso; import com.teocci.ytinbg.R; import com.teocci.ytinbg.utils.LogHelper; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import androidx.annotation.NonNull; import androidx.core.content.ContextCompat; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentActivity; import static android.support.v4.media.MediaMetadataCompat.METADATA_KEY_DURATION; import static android.support.v4.media.session.PlaybackStateCompat.ACTION_SKIP_TO_NEXT; import static android.support.v4.media.session.PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS; import static android.support.v4.media.session.PlaybackStateCompat.STATE_BUFFERING; import static android.support.v4.media.session.PlaybackStateCompat.STATE_NONE; import static android.support.v4.media.session.PlaybackStateCompat.STATE_PAUSED; import static android.support.v4.media.session.PlaybackStateCompat.STATE_PLAYING; import static android.support.v4.media.session.PlaybackStateCompat.STATE_STOPPED; import static android.view.View.INVISIBLE; import static android.view.View.VISIBLE;
package com.teocci.ytinbg.ui.fragments; /** * Created by teocci. * <p> * This fragment shows the current playing youtube video with. Also has controls to seek/pause/play the audio. * * @author teocci@yandex.com on 2017-Jul-03 */ public class PlaybackControlsFragment extends Fragment {
// Path: app/src/main/java/com/teocci/ytinbg/utils/LogHelper.java // public class LogHelper // { // private static final int LOG_PREFIX_LENGTH = LOG_PREFIX.length(); // private static final int MAX_LOG_TAG_LENGTH = 23; // private static final int RESERVED_LENGTH = MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH - 2; // // public static String makeLogTag(String str) // { // return LOG_PREFIX // + '[' // + (str.length() > RESERVED_LENGTH ? str.substring(0, RESERVED_LENGTH - 1) : str) // + ']'; // } // // /** // * Don't use this when obfuscating class names! // */ // public static String makeLogTag(Class cls) // { // return makeLogTag(cls.getSimpleName()); // } // // // public static void v(String tag, Object... messages) // { // // Only log VERBOSE if build type is DEBUG // if (BuildConfig.DEBUG) { // log(tag, Log.VERBOSE, null, messages); // } // } // // public static void d(String tag, Object... messages) // { // // Only log DEBUG if build type is DEBUG // if (BuildConfig.DEBUG) { // log(tag, Log.DEBUG, null, messages); // } // } // // public static void i(String tag, Object... messages) // { // log(tag, Log.INFO, null, messages); // } // // public static void w(String tag, Object... messages) // { // log(tag, Log.WARN, null, messages); // } // // public static void w(String tag, Throwable t, Object... messages) // { // log(tag, Log.WARN, t, messages); // } // // public static void e(String tag, Object... messages) // { // log(tag, Log.ERROR, null, messages); // } // // public static void e(String tag, Throwable t, Object... messages) // { // log(tag, Log.ERROR, t, messages); // } // // public static void log(String tag, int level, Throwable t, Object... messages) // { // if (Log.isLoggable(tag, level)) { // String message; // if (t == null && messages != null && messages.length == 1) { // // Handle this common case without the extra cost of creating a StringBuffer: // message = messages[0].toString(); // } else { // StringBuilder sb = new StringBuilder(); // if (messages != null) for (Object m : messages) { // sb.append(m); // } // if (t != null) { // sb.append("\n").append(Log.getStackTraceString(t)); // } // message = sb.toString(); // } // // Log.println(level, tag, message); // } // } // } // Path: app/src/main/java/com/teocci/ytinbg/ui/fragments/PlaybackControlsFragment.java import android.graphics.Color; import android.graphics.PorterDuff; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.os.Handler; import android.os.SystemClock; import android.support.v4.media.MediaBrowserCompat; import android.support.v4.media.MediaDescriptionCompat; import android.support.v4.media.MediaMetadataCompat; import android.support.v4.media.session.MediaControllerCompat; import android.support.v4.media.session.PlaybackStateCompat; import android.text.TextUtils; import android.text.format.DateUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.SeekBar; import android.widget.TextView; import com.squareup.picasso.Picasso; import com.teocci.ytinbg.R; import com.teocci.ytinbg.utils.LogHelper; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import androidx.annotation.NonNull; import androidx.core.content.ContextCompat; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentActivity; import static android.support.v4.media.MediaMetadataCompat.METADATA_KEY_DURATION; import static android.support.v4.media.session.PlaybackStateCompat.ACTION_SKIP_TO_NEXT; import static android.support.v4.media.session.PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS; import static android.support.v4.media.session.PlaybackStateCompat.STATE_BUFFERING; import static android.support.v4.media.session.PlaybackStateCompat.STATE_NONE; import static android.support.v4.media.session.PlaybackStateCompat.STATE_PAUSED; import static android.support.v4.media.session.PlaybackStateCompat.STATE_PLAYING; import static android.support.v4.media.session.PlaybackStateCompat.STATE_STOPPED; import static android.view.View.INVISIBLE; import static android.view.View.VISIBLE; package com.teocci.ytinbg.ui.fragments; /** * Created by teocci. * <p> * This fragment shows the current playing youtube video with. Also has controls to seek/pause/play the audio. * * @author teocci@yandex.com on 2017-Jul-03 */ public class PlaybackControlsFragment extends Fragment {
private static final String TAG = LogHelper.makeLogTag(PlaybackControlsFragment.class);
teocci/YouTube-In-Background
app/src/main/java/com/teocci/ytinbg/callbacks/SimpleItemTouchCallback.java
// Path: app/src/main/java/com/teocci/ytinbg/interfaces/ItemTouchListener.java // public interface ItemTouchListener // { // /** // * Called when an item has been dragged far enough to trigger a move. This is called every time // * an item is shifted, and <strong>not</strong> at the end of a "drop" event.<br/> // * <br/> // * Implementations should call {@link RecyclerView.Adapter#notifyItemMoved(int, int)} after // * adjusting the underlying data to reflect this move. // * // * @param fromPosition The start position of the moved item. // * @param toPosition Then resolved position of the moved item. // * @return True if the item was moved to the new adapter position. // * @see RecyclerView.ViewHolder#getAdapterPosition() // */ // boolean onItemMove(int fromPosition, int toPosition); // // // /** // * Called when an item has been dismissed by a swipe.<br/> // * <br/> // * Implementations should call {@link RecyclerView.Adapter#notifyItemRemoved(int)} after // * adjusting the underlying data to reflect this removal. // * // * @param position The position of the item dismissed. // * @see RecyclerView.ViewHolder#getAdapterPosition() // */ // void onItemDismiss(int position); // } // // Path: app/src/main/java/com/teocci/ytinbg/interfaces/ItemTouchViewListener.java // public interface ItemTouchViewListener // { // /** // * Called when the {@link ItemTouchHelper} first registers an item as being moved or swiped. // * Implementations should update the item view to indicate it's active state. // */ // void onItemSelected(); // // // /** // * Called when the {@link ItemTouchHelper} has completed the move or swipe, and the active item // * state should be cleared. // */ // void onItemClear(); // }
import android.graphics.Canvas; import com.teocci.ytinbg.interfaces.ItemTouchListener; import com.teocci.ytinbg.interfaces.ItemTouchViewListener; import androidx.annotation.NonNull; import androidx.recyclerview.widget.GridLayoutManager; import androidx.recyclerview.widget.ItemTouchHelper; import androidx.recyclerview.widget.RecyclerView;
package com.teocci.ytinbg.callbacks; /** * Created by teocci. * * @author teocci@yandex.com on 2017-May-15 */ public class SimpleItemTouchCallback extends ItemTouchHelper.Callback { public static final float ALPHA_FULL = 1.0f;
// Path: app/src/main/java/com/teocci/ytinbg/interfaces/ItemTouchListener.java // public interface ItemTouchListener // { // /** // * Called when an item has been dragged far enough to trigger a move. This is called every time // * an item is shifted, and <strong>not</strong> at the end of a "drop" event.<br/> // * <br/> // * Implementations should call {@link RecyclerView.Adapter#notifyItemMoved(int, int)} after // * adjusting the underlying data to reflect this move. // * // * @param fromPosition The start position of the moved item. // * @param toPosition Then resolved position of the moved item. // * @return True if the item was moved to the new adapter position. // * @see RecyclerView.ViewHolder#getAdapterPosition() // */ // boolean onItemMove(int fromPosition, int toPosition); // // // /** // * Called when an item has been dismissed by a swipe.<br/> // * <br/> // * Implementations should call {@link RecyclerView.Adapter#notifyItemRemoved(int)} after // * adjusting the underlying data to reflect this removal. // * // * @param position The position of the item dismissed. // * @see RecyclerView.ViewHolder#getAdapterPosition() // */ // void onItemDismiss(int position); // } // // Path: app/src/main/java/com/teocci/ytinbg/interfaces/ItemTouchViewListener.java // public interface ItemTouchViewListener // { // /** // * Called when the {@link ItemTouchHelper} first registers an item as being moved or swiped. // * Implementations should update the item view to indicate it's active state. // */ // void onItemSelected(); // // // /** // * Called when the {@link ItemTouchHelper} has completed the move or swipe, and the active item // * state should be cleared. // */ // void onItemClear(); // } // Path: app/src/main/java/com/teocci/ytinbg/callbacks/SimpleItemTouchCallback.java import android.graphics.Canvas; import com.teocci.ytinbg.interfaces.ItemTouchListener; import com.teocci.ytinbg.interfaces.ItemTouchViewListener; import androidx.annotation.NonNull; import androidx.recyclerview.widget.GridLayoutManager; import androidx.recyclerview.widget.ItemTouchHelper; import androidx.recyclerview.widget.RecyclerView; package com.teocci.ytinbg.callbacks; /** * Created by teocci. * * @author teocci@yandex.com on 2017-May-15 */ public class SimpleItemTouchCallback extends ItemTouchHelper.Callback { public static final float ALPHA_FULL = 1.0f;
private final ItemTouchListener itemTouchListener;
teocci/YouTube-In-Background
app/src/main/java/com/teocci/ytinbg/callbacks/SimpleItemTouchCallback.java
// Path: app/src/main/java/com/teocci/ytinbg/interfaces/ItemTouchListener.java // public interface ItemTouchListener // { // /** // * Called when an item has been dragged far enough to trigger a move. This is called every time // * an item is shifted, and <strong>not</strong> at the end of a "drop" event.<br/> // * <br/> // * Implementations should call {@link RecyclerView.Adapter#notifyItemMoved(int, int)} after // * adjusting the underlying data to reflect this move. // * // * @param fromPosition The start position of the moved item. // * @param toPosition Then resolved position of the moved item. // * @return True if the item was moved to the new adapter position. // * @see RecyclerView.ViewHolder#getAdapterPosition() // */ // boolean onItemMove(int fromPosition, int toPosition); // // // /** // * Called when an item has been dismissed by a swipe.<br/> // * <br/> // * Implementations should call {@link RecyclerView.Adapter#notifyItemRemoved(int)} after // * adjusting the underlying data to reflect this removal. // * // * @param position The position of the item dismissed. // * @see RecyclerView.ViewHolder#getAdapterPosition() // */ // void onItemDismiss(int position); // } // // Path: app/src/main/java/com/teocci/ytinbg/interfaces/ItemTouchViewListener.java // public interface ItemTouchViewListener // { // /** // * Called when the {@link ItemTouchHelper} first registers an item as being moved or swiped. // * Implementations should update the item view to indicate it's active state. // */ // void onItemSelected(); // // // /** // * Called when the {@link ItemTouchHelper} has completed the move or swipe, and the active item // * state should be cleared. // */ // void onItemClear(); // }
import android.graphics.Canvas; import com.teocci.ytinbg.interfaces.ItemTouchListener; import com.teocci.ytinbg.interfaces.ItemTouchViewListener; import androidx.annotation.NonNull; import androidx.recyclerview.widget.GridLayoutManager; import androidx.recyclerview.widget.ItemTouchHelper; import androidx.recyclerview.widget.RecyclerView;
{ // Notify the adapter of the dismissal itemTouchListener.onItemDismiss(viewHolder.getAdapterPosition()); } @Override public void onChildDraw( @NonNull Canvas c, @NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) { if (actionState == ItemTouchHelper.ACTION_STATE_SWIPE) { // Fade out the view as it is swiped out of the parent's bounds final float alpha = ALPHA_FULL - Math.abs(dX) / (float) viewHolder.itemView.getWidth(); viewHolder.itemView.setAlpha(alpha); viewHolder.itemView.setTranslationX(dX); } else { super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive); } } @Override public void onSelectedChanged(RecyclerView.ViewHolder viewHolder, int actionState) { // We only want the active item to change if (actionState != ItemTouchHelper.ACTION_STATE_IDLE) {
// Path: app/src/main/java/com/teocci/ytinbg/interfaces/ItemTouchListener.java // public interface ItemTouchListener // { // /** // * Called when an item has been dragged far enough to trigger a move. This is called every time // * an item is shifted, and <strong>not</strong> at the end of a "drop" event.<br/> // * <br/> // * Implementations should call {@link RecyclerView.Adapter#notifyItemMoved(int, int)} after // * adjusting the underlying data to reflect this move. // * // * @param fromPosition The start position of the moved item. // * @param toPosition Then resolved position of the moved item. // * @return True if the item was moved to the new adapter position. // * @see RecyclerView.ViewHolder#getAdapterPosition() // */ // boolean onItemMove(int fromPosition, int toPosition); // // // /** // * Called when an item has been dismissed by a swipe.<br/> // * <br/> // * Implementations should call {@link RecyclerView.Adapter#notifyItemRemoved(int)} after // * adjusting the underlying data to reflect this removal. // * // * @param position The position of the item dismissed. // * @see RecyclerView.ViewHolder#getAdapterPosition() // */ // void onItemDismiss(int position); // } // // Path: app/src/main/java/com/teocci/ytinbg/interfaces/ItemTouchViewListener.java // public interface ItemTouchViewListener // { // /** // * Called when the {@link ItemTouchHelper} first registers an item as being moved or swiped. // * Implementations should update the item view to indicate it's active state. // */ // void onItemSelected(); // // // /** // * Called when the {@link ItemTouchHelper} has completed the move or swipe, and the active item // * state should be cleared. // */ // void onItemClear(); // } // Path: app/src/main/java/com/teocci/ytinbg/callbacks/SimpleItemTouchCallback.java import android.graphics.Canvas; import com.teocci.ytinbg.interfaces.ItemTouchListener; import com.teocci.ytinbg.interfaces.ItemTouchViewListener; import androidx.annotation.NonNull; import androidx.recyclerview.widget.GridLayoutManager; import androidx.recyclerview.widget.ItemTouchHelper; import androidx.recyclerview.widget.RecyclerView; { // Notify the adapter of the dismissal itemTouchListener.onItemDismiss(viewHolder.getAdapterPosition()); } @Override public void onChildDraw( @NonNull Canvas c, @NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) { if (actionState == ItemTouchHelper.ACTION_STATE_SWIPE) { // Fade out the view as it is swiped out of the parent's bounds final float alpha = ALPHA_FULL - Math.abs(dX) / (float) viewHolder.itemView.getWidth(); viewHolder.itemView.setAlpha(alpha); viewHolder.itemView.setTranslationX(dX); } else { super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive); } } @Override public void onSelectedChanged(RecyclerView.ViewHolder viewHolder, int actionState) { // We only want the active item to change if (actionState != ItemTouchHelper.ACTION_STATE_IDLE) {
if (viewHolder instanceof ItemTouchViewListener) {
teocci/YouTube-In-Background
app/src/main/java/com/teocci/ytinbg/model/YouTubePlaylist.java
// Path: app/src/main/java/com/teocci/ytinbg/utils/LogHelper.java // public class LogHelper // { // private static final int LOG_PREFIX_LENGTH = LOG_PREFIX.length(); // private static final int MAX_LOG_TAG_LENGTH = 23; // private static final int RESERVED_LENGTH = MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH - 2; // // public static String makeLogTag(String str) // { // return LOG_PREFIX // + '[' // + (str.length() > RESERVED_LENGTH ? str.substring(0, RESERVED_LENGTH - 1) : str) // + ']'; // } // // /** // * Don't use this when obfuscating class names! // */ // public static String makeLogTag(Class cls) // { // return makeLogTag(cls.getSimpleName()); // } // // // public static void v(String tag, Object... messages) // { // // Only log VERBOSE if build type is DEBUG // if (BuildConfig.DEBUG) { // log(tag, Log.VERBOSE, null, messages); // } // } // // public static void d(String tag, Object... messages) // { // // Only log DEBUG if build type is DEBUG // if (BuildConfig.DEBUG) { // log(tag, Log.DEBUG, null, messages); // } // } // // public static void i(String tag, Object... messages) // { // log(tag, Log.INFO, null, messages); // } // // public static void w(String tag, Object... messages) // { // log(tag, Log.WARN, null, messages); // } // // public static void w(String tag, Throwable t, Object... messages) // { // log(tag, Log.WARN, t, messages); // } // // public static void e(String tag, Object... messages) // { // log(tag, Log.ERROR, null, messages); // } // // public static void e(String tag, Throwable t, Object... messages) // { // log(tag, Log.ERROR, t, messages); // } // // public static void log(String tag, int level, Throwable t, Object... messages) // { // if (Log.isLoggable(tag, level)) { // String message; // if (t == null && messages != null && messages.length == 1) { // // Handle this common case without the extra cost of creating a StringBuffer: // message = messages[0].toString(); // } else { // StringBuilder sb = new StringBuilder(); // if (messages != null) for (Object m : messages) { // sb.append(m); // } // if (t != null) { // sb.append("\n").append(Log.getStackTraceString(t)); // } // message = sb.toString(); // } // // Log.println(level, tag, message); // } // } // }
import com.teocci.ytinbg.utils.LogHelper; import java.io.Serializable;
package com.teocci.ytinbg.model; /** * YouTube playlist class * Created by Teocci * * @author teocci@yandex.com on 2016-Aug-18 */ public class YouTubePlaylist implements Serializable {
// Path: app/src/main/java/com/teocci/ytinbg/utils/LogHelper.java // public class LogHelper // { // private static final int LOG_PREFIX_LENGTH = LOG_PREFIX.length(); // private static final int MAX_LOG_TAG_LENGTH = 23; // private static final int RESERVED_LENGTH = MAX_LOG_TAG_LENGTH - LOG_PREFIX_LENGTH - 2; // // public static String makeLogTag(String str) // { // return LOG_PREFIX // + '[' // + (str.length() > RESERVED_LENGTH ? str.substring(0, RESERVED_LENGTH - 1) : str) // + ']'; // } // // /** // * Don't use this when obfuscating class names! // */ // public static String makeLogTag(Class cls) // { // return makeLogTag(cls.getSimpleName()); // } // // // public static void v(String tag, Object... messages) // { // // Only log VERBOSE if build type is DEBUG // if (BuildConfig.DEBUG) { // log(tag, Log.VERBOSE, null, messages); // } // } // // public static void d(String tag, Object... messages) // { // // Only log DEBUG if build type is DEBUG // if (BuildConfig.DEBUG) { // log(tag, Log.DEBUG, null, messages); // } // } // // public static void i(String tag, Object... messages) // { // log(tag, Log.INFO, null, messages); // } // // public static void w(String tag, Object... messages) // { // log(tag, Log.WARN, null, messages); // } // // public static void w(String tag, Throwable t, Object... messages) // { // log(tag, Log.WARN, t, messages); // } // // public static void e(String tag, Object... messages) // { // log(tag, Log.ERROR, null, messages); // } // // public static void e(String tag, Throwable t, Object... messages) // { // log(tag, Log.ERROR, t, messages); // } // // public static void log(String tag, int level, Throwable t, Object... messages) // { // if (Log.isLoggable(tag, level)) { // String message; // if (t == null && messages != null && messages.length == 1) { // // Handle this common case without the extra cost of creating a StringBuffer: // message = messages[0].toString(); // } else { // StringBuilder sb = new StringBuilder(); // if (messages != null) for (Object m : messages) { // sb.append(m); // } // if (t != null) { // sb.append("\n").append(Log.getStackTraceString(t)); // } // message = sb.toString(); // } // // Log.println(level, tag, message); // } // } // } // Path: app/src/main/java/com/teocci/ytinbg/model/YouTubePlaylist.java import com.teocci.ytinbg.utils.LogHelper; import java.io.Serializable; package com.teocci.ytinbg.model; /** * YouTube playlist class * Created by Teocci * * @author teocci@yandex.com on 2016-Aug-18 */ public class YouTubePlaylist implements Serializable {
private static final String TAG = LogHelper.makeLogTag(YouTubePlaylist.class);
mahadirz/UnitenInfo
app/src/main/java/my/madet/adapter/NavDrawerListAdapter.java
// Path: app/src/main/java/my/madet/model/NavDrawerItem.java // public class NavDrawerItem { // // private String title; // private int icon; // private String count = "0"; // // boolean to set visiblity of the counter // private boolean isCounterVisible = false; // // public NavDrawerItem(){} // // public NavDrawerItem(String title, int icon){ // this.title = title; // this.icon = icon; // } // // public NavDrawerItem(String title, int icon, boolean isCounterVisible, String count){ // this.title = title; // this.icon = icon; // this.isCounterVisible = isCounterVisible; // this.count = count; // } // // public String getTitle(){ // return this.title; // } // // public int getIcon(){ // return this.icon; // } // // public String getCount(){ // return this.count; // } // // public boolean getCounterVisibility(){ // return this.isCounterVisible; // } // // public void setTitle(String title){ // this.title = title; // } // // public void setIcon(int icon){ // this.icon = icon; // } // // public void setCount(String count){ // this.count = count; // } // // public void setCounterVisibility(boolean isCounterVisible){ // this.isCounterVisible = isCounterVisible; // } // }
import java.util.ArrayList; import my.madet.model.NavDrawerItem; import my.madet.uniteninfo.R; import android.app.Activity; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView;
/* * The MIT License (MIT) * Copyright (c) 2014 Mahadir Ahmad * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * */ /** * Drawer Navigation adapters * * @author Mahadir Ahmad * @version 1.0 * */ package my.madet.adapter; public class NavDrawerListAdapter extends BaseAdapter { private Context context;
// Path: app/src/main/java/my/madet/model/NavDrawerItem.java // public class NavDrawerItem { // // private String title; // private int icon; // private String count = "0"; // // boolean to set visiblity of the counter // private boolean isCounterVisible = false; // // public NavDrawerItem(){} // // public NavDrawerItem(String title, int icon){ // this.title = title; // this.icon = icon; // } // // public NavDrawerItem(String title, int icon, boolean isCounterVisible, String count){ // this.title = title; // this.icon = icon; // this.isCounterVisible = isCounterVisible; // this.count = count; // } // // public String getTitle(){ // return this.title; // } // // public int getIcon(){ // return this.icon; // } // // public String getCount(){ // return this.count; // } // // public boolean getCounterVisibility(){ // return this.isCounterVisible; // } // // public void setTitle(String title){ // this.title = title; // } // // public void setIcon(int icon){ // this.icon = icon; // } // // public void setCount(String count){ // this.count = count; // } // // public void setCounterVisibility(boolean isCounterVisible){ // this.isCounterVisible = isCounterVisible; // } // } // Path: app/src/main/java/my/madet/adapter/NavDrawerListAdapter.java import java.util.ArrayList; import my.madet.model.NavDrawerItem; import my.madet.uniteninfo.R; import android.app.Activity; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; /* * The MIT License (MIT) * Copyright (c) 2014 Mahadir Ahmad * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * */ /** * Drawer Navigation adapters * * @author Mahadir Ahmad * @version 1.0 * */ package my.madet.adapter; public class NavDrawerListAdapter extends BaseAdapter { private Context context;
private ArrayList<NavDrawerItem> navDrawerItems;
mahadirz/UnitenInfo
app/src/main/java/my/madet/function/HttpParser.java
// Path: app/src/main/java/my/madet/ntlm/NTLMSchemeFactory.java // public class NTLMSchemeFactory implements AuthSchemeFactory // { // @Override // public AuthScheme newInstance(HttpParams params) // { // return new NTLMScheme(new JCIFSEngine()); // } // }
import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import my.madet.ntlm.NTLMSchemeFactory; import org.apache.http.HttpResponse; import org.apache.http.auth.AuthScope; import org.apache.http.auth.NTCredentials; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import android.content.Context; import android.os.Environment; import android.util.Log;
/* * FileWriter fw = new FileWriter(file.getAbsoluteFile()); * BufferedWriter bw = new BufferedWriter(fw); */ byte[] data = str.getBytes(); try { if (!file.exists()) { file.createNewFile(); } fos = new FileOutputStream(file); fos.write(data); fos.flush(); fos.close(); } catch (FileNotFoundException e) { // handle exception Log.e("SaveToSdCard", "File Not found exception"); } catch (IOException e) { // handle exception Log.e("SaveToSdCard", "Exception" + e.toString()); } } public String FetchUrL(String url) { StringBuffer result = new StringBuffer(); DefaultHttpClient httpclient = new DefaultHttpClient(); try { // register ntlm auth scheme httpclient.getAuthSchemes().register("ntlm",
// Path: app/src/main/java/my/madet/ntlm/NTLMSchemeFactory.java // public class NTLMSchemeFactory implements AuthSchemeFactory // { // @Override // public AuthScheme newInstance(HttpParams params) // { // return new NTLMScheme(new JCIFSEngine()); // } // } // Path: app/src/main/java/my/madet/function/HttpParser.java import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import my.madet.ntlm.NTLMSchemeFactory; import org.apache.http.HttpResponse; import org.apache.http.auth.AuthScope; import org.apache.http.auth.NTCredentials; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import android.content.Context; import android.os.Environment; import android.util.Log; /* * FileWriter fw = new FileWriter(file.getAbsoluteFile()); * BufferedWriter bw = new BufferedWriter(fw); */ byte[] data = str.getBytes(); try { if (!file.exists()) { file.createNewFile(); } fos = new FileOutputStream(file); fos.write(data); fos.flush(); fos.close(); } catch (FileNotFoundException e) { // handle exception Log.e("SaveToSdCard", "File Not found exception"); } catch (IOException e) { // handle exception Log.e("SaveToSdCard", "Exception" + e.toString()); } } public String FetchUrL(String url) { StringBuffer result = new StringBuffer(); DefaultHttpClient httpclient = new DefaultHttpClient(); try { // register ntlm auth scheme httpclient.getAuthSchemes().register("ntlm",
new NTLMSchemeFactory());
mahadirz/UnitenInfo
app/src/main/java/my/madet/uniteninfo/CheckUpdateDialog.java
// Path: app/src/main/java/my/madet/function/HttpsClient.java // public class HttpsClient { // // private String contents = ""; // public static String TAG = "HttpsClient"; // private boolean debug = false; // // /** // * Get the contents after the url was opened // * @return // */ // public String getContents() // { // return contents; // } // // /** // * Set Debug // * @param val // */ // public void setDebug(boolean val) // { // debug = val; // } // // public HttpsClient open(String https_url) // { // URL url; // try { // // url = new URL(https_url); // HttpsURLConnection con = (HttpsURLConnection)url.openConnection(); // if (debug) { // //dumpl all cert info // //print_https_cert(con); // } // retrieveContent(con); // // } catch (MalformedURLException e) { // e.printStackTrace(); // } catch (IOException e) { // e.printStackTrace(); // } // // return this; // // } // // private void print_https_cert(HttpsURLConnection con){ // // if(con!=null){ // // try { // // Log.d(TAG, "Response Code : " + con.getResponseCode()); // Log.d(TAG, "Cipher Suite : " + con.getCipherSuite()); // Log.d(TAG, "\n"); // // Certificate[] certs = con.getServerCertificates(); // for(Certificate cert : certs){ // Log.d(TAG, "Cert Type : " + cert.getType()); // Log.d(TAG, "Cert Hash Code : " + cert.hashCode()); // Log.d(TAG, "Cert Public Key Algorithm : " // + cert.getPublicKey().getAlgorithm()); // Log.d(TAG, "Cert Public Key Format : " // + cert.getPublicKey().getFormat()); // Log.d(TAG, "\n"); // } // // } catch (SSLPeerUnverifiedException e) { // e.printStackTrace(); // } catch (IOException e){ // e.printStackTrace(); // } // // } // // } // // private void retrieveContent(HttpsURLConnection con){ // contents = ""; // if(con!=null){ // // try { // BufferedReader br = // new BufferedReader( // new InputStreamReader(con.getInputStream())); // // String input; // String result = ""; // while ((input = br.readLine()) != null){ // result += input; // } // br.close(); // contents = result; // // } catch (IOException e) { // e.printStackTrace(); // } // // } // // } // } // // Path: app/src/main/java/my/madet/function/MyPreferences.java // public class MyPreferences { // // private SharedPreferences sharedPref; // private SharedPreferences.Editor editor; // // public final static String RESULT_PASSWORD_PROTECTED = "prefPasswordProtected"; //bool // public final static String DRAWER_INDEX_POSITION = "drawerPosition"; //int // public final static String UPDATE_ENABLED = "prefCheckUpdate"; //bool // public final static String LAST_UPDATE_CHECKED = "lastupdatechecked"; //DEPRECATED // public final static String NEW_UPDATE_AVAILABLE = "newupdateavailable"; //TODO // // public MyPreferences(Context c){ // sharedPref = c.getSharedPreferences("my.madet.uniteninfo_preferences",Context.MODE_PRIVATE); // } // // public boolean getBooleanPreference(String key){ // return sharedPref.getBoolean(key, false); // } // // public void setBooleanPreference(String key,boolean value){ // editor = sharedPref.edit(); // editor.putBoolean(key, value); // editor.commit(); // } // // public String getStringPreference(String key){ // return sharedPref.getString(key, ""); // } // // public void setStringPreference(String key,String value){ // editor = sharedPref.edit(); // editor.putString(key, value); // editor.commit(); // } // // public int getIntegerPreference(String key){ // return sharedPref.getInt(key, 0); // } // // public long getLongPreference(String key){ // return sharedPref.getLong(key, 0); // } // // public void setIntegerPreference(String key,int value){ // editor = sharedPref.edit(); // editor.putInt(key, value); // editor.commit(); // } // // public void setLongPreference(String key,Long value){ // editor = sharedPref.edit(); // editor.putLong(key, value); // editor.commit(); // } // // }
import my.madet.function.HttpsClient; import my.madet.function.MyPreferences; import org.json.JSONException; import org.json.JSONObject; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager.NameNotFoundException; import android.net.Uri; import android.os.AsyncTask; import android.util.Log;
package my.madet.uniteninfo; public class CheckUpdateDialog { private Context ourContext;
// Path: app/src/main/java/my/madet/function/HttpsClient.java // public class HttpsClient { // // private String contents = ""; // public static String TAG = "HttpsClient"; // private boolean debug = false; // // /** // * Get the contents after the url was opened // * @return // */ // public String getContents() // { // return contents; // } // // /** // * Set Debug // * @param val // */ // public void setDebug(boolean val) // { // debug = val; // } // // public HttpsClient open(String https_url) // { // URL url; // try { // // url = new URL(https_url); // HttpsURLConnection con = (HttpsURLConnection)url.openConnection(); // if (debug) { // //dumpl all cert info // //print_https_cert(con); // } // retrieveContent(con); // // } catch (MalformedURLException e) { // e.printStackTrace(); // } catch (IOException e) { // e.printStackTrace(); // } // // return this; // // } // // private void print_https_cert(HttpsURLConnection con){ // // if(con!=null){ // // try { // // Log.d(TAG, "Response Code : " + con.getResponseCode()); // Log.d(TAG, "Cipher Suite : " + con.getCipherSuite()); // Log.d(TAG, "\n"); // // Certificate[] certs = con.getServerCertificates(); // for(Certificate cert : certs){ // Log.d(TAG, "Cert Type : " + cert.getType()); // Log.d(TAG, "Cert Hash Code : " + cert.hashCode()); // Log.d(TAG, "Cert Public Key Algorithm : " // + cert.getPublicKey().getAlgorithm()); // Log.d(TAG, "Cert Public Key Format : " // + cert.getPublicKey().getFormat()); // Log.d(TAG, "\n"); // } // // } catch (SSLPeerUnverifiedException e) { // e.printStackTrace(); // } catch (IOException e){ // e.printStackTrace(); // } // // } // // } // // private void retrieveContent(HttpsURLConnection con){ // contents = ""; // if(con!=null){ // // try { // BufferedReader br = // new BufferedReader( // new InputStreamReader(con.getInputStream())); // // String input; // String result = ""; // while ((input = br.readLine()) != null){ // result += input; // } // br.close(); // contents = result; // // } catch (IOException e) { // e.printStackTrace(); // } // // } // // } // } // // Path: app/src/main/java/my/madet/function/MyPreferences.java // public class MyPreferences { // // private SharedPreferences sharedPref; // private SharedPreferences.Editor editor; // // public final static String RESULT_PASSWORD_PROTECTED = "prefPasswordProtected"; //bool // public final static String DRAWER_INDEX_POSITION = "drawerPosition"; //int // public final static String UPDATE_ENABLED = "prefCheckUpdate"; //bool // public final static String LAST_UPDATE_CHECKED = "lastupdatechecked"; //DEPRECATED // public final static String NEW_UPDATE_AVAILABLE = "newupdateavailable"; //TODO // // public MyPreferences(Context c){ // sharedPref = c.getSharedPreferences("my.madet.uniteninfo_preferences",Context.MODE_PRIVATE); // } // // public boolean getBooleanPreference(String key){ // return sharedPref.getBoolean(key, false); // } // // public void setBooleanPreference(String key,boolean value){ // editor = sharedPref.edit(); // editor.putBoolean(key, value); // editor.commit(); // } // // public String getStringPreference(String key){ // return sharedPref.getString(key, ""); // } // // public void setStringPreference(String key,String value){ // editor = sharedPref.edit(); // editor.putString(key, value); // editor.commit(); // } // // public int getIntegerPreference(String key){ // return sharedPref.getInt(key, 0); // } // // public long getLongPreference(String key){ // return sharedPref.getLong(key, 0); // } // // public void setIntegerPreference(String key,int value){ // editor = sharedPref.edit(); // editor.putInt(key, value); // editor.commit(); // } // // public void setLongPreference(String key,Long value){ // editor = sharedPref.edit(); // editor.putLong(key, value); // editor.commit(); // } // // } // Path: app/src/main/java/my/madet/uniteninfo/CheckUpdateDialog.java import my.madet.function.HttpsClient; import my.madet.function.MyPreferences; import org.json.JSONException; import org.json.JSONObject; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager.NameNotFoundException; import android.net.Uri; import android.os.AsyncTask; import android.util.Log; package my.madet.uniteninfo; public class CheckUpdateDialog { private Context ourContext;
private MyPreferences myPreferences;
mahadirz/UnitenInfo
app/src/main/java/my/madet/uniteninfo/CheckUpdateDialog.java
// Path: app/src/main/java/my/madet/function/HttpsClient.java // public class HttpsClient { // // private String contents = ""; // public static String TAG = "HttpsClient"; // private boolean debug = false; // // /** // * Get the contents after the url was opened // * @return // */ // public String getContents() // { // return contents; // } // // /** // * Set Debug // * @param val // */ // public void setDebug(boolean val) // { // debug = val; // } // // public HttpsClient open(String https_url) // { // URL url; // try { // // url = new URL(https_url); // HttpsURLConnection con = (HttpsURLConnection)url.openConnection(); // if (debug) { // //dumpl all cert info // //print_https_cert(con); // } // retrieveContent(con); // // } catch (MalformedURLException e) { // e.printStackTrace(); // } catch (IOException e) { // e.printStackTrace(); // } // // return this; // // } // // private void print_https_cert(HttpsURLConnection con){ // // if(con!=null){ // // try { // // Log.d(TAG, "Response Code : " + con.getResponseCode()); // Log.d(TAG, "Cipher Suite : " + con.getCipherSuite()); // Log.d(TAG, "\n"); // // Certificate[] certs = con.getServerCertificates(); // for(Certificate cert : certs){ // Log.d(TAG, "Cert Type : " + cert.getType()); // Log.d(TAG, "Cert Hash Code : " + cert.hashCode()); // Log.d(TAG, "Cert Public Key Algorithm : " // + cert.getPublicKey().getAlgorithm()); // Log.d(TAG, "Cert Public Key Format : " // + cert.getPublicKey().getFormat()); // Log.d(TAG, "\n"); // } // // } catch (SSLPeerUnverifiedException e) { // e.printStackTrace(); // } catch (IOException e){ // e.printStackTrace(); // } // // } // // } // // private void retrieveContent(HttpsURLConnection con){ // contents = ""; // if(con!=null){ // // try { // BufferedReader br = // new BufferedReader( // new InputStreamReader(con.getInputStream())); // // String input; // String result = ""; // while ((input = br.readLine()) != null){ // result += input; // } // br.close(); // contents = result; // // } catch (IOException e) { // e.printStackTrace(); // } // // } // // } // } // // Path: app/src/main/java/my/madet/function/MyPreferences.java // public class MyPreferences { // // private SharedPreferences sharedPref; // private SharedPreferences.Editor editor; // // public final static String RESULT_PASSWORD_PROTECTED = "prefPasswordProtected"; //bool // public final static String DRAWER_INDEX_POSITION = "drawerPosition"; //int // public final static String UPDATE_ENABLED = "prefCheckUpdate"; //bool // public final static String LAST_UPDATE_CHECKED = "lastupdatechecked"; //DEPRECATED // public final static String NEW_UPDATE_AVAILABLE = "newupdateavailable"; //TODO // // public MyPreferences(Context c){ // sharedPref = c.getSharedPreferences("my.madet.uniteninfo_preferences",Context.MODE_PRIVATE); // } // // public boolean getBooleanPreference(String key){ // return sharedPref.getBoolean(key, false); // } // // public void setBooleanPreference(String key,boolean value){ // editor = sharedPref.edit(); // editor.putBoolean(key, value); // editor.commit(); // } // // public String getStringPreference(String key){ // return sharedPref.getString(key, ""); // } // // public void setStringPreference(String key,String value){ // editor = sharedPref.edit(); // editor.putString(key, value); // editor.commit(); // } // // public int getIntegerPreference(String key){ // return sharedPref.getInt(key, 0); // } // // public long getLongPreference(String key){ // return sharedPref.getLong(key, 0); // } // // public void setIntegerPreference(String key,int value){ // editor = sharedPref.edit(); // editor.putInt(key, value); // editor.commit(); // } // // public void setLongPreference(String key,Long value){ // editor = sharedPref.edit(); // editor.putLong(key, value); // editor.commit(); // } // // }
import my.madet.function.HttpsClient; import my.madet.function.MyPreferences; import org.json.JSONException; import org.json.JSONObject; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager.NameNotFoundException; import android.net.Uri; import android.os.AsyncTask; import android.util.Log;
package my.madet.uniteninfo; public class CheckUpdateDialog { private Context ourContext; private MyPreferences myPreferences; public CheckUpdateDialog(Context c){ ourContext = c; myPreferences = new MyPreferences(c); } private class VersionHttpRequest extends AsyncTask<Void,Void,String> { protected String doInBackground(Void... a) {
// Path: app/src/main/java/my/madet/function/HttpsClient.java // public class HttpsClient { // // private String contents = ""; // public static String TAG = "HttpsClient"; // private boolean debug = false; // // /** // * Get the contents after the url was opened // * @return // */ // public String getContents() // { // return contents; // } // // /** // * Set Debug // * @param val // */ // public void setDebug(boolean val) // { // debug = val; // } // // public HttpsClient open(String https_url) // { // URL url; // try { // // url = new URL(https_url); // HttpsURLConnection con = (HttpsURLConnection)url.openConnection(); // if (debug) { // //dumpl all cert info // //print_https_cert(con); // } // retrieveContent(con); // // } catch (MalformedURLException e) { // e.printStackTrace(); // } catch (IOException e) { // e.printStackTrace(); // } // // return this; // // } // // private void print_https_cert(HttpsURLConnection con){ // // if(con!=null){ // // try { // // Log.d(TAG, "Response Code : " + con.getResponseCode()); // Log.d(TAG, "Cipher Suite : " + con.getCipherSuite()); // Log.d(TAG, "\n"); // // Certificate[] certs = con.getServerCertificates(); // for(Certificate cert : certs){ // Log.d(TAG, "Cert Type : " + cert.getType()); // Log.d(TAG, "Cert Hash Code : " + cert.hashCode()); // Log.d(TAG, "Cert Public Key Algorithm : " // + cert.getPublicKey().getAlgorithm()); // Log.d(TAG, "Cert Public Key Format : " // + cert.getPublicKey().getFormat()); // Log.d(TAG, "\n"); // } // // } catch (SSLPeerUnverifiedException e) { // e.printStackTrace(); // } catch (IOException e){ // e.printStackTrace(); // } // // } // // } // // private void retrieveContent(HttpsURLConnection con){ // contents = ""; // if(con!=null){ // // try { // BufferedReader br = // new BufferedReader( // new InputStreamReader(con.getInputStream())); // // String input; // String result = ""; // while ((input = br.readLine()) != null){ // result += input; // } // br.close(); // contents = result; // // } catch (IOException e) { // e.printStackTrace(); // } // // } // // } // } // // Path: app/src/main/java/my/madet/function/MyPreferences.java // public class MyPreferences { // // private SharedPreferences sharedPref; // private SharedPreferences.Editor editor; // // public final static String RESULT_PASSWORD_PROTECTED = "prefPasswordProtected"; //bool // public final static String DRAWER_INDEX_POSITION = "drawerPosition"; //int // public final static String UPDATE_ENABLED = "prefCheckUpdate"; //bool // public final static String LAST_UPDATE_CHECKED = "lastupdatechecked"; //DEPRECATED // public final static String NEW_UPDATE_AVAILABLE = "newupdateavailable"; //TODO // // public MyPreferences(Context c){ // sharedPref = c.getSharedPreferences("my.madet.uniteninfo_preferences",Context.MODE_PRIVATE); // } // // public boolean getBooleanPreference(String key){ // return sharedPref.getBoolean(key, false); // } // // public void setBooleanPreference(String key,boolean value){ // editor = sharedPref.edit(); // editor.putBoolean(key, value); // editor.commit(); // } // // public String getStringPreference(String key){ // return sharedPref.getString(key, ""); // } // // public void setStringPreference(String key,String value){ // editor = sharedPref.edit(); // editor.putString(key, value); // editor.commit(); // } // // public int getIntegerPreference(String key){ // return sharedPref.getInt(key, 0); // } // // public long getLongPreference(String key){ // return sharedPref.getLong(key, 0); // } // // public void setIntegerPreference(String key,int value){ // editor = sharedPref.edit(); // editor.putInt(key, value); // editor.commit(); // } // // public void setLongPreference(String key,Long value){ // editor = sharedPref.edit(); // editor.putLong(key, value); // editor.commit(); // } // // } // Path: app/src/main/java/my/madet/uniteninfo/CheckUpdateDialog.java import my.madet.function.HttpsClient; import my.madet.function.MyPreferences; import org.json.JSONException; import org.json.JSONObject; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager.NameNotFoundException; import android.net.Uri; import android.os.AsyncTask; import android.util.Log; package my.madet.uniteninfo; public class CheckUpdateDialog { private Context ourContext; private MyPreferences myPreferences; public CheckUpdateDialog(Context c){ ourContext = c; myPreferences = new MyPreferences(c); } private class VersionHttpRequest extends AsyncTask<Void,Void,String> { protected String doInBackground(Void... a) {
HttpsClient client = new HttpsClient();
jwzhangjie/AndJie
AndJie/src/com/jwzhangjie/andbase/doc/adapter/AccountAdapter.java
// Path: AndJie/src/com/jwzhangjie/andbase/doc/bean/GsonBean.java // public class GsonBean implements IParcelable{ // // @Override // public int describeContents() { // return 0; // } // // public GsonBean(){ // // } // // public GsonBean(Parcel source){ // readFromParcel(source); // } // // //用户登录账号 // private String user_name; // //用户登录密码 // private String user_pwd; // //其他信息,一定要先初始化 // private List<String> other = new ArrayList<String>(); // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeString(user_name); // dest.writeString(user_pwd); // dest.writeList(other); // } // // @Override // public void readFromParcel(Parcel source) { // user_name = source.readString(); // user_pwd = source.readString(); // source.readList(other, String.class.getClassLoader()); // } // // public static Creator<GsonBean> CREATOR = new Creator<GsonBean>() { // // @Override // public GsonBean createFromParcel(Parcel source) { // return new GsonBean(source); // } // // @Override // public GsonBean[] newArray(int size) { // return new GsonBean[size]; // } // // }; // // public String getUser_name() { // return user_name; // } // // public void setUser_name(String user_name) { // this.user_name = user_name; // } // // public String getUser_pwd() { // return user_pwd; // } // // public void setUser_pwd(String user_pwd) { // this.user_pwd = user_pwd; // } // // public List<String> getOther() { // return other; // } // // public void setOther(List<String> other) { // this.other = other; // } // // // }
import java.util.List; import com.jwzhangjie.andbase.R; import com.jwzhangjie.andbase.doc.bean.GsonBean; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView;
package com.jwzhangjie.andbase.doc.adapter; /** * title: AccountAdapter.java * @author jwzhangjie * Date: 2014-12-6 下午4:50:10 * version 1.0 * {@link http://blog.csdn.net/jwzhangjie} * Description:RecyclerView的适配器 */ public class AccountAdapter extends RecyclerView.Adapter<AccountAdapter.ViewHolder> {
// Path: AndJie/src/com/jwzhangjie/andbase/doc/bean/GsonBean.java // public class GsonBean implements IParcelable{ // // @Override // public int describeContents() { // return 0; // } // // public GsonBean(){ // // } // // public GsonBean(Parcel source){ // readFromParcel(source); // } // // //用户登录账号 // private String user_name; // //用户登录密码 // private String user_pwd; // //其他信息,一定要先初始化 // private List<String> other = new ArrayList<String>(); // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeString(user_name); // dest.writeString(user_pwd); // dest.writeList(other); // } // // @Override // public void readFromParcel(Parcel source) { // user_name = source.readString(); // user_pwd = source.readString(); // source.readList(other, String.class.getClassLoader()); // } // // public static Creator<GsonBean> CREATOR = new Creator<GsonBean>() { // // @Override // public GsonBean createFromParcel(Parcel source) { // return new GsonBean(source); // } // // @Override // public GsonBean[] newArray(int size) { // return new GsonBean[size]; // } // // }; // // public String getUser_name() { // return user_name; // } // // public void setUser_name(String user_name) { // this.user_name = user_name; // } // // public String getUser_pwd() { // return user_pwd; // } // // public void setUser_pwd(String user_pwd) { // this.user_pwd = user_pwd; // } // // public List<String> getOther() { // return other; // } // // public void setOther(List<String> other) { // this.other = other; // } // // // } // Path: AndJie/src/com/jwzhangjie/andbase/doc/adapter/AccountAdapter.java import java.util.List; import com.jwzhangjie.andbase.R; import com.jwzhangjie.andbase.doc.bean.GsonBean; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; package com.jwzhangjie.andbase.doc.adapter; /** * title: AccountAdapter.java * @author jwzhangjie * Date: 2014-12-6 下午4:50:10 * version 1.0 * {@link http://blog.csdn.net/jwzhangjie} * Description:RecyclerView的适配器 */ public class AccountAdapter extends RecyclerView.Adapter<AccountAdapter.ViewHolder> {
private List<GsonBean> listDatas;
jwzhangjie/AndJie
AndJie/src/com/jwzhangjie/andbase/ui/base/JieBasePopup.java
// Path: AndJie/src/com/jwzhangjie/andbase/JieApp.java // public class JieApp extends Application { // // public static JieApp instance = null; // private BaseActivity currentRunningActivity = null; // private LayoutInflater mInflater; // // @Override // public void onCreate() { // super.onCreate(); // instance = this; // initImageLoader(instance); // } // // public BaseActivity getCurrentRunningActivity() { // return currentRunningActivity; // } // // public void setCurrentRunningActivity(BaseActivity currentRunningActivity) { // this.currentRunningActivity = currentRunningActivity; // } // // public LayoutInflater getInflater() { // if (mInflater == null) { // mInflater = LayoutInflater.from(getApplicationContext()); // } // return mInflater; // } // // public static void initImageLoader(Context context) { // ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder( // context).threadPriority(Thread.NORM_PRIORITY - 2) // .denyCacheImageMultipleSizesInMemory() // .diskCacheFileNameGenerator(new Md5FileNameGenerator()) // .tasksProcessingOrder(QueueProcessingType.LIFO) // .writeDebugLogs() // Remove for release app // .build(); // // Initialize ImageLoader with configuration. // ImageLoader.getInstance().init(config); // } // }
import com.jwzhangjie.andbase.JieApp; import com.jwzhangjie.andbase.R; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.view.View; import android.widget.PopupWindow;
package com.jwzhangjie.andbase.ui.base; /** * title: JieBasePopup.java * @author jwzhangjie * Date: 2014-12-7 下午9:09:10 * version 1.0 * {@link http://blog.csdn.net/jwzhangjie} * Description:封装基础的弹出框 */ public abstract class JieBasePopup extends BaseView { protected PopupWindow mPopupWindow; private View parentView; public JieBasePopup() { super(); } public void initPopView(View parent) { parentView = parent; } public void initPopView(View parent, int viewId) { parentView = parent; } public void initPopWindow(int width, int height) { if (mPopupWindow == null) { mPopupWindow = new PopupWindow(view, width, height); /* 设置触摸外面时消失 */ mPopupWindow.setOutsideTouchable(true);
// Path: AndJie/src/com/jwzhangjie/andbase/JieApp.java // public class JieApp extends Application { // // public static JieApp instance = null; // private BaseActivity currentRunningActivity = null; // private LayoutInflater mInflater; // // @Override // public void onCreate() { // super.onCreate(); // instance = this; // initImageLoader(instance); // } // // public BaseActivity getCurrentRunningActivity() { // return currentRunningActivity; // } // // public void setCurrentRunningActivity(BaseActivity currentRunningActivity) { // this.currentRunningActivity = currentRunningActivity; // } // // public LayoutInflater getInflater() { // if (mInflater == null) { // mInflater = LayoutInflater.from(getApplicationContext()); // } // return mInflater; // } // // public static void initImageLoader(Context context) { // ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder( // context).threadPriority(Thread.NORM_PRIORITY - 2) // .denyCacheImageMultipleSizesInMemory() // .diskCacheFileNameGenerator(new Md5FileNameGenerator()) // .tasksProcessingOrder(QueueProcessingType.LIFO) // .writeDebugLogs() // Remove for release app // .build(); // // Initialize ImageLoader with configuration. // ImageLoader.getInstance().init(config); // } // } // Path: AndJie/src/com/jwzhangjie/andbase/ui/base/JieBasePopup.java import com.jwzhangjie.andbase.JieApp; import com.jwzhangjie.andbase.R; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.view.View; import android.widget.PopupWindow; package com.jwzhangjie.andbase.ui.base; /** * title: JieBasePopup.java * @author jwzhangjie * Date: 2014-12-7 下午9:09:10 * version 1.0 * {@link http://blog.csdn.net/jwzhangjie} * Description:封装基础的弹出框 */ public abstract class JieBasePopup extends BaseView { protected PopupWindow mPopupWindow; private View parentView; public JieBasePopup() { super(); } public void initPopView(View parent) { parentView = parent; } public void initPopView(View parent, int viewId) { parentView = parent; } public void initPopWindow(int width, int height) { if (mPopupWindow == null) { mPopupWindow = new PopupWindow(view, width, height); /* 设置触摸外面时消失 */ mPopupWindow.setOutsideTouchable(true);
mPopupWindow.setBackgroundDrawable(JieApp.instance
jwzhangjie/AndJie
AndJie/src/com/jwzhangjie/andbase/doc/DBUsed.java
// Path: AndJie/src/com/jwzhangjie/andbase/doc/db/Users.java // @DatabaseTable(tableName = "users") // public class Users implements Serializable{ // // private static final long serialVersionUID = 1L; // // @DatabaseField(generatedId = true) // private int id; // // @DatabaseField(unique = true) // private String email; // // @DatabaseField // private String pwd; // // @DatabaseField // private String name; // // @DatabaseField // private Date createTime; // // public Users() { // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getPwd() { // return pwd; // } // // public void setPwd(String pwd) { // this.pwd = pwd; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public Date getCreateTime() { // return createTime; // } // // public void setCreateTime(Date createTime) { // this.createTime = createTime; // } // // }
import java.util.ArrayList; import java.util.List; import android.content.Context; import com.jwzhangjie.andbase.doc.db.DBUtils; import com.jwzhangjie.andbase.doc.db.Users;
package com.jwzhangjie.andbase.doc; /** * title: DBUsed.java * @author jwzhangjie * Date: 2014年12月8日 下午12:48:21 * version 1.0 * {@link http://blog.csdn.net/jwzhangjie} * Description:关于ormlite的具体使用实例 */ public class DBUsed { private DBUtils mDbUtils; public DBUsed(Context context){ mDbUtils = new DBUtils(context); } public void createUsers(){
// Path: AndJie/src/com/jwzhangjie/andbase/doc/db/Users.java // @DatabaseTable(tableName = "users") // public class Users implements Serializable{ // // private static final long serialVersionUID = 1L; // // @DatabaseField(generatedId = true) // private int id; // // @DatabaseField(unique = true) // private String email; // // @DatabaseField // private String pwd; // // @DatabaseField // private String name; // // @DatabaseField // private Date createTime; // // public Users() { // } // // public int getId() { // return id; // } // // public void setId(int id) { // this.id = id; // } // // public String getEmail() { // return email; // } // // public void setEmail(String email) { // this.email = email; // } // // public String getPwd() { // return pwd; // } // // public void setPwd(String pwd) { // this.pwd = pwd; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public Date getCreateTime() { // return createTime; // } // // public void setCreateTime(Date createTime) { // this.createTime = createTime; // } // // } // Path: AndJie/src/com/jwzhangjie/andbase/doc/DBUsed.java import java.util.ArrayList; import java.util.List; import android.content.Context; import com.jwzhangjie.andbase.doc.db.DBUtils; import com.jwzhangjie.andbase.doc.db.Users; package com.jwzhangjie.andbase.doc; /** * title: DBUsed.java * @author jwzhangjie * Date: 2014年12月8日 下午12:48:21 * version 1.0 * {@link http://blog.csdn.net/jwzhangjie} * Description:关于ormlite的具体使用实例 */ public class DBUsed { private DBUtils mDbUtils; public DBUsed(Context context){ mDbUtils = new DBUtils(context); } public void createUsers(){
List<Users> users = new ArrayList<Users>();
jwzhangjie/AndJie
AndJie/src/com/jwzhangjie/andbase/JieApp.java
// Path: AndJie/src/com/jwzhangjie/andbase/ui/base/BaseActivity.java // public class BaseActivity extends FragmentActivity implements IActivity { // // protected Intent startIntent; // private Toast mToast; // protected int PULL_FINISH = 0; // public String ISREFRESH = "isReFresh"; // // @SuppressLint("HandlerLeak") // public Handler handlerMain = new Handler() { // // @Override // public void handleMessage(Message msg) { // super.handleMessage(msg); // Msg(msg); // } // }; // // public void Msg(Message msg) { // // } // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // startIntent = new Intent(); // beforeCreate(); // LogUtils.customTagPrefix = "jwzhangjie"; // initView(); // initListener(); // initData(); // } // // protected void beforeCreate() { // ViewUtils.inject(this); // } // // protected void initView() { // } // // protected void initListener() { // // } // // protected void initData() { // // } // // protected void showInfo(String text) { // if (mToast == null) { // mToast = Toast.makeText(this, text, Toast.LENGTH_SHORT); // mToast.setGravity(Gravity.CENTER, 0, 0); // } else { // mToast.setText(text); // mToast.setDuration(Toast.LENGTH_SHORT); // } // mToast.show(); // } // // protected void showInfo(int text) { // if (mToast == null) { // mToast = Toast.makeText(this, text, Toast.LENGTH_SHORT); // mToast.setGravity(Gravity.CENTER, 0, 0); // } else { // mToast.setText(text); // mToast.setDuration(Toast.LENGTH_SHORT); // } // mToast.show(); // } // // @Override // public void startActivity(Class<?> cls, boolean isClose) { // startIntent.setClass(this, cls); // startActivity(startIntent); // if (isClose) { // this.finish(); // } // } // // @Override // public void startActivity(Class<?> cls) { // startIntent.setClass(this, cls); // startActivity(startIntent); // } // // @Override // public void startActivity(Class<?> cls, Bundle bundle, boolean isClose) { // startIntent.setClass(this, cls); // startIntent.putExtras(bundle); // startActivity(startIntent); // if (isClose) { // this.finish(); // } // } // // @Override // public void startActivityForResult(int request) { // } // // @Override // public void startActivityForResult(int request, Class<?> cls, // boolean isClose) { // startIntent.setClass(this, cls); // super.startActivityForResult(startIntent, request); // if (isClose) { // this.finish(); // } // } // // @Override // public void startActivityForResult(int request, Class<?> cls) { // startIntent.setClass(this, cls); // super.startActivityForResult(startIntent, request); // } // // @Override // public void startActivityForResult(int request, Class<?> cls, Bundle bundle) { // startIntent.setClass(this, cls); // startIntent.putExtras(bundle); // super.startActivityForResult(startIntent, request); // } // // }
import com.jwzhangjie.andbase.ui.base.BaseActivity; import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator; import com.nostra13.universalimageloader.core.ImageLoader; import com.nostra13.universalimageloader.core.ImageLoaderConfiguration; import com.nostra13.universalimageloader.core.assist.QueueProcessingType; import android.app.Application; import android.content.Context; import android.view.LayoutInflater;
package com.jwzhangjie.andbase; public class JieApp extends Application { public static JieApp instance = null;
// Path: AndJie/src/com/jwzhangjie/andbase/ui/base/BaseActivity.java // public class BaseActivity extends FragmentActivity implements IActivity { // // protected Intent startIntent; // private Toast mToast; // protected int PULL_FINISH = 0; // public String ISREFRESH = "isReFresh"; // // @SuppressLint("HandlerLeak") // public Handler handlerMain = new Handler() { // // @Override // public void handleMessage(Message msg) { // super.handleMessage(msg); // Msg(msg); // } // }; // // public void Msg(Message msg) { // // } // // @Override // protected void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // startIntent = new Intent(); // beforeCreate(); // LogUtils.customTagPrefix = "jwzhangjie"; // initView(); // initListener(); // initData(); // } // // protected void beforeCreate() { // ViewUtils.inject(this); // } // // protected void initView() { // } // // protected void initListener() { // // } // // protected void initData() { // // } // // protected void showInfo(String text) { // if (mToast == null) { // mToast = Toast.makeText(this, text, Toast.LENGTH_SHORT); // mToast.setGravity(Gravity.CENTER, 0, 0); // } else { // mToast.setText(text); // mToast.setDuration(Toast.LENGTH_SHORT); // } // mToast.show(); // } // // protected void showInfo(int text) { // if (mToast == null) { // mToast = Toast.makeText(this, text, Toast.LENGTH_SHORT); // mToast.setGravity(Gravity.CENTER, 0, 0); // } else { // mToast.setText(text); // mToast.setDuration(Toast.LENGTH_SHORT); // } // mToast.show(); // } // // @Override // public void startActivity(Class<?> cls, boolean isClose) { // startIntent.setClass(this, cls); // startActivity(startIntent); // if (isClose) { // this.finish(); // } // } // // @Override // public void startActivity(Class<?> cls) { // startIntent.setClass(this, cls); // startActivity(startIntent); // } // // @Override // public void startActivity(Class<?> cls, Bundle bundle, boolean isClose) { // startIntent.setClass(this, cls); // startIntent.putExtras(bundle); // startActivity(startIntent); // if (isClose) { // this.finish(); // } // } // // @Override // public void startActivityForResult(int request) { // } // // @Override // public void startActivityForResult(int request, Class<?> cls, // boolean isClose) { // startIntent.setClass(this, cls); // super.startActivityForResult(startIntent, request); // if (isClose) { // this.finish(); // } // } // // @Override // public void startActivityForResult(int request, Class<?> cls) { // startIntent.setClass(this, cls); // super.startActivityForResult(startIntent, request); // } // // @Override // public void startActivityForResult(int request, Class<?> cls, Bundle bundle) { // startIntent.setClass(this, cls); // startIntent.putExtras(bundle); // super.startActivityForResult(startIntent, request); // } // // } // Path: AndJie/src/com/jwzhangjie/andbase/JieApp.java import com.jwzhangjie.andbase.ui.base.BaseActivity; import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator; import com.nostra13.universalimageloader.core.ImageLoader; import com.nostra13.universalimageloader.core.ImageLoaderConfiguration; import com.nostra13.universalimageloader.core.assist.QueueProcessingType; import android.app.Application; import android.content.Context; import android.view.LayoutInflater; package com.jwzhangjie.andbase; public class JieApp extends Application { public static JieApp instance = null;
private BaseActivity currentRunningActivity = null;
jwzhangjie/AndJie
AndJie/src/com/jwzhangjie/andbase/doc/HttpRequestUsed.java
// Path: AndJie/src/com/jwzhangjie/andbase/net/JieHttpClient.java // public class JieHttpClient { // // private static final String BASE_URL = JieContant.URL_Base; // private static AsyncHttpClient client = new AsyncHttpClient(); // // static { // client.setTimeout(30000); // } // // public static void get(String url, RequestParams params, // DefaultJsonResponseHandler responseHandler) { // client.get(getAbsUrl(url), params, responseHandler); // } // // /** // * Title: postJson // * Description:上传参数采用json格式 // * @param context // * @param url // * @param data // * @param responseHandler // */ // public static void postJson(Context context, String url, String data, // DefaultJsonResponseHandler responseHandler) { // StringEntity entity = null; // if (data != null) { // try { // entity = new StringEntity(data); // } catch (UnsupportedEncodingException e) { // e.printStackTrace(); // } // } // client.post(context, url, entity, "application/json", responseHandler); // } // // public static void postBase(String url, RequestParams params, // DefaultJsonResponseHandler responseHandler) { // client.post(getAbsUrl(url), params, responseHandler); // } // // public static void post(String url, RequestParams params, // DefaultJsonResponseHandler responseHandler) { // client.post(url, params, responseHandler); // } // // /** // * // * Title: postFiles // * Description:上传文件 // * @param url // * @param params // * @param listFile // * @param fileKey // * @param responseHandler // */ // public static void postFiles(String url, RequestParams params, // List<File> listFile, String fileKey, // DefaultJsonResponseHandler responseHandler) { // client.post(getAbsUrl(url), params, listFile, fileKey, responseHandler); // } // // public static String getAbsUrl(String string) { // return BASE_URL + string; // } // // }
import org.apache.http.Header; import com.jwzhangjie.andbase.net.DefaultJsonResponseHandler; import com.jwzhangjie.andbase.net.JieHttpClient; import com.loopj.android.http.RequestParams;
package com.jwzhangjie.andbase.doc; /** * title: HttpRequestUsed.java * @author jwzhangjie * Date: 2014-12-6 下午3:16:10 * version 1.0 * {@link http://blog.csdn.net/jwzhangjie} * Description: 网络请求实例 */ public class HttpRequestUsed { public HttpRequestUsed(){ RequestParams params = new RequestParams(); params.put("name", "jwzhangjie"); params.put("pwd", "****"); LoginRequest("/login", params); } /** * * Title: LoginRequest * Description: Post方式请求服务器数据 * @param url * @param params */ public void LoginRequest(String url, RequestParams params){
// Path: AndJie/src/com/jwzhangjie/andbase/net/JieHttpClient.java // public class JieHttpClient { // // private static final String BASE_URL = JieContant.URL_Base; // private static AsyncHttpClient client = new AsyncHttpClient(); // // static { // client.setTimeout(30000); // } // // public static void get(String url, RequestParams params, // DefaultJsonResponseHandler responseHandler) { // client.get(getAbsUrl(url), params, responseHandler); // } // // /** // * Title: postJson // * Description:上传参数采用json格式 // * @param context // * @param url // * @param data // * @param responseHandler // */ // public static void postJson(Context context, String url, String data, // DefaultJsonResponseHandler responseHandler) { // StringEntity entity = null; // if (data != null) { // try { // entity = new StringEntity(data); // } catch (UnsupportedEncodingException e) { // e.printStackTrace(); // } // } // client.post(context, url, entity, "application/json", responseHandler); // } // // public static void postBase(String url, RequestParams params, // DefaultJsonResponseHandler responseHandler) { // client.post(getAbsUrl(url), params, responseHandler); // } // // public static void post(String url, RequestParams params, // DefaultJsonResponseHandler responseHandler) { // client.post(url, params, responseHandler); // } // // /** // * // * Title: postFiles // * Description:上传文件 // * @param url // * @param params // * @param listFile // * @param fileKey // * @param responseHandler // */ // public static void postFiles(String url, RequestParams params, // List<File> listFile, String fileKey, // DefaultJsonResponseHandler responseHandler) { // client.post(getAbsUrl(url), params, listFile, fileKey, responseHandler); // } // // public static String getAbsUrl(String string) { // return BASE_URL + string; // } // // } // Path: AndJie/src/com/jwzhangjie/andbase/doc/HttpRequestUsed.java import org.apache.http.Header; import com.jwzhangjie.andbase.net.DefaultJsonResponseHandler; import com.jwzhangjie.andbase.net.JieHttpClient; import com.loopj.android.http.RequestParams; package com.jwzhangjie.andbase.doc; /** * title: HttpRequestUsed.java * @author jwzhangjie * Date: 2014-12-6 下午3:16:10 * version 1.0 * {@link http://blog.csdn.net/jwzhangjie} * Description: 网络请求实例 */ public class HttpRequestUsed { public HttpRequestUsed(){ RequestParams params = new RequestParams(); params.put("name", "jwzhangjie"); params.put("pwd", "****"); LoginRequest("/login", params); } /** * * Title: LoginRequest * Description: Post方式请求服务器数据 * @param url * @param params */ public void LoginRequest(String url, RequestParams params){
JieHttpClient.postBase(url, params, new DefaultJsonResponseHandler(){
google/dwh-assessment-extraction-tool
src/java/com/google/cloud/bigquery/dwhassessment/extractiontool/executor/SaveCheckerImpl.java
// Path: src/java/com/google/cloud/bigquery/dwhassessment/extractiontool/common/ChunkCheckpoint.java // @AutoValue // public abstract class ChunkCheckpoint { // // public abstract Integer lastSavedChunkNumber(); // // public abstract Instant lastSavedInstant(); // // public static Builder builder() { // return new AutoValue_ChunkCheckpoint.Builder() // .setLastSavedChunkNumber(-1) // .setLastSavedInstant(Instant.ofEpochMilli(0)); // } // // @AutoValue.Builder // public abstract static class Builder { // // public abstract Builder setLastSavedChunkNumber(Integer value); // // public abstract Builder setLastSavedInstant(Instant value); // // public abstract ChunkCheckpoint build(); // } // }
import static java.util.stream.Collectors.toList; import static java.util.stream.Collectors.groupingBy; import static java.util.stream.Collectors.mapping; import static java.util.stream.Collectors.collectingAndThen; import com.google.cloud.bigquery.dwhassessment.extractiontool.common.ChunkCheckpoint; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Iterables; import com.google.re2j.Matcher; import com.google.re2j.Pattern; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.time.Instant; import java.time.LocalDateTime; import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatterBuilder; import java.time.format.DateTimeParseException; import java.util.Comparator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.function.Function;
.filter(Files::isRegularFile) .map(oneFile -> INPUT_CHUNK_PATTERN.matcher(oneFile.getFileName().toString())) .filter(Matcher::matches) .collect( groupingBy( (Matcher matcher) -> matcher.group("scriptName"), mapping( Function.identity(), collectingAndThen( toList(), list -> list.stream() .sorted( Comparator.comparingInt( matcher -> Integer.parseInt(matcher.group("chunkNumber")))) .collect(toList()))))); } catch (IOException e) { throw new IllegalStateException( String.format("Error reading path '%s'.", path.toString()), e); } } private static Instant getInstantFromFilenameTimestamp(String timestamp) { return ZonedDateTime.of( chunkTimestampFormatter.parse(timestamp, LocalDateTime::from), ZoneOffset.UTC) .toInstant(); } @Override
// Path: src/java/com/google/cloud/bigquery/dwhassessment/extractiontool/common/ChunkCheckpoint.java // @AutoValue // public abstract class ChunkCheckpoint { // // public abstract Integer lastSavedChunkNumber(); // // public abstract Instant lastSavedInstant(); // // public static Builder builder() { // return new AutoValue_ChunkCheckpoint.Builder() // .setLastSavedChunkNumber(-1) // .setLastSavedInstant(Instant.ofEpochMilli(0)); // } // // @AutoValue.Builder // public abstract static class Builder { // // public abstract Builder setLastSavedChunkNumber(Integer value); // // public abstract Builder setLastSavedInstant(Instant value); // // public abstract ChunkCheckpoint build(); // } // } // Path: src/java/com/google/cloud/bigquery/dwhassessment/extractiontool/executor/SaveCheckerImpl.java import static java.util.stream.Collectors.toList; import static java.util.stream.Collectors.groupingBy; import static java.util.stream.Collectors.mapping; import static java.util.stream.Collectors.collectingAndThen; import com.google.cloud.bigquery.dwhassessment.extractiontool.common.ChunkCheckpoint; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Iterables; import com.google.re2j.Matcher; import com.google.re2j.Pattern; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.time.Instant; import java.time.LocalDateTime; import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatterBuilder; import java.time.format.DateTimeParseException; import java.util.Comparator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.function.Function; .filter(Files::isRegularFile) .map(oneFile -> INPUT_CHUNK_PATTERN.matcher(oneFile.getFileName().toString())) .filter(Matcher::matches) .collect( groupingBy( (Matcher matcher) -> matcher.group("scriptName"), mapping( Function.identity(), collectingAndThen( toList(), list -> list.stream() .sorted( Comparator.comparingInt( matcher -> Integer.parseInt(matcher.group("chunkNumber")))) .collect(toList()))))); } catch (IOException e) { throw new IllegalStateException( String.format("Error reading path '%s'.", path.toString()), e); } } private static Instant getInstantFromFilenameTimestamp(String timestamp) { return ZonedDateTime.of( chunkTimestampFormatter.parse(timestamp, LocalDateTime::from), ZoneOffset.UTC) .toInstant(); } @Override
public ImmutableMap<String, ChunkCheckpoint> getScriptCheckPoints(Path path) {
google/dwh-assessment-extraction-tool
src/javatests/com/google/cloud/bigquery/dwhassessment/extractiontool/db/AvroHelperTest.java
// Path: src/java/com/google/cloud/bigquery/dwhassessment/extractiontool/db/AvroHelper.java // public static void dumpResults( // ImmutableList<GenericRecord> records, OutputStream outputStream, Schema schema) // throws IOException { // GenericDatumWriter<GenericRecord> writer = new GenericDatumWriter<>(schema); // DataFileWriter<GenericRecord> dataFileWriter = new DataFileWriter<>(writer); // dataFileWriter.create(schema, outputStream); // // records.stream() // .forEach( // record -> { // try { // dataFileWriter.append(record); // } catch (IOException e) { // throw new IllegalStateException( // String.format( // "Failed to encode query result %s to file with error message: %s", // record.toString(), e.getMessage())); // } // }); // dataFileWriter.close(); // outputStream.close(); // } // // Path: src/java/com/google/cloud/bigquery/dwhassessment/extractiontool/db/AvroHelper.java // public static Schema getAvroSchema( // String schemaName, String namespace, ResultSetMetaData metaData) throws SQLException { // Preconditions.checkArgument(!schemaName.isEmpty(), "Schema name cannot be empty."); // Preconditions.checkArgument(!namespace.isEmpty(), "Namespace cannot be empty."); // SchemaBuilder.FieldAssembler<Schema> schemaAssembler = // SchemaBuilder.record(schemaName).namespace(namespace).fields(); // // for (int columnIndex = 1; columnIndex <= metaData.getColumnCount(); columnIndex++) { // SchemaBuilder.FieldBuilder<Schema> fieldBuilder = // schemaAssembler.name(metaData.getColumnName(columnIndex)); // AvroHelper.convertColumnTypeToAvroType(fieldBuilder, metaData, columnIndex); // } // return schemaAssembler.endRecord(); // } // // Path: src/java/com/google/cloud/bigquery/dwhassessment/extractiontool/db/AvroHelper.java // public static GenericRecord parseRowToAvro(ResultSet row, Schema schema) throws SQLException { // GenericRecordBuilder recordBuilder = new GenericRecordBuilder(schema); // ResultSetMetaData metaData = row.getMetaData(); // for (int columnIndex = 1; columnIndex <= row.getMetaData().getColumnCount(); columnIndex++) { // recordBuilder.set( // metaData.getColumnName(columnIndex), getRowObject(metaData, row, columnIndex)); // } // return recordBuilder.build(); // }
import static com.google.cloud.bigquery.dwhassessment.extractiontool.db.AvroHelper.dumpResults; import static com.google.cloud.bigquery.dwhassessment.extractiontool.db.AvroHelper.getAvroSchema; import static com.google.cloud.bigquery.dwhassessment.extractiontool.db.AvroHelper.parseRowToAvro; import static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.assertThrows; import com.google.common.collect.ImmutableList; import java.io.ByteArrayOutputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.Statement; import org.apache.avro.Schema; import org.apache.avro.file.DataFileReader; import org.apache.avro.file.SeekableByteArrayInput; import org.apache.avro.generic.GenericData.Record; import org.apache.avro.generic.GenericDatumReader; import org.apache.avro.generic.GenericRecord; import org.apache.avro.generic.GenericRecordBuilder; import org.apache.avro.io.DatumReader; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4;
Statement baseStmt = connection.createStatement(); baseStmt.execute( "CREATE TABLE T0 (" + "INT_COL INTEGER, " + "VARCHAR_COL VARCHAR(100), " + "CHAR_COL CHAR(100), " + "LONGVARCHAR_COL LONGVARCHAR(100), " + "SMALLINT_COL SMALLINT, " + "BIGINT_COL BIGINT, " + "DECIMAL_COL DECIMAL, " + "TIMESTAMP_COL TIMESTAMP, " + "DATE_COL DATE, " + "BINARY_COL BINARY, " + "FLOAT_COL FLOAT, " + "DOUBLE_COL DOUBLE, " + "BIT_COL BIT, " + "BOOLEAN_COL BOOLEAN, " + "TINYINT_COL TINYINT, " + "REAL_COL REAL)"); baseStmt.execute( "CREATE TABLE SIMPLE_TABLE (ID INTEGER, NAME VARCHAR(100), CHAR_COL CHAR(20))"); baseStmt.execute("INSERT INTO SIMPLE_TABLE VALUES (0, 'name_0', ' two words')"); baseStmt.close(); connection.commit(); metaData = connection.createStatement().executeQuery("SELECT * FROM T0").getMetaData(); } @Test public void getAvroSchemaTest() throws Exception {
// Path: src/java/com/google/cloud/bigquery/dwhassessment/extractiontool/db/AvroHelper.java // public static void dumpResults( // ImmutableList<GenericRecord> records, OutputStream outputStream, Schema schema) // throws IOException { // GenericDatumWriter<GenericRecord> writer = new GenericDatumWriter<>(schema); // DataFileWriter<GenericRecord> dataFileWriter = new DataFileWriter<>(writer); // dataFileWriter.create(schema, outputStream); // // records.stream() // .forEach( // record -> { // try { // dataFileWriter.append(record); // } catch (IOException e) { // throw new IllegalStateException( // String.format( // "Failed to encode query result %s to file with error message: %s", // record.toString(), e.getMessage())); // } // }); // dataFileWriter.close(); // outputStream.close(); // } // // Path: src/java/com/google/cloud/bigquery/dwhassessment/extractiontool/db/AvroHelper.java // public static Schema getAvroSchema( // String schemaName, String namespace, ResultSetMetaData metaData) throws SQLException { // Preconditions.checkArgument(!schemaName.isEmpty(), "Schema name cannot be empty."); // Preconditions.checkArgument(!namespace.isEmpty(), "Namespace cannot be empty."); // SchemaBuilder.FieldAssembler<Schema> schemaAssembler = // SchemaBuilder.record(schemaName).namespace(namespace).fields(); // // for (int columnIndex = 1; columnIndex <= metaData.getColumnCount(); columnIndex++) { // SchemaBuilder.FieldBuilder<Schema> fieldBuilder = // schemaAssembler.name(metaData.getColumnName(columnIndex)); // AvroHelper.convertColumnTypeToAvroType(fieldBuilder, metaData, columnIndex); // } // return schemaAssembler.endRecord(); // } // // Path: src/java/com/google/cloud/bigquery/dwhassessment/extractiontool/db/AvroHelper.java // public static GenericRecord parseRowToAvro(ResultSet row, Schema schema) throws SQLException { // GenericRecordBuilder recordBuilder = new GenericRecordBuilder(schema); // ResultSetMetaData metaData = row.getMetaData(); // for (int columnIndex = 1; columnIndex <= row.getMetaData().getColumnCount(); columnIndex++) { // recordBuilder.set( // metaData.getColumnName(columnIndex), getRowObject(metaData, row, columnIndex)); // } // return recordBuilder.build(); // } // Path: src/javatests/com/google/cloud/bigquery/dwhassessment/extractiontool/db/AvroHelperTest.java import static com.google.cloud.bigquery.dwhassessment.extractiontool.db.AvroHelper.dumpResults; import static com.google.cloud.bigquery.dwhassessment.extractiontool.db.AvroHelper.getAvroSchema; import static com.google.cloud.bigquery.dwhassessment.extractiontool.db.AvroHelper.parseRowToAvro; import static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.assertThrows; import com.google.common.collect.ImmutableList; import java.io.ByteArrayOutputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.Statement; import org.apache.avro.Schema; import org.apache.avro.file.DataFileReader; import org.apache.avro.file.SeekableByteArrayInput; import org.apache.avro.generic.GenericData.Record; import org.apache.avro.generic.GenericDatumReader; import org.apache.avro.generic.GenericRecord; import org.apache.avro.generic.GenericRecordBuilder; import org.apache.avro.io.DatumReader; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; Statement baseStmt = connection.createStatement(); baseStmt.execute( "CREATE TABLE T0 (" + "INT_COL INTEGER, " + "VARCHAR_COL VARCHAR(100), " + "CHAR_COL CHAR(100), " + "LONGVARCHAR_COL LONGVARCHAR(100), " + "SMALLINT_COL SMALLINT, " + "BIGINT_COL BIGINT, " + "DECIMAL_COL DECIMAL, " + "TIMESTAMP_COL TIMESTAMP, " + "DATE_COL DATE, " + "BINARY_COL BINARY, " + "FLOAT_COL FLOAT, " + "DOUBLE_COL DOUBLE, " + "BIT_COL BIT, " + "BOOLEAN_COL BOOLEAN, " + "TINYINT_COL TINYINT, " + "REAL_COL REAL)"); baseStmt.execute( "CREATE TABLE SIMPLE_TABLE (ID INTEGER, NAME VARCHAR(100), CHAR_COL CHAR(20))"); baseStmt.execute("INSERT INTO SIMPLE_TABLE VALUES (0, 'name_0', ' two words')"); baseStmt.close(); connection.commit(); metaData = connection.createStatement().executeQuery("SELECT * FROM T0").getMetaData(); } @Test public void getAvroSchemaTest() throws Exception {
Schema schema = getAvroSchema("schemaName", "namespace", metaData);
google/dwh-assessment-extraction-tool
src/javatests/com/google/cloud/bigquery/dwhassessment/extractiontool/db/AvroHelperTest.java
// Path: src/java/com/google/cloud/bigquery/dwhassessment/extractiontool/db/AvroHelper.java // public static void dumpResults( // ImmutableList<GenericRecord> records, OutputStream outputStream, Schema schema) // throws IOException { // GenericDatumWriter<GenericRecord> writer = new GenericDatumWriter<>(schema); // DataFileWriter<GenericRecord> dataFileWriter = new DataFileWriter<>(writer); // dataFileWriter.create(schema, outputStream); // // records.stream() // .forEach( // record -> { // try { // dataFileWriter.append(record); // } catch (IOException e) { // throw new IllegalStateException( // String.format( // "Failed to encode query result %s to file with error message: %s", // record.toString(), e.getMessage())); // } // }); // dataFileWriter.close(); // outputStream.close(); // } // // Path: src/java/com/google/cloud/bigquery/dwhassessment/extractiontool/db/AvroHelper.java // public static Schema getAvroSchema( // String schemaName, String namespace, ResultSetMetaData metaData) throws SQLException { // Preconditions.checkArgument(!schemaName.isEmpty(), "Schema name cannot be empty."); // Preconditions.checkArgument(!namespace.isEmpty(), "Namespace cannot be empty."); // SchemaBuilder.FieldAssembler<Schema> schemaAssembler = // SchemaBuilder.record(schemaName).namespace(namespace).fields(); // // for (int columnIndex = 1; columnIndex <= metaData.getColumnCount(); columnIndex++) { // SchemaBuilder.FieldBuilder<Schema> fieldBuilder = // schemaAssembler.name(metaData.getColumnName(columnIndex)); // AvroHelper.convertColumnTypeToAvroType(fieldBuilder, metaData, columnIndex); // } // return schemaAssembler.endRecord(); // } // // Path: src/java/com/google/cloud/bigquery/dwhassessment/extractiontool/db/AvroHelper.java // public static GenericRecord parseRowToAvro(ResultSet row, Schema schema) throws SQLException { // GenericRecordBuilder recordBuilder = new GenericRecordBuilder(schema); // ResultSetMetaData metaData = row.getMetaData(); // for (int columnIndex = 1; columnIndex <= row.getMetaData().getColumnCount(); columnIndex++) { // recordBuilder.set( // metaData.getColumnName(columnIndex), getRowObject(metaData, row, columnIndex)); // } // return recordBuilder.build(); // }
import static com.google.cloud.bigquery.dwhassessment.extractiontool.db.AvroHelper.dumpResults; import static com.google.cloud.bigquery.dwhassessment.extractiontool.db.AvroHelper.getAvroSchema; import static com.google.cloud.bigquery.dwhassessment.extractiontool.db.AvroHelper.parseRowToAvro; import static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.assertThrows; import com.google.common.collect.ImmutableList; import java.io.ByteArrayOutputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.Statement; import org.apache.avro.Schema; import org.apache.avro.file.DataFileReader; import org.apache.avro.file.SeekableByteArrayInput; import org.apache.avro.generic.GenericData.Record; import org.apache.avro.generic.GenericDatumReader; import org.apache.avro.generic.GenericRecord; import org.apache.avro.generic.GenericRecordBuilder; import org.apache.avro.io.DatumReader; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4;
"CREATE TABLE SIMPLE_TABLE (ID INTEGER, NAME VARCHAR(100), CHAR_COL CHAR(20))"); baseStmt.execute("INSERT INTO SIMPLE_TABLE VALUES (0, 'name_0', ' two words')"); baseStmt.close(); connection.commit(); metaData = connection.createStatement().executeQuery("SELECT * FROM T0").getMetaData(); } @Test public void getAvroSchemaTest() throws Exception { Schema schema = getAvroSchema("schemaName", "namespace", metaData); assertThat(schema).isEqualTo(new Schema.Parser().parse(TEST_SCHEMA)); } @Test public void getAvroSchema_emptySchemaName() throws Exception { assertThrows(IllegalArgumentException.class, () -> getAvroSchema("", "namespace", metaData)); } @Test public void getAvroSchema_emptyNamespace() throws Exception { assertThrows(IllegalArgumentException.class, () -> getAvroSchema("schemaName", "", metaData)); } @Test public void parseRowToAvroTest() throws Exception { Schema testSchema = new Schema.Parser().parse(SIMPLE_TEST_SCHEMA); ResultSet resultSet = connection.createStatement().executeQuery("SELECT * FROM SIMPLE_TABLE"); while (resultSet.next()) {
// Path: src/java/com/google/cloud/bigquery/dwhassessment/extractiontool/db/AvroHelper.java // public static void dumpResults( // ImmutableList<GenericRecord> records, OutputStream outputStream, Schema schema) // throws IOException { // GenericDatumWriter<GenericRecord> writer = new GenericDatumWriter<>(schema); // DataFileWriter<GenericRecord> dataFileWriter = new DataFileWriter<>(writer); // dataFileWriter.create(schema, outputStream); // // records.stream() // .forEach( // record -> { // try { // dataFileWriter.append(record); // } catch (IOException e) { // throw new IllegalStateException( // String.format( // "Failed to encode query result %s to file with error message: %s", // record.toString(), e.getMessage())); // } // }); // dataFileWriter.close(); // outputStream.close(); // } // // Path: src/java/com/google/cloud/bigquery/dwhassessment/extractiontool/db/AvroHelper.java // public static Schema getAvroSchema( // String schemaName, String namespace, ResultSetMetaData metaData) throws SQLException { // Preconditions.checkArgument(!schemaName.isEmpty(), "Schema name cannot be empty."); // Preconditions.checkArgument(!namespace.isEmpty(), "Namespace cannot be empty."); // SchemaBuilder.FieldAssembler<Schema> schemaAssembler = // SchemaBuilder.record(schemaName).namespace(namespace).fields(); // // for (int columnIndex = 1; columnIndex <= metaData.getColumnCount(); columnIndex++) { // SchemaBuilder.FieldBuilder<Schema> fieldBuilder = // schemaAssembler.name(metaData.getColumnName(columnIndex)); // AvroHelper.convertColumnTypeToAvroType(fieldBuilder, metaData, columnIndex); // } // return schemaAssembler.endRecord(); // } // // Path: src/java/com/google/cloud/bigquery/dwhassessment/extractiontool/db/AvroHelper.java // public static GenericRecord parseRowToAvro(ResultSet row, Schema schema) throws SQLException { // GenericRecordBuilder recordBuilder = new GenericRecordBuilder(schema); // ResultSetMetaData metaData = row.getMetaData(); // for (int columnIndex = 1; columnIndex <= row.getMetaData().getColumnCount(); columnIndex++) { // recordBuilder.set( // metaData.getColumnName(columnIndex), getRowObject(metaData, row, columnIndex)); // } // return recordBuilder.build(); // } // Path: src/javatests/com/google/cloud/bigquery/dwhassessment/extractiontool/db/AvroHelperTest.java import static com.google.cloud.bigquery.dwhassessment.extractiontool.db.AvroHelper.dumpResults; import static com.google.cloud.bigquery.dwhassessment.extractiontool.db.AvroHelper.getAvroSchema; import static com.google.cloud.bigquery.dwhassessment.extractiontool.db.AvroHelper.parseRowToAvro; import static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.assertThrows; import com.google.common.collect.ImmutableList; import java.io.ByteArrayOutputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.Statement; import org.apache.avro.Schema; import org.apache.avro.file.DataFileReader; import org.apache.avro.file.SeekableByteArrayInput; import org.apache.avro.generic.GenericData.Record; import org.apache.avro.generic.GenericDatumReader; import org.apache.avro.generic.GenericRecord; import org.apache.avro.generic.GenericRecordBuilder; import org.apache.avro.io.DatumReader; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; "CREATE TABLE SIMPLE_TABLE (ID INTEGER, NAME VARCHAR(100), CHAR_COL CHAR(20))"); baseStmt.execute("INSERT INTO SIMPLE_TABLE VALUES (0, 'name_0', ' two words')"); baseStmt.close(); connection.commit(); metaData = connection.createStatement().executeQuery("SELECT * FROM T0").getMetaData(); } @Test public void getAvroSchemaTest() throws Exception { Schema schema = getAvroSchema("schemaName", "namespace", metaData); assertThat(schema).isEqualTo(new Schema.Parser().parse(TEST_SCHEMA)); } @Test public void getAvroSchema_emptySchemaName() throws Exception { assertThrows(IllegalArgumentException.class, () -> getAvroSchema("", "namespace", metaData)); } @Test public void getAvroSchema_emptyNamespace() throws Exception { assertThrows(IllegalArgumentException.class, () -> getAvroSchema("schemaName", "", metaData)); } @Test public void parseRowToAvroTest() throws Exception { Schema testSchema = new Schema.Parser().parse(SIMPLE_TEST_SCHEMA); ResultSet resultSet = connection.createStatement().executeQuery("SELECT * FROM SIMPLE_TABLE"); while (resultSet.next()) {
GenericRecord result = parseRowToAvro(resultSet, testSchema);
google/dwh-assessment-extraction-tool
src/javatests/com/google/cloud/bigquery/dwhassessment/extractiontool/db/AvroHelperTest.java
// Path: src/java/com/google/cloud/bigquery/dwhassessment/extractiontool/db/AvroHelper.java // public static void dumpResults( // ImmutableList<GenericRecord> records, OutputStream outputStream, Schema schema) // throws IOException { // GenericDatumWriter<GenericRecord> writer = new GenericDatumWriter<>(schema); // DataFileWriter<GenericRecord> dataFileWriter = new DataFileWriter<>(writer); // dataFileWriter.create(schema, outputStream); // // records.stream() // .forEach( // record -> { // try { // dataFileWriter.append(record); // } catch (IOException e) { // throw new IllegalStateException( // String.format( // "Failed to encode query result %s to file with error message: %s", // record.toString(), e.getMessage())); // } // }); // dataFileWriter.close(); // outputStream.close(); // } // // Path: src/java/com/google/cloud/bigquery/dwhassessment/extractiontool/db/AvroHelper.java // public static Schema getAvroSchema( // String schemaName, String namespace, ResultSetMetaData metaData) throws SQLException { // Preconditions.checkArgument(!schemaName.isEmpty(), "Schema name cannot be empty."); // Preconditions.checkArgument(!namespace.isEmpty(), "Namespace cannot be empty."); // SchemaBuilder.FieldAssembler<Schema> schemaAssembler = // SchemaBuilder.record(schemaName).namespace(namespace).fields(); // // for (int columnIndex = 1; columnIndex <= metaData.getColumnCount(); columnIndex++) { // SchemaBuilder.FieldBuilder<Schema> fieldBuilder = // schemaAssembler.name(metaData.getColumnName(columnIndex)); // AvroHelper.convertColumnTypeToAvroType(fieldBuilder, metaData, columnIndex); // } // return schemaAssembler.endRecord(); // } // // Path: src/java/com/google/cloud/bigquery/dwhassessment/extractiontool/db/AvroHelper.java // public static GenericRecord parseRowToAvro(ResultSet row, Schema schema) throws SQLException { // GenericRecordBuilder recordBuilder = new GenericRecordBuilder(schema); // ResultSetMetaData metaData = row.getMetaData(); // for (int columnIndex = 1; columnIndex <= row.getMetaData().getColumnCount(); columnIndex++) { // recordBuilder.set( // metaData.getColumnName(columnIndex), getRowObject(metaData, row, columnIndex)); // } // return recordBuilder.build(); // }
import static com.google.cloud.bigquery.dwhassessment.extractiontool.db.AvroHelper.dumpResults; import static com.google.cloud.bigquery.dwhassessment.extractiontool.db.AvroHelper.getAvroSchema; import static com.google.cloud.bigquery.dwhassessment.extractiontool.db.AvroHelper.parseRowToAvro; import static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.assertThrows; import com.google.common.collect.ImmutableList; import java.io.ByteArrayOutputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.Statement; import org.apache.avro.Schema; import org.apache.avro.file.DataFileReader; import org.apache.avro.file.SeekableByteArrayInput; import org.apache.avro.generic.GenericData.Record; import org.apache.avro.generic.GenericDatumReader; import org.apache.avro.generic.GenericRecord; import org.apache.avro.generic.GenericRecordBuilder; import org.apache.avro.io.DatumReader; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4;
} @Test public void parseRowToAvroTest() throws Exception { Schema testSchema = new Schema.Parser().parse(SIMPLE_TEST_SCHEMA); ResultSet resultSet = connection.createStatement().executeQuery("SELECT * FROM SIMPLE_TABLE"); while (resultSet.next()) { GenericRecord result = parseRowToAvro(resultSet, testSchema); assertThat(result) .isEqualTo( new GenericRecordBuilder(testSchema) .set("ID", 0) .set("NAME", "name_0") .set("CHAR_COL", " two words") .build()); } } @Test public void dumpResultsTest() throws Exception { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ScriptRunner scriptRunner = new ScriptRunnerImpl(); ResultSetMetaData simpleTestMetadata = connection.createStatement().executeQuery("SELECT * FROM SIMPLE_TABLE").getMetaData(); Schema schema = getAvroSchema("schemaName", "namespace", simpleTestMetadata); ImmutableList.Builder<GenericRecord> records = ImmutableList.builder(); scriptRunner.executeScriptToAvro( connection, "SELECT * FROM SIMPLE_TABLE", schema, records::add);
// Path: src/java/com/google/cloud/bigquery/dwhassessment/extractiontool/db/AvroHelper.java // public static void dumpResults( // ImmutableList<GenericRecord> records, OutputStream outputStream, Schema schema) // throws IOException { // GenericDatumWriter<GenericRecord> writer = new GenericDatumWriter<>(schema); // DataFileWriter<GenericRecord> dataFileWriter = new DataFileWriter<>(writer); // dataFileWriter.create(schema, outputStream); // // records.stream() // .forEach( // record -> { // try { // dataFileWriter.append(record); // } catch (IOException e) { // throw new IllegalStateException( // String.format( // "Failed to encode query result %s to file with error message: %s", // record.toString(), e.getMessage())); // } // }); // dataFileWriter.close(); // outputStream.close(); // } // // Path: src/java/com/google/cloud/bigquery/dwhassessment/extractiontool/db/AvroHelper.java // public static Schema getAvroSchema( // String schemaName, String namespace, ResultSetMetaData metaData) throws SQLException { // Preconditions.checkArgument(!schemaName.isEmpty(), "Schema name cannot be empty."); // Preconditions.checkArgument(!namespace.isEmpty(), "Namespace cannot be empty."); // SchemaBuilder.FieldAssembler<Schema> schemaAssembler = // SchemaBuilder.record(schemaName).namespace(namespace).fields(); // // for (int columnIndex = 1; columnIndex <= metaData.getColumnCount(); columnIndex++) { // SchemaBuilder.FieldBuilder<Schema> fieldBuilder = // schemaAssembler.name(metaData.getColumnName(columnIndex)); // AvroHelper.convertColumnTypeToAvroType(fieldBuilder, metaData, columnIndex); // } // return schemaAssembler.endRecord(); // } // // Path: src/java/com/google/cloud/bigquery/dwhassessment/extractiontool/db/AvroHelper.java // public static GenericRecord parseRowToAvro(ResultSet row, Schema schema) throws SQLException { // GenericRecordBuilder recordBuilder = new GenericRecordBuilder(schema); // ResultSetMetaData metaData = row.getMetaData(); // for (int columnIndex = 1; columnIndex <= row.getMetaData().getColumnCount(); columnIndex++) { // recordBuilder.set( // metaData.getColumnName(columnIndex), getRowObject(metaData, row, columnIndex)); // } // return recordBuilder.build(); // } // Path: src/javatests/com/google/cloud/bigquery/dwhassessment/extractiontool/db/AvroHelperTest.java import static com.google.cloud.bigquery.dwhassessment.extractiontool.db.AvroHelper.dumpResults; import static com.google.cloud.bigquery.dwhassessment.extractiontool.db.AvroHelper.getAvroSchema; import static com.google.cloud.bigquery.dwhassessment.extractiontool.db.AvroHelper.parseRowToAvro; import static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.assertThrows; import com.google.common.collect.ImmutableList; import java.io.ByteArrayOutputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.Statement; import org.apache.avro.Schema; import org.apache.avro.file.DataFileReader; import org.apache.avro.file.SeekableByteArrayInput; import org.apache.avro.generic.GenericData.Record; import org.apache.avro.generic.GenericDatumReader; import org.apache.avro.generic.GenericRecord; import org.apache.avro.generic.GenericRecordBuilder; import org.apache.avro.io.DatumReader; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; } @Test public void parseRowToAvroTest() throws Exception { Schema testSchema = new Schema.Parser().parse(SIMPLE_TEST_SCHEMA); ResultSet resultSet = connection.createStatement().executeQuery("SELECT * FROM SIMPLE_TABLE"); while (resultSet.next()) { GenericRecord result = parseRowToAvro(resultSet, testSchema); assertThat(result) .isEqualTo( new GenericRecordBuilder(testSchema) .set("ID", 0) .set("NAME", "name_0") .set("CHAR_COL", " two words") .build()); } } @Test public void dumpResultsTest() throws Exception { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ScriptRunner scriptRunner = new ScriptRunnerImpl(); ResultSetMetaData simpleTestMetadata = connection.createStatement().executeQuery("SELECT * FROM SIMPLE_TABLE").getMetaData(); Schema schema = getAvroSchema("schemaName", "namespace", simpleTestMetadata); ImmutableList.Builder<GenericRecord> records = ImmutableList.builder(); scriptRunner.executeScriptToAvro( connection, "SELECT * FROM SIMPLE_TABLE", schema, records::add);
dumpResults(records.build(), outputStream, schema);
google/dwh-assessment-extraction-tool
src/java/com/google/cloud/bigquery/dwhassessment/extractiontool/db/ScriptManagerImpl.java
// Path: src/java/com/google/cloud/bigquery/dwhassessment/extractiontool/db/AvroHelper.java // public static GenericRecord parseRowToAvro(ResultSet row, Schema schema) throws SQLException { // GenericRecordBuilder recordBuilder = new GenericRecordBuilder(schema); // ResultSetMetaData metaData = row.getMetaData(); // for (int columnIndex = 1; columnIndex <= row.getMetaData().getColumnCount(); columnIndex++) { // recordBuilder.set( // metaData.getColumnName(columnIndex), getRowObject(metaData, row, columnIndex)); // } // return recordBuilder.build(); // } // // Path: src/java/com/google/cloud/bigquery/dwhassessment/extractiontool/dumper/DataEntityManager.java // public interface DataEntityManager extends Closeable { // // /** // * Get the output stream for an entity. // * // * @param name The name of the output entity. // */ // OutputStream getEntityOutputStream(String name) throws IOException; // // /** // * Indicate whether the data entity allows resumable processing. // * // * @return true if some progress can be retained after the writing is interrupted. // */ // boolean isResumable(); // // /** // * Get the absolute path of a file given its name. // * // * @param name The name of the file. // */ // Path getAbsolutePath(String name); // }
import static com.google.cloud.bigquery.dwhassessment.extractiontool.db.AvroHelper.parseRowToAvro; import static java.nio.file.StandardCopyOption.ATOMIC_MOVE; import com.google.cloud.bigquery.dwhassessment.extractiontool.dumper.DataEntityManager; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import java.io.IOException; import java.nio.file.Files; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Timestamp; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.Locale; import java.util.function.Supplier; import java.util.logging.Logger; import org.apache.avro.Schema; import org.apache.avro.generic.GenericRecord;
/* * Copyright 2021 Google LLC * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.bigquery.dwhassessment.extractiontool.db; /** * Implementation of script manager. Manages mapping from script name to SQL script. Executes script * and writes results to an output stream. */ public class ScriptManagerImpl implements ScriptManager { private static final Logger LOGGER = Logger.getLogger(ScriptManagerImpl.class.getName()); private final ImmutableMap<String, Supplier<String>> scriptsMap; private final ImmutableMap<String, ImmutableList<String>> sortingColumnsMap; private final ScriptRunner scriptRunner; public ScriptManagerImpl( ScriptRunner scriptRunner, ImmutableMap<String, Supplier<String>> scriptsMap, ImmutableMap<String, ImmutableList<String>> sortingColumnsMap) { this.scriptRunner = scriptRunner; this.scriptsMap = scriptsMap; this.sortingColumnsMap = sortingColumnsMap; } @Override public void executeScript( Connection connection, boolean dryRun, SqlTemplateRenderer sqlTemplateRenderer, String scriptName,
// Path: src/java/com/google/cloud/bigquery/dwhassessment/extractiontool/db/AvroHelper.java // public static GenericRecord parseRowToAvro(ResultSet row, Schema schema) throws SQLException { // GenericRecordBuilder recordBuilder = new GenericRecordBuilder(schema); // ResultSetMetaData metaData = row.getMetaData(); // for (int columnIndex = 1; columnIndex <= row.getMetaData().getColumnCount(); columnIndex++) { // recordBuilder.set( // metaData.getColumnName(columnIndex), getRowObject(metaData, row, columnIndex)); // } // return recordBuilder.build(); // } // // Path: src/java/com/google/cloud/bigquery/dwhassessment/extractiontool/dumper/DataEntityManager.java // public interface DataEntityManager extends Closeable { // // /** // * Get the output stream for an entity. // * // * @param name The name of the output entity. // */ // OutputStream getEntityOutputStream(String name) throws IOException; // // /** // * Indicate whether the data entity allows resumable processing. // * // * @return true if some progress can be retained after the writing is interrupted. // */ // boolean isResumable(); // // /** // * Get the absolute path of a file given its name. // * // * @param name The name of the file. // */ // Path getAbsolutePath(String name); // } // Path: src/java/com/google/cloud/bigquery/dwhassessment/extractiontool/db/ScriptManagerImpl.java import static com.google.cloud.bigquery.dwhassessment.extractiontool.db.AvroHelper.parseRowToAvro; import static java.nio.file.StandardCopyOption.ATOMIC_MOVE; import com.google.cloud.bigquery.dwhassessment.extractiontool.dumper.DataEntityManager; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import java.io.IOException; import java.nio.file.Files; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Timestamp; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.Locale; import java.util.function.Supplier; import java.util.logging.Logger; import org.apache.avro.Schema; import org.apache.avro.generic.GenericRecord; /* * Copyright 2021 Google LLC * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.bigquery.dwhassessment.extractiontool.db; /** * Implementation of script manager. Manages mapping from script name to SQL script. Executes script * and writes results to an output stream. */ public class ScriptManagerImpl implements ScriptManager { private static final Logger LOGGER = Logger.getLogger(ScriptManagerImpl.class.getName()); private final ImmutableMap<String, Supplier<String>> scriptsMap; private final ImmutableMap<String, ImmutableList<String>> sortingColumnsMap; private final ScriptRunner scriptRunner; public ScriptManagerImpl( ScriptRunner scriptRunner, ImmutableMap<String, Supplier<String>> scriptsMap, ImmutableMap<String, ImmutableList<String>> sortingColumnsMap) { this.scriptRunner = scriptRunner; this.scriptsMap = scriptsMap; this.sortingColumnsMap = sortingColumnsMap; } @Override public void executeScript( Connection connection, boolean dryRun, SqlTemplateRenderer sqlTemplateRenderer, String scriptName,
DataEntityManager dataEntityManager,
google/dwh-assessment-extraction-tool
src/java/com/google/cloud/bigquery/dwhassessment/extractiontool/db/ScriptManagerImpl.java
// Path: src/java/com/google/cloud/bigquery/dwhassessment/extractiontool/db/AvroHelper.java // public static GenericRecord parseRowToAvro(ResultSet row, Schema schema) throws SQLException { // GenericRecordBuilder recordBuilder = new GenericRecordBuilder(schema); // ResultSetMetaData metaData = row.getMetaData(); // for (int columnIndex = 1; columnIndex <= row.getMetaData().getColumnCount(); columnIndex++) { // recordBuilder.set( // metaData.getColumnName(columnIndex), getRowObject(metaData, row, columnIndex)); // } // return recordBuilder.build(); // } // // Path: src/java/com/google/cloud/bigquery/dwhassessment/extractiontool/dumper/DataEntityManager.java // public interface DataEntityManager extends Closeable { // // /** // * Get the output stream for an entity. // * // * @param name The name of the output entity. // */ // OutputStream getEntityOutputStream(String name) throws IOException; // // /** // * Indicate whether the data entity allows resumable processing. // * // * @return true if some progress can be retained after the writing is interrupted. // */ // boolean isResumable(); // // /** // * Get the absolute path of a file given its name. // * // * @param name The name of the file. // */ // Path getAbsolutePath(String name); // }
import static com.google.cloud.bigquery.dwhassessment.extractiontool.db.AvroHelper.parseRowToAvro; import static java.nio.file.StandardCopyOption.ATOMIC_MOVE; import com.google.cloud.bigquery.dwhassessment.extractiontool.dumper.DataEntityManager; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import java.io.IOException; import java.nio.file.Files; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Timestamp; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.Locale; import java.util.function.Supplier; import java.util.logging.Logger; import org.apache.avro.Schema; import org.apache.avro.generic.GenericRecord;
while (!resultSet.isAfterLast()) { executeScriptChunk( resultSet, schema, dataEntityManager, chunkRows, labelColumn, scriptName, chunkNumber); chunkNumber++; } return; } executeScriptOneSwoop(connection, scriptName, script, schema, dataEntityManager); } private void executeScriptChunk( ResultSet resultSet, Schema schema, DataEntityManager dataEntityManager, Integer chunkRows, String labelColumn, String scriptName, Integer chunkNumber) throws SQLException, IOException { Timestamp previousTimestamp = new Timestamp(0); Timestamp currentTimestamp = resultSet.getTimestamp(labelColumn); String firstRowStamp = getUtcTimeStringFromTimestamp(currentTimestamp); String tempFileName = String.format("%s-%s_%d_temp.avro", scriptName, firstRowStamp, chunkNumber); try (ResultSetRecorder<GenericRecord> dumper = AvroResultSetRecorder.create( schema, dataEntityManager.getEntityOutputStream(tempFileName))) { int rowCount = 0; while (rowCount < chunkRows || currentTimestamp.equals(previousTimestamp)) { // Process first, then advance the row.
// Path: src/java/com/google/cloud/bigquery/dwhassessment/extractiontool/db/AvroHelper.java // public static GenericRecord parseRowToAvro(ResultSet row, Schema schema) throws SQLException { // GenericRecordBuilder recordBuilder = new GenericRecordBuilder(schema); // ResultSetMetaData metaData = row.getMetaData(); // for (int columnIndex = 1; columnIndex <= row.getMetaData().getColumnCount(); columnIndex++) { // recordBuilder.set( // metaData.getColumnName(columnIndex), getRowObject(metaData, row, columnIndex)); // } // return recordBuilder.build(); // } // // Path: src/java/com/google/cloud/bigquery/dwhassessment/extractiontool/dumper/DataEntityManager.java // public interface DataEntityManager extends Closeable { // // /** // * Get the output stream for an entity. // * // * @param name The name of the output entity. // */ // OutputStream getEntityOutputStream(String name) throws IOException; // // /** // * Indicate whether the data entity allows resumable processing. // * // * @return true if some progress can be retained after the writing is interrupted. // */ // boolean isResumable(); // // /** // * Get the absolute path of a file given its name. // * // * @param name The name of the file. // */ // Path getAbsolutePath(String name); // } // Path: src/java/com/google/cloud/bigquery/dwhassessment/extractiontool/db/ScriptManagerImpl.java import static com.google.cloud.bigquery.dwhassessment.extractiontool.db.AvroHelper.parseRowToAvro; import static java.nio.file.StandardCopyOption.ATOMIC_MOVE; import com.google.cloud.bigquery.dwhassessment.extractiontool.dumper.DataEntityManager; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import java.io.IOException; import java.nio.file.Files; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Timestamp; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.Locale; import java.util.function.Supplier; import java.util.logging.Logger; import org.apache.avro.Schema; import org.apache.avro.generic.GenericRecord; while (!resultSet.isAfterLast()) { executeScriptChunk( resultSet, schema, dataEntityManager, chunkRows, labelColumn, scriptName, chunkNumber); chunkNumber++; } return; } executeScriptOneSwoop(connection, scriptName, script, schema, dataEntityManager); } private void executeScriptChunk( ResultSet resultSet, Schema schema, DataEntityManager dataEntityManager, Integer chunkRows, String labelColumn, String scriptName, Integer chunkNumber) throws SQLException, IOException { Timestamp previousTimestamp = new Timestamp(0); Timestamp currentTimestamp = resultSet.getTimestamp(labelColumn); String firstRowStamp = getUtcTimeStringFromTimestamp(currentTimestamp); String tempFileName = String.format("%s-%s_%d_temp.avro", scriptName, firstRowStamp, chunkNumber); try (ResultSetRecorder<GenericRecord> dumper = AvroResultSetRecorder.create( schema, dataEntityManager.getEntityOutputStream(tempFileName))) { int rowCount = 0; while (rowCount < chunkRows || currentTimestamp.equals(previousTimestamp)) { // Process first, then advance the row.
dumper.add(parseRowToAvro(resultSet, schema));
google/dwh-assessment-extraction-tool
src/javatests/com/google/cloud/bigquery/dwhassessment/extractiontool/db/SqlTemplateRendererTest.java
// Path: src/java/com/google/cloud/bigquery/dwhassessment/extractiontool/db/SqlScriptVariables.java // @AutoValue // public abstract class SqlScriptVariables { // // public static Builder builder() { // return new AutoValue_SqlScriptVariables.Builder() // .setBaseDatabase("DBC") // .setVars(ImmutableMap.of()) // .setSortingColumns(ImmutableList.of()); // } // // public abstract String getBaseDatabase(); // // public abstract List<String> getSortingColumns(); // // public abstract QueryLogsVariables getQueryLogsVariables(); // // public abstract Map<String, String> getVars(); // // @AutoValue // public abstract static class QueryLogsVariables { // // public static Builder builder() { // return new AutoValue_SqlScriptVariables_QueryLogsVariables.Builder(); // } // // public abstract Optional<TimeRange> timeRange(); // // // Value accessor for handlebars. // public TimeRange getTimeRange() { // if (timeRange().isPresent()) { // return timeRange().get(); // } // return null; // } // // @AutoValue // public abstract static class TimeRange { // private static final String minTime = "0001-01-01 00:00:00+00:00"; // private static final String maxTime = "9999-12-31 23:59:59.99+00:00"; // // public static Builder builder() { // return new AutoValue_SqlScriptVariables_QueryLogsVariables_TimeRange.Builder() // .setStartTimestamp(minTime) // .setEndTimestamp(maxTime); // } // // public abstract String getStartTimestamp(); // // public abstract String getEndTimestamp(); // // @AutoValue.Builder // public abstract static class Builder { // public abstract Builder setStartTimestamp(String timestamp); // // public abstract Builder setEndTimestamp(String timestamp); // // public abstract TimeRange build(); // } // } // // @AutoValue.Builder // public abstract static class Builder { // public abstract Builder setTimeRange(TimeRange value); // // public abstract QueryLogsVariables build(); // } // } // // @AutoValue.Builder // public abstract static class Builder { // // public abstract Builder setBaseDatabase(String value); // // public abstract Builder setSortingColumns(List<String> value); // // public abstract Builder setQueryLogsVariables(QueryLogsVariables value); // // public abstract Builder setVars(Map<String, String> variables); // // public abstract SqlScriptVariables build(); // } // }
import static com.google.cloud.bigquery.dwhassessment.extractiontool.db.SqlScriptVariables.*; import static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.assertThrows; import com.google.common.collect.ImmutableList; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4;
/* * Copyright 2021 Google LLC * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.bigquery.dwhassessment.extractiontool.db; @RunWith(JUnit4.class) public class SqlTemplateRendererTest { private SqlTemplateRenderer underTest;
// Path: src/java/com/google/cloud/bigquery/dwhassessment/extractiontool/db/SqlScriptVariables.java // @AutoValue // public abstract class SqlScriptVariables { // // public static Builder builder() { // return new AutoValue_SqlScriptVariables.Builder() // .setBaseDatabase("DBC") // .setVars(ImmutableMap.of()) // .setSortingColumns(ImmutableList.of()); // } // // public abstract String getBaseDatabase(); // // public abstract List<String> getSortingColumns(); // // public abstract QueryLogsVariables getQueryLogsVariables(); // // public abstract Map<String, String> getVars(); // // @AutoValue // public abstract static class QueryLogsVariables { // // public static Builder builder() { // return new AutoValue_SqlScriptVariables_QueryLogsVariables.Builder(); // } // // public abstract Optional<TimeRange> timeRange(); // // // Value accessor for handlebars. // public TimeRange getTimeRange() { // if (timeRange().isPresent()) { // return timeRange().get(); // } // return null; // } // // @AutoValue // public abstract static class TimeRange { // private static final String minTime = "0001-01-01 00:00:00+00:00"; // private static final String maxTime = "9999-12-31 23:59:59.99+00:00"; // // public static Builder builder() { // return new AutoValue_SqlScriptVariables_QueryLogsVariables_TimeRange.Builder() // .setStartTimestamp(minTime) // .setEndTimestamp(maxTime); // } // // public abstract String getStartTimestamp(); // // public abstract String getEndTimestamp(); // // @AutoValue.Builder // public abstract static class Builder { // public abstract Builder setStartTimestamp(String timestamp); // // public abstract Builder setEndTimestamp(String timestamp); // // public abstract TimeRange build(); // } // } // // @AutoValue.Builder // public abstract static class Builder { // public abstract Builder setTimeRange(TimeRange value); // // public abstract QueryLogsVariables build(); // } // } // // @AutoValue.Builder // public abstract static class Builder { // // public abstract Builder setBaseDatabase(String value); // // public abstract Builder setSortingColumns(List<String> value); // // public abstract Builder setQueryLogsVariables(QueryLogsVariables value); // // public abstract Builder setVars(Map<String, String> variables); // // public abstract SqlScriptVariables build(); // } // } // Path: src/javatests/com/google/cloud/bigquery/dwhassessment/extractiontool/db/SqlTemplateRendererTest.java import static com.google.cloud.bigquery.dwhassessment.extractiontool.db.SqlScriptVariables.*; import static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.assertThrows; import com.google.common.collect.ImmutableList; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /* * Copyright 2021 Google LLC * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.bigquery.dwhassessment.extractiontool.db; @RunWith(JUnit4.class) public class SqlTemplateRendererTest { private SqlTemplateRenderer underTest;
private SqlScriptVariables.Builder baseVariablesBuilder;
google/dwh-assessment-extraction-tool
src/javatests/com/google/cloud/bigquery/dwhassessment/extractiontool/db/SchemaManagerImplTest.java
// Path: src/java/com/google/cloud/bigquery/dwhassessment/extractiontool/db/AvroHelper.java // public static Schema getAvroSchema( // String schemaName, String namespace, ResultSetMetaData metaData) throws SQLException { // Preconditions.checkArgument(!schemaName.isEmpty(), "Schema name cannot be empty."); // Preconditions.checkArgument(!namespace.isEmpty(), "Namespace cannot be empty."); // SchemaBuilder.FieldAssembler<Schema> schemaAssembler = // SchemaBuilder.record(schemaName).namespace(namespace).fields(); // // for (int columnIndex = 1; columnIndex <= metaData.getColumnCount(); columnIndex++) { // SchemaBuilder.FieldBuilder<Schema> fieldBuilder = // schemaAssembler.name(metaData.getColumnName(columnIndex)); // AvroHelper.convertColumnTypeToAvroType(fieldBuilder, metaData, columnIndex); // } // return schemaAssembler.endRecord(); // } // // Path: src/java/com/google/cloud/bigquery/dwhassessment/extractiontool/db/SchemaManager.java // @AutoValue // abstract class SchemaKey { // public static SchemaKey create(String databaseName, String tableName) { // return new AutoValue_SchemaManager_SchemaKey(databaseName, tableName); // } // // public abstract String databaseName(); // // public abstract String tableName(); // }
import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import static com.google.cloud.bigquery.dwhassessment.extractiontool.db.AvroHelper.getAvroSchema; import static com.google.common.truth.Truth.assertThat; import com.google.cloud.bigquery.dwhassessment.extractiontool.db.SchemaManager.SchemaKey; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.re2j.Pattern; import java.io.ByteArrayOutputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.Statement; import org.apache.avro.Schema; import org.apache.avro.generic.GenericRecord; import org.apache.avro.generic.GenericRecordBuilder; import org.junit.BeforeClass;
/* * Copyright 2021 Google LLC * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.bigquery.dwhassessment.extractiontool.db; @RunWith(JUnit4.class) public final class SchemaManagerImplTest { private static SchemaManager schemaManager; private static Connection connection; @BeforeClass public static void setUp() throws Exception { schemaManager = new SchemaManagerImpl(); connection = DriverManager.getConnection("jdbc:hsqldb:mem:db_0"); Statement baseStmt = connection.createStatement(); baseStmt.execute("CREATE TABLE FOO (ID VARCHAR(1), NAME VARCHAR(100))"); baseStmt.execute("CREATE TABLE FOOBAR (ID INTEGER, NAME VARCHAR(100))"); baseStmt.execute("CREATE TABLE BAR (ID INTEGER, NAME VARCHAR(100))"); baseStmt.close(); connection.commit(); } @Test public void getSchemaKeys_onlyTableFilter_success() {
// Path: src/java/com/google/cloud/bigquery/dwhassessment/extractiontool/db/AvroHelper.java // public static Schema getAvroSchema( // String schemaName, String namespace, ResultSetMetaData metaData) throws SQLException { // Preconditions.checkArgument(!schemaName.isEmpty(), "Schema name cannot be empty."); // Preconditions.checkArgument(!namespace.isEmpty(), "Namespace cannot be empty."); // SchemaBuilder.FieldAssembler<Schema> schemaAssembler = // SchemaBuilder.record(schemaName).namespace(namespace).fields(); // // for (int columnIndex = 1; columnIndex <= metaData.getColumnCount(); columnIndex++) { // SchemaBuilder.FieldBuilder<Schema> fieldBuilder = // schemaAssembler.name(metaData.getColumnName(columnIndex)); // AvroHelper.convertColumnTypeToAvroType(fieldBuilder, metaData, columnIndex); // } // return schemaAssembler.endRecord(); // } // // Path: src/java/com/google/cloud/bigquery/dwhassessment/extractiontool/db/SchemaManager.java // @AutoValue // abstract class SchemaKey { // public static SchemaKey create(String databaseName, String tableName) { // return new AutoValue_SchemaManager_SchemaKey(databaseName, tableName); // } // // public abstract String databaseName(); // // public abstract String tableName(); // } // Path: src/javatests/com/google/cloud/bigquery/dwhassessment/extractiontool/db/SchemaManagerImplTest.java import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import static com.google.cloud.bigquery.dwhassessment.extractiontool.db.AvroHelper.getAvroSchema; import static com.google.common.truth.Truth.assertThat; import com.google.cloud.bigquery.dwhassessment.extractiontool.db.SchemaManager.SchemaKey; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.re2j.Pattern; import java.io.ByteArrayOutputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.Statement; import org.apache.avro.Schema; import org.apache.avro.generic.GenericRecord; import org.apache.avro.generic.GenericRecordBuilder; import org.junit.BeforeClass; /* * Copyright 2021 Google LLC * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.bigquery.dwhassessment.extractiontool.db; @RunWith(JUnit4.class) public final class SchemaManagerImplTest { private static SchemaManager schemaManager; private static Connection connection; @BeforeClass public static void setUp() throws Exception { schemaManager = new SchemaManagerImpl(); connection = DriverManager.getConnection("jdbc:hsqldb:mem:db_0"); Statement baseStmt = connection.createStatement(); baseStmt.execute("CREATE TABLE FOO (ID VARCHAR(1), NAME VARCHAR(100))"); baseStmt.execute("CREATE TABLE FOOBAR (ID INTEGER, NAME VARCHAR(100))"); baseStmt.execute("CREATE TABLE BAR (ID INTEGER, NAME VARCHAR(100))"); baseStmt.close(); connection.commit(); } @Test public void getSchemaKeys_onlyTableFilter_success() {
ImmutableSet<SchemaKey> results = schemaManager.getSchemaKeys(connection, ImmutableList.of());
google/dwh-assessment-extraction-tool
src/javatests/com/google/cloud/bigquery/dwhassessment/extractiontool/db/SchemaManagerImplTest.java
// Path: src/java/com/google/cloud/bigquery/dwhassessment/extractiontool/db/AvroHelper.java // public static Schema getAvroSchema( // String schemaName, String namespace, ResultSetMetaData metaData) throws SQLException { // Preconditions.checkArgument(!schemaName.isEmpty(), "Schema name cannot be empty."); // Preconditions.checkArgument(!namespace.isEmpty(), "Namespace cannot be empty."); // SchemaBuilder.FieldAssembler<Schema> schemaAssembler = // SchemaBuilder.record(schemaName).namespace(namespace).fields(); // // for (int columnIndex = 1; columnIndex <= metaData.getColumnCount(); columnIndex++) { // SchemaBuilder.FieldBuilder<Schema> fieldBuilder = // schemaAssembler.name(metaData.getColumnName(columnIndex)); // AvroHelper.convertColumnTypeToAvroType(fieldBuilder, metaData, columnIndex); // } // return schemaAssembler.endRecord(); // } // // Path: src/java/com/google/cloud/bigquery/dwhassessment/extractiontool/db/SchemaManager.java // @AutoValue // abstract class SchemaKey { // public static SchemaKey create(String databaseName, String tableName) { // return new AutoValue_SchemaManager_SchemaKey(databaseName, tableName); // } // // public abstract String databaseName(); // // public abstract String tableName(); // }
import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import static com.google.cloud.bigquery.dwhassessment.extractiontool.db.AvroHelper.getAvroSchema; import static com.google.common.truth.Truth.assertThat; import com.google.cloud.bigquery.dwhassessment.extractiontool.db.SchemaManager.SchemaKey; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.re2j.Pattern; import java.io.ByteArrayOutputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.Statement; import org.apache.avro.Schema; import org.apache.avro.generic.GenericRecord; import org.apache.avro.generic.GenericRecordBuilder; import org.junit.BeforeClass;
SchemaFilter.builder().setTableName(Pattern.compile("FOO.*")).build())); assertThat(results) .containsAtLeastElementsIn( ImmutableSet.of( SchemaKey.create("HSQL Database Engine", "FOO"), SchemaKey.create("HSQL Database Engine", "FOOBAR"))); } @Test public void getSchemaKeys_multipleFilter_success() { ImmutableSet<SchemaKey> results = schemaManager.getSchemaKeys( connection, ImmutableList.of(SchemaFilter.builder().setTableName(Pattern.compile("FOO.*")).build(), SchemaFilter.builder().setTableName(Pattern.compile(".*BAR")).build())); assertThat(results) .containsAtLeastElementsIn( ImmutableSet.of( SchemaKey.create("HSQL Database Engine", "FOO"), SchemaKey.create("HSQL Database Engine", "FOOBAR"), SchemaKey.create("HSQL Database Engine", "BAR"))); } @Test public void retrieveSchemaTest() throws Exception { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); String databaseName = "HSQL Database Engine"; String tableName = "FOO"; Schema schema =
// Path: src/java/com/google/cloud/bigquery/dwhassessment/extractiontool/db/AvroHelper.java // public static Schema getAvroSchema( // String schemaName, String namespace, ResultSetMetaData metaData) throws SQLException { // Preconditions.checkArgument(!schemaName.isEmpty(), "Schema name cannot be empty."); // Preconditions.checkArgument(!namespace.isEmpty(), "Namespace cannot be empty."); // SchemaBuilder.FieldAssembler<Schema> schemaAssembler = // SchemaBuilder.record(schemaName).namespace(namespace).fields(); // // for (int columnIndex = 1; columnIndex <= metaData.getColumnCount(); columnIndex++) { // SchemaBuilder.FieldBuilder<Schema> fieldBuilder = // schemaAssembler.name(metaData.getColumnName(columnIndex)); // AvroHelper.convertColumnTypeToAvroType(fieldBuilder, metaData, columnIndex); // } // return schemaAssembler.endRecord(); // } // // Path: src/java/com/google/cloud/bigquery/dwhassessment/extractiontool/db/SchemaManager.java // @AutoValue // abstract class SchemaKey { // public static SchemaKey create(String databaseName, String tableName) { // return new AutoValue_SchemaManager_SchemaKey(databaseName, tableName); // } // // public abstract String databaseName(); // // public abstract String tableName(); // } // Path: src/javatests/com/google/cloud/bigquery/dwhassessment/extractiontool/db/SchemaManagerImplTest.java import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import static com.google.cloud.bigquery.dwhassessment.extractiontool.db.AvroHelper.getAvroSchema; import static com.google.common.truth.Truth.assertThat; import com.google.cloud.bigquery.dwhassessment.extractiontool.db.SchemaManager.SchemaKey; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.re2j.Pattern; import java.io.ByteArrayOutputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.Statement; import org.apache.avro.Schema; import org.apache.avro.generic.GenericRecord; import org.apache.avro.generic.GenericRecordBuilder; import org.junit.BeforeClass; SchemaFilter.builder().setTableName(Pattern.compile("FOO.*")).build())); assertThat(results) .containsAtLeastElementsIn( ImmutableSet.of( SchemaKey.create("HSQL Database Engine", "FOO"), SchemaKey.create("HSQL Database Engine", "FOOBAR"))); } @Test public void getSchemaKeys_multipleFilter_success() { ImmutableSet<SchemaKey> results = schemaManager.getSchemaKeys( connection, ImmutableList.of(SchemaFilter.builder().setTableName(Pattern.compile("FOO.*")).build(), SchemaFilter.builder().setTableName(Pattern.compile(".*BAR")).build())); assertThat(results) .containsAtLeastElementsIn( ImmutableSet.of( SchemaKey.create("HSQL Database Engine", "FOO"), SchemaKey.create("HSQL Database Engine", "FOOBAR"), SchemaKey.create("HSQL Database Engine", "BAR"))); } @Test public void retrieveSchemaTest() throws Exception { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); String databaseName = "HSQL Database Engine"; String tableName = "FOO"; Schema schema =
getAvroSchema(
google/dwh-assessment-extraction-tool
src/java/com/google/cloud/bigquery/dwhassessment/extractiontool/db/ScriptRunnerImpl.java
// Path: src/java/com/google/cloud/bigquery/dwhassessment/extractiontool/db/AvroHelper.java // public static Schema getAvroSchema( // String schemaName, String namespace, ResultSetMetaData metaData) throws SQLException { // Preconditions.checkArgument(!schemaName.isEmpty(), "Schema name cannot be empty."); // Preconditions.checkArgument(!namespace.isEmpty(), "Namespace cannot be empty."); // SchemaBuilder.FieldAssembler<Schema> schemaAssembler = // SchemaBuilder.record(schemaName).namespace(namespace).fields(); // // for (int columnIndex = 1; columnIndex <= metaData.getColumnCount(); columnIndex++) { // SchemaBuilder.FieldBuilder<Schema> fieldBuilder = // schemaAssembler.name(metaData.getColumnName(columnIndex)); // AvroHelper.convertColumnTypeToAvroType(fieldBuilder, metaData, columnIndex); // } // return schemaAssembler.endRecord(); // } // // Path: src/java/com/google/cloud/bigquery/dwhassessment/extractiontool/db/AvroHelper.java // public static GenericRecord parseRowToAvro(ResultSet row, Schema schema) throws SQLException { // GenericRecordBuilder recordBuilder = new GenericRecordBuilder(schema); // ResultSetMetaData metaData = row.getMetaData(); // for (int columnIndex = 1; columnIndex <= row.getMetaData().getColumnCount(); columnIndex++) { // recordBuilder.set( // metaData.getColumnName(columnIndex), getRowObject(metaData, row, columnIndex)); // } // return recordBuilder.build(); // }
import static com.google.cloud.bigquery.dwhassessment.extractiontool.db.AvroHelper.getAvroSchema; import static com.google.cloud.bigquery.dwhassessment.extractiontool.db.AvroHelper.parseRowToAvro; import java.sql.Connection; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.util.function.Consumer; import org.apache.avro.Schema; import org.apache.avro.generic.GenericRecord;
/* * Copyright 2021 Google LLC * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.bigquery.dwhassessment.extractiontool.db; /** * Implementation of ScriptRunner. Executes SQL script and converts query results to desired format, * i.e. Avro. */ public class ScriptRunnerImpl implements ScriptRunner { @Override public void executeScriptToAvro( Connection connection, String sqlScript, Schema schema, Consumer<GenericRecord> recordConsumer) throws SQLException { ResultSet resultSet = connection.createStatement().executeQuery(sqlScript); while (resultSet.next()) {
// Path: src/java/com/google/cloud/bigquery/dwhassessment/extractiontool/db/AvroHelper.java // public static Schema getAvroSchema( // String schemaName, String namespace, ResultSetMetaData metaData) throws SQLException { // Preconditions.checkArgument(!schemaName.isEmpty(), "Schema name cannot be empty."); // Preconditions.checkArgument(!namespace.isEmpty(), "Namespace cannot be empty."); // SchemaBuilder.FieldAssembler<Schema> schemaAssembler = // SchemaBuilder.record(schemaName).namespace(namespace).fields(); // // for (int columnIndex = 1; columnIndex <= metaData.getColumnCount(); columnIndex++) { // SchemaBuilder.FieldBuilder<Schema> fieldBuilder = // schemaAssembler.name(metaData.getColumnName(columnIndex)); // AvroHelper.convertColumnTypeToAvroType(fieldBuilder, metaData, columnIndex); // } // return schemaAssembler.endRecord(); // } // // Path: src/java/com/google/cloud/bigquery/dwhassessment/extractiontool/db/AvroHelper.java // public static GenericRecord parseRowToAvro(ResultSet row, Schema schema) throws SQLException { // GenericRecordBuilder recordBuilder = new GenericRecordBuilder(schema); // ResultSetMetaData metaData = row.getMetaData(); // for (int columnIndex = 1; columnIndex <= row.getMetaData().getColumnCount(); columnIndex++) { // recordBuilder.set( // metaData.getColumnName(columnIndex), getRowObject(metaData, row, columnIndex)); // } // return recordBuilder.build(); // } // Path: src/java/com/google/cloud/bigquery/dwhassessment/extractiontool/db/ScriptRunnerImpl.java import static com.google.cloud.bigquery.dwhassessment.extractiontool.db.AvroHelper.getAvroSchema; import static com.google.cloud.bigquery.dwhassessment.extractiontool.db.AvroHelper.parseRowToAvro; import java.sql.Connection; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.util.function.Consumer; import org.apache.avro.Schema; import org.apache.avro.generic.GenericRecord; /* * Copyright 2021 Google LLC * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.bigquery.dwhassessment.extractiontool.db; /** * Implementation of ScriptRunner. Executes SQL script and converts query results to desired format, * i.e. Avro. */ public class ScriptRunnerImpl implements ScriptRunner { @Override public void executeScriptToAvro( Connection connection, String sqlScript, Schema schema, Consumer<GenericRecord> recordConsumer) throws SQLException { ResultSet resultSet = connection.createStatement().executeQuery(sqlScript); while (resultSet.next()) {
recordConsumer.accept(parseRowToAvro(resultSet, schema));
google/dwh-assessment-extraction-tool
src/java/com/google/cloud/bigquery/dwhassessment/extractiontool/db/ScriptRunnerImpl.java
// Path: src/java/com/google/cloud/bigquery/dwhassessment/extractiontool/db/AvroHelper.java // public static Schema getAvroSchema( // String schemaName, String namespace, ResultSetMetaData metaData) throws SQLException { // Preconditions.checkArgument(!schemaName.isEmpty(), "Schema name cannot be empty."); // Preconditions.checkArgument(!namespace.isEmpty(), "Namespace cannot be empty."); // SchemaBuilder.FieldAssembler<Schema> schemaAssembler = // SchemaBuilder.record(schemaName).namespace(namespace).fields(); // // for (int columnIndex = 1; columnIndex <= metaData.getColumnCount(); columnIndex++) { // SchemaBuilder.FieldBuilder<Schema> fieldBuilder = // schemaAssembler.name(metaData.getColumnName(columnIndex)); // AvroHelper.convertColumnTypeToAvroType(fieldBuilder, metaData, columnIndex); // } // return schemaAssembler.endRecord(); // } // // Path: src/java/com/google/cloud/bigquery/dwhassessment/extractiontool/db/AvroHelper.java // public static GenericRecord parseRowToAvro(ResultSet row, Schema schema) throws SQLException { // GenericRecordBuilder recordBuilder = new GenericRecordBuilder(schema); // ResultSetMetaData metaData = row.getMetaData(); // for (int columnIndex = 1; columnIndex <= row.getMetaData().getColumnCount(); columnIndex++) { // recordBuilder.set( // metaData.getColumnName(columnIndex), getRowObject(metaData, row, columnIndex)); // } // return recordBuilder.build(); // }
import static com.google.cloud.bigquery.dwhassessment.extractiontool.db.AvroHelper.getAvroSchema; import static com.google.cloud.bigquery.dwhassessment.extractiontool.db.AvroHelper.parseRowToAvro; import java.sql.Connection; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.util.function.Consumer; import org.apache.avro.Schema; import org.apache.avro.generic.GenericRecord;
/* * Copyright 2021 Google LLC * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.bigquery.dwhassessment.extractiontool.db; /** * Implementation of ScriptRunner. Executes SQL script and converts query results to desired format, * i.e. Avro. */ public class ScriptRunnerImpl implements ScriptRunner { @Override public void executeScriptToAvro( Connection connection, String sqlScript, Schema schema, Consumer<GenericRecord> recordConsumer) throws SQLException { ResultSet resultSet = connection.createStatement().executeQuery(sqlScript); while (resultSet.next()) { recordConsumer.accept(parseRowToAvro(resultSet, schema)); } } @Override public Schema extractSchema( Connection connection, String sqlScript, String schemaName, String namespace) throws SQLException { ResultSetMetaData metaData = connection.createStatement().executeQuery(sqlScript).getMetaData();
// Path: src/java/com/google/cloud/bigquery/dwhassessment/extractiontool/db/AvroHelper.java // public static Schema getAvroSchema( // String schemaName, String namespace, ResultSetMetaData metaData) throws SQLException { // Preconditions.checkArgument(!schemaName.isEmpty(), "Schema name cannot be empty."); // Preconditions.checkArgument(!namespace.isEmpty(), "Namespace cannot be empty."); // SchemaBuilder.FieldAssembler<Schema> schemaAssembler = // SchemaBuilder.record(schemaName).namespace(namespace).fields(); // // for (int columnIndex = 1; columnIndex <= metaData.getColumnCount(); columnIndex++) { // SchemaBuilder.FieldBuilder<Schema> fieldBuilder = // schemaAssembler.name(metaData.getColumnName(columnIndex)); // AvroHelper.convertColumnTypeToAvroType(fieldBuilder, metaData, columnIndex); // } // return schemaAssembler.endRecord(); // } // // Path: src/java/com/google/cloud/bigquery/dwhassessment/extractiontool/db/AvroHelper.java // public static GenericRecord parseRowToAvro(ResultSet row, Schema schema) throws SQLException { // GenericRecordBuilder recordBuilder = new GenericRecordBuilder(schema); // ResultSetMetaData metaData = row.getMetaData(); // for (int columnIndex = 1; columnIndex <= row.getMetaData().getColumnCount(); columnIndex++) { // recordBuilder.set( // metaData.getColumnName(columnIndex), getRowObject(metaData, row, columnIndex)); // } // return recordBuilder.build(); // } // Path: src/java/com/google/cloud/bigquery/dwhassessment/extractiontool/db/ScriptRunnerImpl.java import static com.google.cloud.bigquery.dwhassessment.extractiontool.db.AvroHelper.getAvroSchema; import static com.google.cloud.bigquery.dwhassessment.extractiontool.db.AvroHelper.parseRowToAvro; import java.sql.Connection; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.util.function.Consumer; import org.apache.avro.Schema; import org.apache.avro.generic.GenericRecord; /* * Copyright 2021 Google LLC * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.bigquery.dwhassessment.extractiontool.db; /** * Implementation of ScriptRunner. Executes SQL script and converts query results to desired format, * i.e. Avro. */ public class ScriptRunnerImpl implements ScriptRunner { @Override public void executeScriptToAvro( Connection connection, String sqlScript, Schema schema, Consumer<GenericRecord> recordConsumer) throws SQLException { ResultSet resultSet = connection.createStatement().executeQuery(sqlScript); while (resultSet.next()) { recordConsumer.accept(parseRowToAvro(resultSet, schema)); } } @Override public Schema extractSchema( Connection connection, String sqlScript, String schemaName, String namespace) throws SQLException { ResultSetMetaData metaData = connection.createStatement().executeQuery(sqlScript).getMetaData();
return getAvroSchema(schemaName, namespace, metaData);
google/dwh-assessment-extraction-tool
src/java/com/google/cloud/bigquery/dwhassessment/extractiontool/db/ScriptManager.java
// Path: src/java/com/google/cloud/bigquery/dwhassessment/extractiontool/dumper/DataEntityManager.java // public interface DataEntityManager extends Closeable { // // /** // * Get the output stream for an entity. // * // * @param name The name of the output entity. // */ // OutputStream getEntityOutputStream(String name) throws IOException; // // /** // * Indicate whether the data entity allows resumable processing. // * // * @return true if some progress can be retained after the writing is interrupted. // */ // boolean isResumable(); // // /** // * Get the absolute path of a file given its name. // * // * @param name The name of the file. // */ // Path getAbsolutePath(String name); // }
import com.google.cloud.bigquery.dwhassessment.extractiontool.dumper.DataEntityManager; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import java.io.IOException; import java.sql.Connection; import java.sql.SQLException;
/* * Copyright 2021 Google LLC * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.bigquery.dwhassessment.extractiontool.db; /** Interface to manage SQL scripts. */ public interface ScriptManager { /** * Executes a script against a DB connection and writes the output to a stream. * * @param connection The JDBC connection to the database. * @param dryRun Whether to just perform a dry run, which just logs out the action to perform. * @param sqlTemplateRenderer A template renderer to apply on the SQL script before execution. * @param scriptName The name of the script. This is not a file name. The interpretation of the * name is left to the implementation but can also map to several files (e.g., an SQL file and * a schema definition file). * @param dataEntityManager The data entity manager to use to write the output. * @param chunkRows The maximum number of rows (records) in one output file. * @param startingChunkNumber The starting chunk number for this run (as continued from previous * run, if specified). */ void executeScript( Connection connection, boolean dryRun, SqlTemplateRenderer sqlTemplateRenderer, String scriptName,
// Path: src/java/com/google/cloud/bigquery/dwhassessment/extractiontool/dumper/DataEntityManager.java // public interface DataEntityManager extends Closeable { // // /** // * Get the output stream for an entity. // * // * @param name The name of the output entity. // */ // OutputStream getEntityOutputStream(String name) throws IOException; // // /** // * Indicate whether the data entity allows resumable processing. // * // * @return true if some progress can be retained after the writing is interrupted. // */ // boolean isResumable(); // // /** // * Get the absolute path of a file given its name. // * // * @param name The name of the file. // */ // Path getAbsolutePath(String name); // } // Path: src/java/com/google/cloud/bigquery/dwhassessment/extractiontool/db/ScriptManager.java import com.google.cloud.bigquery.dwhassessment.extractiontool.dumper.DataEntityManager; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import java.io.IOException; import java.sql.Connection; import java.sql.SQLException; /* * Copyright 2021 Google LLC * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.bigquery.dwhassessment.extractiontool.db; /** Interface to manage SQL scripts. */ public interface ScriptManager { /** * Executes a script against a DB connection and writes the output to a stream. * * @param connection The JDBC connection to the database. * @param dryRun Whether to just perform a dry run, which just logs out the action to perform. * @param sqlTemplateRenderer A template renderer to apply on the SQL script before execution. * @param scriptName The name of the script. This is not a file name. The interpretation of the * name is left to the implementation but can also map to several files (e.g., an SQL file and * a schema definition file). * @param dataEntityManager The data entity manager to use to write the output. * @param chunkRows The maximum number of rows (records) in one output file. * @param startingChunkNumber The starting chunk number for this run (as continued from previous * run, if specified). */ void executeScript( Connection connection, boolean dryRun, SqlTemplateRenderer sqlTemplateRenderer, String scriptName,
DataEntityManager dataEntityManager,
google/dwh-assessment-extraction-tool
src/javatests/com/google/cloud/bigquery/dwhassessment/extractiontool/db/ScriptManagerImplTest.java
// Path: src/java/com/google/cloud/bigquery/dwhassessment/extractiontool/db/ScriptManagerImpl.java // @VisibleForTesting // static String getUtcTimeStringFromTimestamp(Timestamp timestamp) { // Instant instant = timestamp.toInstant(); // // Remove the "Z" (that signifies UTC timezone) and the separators that are not necessary for // // human interpretation. // String instantWithoutNanoseconds = // instant.truncatedTo(ChronoUnit.SECONDS).toString().replaceAll("[Z\\-:]", "").trim(); // // Keep 6 digits of the fractional seconds from nano, which is equivalent to round(nanos / 10^9 // // * 10^6) with left-padded zeros. Prepend with S to separate from seconds. // String sixDigitNanos = // String.format((Locale) null, "S%06d", Math.round(timestamp.getNanos() / Math.pow(10, 3))); // return instantWithoutNanoseconds + sixDigitNanos; // } // // Path: src/java/com/google/cloud/bigquery/dwhassessment/extractiontool/dumper/DataEntityManager.java // public interface DataEntityManager extends Closeable { // // /** // * Get the output stream for an entity. // * // * @param name The name of the output entity. // */ // OutputStream getEntityOutputStream(String name) throws IOException; // // /** // * Indicate whether the data entity allows resumable processing. // * // * @return true if some progress can be retained after the writing is interrupted. // */ // boolean isResumable(); // // /** // * Get the absolute path of a file given its name. // * // * @param name The name of the file. // */ // Path getAbsolutePath(String name); // } // // Path: src/javatests/com/google/cloud/bigquery/dwhassessment/extractiontool/dumper/FakeDataEntityManagerImpl.java // public class FakeDataEntityManagerImpl implements DataEntityManager { // // private final Path tmpDir; // private final ByteArrayOutputStream outputStream; // private final boolean bareStreamMode; // // /** // * Constructs a fake DataEntityManager for testing; it supports chunked writing; the output files // * are saved in a temporary directory. // */ // public FakeDataEntityManagerImpl(String testDirName) throws IOException { // this.tmpDir = Files.createTempDirectory(testDirName); // this.outputStream = null; // bareStreamMode = false; // } // // /** // * Construct a fake DataEntityManager with a fixed reference of ByteArrayOutputStream; it does not // * support any file operations. // */ // public FakeDataEntityManagerImpl(ByteArrayOutputStream outputStream) { // this.outputStream = outputStream; // this.tmpDir = null; // bareStreamMode = true; // } // // @Override // public OutputStream getEntityOutputStream(String name) throws IOException { // return bareStreamMode ? outputStream : Files.newOutputStream(tmpDir.resolve(name)); // } // // @Override // public boolean isResumable() { // return !bareStreamMode; // } // // @Override // public Path getAbsolutePath(String name) { // return bareStreamMode ? null : tmpDir.resolve(name); // } // // @Override // public void close() throws IOException {} // }
import static com.google.common.truth.Truth.assertThat; import static com.google.cloud.bigquery.dwhassessment.extractiontool.db.ScriptManagerImpl.getUtcTimeStringFromTimestamp; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThrows; import com.google.cloud.bigquery.dwhassessment.extractiontool.dumper.DataEntityManager; import com.google.cloud.bigquery.dwhassessment.extractiontool.dumper.FakeDataEntityManagerImpl; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; import java.sql.Timestamp; import java.time.Instant; import java.util.NoSuchElementException; import java.util.function.Supplier; import java.util.stream.Collectors; import org.apache.avro.Schema; import org.apache.avro.file.DataFileReader; import org.apache.avro.file.SeekableByteArrayInput; import org.apache.avro.generic.GenericData.Record; import org.apache.avro.generic.GenericDatumReader; import org.apache.avro.generic.GenericRecordBuilder; import org.apache.avro.io.DatumReader; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4;
/* * Copyright 2021 Google LLC * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.bigquery.dwhassessment.extractiontool.db; @RunWith(JUnit4.class) public final class ScriptManagerImplTest { private final String baseScript = "SELECT * FROM TestTable"; private final ImmutableMap<String, Supplier<String>> scriptsMap = ImmutableMap.of( "default", () -> baseScript, "default_chunked", () -> baseScript + "{{#if sortingColumns}}\n" + "ORDER BY {{#each sortingColumns}}{{this}}{{#unless" + " @last}},{{/unless}}{{/each}} ASC NULLS FIRST\n" + "{{/if}}"); private final ImmutableMap<String, ImmutableList<String>> sortingColumnsMap = ImmutableMap.of("default_chunked", ImmutableList.of("TIMESTAMPS")); private final SqlTemplateRenderer sqlTemplateRenderer = new SqlTemplateRendererImpl( SqlScriptVariables.builder() .setBaseDatabase("test-db") .setQueryLogsVariables(SqlScriptVariables.QueryLogsVariables.builder().build())); private ScriptManager scriptManager;
// Path: src/java/com/google/cloud/bigquery/dwhassessment/extractiontool/db/ScriptManagerImpl.java // @VisibleForTesting // static String getUtcTimeStringFromTimestamp(Timestamp timestamp) { // Instant instant = timestamp.toInstant(); // // Remove the "Z" (that signifies UTC timezone) and the separators that are not necessary for // // human interpretation. // String instantWithoutNanoseconds = // instant.truncatedTo(ChronoUnit.SECONDS).toString().replaceAll("[Z\\-:]", "").trim(); // // Keep 6 digits of the fractional seconds from nano, which is equivalent to round(nanos / 10^9 // // * 10^6) with left-padded zeros. Prepend with S to separate from seconds. // String sixDigitNanos = // String.format((Locale) null, "S%06d", Math.round(timestamp.getNanos() / Math.pow(10, 3))); // return instantWithoutNanoseconds + sixDigitNanos; // } // // Path: src/java/com/google/cloud/bigquery/dwhassessment/extractiontool/dumper/DataEntityManager.java // public interface DataEntityManager extends Closeable { // // /** // * Get the output stream for an entity. // * // * @param name The name of the output entity. // */ // OutputStream getEntityOutputStream(String name) throws IOException; // // /** // * Indicate whether the data entity allows resumable processing. // * // * @return true if some progress can be retained after the writing is interrupted. // */ // boolean isResumable(); // // /** // * Get the absolute path of a file given its name. // * // * @param name The name of the file. // */ // Path getAbsolutePath(String name); // } // // Path: src/javatests/com/google/cloud/bigquery/dwhassessment/extractiontool/dumper/FakeDataEntityManagerImpl.java // public class FakeDataEntityManagerImpl implements DataEntityManager { // // private final Path tmpDir; // private final ByteArrayOutputStream outputStream; // private final boolean bareStreamMode; // // /** // * Constructs a fake DataEntityManager for testing; it supports chunked writing; the output files // * are saved in a temporary directory. // */ // public FakeDataEntityManagerImpl(String testDirName) throws IOException { // this.tmpDir = Files.createTempDirectory(testDirName); // this.outputStream = null; // bareStreamMode = false; // } // // /** // * Construct a fake DataEntityManager with a fixed reference of ByteArrayOutputStream; it does not // * support any file operations. // */ // public FakeDataEntityManagerImpl(ByteArrayOutputStream outputStream) { // this.outputStream = outputStream; // this.tmpDir = null; // bareStreamMode = true; // } // // @Override // public OutputStream getEntityOutputStream(String name) throws IOException { // return bareStreamMode ? outputStream : Files.newOutputStream(tmpDir.resolve(name)); // } // // @Override // public boolean isResumable() { // return !bareStreamMode; // } // // @Override // public Path getAbsolutePath(String name) { // return bareStreamMode ? null : tmpDir.resolve(name); // } // // @Override // public void close() throws IOException {} // } // Path: src/javatests/com/google/cloud/bigquery/dwhassessment/extractiontool/db/ScriptManagerImplTest.java import static com.google.common.truth.Truth.assertThat; import static com.google.cloud.bigquery.dwhassessment.extractiontool.db.ScriptManagerImpl.getUtcTimeStringFromTimestamp; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThrows; import com.google.cloud.bigquery.dwhassessment.extractiontool.dumper.DataEntityManager; import com.google.cloud.bigquery.dwhassessment.extractiontool.dumper.FakeDataEntityManagerImpl; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; import java.sql.Timestamp; import java.time.Instant; import java.util.NoSuchElementException; import java.util.function.Supplier; import java.util.stream.Collectors; import org.apache.avro.Schema; import org.apache.avro.file.DataFileReader; import org.apache.avro.file.SeekableByteArrayInput; import org.apache.avro.generic.GenericData.Record; import org.apache.avro.generic.GenericDatumReader; import org.apache.avro.generic.GenericRecordBuilder; import org.apache.avro.io.DatumReader; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /* * Copyright 2021 Google LLC * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.bigquery.dwhassessment.extractiontool.db; @RunWith(JUnit4.class) public final class ScriptManagerImplTest { private final String baseScript = "SELECT * FROM TestTable"; private final ImmutableMap<String, Supplier<String>> scriptsMap = ImmutableMap.of( "default", () -> baseScript, "default_chunked", () -> baseScript + "{{#if sortingColumns}}\n" + "ORDER BY {{#each sortingColumns}}{{this}}{{#unless" + " @last}},{{/unless}}{{/each}} ASC NULLS FIRST\n" + "{{/if}}"); private final ImmutableMap<String, ImmutableList<String>> sortingColumnsMap = ImmutableMap.of("default_chunked", ImmutableList.of("TIMESTAMPS")); private final SqlTemplateRenderer sqlTemplateRenderer = new SqlTemplateRendererImpl( SqlScriptVariables.builder() .setBaseDatabase("test-db") .setQueryLogsVariables(SqlScriptVariables.QueryLogsVariables.builder().build())); private ScriptManager scriptManager;
private DataEntityManager dataEntityManager;
google/dwh-assessment-extraction-tool
src/javatests/com/google/cloud/bigquery/dwhassessment/extractiontool/db/ScriptManagerImplTest.java
// Path: src/java/com/google/cloud/bigquery/dwhassessment/extractiontool/db/ScriptManagerImpl.java // @VisibleForTesting // static String getUtcTimeStringFromTimestamp(Timestamp timestamp) { // Instant instant = timestamp.toInstant(); // // Remove the "Z" (that signifies UTC timezone) and the separators that are not necessary for // // human interpretation. // String instantWithoutNanoseconds = // instant.truncatedTo(ChronoUnit.SECONDS).toString().replaceAll("[Z\\-:]", "").trim(); // // Keep 6 digits of the fractional seconds from nano, which is equivalent to round(nanos / 10^9 // // * 10^6) with left-padded zeros. Prepend with S to separate from seconds. // String sixDigitNanos = // String.format((Locale) null, "S%06d", Math.round(timestamp.getNanos() / Math.pow(10, 3))); // return instantWithoutNanoseconds + sixDigitNanos; // } // // Path: src/java/com/google/cloud/bigquery/dwhassessment/extractiontool/dumper/DataEntityManager.java // public interface DataEntityManager extends Closeable { // // /** // * Get the output stream for an entity. // * // * @param name The name of the output entity. // */ // OutputStream getEntityOutputStream(String name) throws IOException; // // /** // * Indicate whether the data entity allows resumable processing. // * // * @return true if some progress can be retained after the writing is interrupted. // */ // boolean isResumable(); // // /** // * Get the absolute path of a file given its name. // * // * @param name The name of the file. // */ // Path getAbsolutePath(String name); // } // // Path: src/javatests/com/google/cloud/bigquery/dwhassessment/extractiontool/dumper/FakeDataEntityManagerImpl.java // public class FakeDataEntityManagerImpl implements DataEntityManager { // // private final Path tmpDir; // private final ByteArrayOutputStream outputStream; // private final boolean bareStreamMode; // // /** // * Constructs a fake DataEntityManager for testing; it supports chunked writing; the output files // * are saved in a temporary directory. // */ // public FakeDataEntityManagerImpl(String testDirName) throws IOException { // this.tmpDir = Files.createTempDirectory(testDirName); // this.outputStream = null; // bareStreamMode = false; // } // // /** // * Construct a fake DataEntityManager with a fixed reference of ByteArrayOutputStream; it does not // * support any file operations. // */ // public FakeDataEntityManagerImpl(ByteArrayOutputStream outputStream) { // this.outputStream = outputStream; // this.tmpDir = null; // bareStreamMode = true; // } // // @Override // public OutputStream getEntityOutputStream(String name) throws IOException { // return bareStreamMode ? outputStream : Files.newOutputStream(tmpDir.resolve(name)); // } // // @Override // public boolean isResumable() { // return !bareStreamMode; // } // // @Override // public Path getAbsolutePath(String name) { // return bareStreamMode ? null : tmpDir.resolve(name); // } // // @Override // public void close() throws IOException {} // }
import static com.google.common.truth.Truth.assertThat; import static com.google.cloud.bigquery.dwhassessment.extractiontool.db.ScriptManagerImpl.getUtcTimeStringFromTimestamp; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThrows; import com.google.cloud.bigquery.dwhassessment.extractiontool.dumper.DataEntityManager; import com.google.cloud.bigquery.dwhassessment.extractiontool.dumper.FakeDataEntityManagerImpl; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; import java.sql.Timestamp; import java.time.Instant; import java.util.NoSuchElementException; import java.util.function.Supplier; import java.util.stream.Collectors; import org.apache.avro.Schema; import org.apache.avro.file.DataFileReader; import org.apache.avro.file.SeekableByteArrayInput; import org.apache.avro.generic.GenericData.Record; import org.apache.avro.generic.GenericDatumReader; import org.apache.avro.generic.GenericRecordBuilder; import org.apache.avro.io.DatumReader; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4;
"CREATE Table TestTable (" + "ID INTEGER," + "TIMESTAMPS TIMESTAMP(6) WITH TIME ZONE" + ")"); baseStmt.execute( "INSERT INTO TestTable VALUES (4, TIMESTAMP '2007-07-07 20:07:07.007000' AT TIME ZONE" + " INTERVAL '0:00' HOUR TO MINUTE)"); baseStmt.close(); connection.commit(); scriptManager.executeScript( connection, /*dryRun=*/ false, sqlTemplateRenderer, "default_chunked", dataEntityManagerTmp, /*chunkRows=*/ 2, /*startingChunkNumber=*/ 7); DataFileReader<Record> readerForFirstChunk = getAssertingReaderForAvroResults( dataEntityManagerTmp.getAbsolutePath( "default_chunked-20070707T200707S007000-20070707T200707S007000_7.avro")); assertThat(readerForFirstChunk.next().get(1)) .isEqualTo(Instant.parse("2007-07-07T20:07:07.007000000Z").toEpochMilli()); assertFalse(readerForFirstChunk.hasNext()); } @Test public void getUtcTimeStringFromTimestamp_outputShouldBeCorrect() {
// Path: src/java/com/google/cloud/bigquery/dwhassessment/extractiontool/db/ScriptManagerImpl.java // @VisibleForTesting // static String getUtcTimeStringFromTimestamp(Timestamp timestamp) { // Instant instant = timestamp.toInstant(); // // Remove the "Z" (that signifies UTC timezone) and the separators that are not necessary for // // human interpretation. // String instantWithoutNanoseconds = // instant.truncatedTo(ChronoUnit.SECONDS).toString().replaceAll("[Z\\-:]", "").trim(); // // Keep 6 digits of the fractional seconds from nano, which is equivalent to round(nanos / 10^9 // // * 10^6) with left-padded zeros. Prepend with S to separate from seconds. // String sixDigitNanos = // String.format((Locale) null, "S%06d", Math.round(timestamp.getNanos() / Math.pow(10, 3))); // return instantWithoutNanoseconds + sixDigitNanos; // } // // Path: src/java/com/google/cloud/bigquery/dwhassessment/extractiontool/dumper/DataEntityManager.java // public interface DataEntityManager extends Closeable { // // /** // * Get the output stream for an entity. // * // * @param name The name of the output entity. // */ // OutputStream getEntityOutputStream(String name) throws IOException; // // /** // * Indicate whether the data entity allows resumable processing. // * // * @return true if some progress can be retained after the writing is interrupted. // */ // boolean isResumable(); // // /** // * Get the absolute path of a file given its name. // * // * @param name The name of the file. // */ // Path getAbsolutePath(String name); // } // // Path: src/javatests/com/google/cloud/bigquery/dwhassessment/extractiontool/dumper/FakeDataEntityManagerImpl.java // public class FakeDataEntityManagerImpl implements DataEntityManager { // // private final Path tmpDir; // private final ByteArrayOutputStream outputStream; // private final boolean bareStreamMode; // // /** // * Constructs a fake DataEntityManager for testing; it supports chunked writing; the output files // * are saved in a temporary directory. // */ // public FakeDataEntityManagerImpl(String testDirName) throws IOException { // this.tmpDir = Files.createTempDirectory(testDirName); // this.outputStream = null; // bareStreamMode = false; // } // // /** // * Construct a fake DataEntityManager with a fixed reference of ByteArrayOutputStream; it does not // * support any file operations. // */ // public FakeDataEntityManagerImpl(ByteArrayOutputStream outputStream) { // this.outputStream = outputStream; // this.tmpDir = null; // bareStreamMode = true; // } // // @Override // public OutputStream getEntityOutputStream(String name) throws IOException { // return bareStreamMode ? outputStream : Files.newOutputStream(tmpDir.resolve(name)); // } // // @Override // public boolean isResumable() { // return !bareStreamMode; // } // // @Override // public Path getAbsolutePath(String name) { // return bareStreamMode ? null : tmpDir.resolve(name); // } // // @Override // public void close() throws IOException {} // } // Path: src/javatests/com/google/cloud/bigquery/dwhassessment/extractiontool/db/ScriptManagerImplTest.java import static com.google.common.truth.Truth.assertThat; import static com.google.cloud.bigquery.dwhassessment.extractiontool.db.ScriptManagerImpl.getUtcTimeStringFromTimestamp; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThrows; import com.google.cloud.bigquery.dwhassessment.extractiontool.dumper.DataEntityManager; import com.google.cloud.bigquery.dwhassessment.extractiontool.dumper.FakeDataEntityManagerImpl; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; import java.sql.Timestamp; import java.time.Instant; import java.util.NoSuchElementException; import java.util.function.Supplier; import java.util.stream.Collectors; import org.apache.avro.Schema; import org.apache.avro.file.DataFileReader; import org.apache.avro.file.SeekableByteArrayInput; import org.apache.avro.generic.GenericData.Record; import org.apache.avro.generic.GenericDatumReader; import org.apache.avro.generic.GenericRecordBuilder; import org.apache.avro.io.DatumReader; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; "CREATE Table TestTable (" + "ID INTEGER," + "TIMESTAMPS TIMESTAMP(6) WITH TIME ZONE" + ")"); baseStmt.execute( "INSERT INTO TestTable VALUES (4, TIMESTAMP '2007-07-07 20:07:07.007000' AT TIME ZONE" + " INTERVAL '0:00' HOUR TO MINUTE)"); baseStmt.close(); connection.commit(); scriptManager.executeScript( connection, /*dryRun=*/ false, sqlTemplateRenderer, "default_chunked", dataEntityManagerTmp, /*chunkRows=*/ 2, /*startingChunkNumber=*/ 7); DataFileReader<Record> readerForFirstChunk = getAssertingReaderForAvroResults( dataEntityManagerTmp.getAbsolutePath( "default_chunked-20070707T200707S007000-20070707T200707S007000_7.avro")); assertThat(readerForFirstChunk.next().get(1)) .isEqualTo(Instant.parse("2007-07-07T20:07:07.007000000Z").toEpochMilli()); assertFalse(readerForFirstChunk.hasNext()); } @Test public void getUtcTimeStringFromTimestamp_outputShouldBeCorrect() {
assertThat(getUtcTimeStringFromTimestamp(Timestamp.from(Instant.parse("2022-01-24T14:52:00Z"))))
google/dwh-assessment-extraction-tool
src/javatests/com/google/cloud/bigquery/dwhassessment/extractiontool/db/SchemaFiltersTest.java
// Path: src/java/com/google/cloud/bigquery/dwhassessment/extractiontool/db/SchemaFilters.java // public static SchemaFilter parse(String input) { // Map<String, String> filterMap = // "".equals(input) // ? ImmutableMap.of() // : Splitter.onPattern(",\\s*").withKeyValueSeparator(':').split(input); // Sets.SetView<String> unknownKeys = Sets.difference(filterMap.keySet(), VALID_KEYS); // Preconditions.checkState( // unknownKeys.isEmpty(), // "Got filter with invalid key(s): %s.", // Joiner.on(", ").join(unknownKeys)); // // SchemaFilter.Builder filterBuilder = SchemaFilter.builder(); // if (filterMap.containsKey(KEY_DB)) { // filterBuilder.setDatabaseName(compilePattern(KEY_DB, filterMap.get(KEY_DB))); // } // if (filterMap.containsKey(KEY_TABLE)) { // filterBuilder.setTableName(compilePattern(KEY_TABLE, filterMap.get(KEY_TABLE))); // } // return filterBuilder.build(); // }
import static com.google.cloud.bigquery.dwhassessment.extractiontool.db.SchemaFilters.parse; import static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.assertThrows; import com.google.re2j.Pattern; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4;
/* * Copyright 2021 Google LLC * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.bigquery.dwhassessment.extractiontool.db; @RunWith(JUnit4.class) public final class SchemaFiltersTest { @Test public void parse_empty_success() {
// Path: src/java/com/google/cloud/bigquery/dwhassessment/extractiontool/db/SchemaFilters.java // public static SchemaFilter parse(String input) { // Map<String, String> filterMap = // "".equals(input) // ? ImmutableMap.of() // : Splitter.onPattern(",\\s*").withKeyValueSeparator(':').split(input); // Sets.SetView<String> unknownKeys = Sets.difference(filterMap.keySet(), VALID_KEYS); // Preconditions.checkState( // unknownKeys.isEmpty(), // "Got filter with invalid key(s): %s.", // Joiner.on(", ").join(unknownKeys)); // // SchemaFilter.Builder filterBuilder = SchemaFilter.builder(); // if (filterMap.containsKey(KEY_DB)) { // filterBuilder.setDatabaseName(compilePattern(KEY_DB, filterMap.get(KEY_DB))); // } // if (filterMap.containsKey(KEY_TABLE)) { // filterBuilder.setTableName(compilePattern(KEY_TABLE, filterMap.get(KEY_TABLE))); // } // return filterBuilder.build(); // } // Path: src/javatests/com/google/cloud/bigquery/dwhassessment/extractiontool/db/SchemaFiltersTest.java import static com.google.cloud.bigquery.dwhassessment.extractiontool.db.SchemaFilters.parse; import static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.assertThrows; import com.google.re2j.Pattern; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /* * Copyright 2021 Google LLC * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.bigquery.dwhassessment.extractiontool.db; @RunWith(JUnit4.class) public final class SchemaFiltersTest { @Test public void parse_empty_success() {
assertThat(parse("")).isEqualTo(SchemaFilter.builder().build());
google/dwh-assessment-extraction-tool
src/javatests/com/google/cloud/bigquery/dwhassessment/extractiontool/executor/SaveCheckerImplTest.java
// Path: src/java/com/google/cloud/bigquery/dwhassessment/extractiontool/common/ChunkCheckpoint.java // @AutoValue // public abstract class ChunkCheckpoint { // // public abstract Integer lastSavedChunkNumber(); // // public abstract Instant lastSavedInstant(); // // public static Builder builder() { // return new AutoValue_ChunkCheckpoint.Builder() // .setLastSavedChunkNumber(-1) // .setLastSavedInstant(Instant.ofEpochMilli(0)); // } // // @AutoValue.Builder // public abstract static class Builder { // // public abstract Builder setLastSavedChunkNumber(Integer value); // // public abstract Builder setLastSavedInstant(Instant value); // // public abstract ChunkCheckpoint build(); // } // }
import static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.assertThrows; import com.google.cloud.bigquery.dwhassessment.extractiontool.common.ChunkCheckpoint; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.time.Instant; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4;
/* * Copyright 2021 Google LLC * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.bigquery.dwhassessment.extractiontool.executor; @RunWith(JUnit4.class) public class SaveCheckerImplTest { private Path tmpDir; private SaveCheckerImpl saveChecker; private static final String DIR_NAME = "testDir"; private static final String SCRIPT_NAME = "test_script"; private static final String AVRO_SUFFIX = ".avro"; @Before public void setUp() throws IOException { tmpDir = Files.createTempDirectory(DIR_NAME); saveChecker = new SaveCheckerImpl(ImmutableMap.of(SCRIPT_NAME, ImmutableList.of("testTimestampColumn"))); } @Test public void getScriptCheckpoints_success() throws IOException { Files.createFile( tmpDir.resolve( SCRIPT_NAME + "-20140707T170707S000007-20140707T170707S000008_0" + AVRO_SUFFIX)); Files.createFile( tmpDir.resolve( SCRIPT_NAME + "-20140707T170707S000017-20140707T170707S000018_1" + AVRO_SUFFIX)); Files.createFile( tmpDir.resolve( SCRIPT_NAME + "-20140707T170707S000027-20140707T170707S000028_2" + AVRO_SUFFIX)); Files.createFile(tmpDir.resolve("file_to_be_ignored"));
// Path: src/java/com/google/cloud/bigquery/dwhassessment/extractiontool/common/ChunkCheckpoint.java // @AutoValue // public abstract class ChunkCheckpoint { // // public abstract Integer lastSavedChunkNumber(); // // public abstract Instant lastSavedInstant(); // // public static Builder builder() { // return new AutoValue_ChunkCheckpoint.Builder() // .setLastSavedChunkNumber(-1) // .setLastSavedInstant(Instant.ofEpochMilli(0)); // } // // @AutoValue.Builder // public abstract static class Builder { // // public abstract Builder setLastSavedChunkNumber(Integer value); // // public abstract Builder setLastSavedInstant(Instant value); // // public abstract ChunkCheckpoint build(); // } // } // Path: src/javatests/com/google/cloud/bigquery/dwhassessment/extractiontool/executor/SaveCheckerImplTest.java import static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.assertThrows; import com.google.cloud.bigquery.dwhassessment.extractiontool.common.ChunkCheckpoint; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.time.Instant; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; /* * Copyright 2021 Google LLC * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.cloud.bigquery.dwhassessment.extractiontool.executor; @RunWith(JUnit4.class) public class SaveCheckerImplTest { private Path tmpDir; private SaveCheckerImpl saveChecker; private static final String DIR_NAME = "testDir"; private static final String SCRIPT_NAME = "test_script"; private static final String AVRO_SUFFIX = ".avro"; @Before public void setUp() throws IOException { tmpDir = Files.createTempDirectory(DIR_NAME); saveChecker = new SaveCheckerImpl(ImmutableMap.of(SCRIPT_NAME, ImmutableList.of("testTimestampColumn"))); } @Test public void getScriptCheckpoints_success() throws IOException { Files.createFile( tmpDir.resolve( SCRIPT_NAME + "-20140707T170707S000007-20140707T170707S000008_0" + AVRO_SUFFIX)); Files.createFile( tmpDir.resolve( SCRIPT_NAME + "-20140707T170707S000017-20140707T170707S000018_1" + AVRO_SUFFIX)); Files.createFile( tmpDir.resolve( SCRIPT_NAME + "-20140707T170707S000027-20140707T170707S000028_2" + AVRO_SUFFIX)); Files.createFile(tmpDir.resolve("file_to_be_ignored"));
ImmutableMap<String, ChunkCheckpoint> checkpoints = saveChecker.getScriptCheckPoints(tmpDir);
joshsh/rdfagents
rdfagents-core/src/main/java/net/fortytwo/rdfagents/messaging/query/QueryProvider.java
// Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/messaging/Commitment.java // public class Commitment { // // public enum Decision { // AGREE_AND_NOTIFY, // Query and Subscribe // AGREE_SILENTLY, // Query only // REFUSE // Query and Subscribe // } // // private final Decision decision; // private final ErrorExplanation explanation; // // public Commitment(final Decision decision, // final ErrorExplanation explanation) { // this.decision = decision; // this.explanation = explanation; // } // // public Decision getDecision() { // return decision; // } // // public ErrorExplanation getExplanation() { // return explanation; // } // } // // Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/messaging/LocalFailure.java // public class LocalFailure extends Exception { // public LocalFailure(final Throwable cause) { // super(cause); // } // // public LocalFailure(final String message) { // super(message); // } // } // // Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/messaging/Role.java // public abstract class Role { // protected final RDFAgent agent; // // public Role(final RDFAgent agent) { // this.agent = agent; // } // } // // Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/model/AgentId.java // public class AgentId { // private final String name; // private final IRI iri; // private final IRI[] transportAddresses; // // public AgentId(final String name, // final String... transportAddresses) { // this.name = name; // // this.iri = iriFromName(name); // // this.transportAddresses = new IRI[transportAddresses.length]; // for (int i = 0; i < transportAddresses.length; i++) { // this.transportAddresses[i] = SimpleValueFactory.getInstance().createIRI(transportAddresses[i]); // } // } // // public AgentId(final IRI iri, // final IRI[] transportAddresses) { // this.iri = iri; // this.name = nameFromIri(iri); // this.transportAddresses = transportAddresses; // } // // public String getName() { // return name; // } // // public IRI getIri() { // return iri; // } // // public IRI[] getTransportAddresses() { // return transportAddresses; // } // // private static IRI iriFromName(String name) { // // attempt to make the name into an IRI if it isn't one already. // // It is not always possible to pass a valid IRI as an agent identifier. // String iriStr = name; // if (!iriStr.startsWith("http://") && !iriStr.startsWith("urn:")) { // iriStr = "urn:" + iriStr; // } // // return SimpleValueFactory.getInstance().createIRI(iriStr); // } // // private static String nameFromIri(final IRI iri) { // String s = iri.stringValue(); // return s.startsWith("http://") ? s.substring(7) : s.startsWith("urn:") ? s.substring(4) : s; // } // } // // Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/model/RDFAgent.java // public abstract class RDFAgent { // protected final AgentId identity; // // public RDFAgent(final RDFAgentsPlatform platform, // final AgentId id) throws RDFAgentException { // // if (0 == id.getTransportAddresses().length) { // throw new IllegalArgumentException("at least one transport address must be specified"); // } // // identity = id; // } // // public AgentId getIdentity() { // return identity; // } // // public abstract void setQueryProvider(QueryProvider<Value, Dataset> queryProvider); // // public abstract void setPubsubProvider(PubsubProvider<Value, Dataset> pubsubProvider); // // public static class RDFAgentException extends Exception { // public RDFAgentException(final Throwable cause) { // super(cause); // } // } // // // TODO: remove/shutdown method // }
import net.fortytwo.rdfagents.messaging.Commitment; import net.fortytwo.rdfagents.messaging.LocalFailure; import net.fortytwo.rdfagents.messaging.Role; import net.fortytwo.rdfagents.model.AgentId; import net.fortytwo.rdfagents.model.RDFAgent;
package net.fortytwo.rdfagents.messaging.query; /** * The agent role of answering queries posed by other agents. * Query answering in RDFAgents follows FIPA's * <a href="http://www.fipa.org/specs/fipa00027/index.html">Query Interaction Protocol</a>. * For more details, see <a href="http://fortytwo.net/2011/rdfagents/spec#query">the specification</a>. * * @param <Q> a class of queries * @param <A> a class of query answers * * @author Joshua Shinavier (http://fortytwo.net). */ public abstract class QueryProvider<Q, A> extends Role { public QueryProvider(final RDFAgent agent) { super(agent); } /** * @param conversationId the conversation of the query * @param query the query to be answered * @param initiator the requester of the query * @return the commitment of this server towards answering the query */
// Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/messaging/Commitment.java // public class Commitment { // // public enum Decision { // AGREE_AND_NOTIFY, // Query and Subscribe // AGREE_SILENTLY, // Query only // REFUSE // Query and Subscribe // } // // private final Decision decision; // private final ErrorExplanation explanation; // // public Commitment(final Decision decision, // final ErrorExplanation explanation) { // this.decision = decision; // this.explanation = explanation; // } // // public Decision getDecision() { // return decision; // } // // public ErrorExplanation getExplanation() { // return explanation; // } // } // // Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/messaging/LocalFailure.java // public class LocalFailure extends Exception { // public LocalFailure(final Throwable cause) { // super(cause); // } // // public LocalFailure(final String message) { // super(message); // } // } // // Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/messaging/Role.java // public abstract class Role { // protected final RDFAgent agent; // // public Role(final RDFAgent agent) { // this.agent = agent; // } // } // // Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/model/AgentId.java // public class AgentId { // private final String name; // private final IRI iri; // private final IRI[] transportAddresses; // // public AgentId(final String name, // final String... transportAddresses) { // this.name = name; // // this.iri = iriFromName(name); // // this.transportAddresses = new IRI[transportAddresses.length]; // for (int i = 0; i < transportAddresses.length; i++) { // this.transportAddresses[i] = SimpleValueFactory.getInstance().createIRI(transportAddresses[i]); // } // } // // public AgentId(final IRI iri, // final IRI[] transportAddresses) { // this.iri = iri; // this.name = nameFromIri(iri); // this.transportAddresses = transportAddresses; // } // // public String getName() { // return name; // } // // public IRI getIri() { // return iri; // } // // public IRI[] getTransportAddresses() { // return transportAddresses; // } // // private static IRI iriFromName(String name) { // // attempt to make the name into an IRI if it isn't one already. // // It is not always possible to pass a valid IRI as an agent identifier. // String iriStr = name; // if (!iriStr.startsWith("http://") && !iriStr.startsWith("urn:")) { // iriStr = "urn:" + iriStr; // } // // return SimpleValueFactory.getInstance().createIRI(iriStr); // } // // private static String nameFromIri(final IRI iri) { // String s = iri.stringValue(); // return s.startsWith("http://") ? s.substring(7) : s.startsWith("urn:") ? s.substring(4) : s; // } // } // // Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/model/RDFAgent.java // public abstract class RDFAgent { // protected final AgentId identity; // // public RDFAgent(final RDFAgentsPlatform platform, // final AgentId id) throws RDFAgentException { // // if (0 == id.getTransportAddresses().length) { // throw new IllegalArgumentException("at least one transport address must be specified"); // } // // identity = id; // } // // public AgentId getIdentity() { // return identity; // } // // public abstract void setQueryProvider(QueryProvider<Value, Dataset> queryProvider); // // public abstract void setPubsubProvider(PubsubProvider<Value, Dataset> pubsubProvider); // // public static class RDFAgentException extends Exception { // public RDFAgentException(final Throwable cause) { // super(cause); // } // } // // // TODO: remove/shutdown method // } // Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/messaging/query/QueryProvider.java import net.fortytwo.rdfagents.messaging.Commitment; import net.fortytwo.rdfagents.messaging.LocalFailure; import net.fortytwo.rdfagents.messaging.Role; import net.fortytwo.rdfagents.model.AgentId; import net.fortytwo.rdfagents.model.RDFAgent; package net.fortytwo.rdfagents.messaging.query; /** * The agent role of answering queries posed by other agents. * Query answering in RDFAgents follows FIPA's * <a href="http://www.fipa.org/specs/fipa00027/index.html">Query Interaction Protocol</a>. * For more details, see <a href="http://fortytwo.net/2011/rdfagents/spec#query">the specification</a>. * * @param <Q> a class of queries * @param <A> a class of query answers * * @author Joshua Shinavier (http://fortytwo.net). */ public abstract class QueryProvider<Q, A> extends Role { public QueryProvider(final RDFAgent agent) { super(agent); } /** * @param conversationId the conversation of the query * @param query the query to be answered * @param initiator the requester of the query * @return the commitment of this server towards answering the query */
public abstract Commitment considerQueryRequest(String conversationId,
joshsh/rdfagents
rdfagents-core/src/main/java/net/fortytwo/rdfagents/messaging/query/QueryProvider.java
// Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/messaging/Commitment.java // public class Commitment { // // public enum Decision { // AGREE_AND_NOTIFY, // Query and Subscribe // AGREE_SILENTLY, // Query only // REFUSE // Query and Subscribe // } // // private final Decision decision; // private final ErrorExplanation explanation; // // public Commitment(final Decision decision, // final ErrorExplanation explanation) { // this.decision = decision; // this.explanation = explanation; // } // // public Decision getDecision() { // return decision; // } // // public ErrorExplanation getExplanation() { // return explanation; // } // } // // Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/messaging/LocalFailure.java // public class LocalFailure extends Exception { // public LocalFailure(final Throwable cause) { // super(cause); // } // // public LocalFailure(final String message) { // super(message); // } // } // // Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/messaging/Role.java // public abstract class Role { // protected final RDFAgent agent; // // public Role(final RDFAgent agent) { // this.agent = agent; // } // } // // Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/model/AgentId.java // public class AgentId { // private final String name; // private final IRI iri; // private final IRI[] transportAddresses; // // public AgentId(final String name, // final String... transportAddresses) { // this.name = name; // // this.iri = iriFromName(name); // // this.transportAddresses = new IRI[transportAddresses.length]; // for (int i = 0; i < transportAddresses.length; i++) { // this.transportAddresses[i] = SimpleValueFactory.getInstance().createIRI(transportAddresses[i]); // } // } // // public AgentId(final IRI iri, // final IRI[] transportAddresses) { // this.iri = iri; // this.name = nameFromIri(iri); // this.transportAddresses = transportAddresses; // } // // public String getName() { // return name; // } // // public IRI getIri() { // return iri; // } // // public IRI[] getTransportAddresses() { // return transportAddresses; // } // // private static IRI iriFromName(String name) { // // attempt to make the name into an IRI if it isn't one already. // // It is not always possible to pass a valid IRI as an agent identifier. // String iriStr = name; // if (!iriStr.startsWith("http://") && !iriStr.startsWith("urn:")) { // iriStr = "urn:" + iriStr; // } // // return SimpleValueFactory.getInstance().createIRI(iriStr); // } // // private static String nameFromIri(final IRI iri) { // String s = iri.stringValue(); // return s.startsWith("http://") ? s.substring(7) : s.startsWith("urn:") ? s.substring(4) : s; // } // } // // Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/model/RDFAgent.java // public abstract class RDFAgent { // protected final AgentId identity; // // public RDFAgent(final RDFAgentsPlatform platform, // final AgentId id) throws RDFAgentException { // // if (0 == id.getTransportAddresses().length) { // throw new IllegalArgumentException("at least one transport address must be specified"); // } // // identity = id; // } // // public AgentId getIdentity() { // return identity; // } // // public abstract void setQueryProvider(QueryProvider<Value, Dataset> queryProvider); // // public abstract void setPubsubProvider(PubsubProvider<Value, Dataset> pubsubProvider); // // public static class RDFAgentException extends Exception { // public RDFAgentException(final Throwable cause) { // super(cause); // } // } // // // TODO: remove/shutdown method // }
import net.fortytwo.rdfagents.messaging.Commitment; import net.fortytwo.rdfagents.messaging.LocalFailure; import net.fortytwo.rdfagents.messaging.Role; import net.fortytwo.rdfagents.model.AgentId; import net.fortytwo.rdfagents.model.RDFAgent;
package net.fortytwo.rdfagents.messaging.query; /** * The agent role of answering queries posed by other agents. * Query answering in RDFAgents follows FIPA's * <a href="http://www.fipa.org/specs/fipa00027/index.html">Query Interaction Protocol</a>. * For more details, see <a href="http://fortytwo.net/2011/rdfagents/spec#query">the specification</a>. * * @param <Q> a class of queries * @param <A> a class of query answers * * @author Joshua Shinavier (http://fortytwo.net). */ public abstract class QueryProvider<Q, A> extends Role { public QueryProvider(final RDFAgent agent) { super(agent); } /** * @param conversationId the conversation of the query * @param query the query to be answered * @param initiator the requester of the query * @return the commitment of this server towards answering the query */ public abstract Commitment considerQueryRequest(String conversationId, Q query,
// Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/messaging/Commitment.java // public class Commitment { // // public enum Decision { // AGREE_AND_NOTIFY, // Query and Subscribe // AGREE_SILENTLY, // Query only // REFUSE // Query and Subscribe // } // // private final Decision decision; // private final ErrorExplanation explanation; // // public Commitment(final Decision decision, // final ErrorExplanation explanation) { // this.decision = decision; // this.explanation = explanation; // } // // public Decision getDecision() { // return decision; // } // // public ErrorExplanation getExplanation() { // return explanation; // } // } // // Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/messaging/LocalFailure.java // public class LocalFailure extends Exception { // public LocalFailure(final Throwable cause) { // super(cause); // } // // public LocalFailure(final String message) { // super(message); // } // } // // Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/messaging/Role.java // public abstract class Role { // protected final RDFAgent agent; // // public Role(final RDFAgent agent) { // this.agent = agent; // } // } // // Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/model/AgentId.java // public class AgentId { // private final String name; // private final IRI iri; // private final IRI[] transportAddresses; // // public AgentId(final String name, // final String... transportAddresses) { // this.name = name; // // this.iri = iriFromName(name); // // this.transportAddresses = new IRI[transportAddresses.length]; // for (int i = 0; i < transportAddresses.length; i++) { // this.transportAddresses[i] = SimpleValueFactory.getInstance().createIRI(transportAddresses[i]); // } // } // // public AgentId(final IRI iri, // final IRI[] transportAddresses) { // this.iri = iri; // this.name = nameFromIri(iri); // this.transportAddresses = transportAddresses; // } // // public String getName() { // return name; // } // // public IRI getIri() { // return iri; // } // // public IRI[] getTransportAddresses() { // return transportAddresses; // } // // private static IRI iriFromName(String name) { // // attempt to make the name into an IRI if it isn't one already. // // It is not always possible to pass a valid IRI as an agent identifier. // String iriStr = name; // if (!iriStr.startsWith("http://") && !iriStr.startsWith("urn:")) { // iriStr = "urn:" + iriStr; // } // // return SimpleValueFactory.getInstance().createIRI(iriStr); // } // // private static String nameFromIri(final IRI iri) { // String s = iri.stringValue(); // return s.startsWith("http://") ? s.substring(7) : s.startsWith("urn:") ? s.substring(4) : s; // } // } // // Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/model/RDFAgent.java // public abstract class RDFAgent { // protected final AgentId identity; // // public RDFAgent(final RDFAgentsPlatform platform, // final AgentId id) throws RDFAgentException { // // if (0 == id.getTransportAddresses().length) { // throw new IllegalArgumentException("at least one transport address must be specified"); // } // // identity = id; // } // // public AgentId getIdentity() { // return identity; // } // // public abstract void setQueryProvider(QueryProvider<Value, Dataset> queryProvider); // // public abstract void setPubsubProvider(PubsubProvider<Value, Dataset> pubsubProvider); // // public static class RDFAgentException extends Exception { // public RDFAgentException(final Throwable cause) { // super(cause); // } // } // // // TODO: remove/shutdown method // } // Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/messaging/query/QueryProvider.java import net.fortytwo.rdfagents.messaging.Commitment; import net.fortytwo.rdfagents.messaging.LocalFailure; import net.fortytwo.rdfagents.messaging.Role; import net.fortytwo.rdfagents.model.AgentId; import net.fortytwo.rdfagents.model.RDFAgent; package net.fortytwo.rdfagents.messaging.query; /** * The agent role of answering queries posed by other agents. * Query answering in RDFAgents follows FIPA's * <a href="http://www.fipa.org/specs/fipa00027/index.html">Query Interaction Protocol</a>. * For more details, see <a href="http://fortytwo.net/2011/rdfagents/spec#query">the specification</a>. * * @param <Q> a class of queries * @param <A> a class of query answers * * @author Joshua Shinavier (http://fortytwo.net). */ public abstract class QueryProvider<Q, A> extends Role { public QueryProvider(final RDFAgent agent) { super(agent); } /** * @param conversationId the conversation of the query * @param query the query to be answered * @param initiator the requester of the query * @return the commitment of this server towards answering the query */ public abstract Commitment considerQueryRequest(String conversationId, Q query,
AgentId initiator);
joshsh/rdfagents
rdfagents-core/src/main/java/net/fortytwo/rdfagents/messaging/query/QueryProvider.java
// Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/messaging/Commitment.java // public class Commitment { // // public enum Decision { // AGREE_AND_NOTIFY, // Query and Subscribe // AGREE_SILENTLY, // Query only // REFUSE // Query and Subscribe // } // // private final Decision decision; // private final ErrorExplanation explanation; // // public Commitment(final Decision decision, // final ErrorExplanation explanation) { // this.decision = decision; // this.explanation = explanation; // } // // public Decision getDecision() { // return decision; // } // // public ErrorExplanation getExplanation() { // return explanation; // } // } // // Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/messaging/LocalFailure.java // public class LocalFailure extends Exception { // public LocalFailure(final Throwable cause) { // super(cause); // } // // public LocalFailure(final String message) { // super(message); // } // } // // Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/messaging/Role.java // public abstract class Role { // protected final RDFAgent agent; // // public Role(final RDFAgent agent) { // this.agent = agent; // } // } // // Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/model/AgentId.java // public class AgentId { // private final String name; // private final IRI iri; // private final IRI[] transportAddresses; // // public AgentId(final String name, // final String... transportAddresses) { // this.name = name; // // this.iri = iriFromName(name); // // this.transportAddresses = new IRI[transportAddresses.length]; // for (int i = 0; i < transportAddresses.length; i++) { // this.transportAddresses[i] = SimpleValueFactory.getInstance().createIRI(transportAddresses[i]); // } // } // // public AgentId(final IRI iri, // final IRI[] transportAddresses) { // this.iri = iri; // this.name = nameFromIri(iri); // this.transportAddresses = transportAddresses; // } // // public String getName() { // return name; // } // // public IRI getIri() { // return iri; // } // // public IRI[] getTransportAddresses() { // return transportAddresses; // } // // private static IRI iriFromName(String name) { // // attempt to make the name into an IRI if it isn't one already. // // It is not always possible to pass a valid IRI as an agent identifier. // String iriStr = name; // if (!iriStr.startsWith("http://") && !iriStr.startsWith("urn:")) { // iriStr = "urn:" + iriStr; // } // // return SimpleValueFactory.getInstance().createIRI(iriStr); // } // // private static String nameFromIri(final IRI iri) { // String s = iri.stringValue(); // return s.startsWith("http://") ? s.substring(7) : s.startsWith("urn:") ? s.substring(4) : s; // } // } // // Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/model/RDFAgent.java // public abstract class RDFAgent { // protected final AgentId identity; // // public RDFAgent(final RDFAgentsPlatform platform, // final AgentId id) throws RDFAgentException { // // if (0 == id.getTransportAddresses().length) { // throw new IllegalArgumentException("at least one transport address must be specified"); // } // // identity = id; // } // // public AgentId getIdentity() { // return identity; // } // // public abstract void setQueryProvider(QueryProvider<Value, Dataset> queryProvider); // // public abstract void setPubsubProvider(PubsubProvider<Value, Dataset> pubsubProvider); // // public static class RDFAgentException extends Exception { // public RDFAgentException(final Throwable cause) { // super(cause); // } // } // // // TODO: remove/shutdown method // }
import net.fortytwo.rdfagents.messaging.Commitment; import net.fortytwo.rdfagents.messaging.LocalFailure; import net.fortytwo.rdfagents.messaging.Role; import net.fortytwo.rdfagents.model.AgentId; import net.fortytwo.rdfagents.model.RDFAgent;
package net.fortytwo.rdfagents.messaging.query; /** * The agent role of answering queries posed by other agents. * Query answering in RDFAgents follows FIPA's * <a href="http://www.fipa.org/specs/fipa00027/index.html">Query Interaction Protocol</a>. * For more details, see <a href="http://fortytwo.net/2011/rdfagents/spec#query">the specification</a>. * * @param <Q> a class of queries * @param <A> a class of query answers * * @author Joshua Shinavier (http://fortytwo.net). */ public abstract class QueryProvider<Q, A> extends Role { public QueryProvider(final RDFAgent agent) { super(agent); } /** * @param conversationId the conversation of the query * @param query the query to be answered * @param initiator the requester of the query * @return the commitment of this server towards answering the query */ public abstract Commitment considerQueryRequest(String conversationId, Q query, AgentId initiator); /** * Evaluate a query to produce a result. * While the query request has previously been accepted or refused based on the identity of the initiator, * the actual query is answered independently of the initiator. * * @param query the query to answer * @return the answer to the query * @throws LocalFailure if query answering fails */
// Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/messaging/Commitment.java // public class Commitment { // // public enum Decision { // AGREE_AND_NOTIFY, // Query and Subscribe // AGREE_SILENTLY, // Query only // REFUSE // Query and Subscribe // } // // private final Decision decision; // private final ErrorExplanation explanation; // // public Commitment(final Decision decision, // final ErrorExplanation explanation) { // this.decision = decision; // this.explanation = explanation; // } // // public Decision getDecision() { // return decision; // } // // public ErrorExplanation getExplanation() { // return explanation; // } // } // // Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/messaging/LocalFailure.java // public class LocalFailure extends Exception { // public LocalFailure(final Throwable cause) { // super(cause); // } // // public LocalFailure(final String message) { // super(message); // } // } // // Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/messaging/Role.java // public abstract class Role { // protected final RDFAgent agent; // // public Role(final RDFAgent agent) { // this.agent = agent; // } // } // // Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/model/AgentId.java // public class AgentId { // private final String name; // private final IRI iri; // private final IRI[] transportAddresses; // // public AgentId(final String name, // final String... transportAddresses) { // this.name = name; // // this.iri = iriFromName(name); // // this.transportAddresses = new IRI[transportAddresses.length]; // for (int i = 0; i < transportAddresses.length; i++) { // this.transportAddresses[i] = SimpleValueFactory.getInstance().createIRI(transportAddresses[i]); // } // } // // public AgentId(final IRI iri, // final IRI[] transportAddresses) { // this.iri = iri; // this.name = nameFromIri(iri); // this.transportAddresses = transportAddresses; // } // // public String getName() { // return name; // } // // public IRI getIri() { // return iri; // } // // public IRI[] getTransportAddresses() { // return transportAddresses; // } // // private static IRI iriFromName(String name) { // // attempt to make the name into an IRI if it isn't one already. // // It is not always possible to pass a valid IRI as an agent identifier. // String iriStr = name; // if (!iriStr.startsWith("http://") && !iriStr.startsWith("urn:")) { // iriStr = "urn:" + iriStr; // } // // return SimpleValueFactory.getInstance().createIRI(iriStr); // } // // private static String nameFromIri(final IRI iri) { // String s = iri.stringValue(); // return s.startsWith("http://") ? s.substring(7) : s.startsWith("urn:") ? s.substring(4) : s; // } // } // // Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/model/RDFAgent.java // public abstract class RDFAgent { // protected final AgentId identity; // // public RDFAgent(final RDFAgentsPlatform platform, // final AgentId id) throws RDFAgentException { // // if (0 == id.getTransportAddresses().length) { // throw new IllegalArgumentException("at least one transport address must be specified"); // } // // identity = id; // } // // public AgentId getIdentity() { // return identity; // } // // public abstract void setQueryProvider(QueryProvider<Value, Dataset> queryProvider); // // public abstract void setPubsubProvider(PubsubProvider<Value, Dataset> pubsubProvider); // // public static class RDFAgentException extends Exception { // public RDFAgentException(final Throwable cause) { // super(cause); // } // } // // // TODO: remove/shutdown method // } // Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/messaging/query/QueryProvider.java import net.fortytwo.rdfagents.messaging.Commitment; import net.fortytwo.rdfagents.messaging.LocalFailure; import net.fortytwo.rdfagents.messaging.Role; import net.fortytwo.rdfagents.model.AgentId; import net.fortytwo.rdfagents.model.RDFAgent; package net.fortytwo.rdfagents.messaging.query; /** * The agent role of answering queries posed by other agents. * Query answering in RDFAgents follows FIPA's * <a href="http://www.fipa.org/specs/fipa00027/index.html">Query Interaction Protocol</a>. * For more details, see <a href="http://fortytwo.net/2011/rdfagents/spec#query">the specification</a>. * * @param <Q> a class of queries * @param <A> a class of query answers * * @author Joshua Shinavier (http://fortytwo.net). */ public abstract class QueryProvider<Q, A> extends Role { public QueryProvider(final RDFAgent agent) { super(agent); } /** * @param conversationId the conversation of the query * @param query the query to be answered * @param initiator the requester of the query * @return the commitment of this server towards answering the query */ public abstract Commitment considerQueryRequest(String conversationId, Q query, AgentId initiator); /** * Evaluate a query to produce a result. * While the query request has previously been accepted or refused based on the identity of the initiator, * the actual query is answered independently of the initiator. * * @param query the query to answer * @return the answer to the query * @throws LocalFailure if query answering fails */
public abstract A answer(Q query) throws LocalFailure;
joshsh/rdfagents
rdfagents-core/src/main/java/net/fortytwo/rdfagents/messaging/subscribe/old/SubscriberOld.java
// Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/messaging/Role.java // public abstract class Role { // protected final RDFAgent agent; // // public Role(final RDFAgent agent) { // this.agent = agent; // } // } // // Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/model/ErrorExplanation.java // public class ErrorExplanation { // private final Type type; // private final String message; // // public enum Type { // ExternalError("external-error"), // InteractionExplired("interaction-expired"), // InternalError("internal-error"), // InvalidMessage("invalid-message"), // NotImplemented("not-implemented"), // Unavailable("unavailable"); // // private final String fipaName; // // private Type(final String fipaName) { // this.fipaName = fipaName; // } // // public String getFipaName() { // return fipaName; // } // // public static Type getByFipaName(final String fipaName) { // for (Type t : values()) { // if (t.fipaName.equals(fipaName)) { // return t; // } // } // // return null; // } // } // // public ErrorExplanation(final Type type, // final String message) { // this.type = type; // this.message = message; // // if (null == type) { // throw new IllegalArgumentException("null type"); // } // // if (null == message) { // throw new IllegalArgumentException("null message"); // } // // if (0 == message.length()) { // throw new IllegalArgumentException("empty message"); // } // } // // public Type getType() { // return type; // } // // public String getMessage() { // return message; // } // // public String toString() { // return type + " (" + message + ")"; // } // } // // Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/model/RDFAgent.java // public abstract class RDFAgent { // protected final AgentId identity; // // public RDFAgent(final RDFAgentsPlatform platform, // final AgentId id) throws RDFAgentException { // // if (0 == id.getTransportAddresses().length) { // throw new IllegalArgumentException("at least one transport address must be specified"); // } // // identity = id; // } // // public AgentId getIdentity() { // return identity; // } // // public abstract void setQueryProvider(QueryProvider<Value, Dataset> queryProvider); // // public abstract void setPubsubProvider(PubsubProvider<Value, Dataset> pubsubProvider); // // public static class RDFAgentException extends Exception { // public RDFAgentException(final Throwable cause) { // super(cause); // } // } // // // TODO: remove/shutdown method // }
import net.fortytwo.rdfagents.messaging.Role; import net.fortytwo.rdfagents.model.ErrorExplanation; import net.fortytwo.rdfagents.model.RDFAgent;
package net.fortytwo.rdfagents.messaging.subscribe.old; /** * An agent role for subscribing to streams of updates from other agents. * Subscriptions in RDFAgents follow FIPA's * <a href="http://www.fipa.org/specs/fipa00035/SC00035H.html">Subscribe Interaction Protocol</a>. * For more details, see <a href="http://fortytwo.net/2011/rdfagents/spec#pubsub">the specification</a>. * * @author Joshua Shinavier (http://fortytwo.net) */ public abstract class SubscriberOld<Q, A> extends Role { public SubscriberOld(final RDFAgent client) { super(client); } /** * Submits a query to a remote agent, initiating a new query interaction. * * @param request the query request the be submitted * @param callback a handler for all possible outcomes of the query request. * Note: its methods typically execute in a thread other than the calling thread. */ public abstract void submit(SubscribeRequestOld<Q> request, QueryCallback<A> callback); /** * Submits a cancellation request for a previously submitted query. * * @param request the previously submitted query request to be cancelled * @param callback a handler for all possible outcomes of the cancellation request. * Note: its methods typically execute in a thread other than the calling thread. */ public abstract void cancel(SubscribeRequestOld<Q> request, CancellationCallback callback); /** * A handler for all possible outcomes of a query request. * * @param <A> a class of query answers */ public interface QueryCallback<A> { /** * Indicates success of the query request and provides the query answer. * * @param answer the answer to the submitted query */ void success(A answer); /** * Indicates that the remote participant has agreed to answer the query. */ void agreed(); /** * Indicates that the remote participant has refused to answer the query. * * @param explanation an explanation of the refusal, provided by the remote participant */
// Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/messaging/Role.java // public abstract class Role { // protected final RDFAgent agent; // // public Role(final RDFAgent agent) { // this.agent = agent; // } // } // // Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/model/ErrorExplanation.java // public class ErrorExplanation { // private final Type type; // private final String message; // // public enum Type { // ExternalError("external-error"), // InteractionExplired("interaction-expired"), // InternalError("internal-error"), // InvalidMessage("invalid-message"), // NotImplemented("not-implemented"), // Unavailable("unavailable"); // // private final String fipaName; // // private Type(final String fipaName) { // this.fipaName = fipaName; // } // // public String getFipaName() { // return fipaName; // } // // public static Type getByFipaName(final String fipaName) { // for (Type t : values()) { // if (t.fipaName.equals(fipaName)) { // return t; // } // } // // return null; // } // } // // public ErrorExplanation(final Type type, // final String message) { // this.type = type; // this.message = message; // // if (null == type) { // throw new IllegalArgumentException("null type"); // } // // if (null == message) { // throw new IllegalArgumentException("null message"); // } // // if (0 == message.length()) { // throw new IllegalArgumentException("empty message"); // } // } // // public Type getType() { // return type; // } // // public String getMessage() { // return message; // } // // public String toString() { // return type + " (" + message + ")"; // } // } // // Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/model/RDFAgent.java // public abstract class RDFAgent { // protected final AgentId identity; // // public RDFAgent(final RDFAgentsPlatform platform, // final AgentId id) throws RDFAgentException { // // if (0 == id.getTransportAddresses().length) { // throw new IllegalArgumentException("at least one transport address must be specified"); // } // // identity = id; // } // // public AgentId getIdentity() { // return identity; // } // // public abstract void setQueryProvider(QueryProvider<Value, Dataset> queryProvider); // // public abstract void setPubsubProvider(PubsubProvider<Value, Dataset> pubsubProvider); // // public static class RDFAgentException extends Exception { // public RDFAgentException(final Throwable cause) { // super(cause); // } // } // // // TODO: remove/shutdown method // } // Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/messaging/subscribe/old/SubscriberOld.java import net.fortytwo.rdfagents.messaging.Role; import net.fortytwo.rdfagents.model.ErrorExplanation; import net.fortytwo.rdfagents.model.RDFAgent; package net.fortytwo.rdfagents.messaging.subscribe.old; /** * An agent role for subscribing to streams of updates from other agents. * Subscriptions in RDFAgents follow FIPA's * <a href="http://www.fipa.org/specs/fipa00035/SC00035H.html">Subscribe Interaction Protocol</a>. * For more details, see <a href="http://fortytwo.net/2011/rdfagents/spec#pubsub">the specification</a>. * * @author Joshua Shinavier (http://fortytwo.net) */ public abstract class SubscriberOld<Q, A> extends Role { public SubscriberOld(final RDFAgent client) { super(client); } /** * Submits a query to a remote agent, initiating a new query interaction. * * @param request the query request the be submitted * @param callback a handler for all possible outcomes of the query request. * Note: its methods typically execute in a thread other than the calling thread. */ public abstract void submit(SubscribeRequestOld<Q> request, QueryCallback<A> callback); /** * Submits a cancellation request for a previously submitted query. * * @param request the previously submitted query request to be cancelled * @param callback a handler for all possible outcomes of the cancellation request. * Note: its methods typically execute in a thread other than the calling thread. */ public abstract void cancel(SubscribeRequestOld<Q> request, CancellationCallback callback); /** * A handler for all possible outcomes of a query request. * * @param <A> a class of query answers */ public interface QueryCallback<A> { /** * Indicates success of the query request and provides the query answer. * * @param answer the answer to the submitted query */ void success(A answer); /** * Indicates that the remote participant has agreed to answer the query. */ void agreed(); /** * Indicates that the remote participant has refused to answer the query. * * @param explanation an explanation of the refusal, provided by the remote participant */
void refused(ErrorExplanation explanation);
joshsh/rdfagents
rdfagents-core/src/main/java/net/fortytwo/rdfagents/messaging/ConsumerCallback.java
// Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/model/ErrorExplanation.java // public class ErrorExplanation { // private final Type type; // private final String message; // // public enum Type { // ExternalError("external-error"), // InteractionExplired("interaction-expired"), // InternalError("internal-error"), // InvalidMessage("invalid-message"), // NotImplemented("not-implemented"), // Unavailable("unavailable"); // // private final String fipaName; // // private Type(final String fipaName) { // this.fipaName = fipaName; // } // // public String getFipaName() { // return fipaName; // } // // public static Type getByFipaName(final String fipaName) { // for (Type t : values()) { // if (t.fipaName.equals(fipaName)) { // return t; // } // } // // return null; // } // } // // public ErrorExplanation(final Type type, // final String message) { // this.type = type; // this.message = message; // // if (null == type) { // throw new IllegalArgumentException("null type"); // } // // if (null == message) { // throw new IllegalArgumentException("null message"); // } // // if (0 == message.length()) { // throw new IllegalArgumentException("empty message"); // } // } // // public Type getType() { // return type; // } // // public String getMessage() { // return message; // } // // public String toString() { // return type + " (" + message + ")"; // } // }
import net.fortytwo.rdfagents.model.ErrorExplanation;
package net.fortytwo.rdfagents.messaging; /** * A handler for all possible outcomes of a query request. * * @param <A> a class of query answers * * @author Joshua Shinavier (http://fortytwo.net) */ public interface ConsumerCallback<A> { /** * Indicates success of the query request and provides the query answer. * * @param answer the answer to the submitted query */ void success(A answer); /** * Indicates that the remote participant has agreed to answer the query. */ void agreed(); /** * Indicates that the remote participant has refused to answer the query. * * @param explanation an explanation of the refusal, provided by the remote participant */
// Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/model/ErrorExplanation.java // public class ErrorExplanation { // private final Type type; // private final String message; // // public enum Type { // ExternalError("external-error"), // InteractionExplired("interaction-expired"), // InternalError("internal-error"), // InvalidMessage("invalid-message"), // NotImplemented("not-implemented"), // Unavailable("unavailable"); // // private final String fipaName; // // private Type(final String fipaName) { // this.fipaName = fipaName; // } // // public String getFipaName() { // return fipaName; // } // // public static Type getByFipaName(final String fipaName) { // for (Type t : values()) { // if (t.fipaName.equals(fipaName)) { // return t; // } // } // // return null; // } // } // // public ErrorExplanation(final Type type, // final String message) { // this.type = type; // this.message = message; // // if (null == type) { // throw new IllegalArgumentException("null type"); // } // // if (null == message) { // throw new IllegalArgumentException("null message"); // } // // if (0 == message.length()) { // throw new IllegalArgumentException("empty message"); // } // } // // public Type getType() { // return type; // } // // public String getMessage() { // return message; // } // // public String toString() { // return type + " (" + message + ")"; // } // } // Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/messaging/ConsumerCallback.java import net.fortytwo.rdfagents.model.ErrorExplanation; package net.fortytwo.rdfagents.messaging; /** * A handler for all possible outcomes of a query request. * * @param <A> a class of query answers * * @author Joshua Shinavier (http://fortytwo.net) */ public interface ConsumerCallback<A> { /** * Indicates success of the query request and provides the query answer. * * @param answer the answer to the submitted query */ void success(A answer); /** * Indicates that the remote participant has agreed to answer the query. */ void agreed(); /** * Indicates that the remote participant has refused to answer the query. * * @param explanation an explanation of the refusal, provided by the remote participant */
void refused(ErrorExplanation explanation);
joshsh/rdfagents
rdfagents-jade/src/main/java/net/fortytwo/rdfagents/jade/RDFAgentsOntology.java
// Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/RDFAgents.java // public class RDFAgents { // private static final Logger logger = Logger.getLogger(RDFAgents.class.getName()); // // // Agent profile properties // public static final String // QUERY_ANSWERING_SUPPORTED = "behavior.query.answer.supported", // QUERY_ASKING_SUPPORTED = "behavior.query.ask.supported"; // // public static final String // // TODO // BASE_IRI = "http://example.org/", // RDFAGENTS_ONTOLOGY_NAME = "rdfagents", // RDFAGENTS_ACCEPT_PARAMETER = "X-rdfagents-accept"; // // public static final String NAME_PREFIX = "urn:x-agent:"; // public static final String XMPP_URI_PREFIX = "xmpp://"; // // public enum Protocol { // Query("fipa-query"), Subscribe("fipa-subscribe"); // // private final String fipaName; // // private Protocol(final String fipaName) { // this.fipaName = fipaName; // } // // public String getFipaName() { // return fipaName; // } // // public static Protocol getByName(final String name) { // for (Protocol l : Protocol.values()) { // if (l.fipaName.equals(name)) { // return l; // } // } // // return null; // } // } // // private RDFAgents() { // } // // public static boolean isValidIRI(final String iri) { // // TODO: make this more efficient, and base it on the IRI spec // try { // createIRI(iri); // return true; // } catch (Exception t) { // return false; // } // } // // public static IRI createIRI(String iri) { // return SimpleValueFactory.getInstance().createIRI(iri); // } // // public static Literal createLiteral(String iri) { // return SimpleValueFactory.getInstance().createLiteral(iri); // } // // public static Statement createStatement(Resource subject, IRI predicate, Value object) { // return SimpleValueFactory.getInstance().createStatement(subject, predicate, object); // } // } // // Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/model/ErrorExplanation.java // public class ErrorExplanation { // private final Type type; // private final String message; // // public enum Type { // ExternalError("external-error"), // InteractionExplired("interaction-expired"), // InternalError("internal-error"), // InvalidMessage("invalid-message"), // NotImplemented("not-implemented"), // Unavailable("unavailable"); // // private final String fipaName; // // private Type(final String fipaName) { // this.fipaName = fipaName; // } // // public String getFipaName() { // return fipaName; // } // // public static Type getByFipaName(final String fipaName) { // for (Type t : values()) { // if (t.fipaName.equals(fipaName)) { // return t; // } // } // // return null; // } // } // // public ErrorExplanation(final Type type, // final String message) { // this.type = type; // this.message = message; // // if (null == type) { // throw new IllegalArgumentException("null type"); // } // // if (null == message) { // throw new IllegalArgumentException("null message"); // } // // if (0 == message.length()) { // throw new IllegalArgumentException("empty message"); // } // } // // public Type getType() { // return type; // } // // public String getMessage() { // return message; // } // // public String toString() { // return type + " (" + message + ")"; // } // }
import jade.content.lang.sl.SLOntology; import jade.content.onto.BasicOntology; import jade.content.onto.Ontology; import jade.content.onto.OntologyException; import jade.content.schema.ConceptSchema; import jade.content.schema.ObjectSchema; import jade.content.schema.PredicateSchema; import jade.content.schema.PrimitiveSchema; import net.fortytwo.rdfagents.RDFAgents; import net.fortytwo.rdfagents.model.ErrorExplanation;
package net.fortytwo.rdfagents.jade; /** * @author Joshua Shinavier (http://fortytwo.net) */ public class RDFAgentsOntology extends Ontology { private static final RDFAgentsOntology INSTANCE; static { try { INSTANCE = new RDFAgentsOntology(); } catch (OntologyException e) { throw new ExceptionInInitializerError(e); } } public static final String DATASET = "dataset", // implicit (used only as a variable) DESCRIBES = "describes", DESCRIBES_DATASET = "dataset", // implicit (unnamed parameter) DESCRIBES_SUBJECT = "subject", // implicit (unnamed parameter) EXPLANATION = "explanation", // implicit (abstract class) -- specific errors are in ErrorExplanation EXPLANATION_MESSAGE = "message", LITERAL = "literal", LITERAL_DATATYPE = "datatype", LITERAL_LANGUAGE = "language", LITERAL_LABEL = "label", VALUE = "value", // implicit (abstract class) RESOURCE = "resource", RESOURCE_IRI = "iri"; private RDFAgentsOntology() throws OntologyException {
// Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/RDFAgents.java // public class RDFAgents { // private static final Logger logger = Logger.getLogger(RDFAgents.class.getName()); // // // Agent profile properties // public static final String // QUERY_ANSWERING_SUPPORTED = "behavior.query.answer.supported", // QUERY_ASKING_SUPPORTED = "behavior.query.ask.supported"; // // public static final String // // TODO // BASE_IRI = "http://example.org/", // RDFAGENTS_ONTOLOGY_NAME = "rdfagents", // RDFAGENTS_ACCEPT_PARAMETER = "X-rdfagents-accept"; // // public static final String NAME_PREFIX = "urn:x-agent:"; // public static final String XMPP_URI_PREFIX = "xmpp://"; // // public enum Protocol { // Query("fipa-query"), Subscribe("fipa-subscribe"); // // private final String fipaName; // // private Protocol(final String fipaName) { // this.fipaName = fipaName; // } // // public String getFipaName() { // return fipaName; // } // // public static Protocol getByName(final String name) { // for (Protocol l : Protocol.values()) { // if (l.fipaName.equals(name)) { // return l; // } // } // // return null; // } // } // // private RDFAgents() { // } // // public static boolean isValidIRI(final String iri) { // // TODO: make this more efficient, and base it on the IRI spec // try { // createIRI(iri); // return true; // } catch (Exception t) { // return false; // } // } // // public static IRI createIRI(String iri) { // return SimpleValueFactory.getInstance().createIRI(iri); // } // // public static Literal createLiteral(String iri) { // return SimpleValueFactory.getInstance().createLiteral(iri); // } // // public static Statement createStatement(Resource subject, IRI predicate, Value object) { // return SimpleValueFactory.getInstance().createStatement(subject, predicate, object); // } // } // // Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/model/ErrorExplanation.java // public class ErrorExplanation { // private final Type type; // private final String message; // // public enum Type { // ExternalError("external-error"), // InteractionExplired("interaction-expired"), // InternalError("internal-error"), // InvalidMessage("invalid-message"), // NotImplemented("not-implemented"), // Unavailable("unavailable"); // // private final String fipaName; // // private Type(final String fipaName) { // this.fipaName = fipaName; // } // // public String getFipaName() { // return fipaName; // } // // public static Type getByFipaName(final String fipaName) { // for (Type t : values()) { // if (t.fipaName.equals(fipaName)) { // return t; // } // } // // return null; // } // } // // public ErrorExplanation(final Type type, // final String message) { // this.type = type; // this.message = message; // // if (null == type) { // throw new IllegalArgumentException("null type"); // } // // if (null == message) { // throw new IllegalArgumentException("null message"); // } // // if (0 == message.length()) { // throw new IllegalArgumentException("empty message"); // } // } // // public Type getType() { // return type; // } // // public String getMessage() { // return message; // } // // public String toString() { // return type + " (" + message + ")"; // } // } // Path: rdfagents-jade/src/main/java/net/fortytwo/rdfagents/jade/RDFAgentsOntology.java import jade.content.lang.sl.SLOntology; import jade.content.onto.BasicOntology; import jade.content.onto.Ontology; import jade.content.onto.OntologyException; import jade.content.schema.ConceptSchema; import jade.content.schema.ObjectSchema; import jade.content.schema.PredicateSchema; import jade.content.schema.PrimitiveSchema; import net.fortytwo.rdfagents.RDFAgents; import net.fortytwo.rdfagents.model.ErrorExplanation; package net.fortytwo.rdfagents.jade; /** * @author Joshua Shinavier (http://fortytwo.net) */ public class RDFAgentsOntology extends Ontology { private static final RDFAgentsOntology INSTANCE; static { try { INSTANCE = new RDFAgentsOntology(); } catch (OntologyException e) { throw new ExceptionInInitializerError(e); } } public static final String DATASET = "dataset", // implicit (used only as a variable) DESCRIBES = "describes", DESCRIBES_DATASET = "dataset", // implicit (unnamed parameter) DESCRIBES_SUBJECT = "subject", // implicit (unnamed parameter) EXPLANATION = "explanation", // implicit (abstract class) -- specific errors are in ErrorExplanation EXPLANATION_MESSAGE = "message", LITERAL = "literal", LITERAL_DATATYPE = "datatype", LITERAL_LANGUAGE = "language", LITERAL_LABEL = "label", VALUE = "value", // implicit (abstract class) RESOURCE = "resource", RESOURCE_IRI = "iri"; private RDFAgentsOntology() throws OntologyException {
super(RDFAgents.RDFAGENTS_ONTOLOGY_NAME, SLOntology.getInstance());
joshsh/rdfagents
rdfagents-jade/src/main/java/net/fortytwo/rdfagents/jade/RDFAgentsOntology.java
// Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/RDFAgents.java // public class RDFAgents { // private static final Logger logger = Logger.getLogger(RDFAgents.class.getName()); // // // Agent profile properties // public static final String // QUERY_ANSWERING_SUPPORTED = "behavior.query.answer.supported", // QUERY_ASKING_SUPPORTED = "behavior.query.ask.supported"; // // public static final String // // TODO // BASE_IRI = "http://example.org/", // RDFAGENTS_ONTOLOGY_NAME = "rdfagents", // RDFAGENTS_ACCEPT_PARAMETER = "X-rdfagents-accept"; // // public static final String NAME_PREFIX = "urn:x-agent:"; // public static final String XMPP_URI_PREFIX = "xmpp://"; // // public enum Protocol { // Query("fipa-query"), Subscribe("fipa-subscribe"); // // private final String fipaName; // // private Protocol(final String fipaName) { // this.fipaName = fipaName; // } // // public String getFipaName() { // return fipaName; // } // // public static Protocol getByName(final String name) { // for (Protocol l : Protocol.values()) { // if (l.fipaName.equals(name)) { // return l; // } // } // // return null; // } // } // // private RDFAgents() { // } // // public static boolean isValidIRI(final String iri) { // // TODO: make this more efficient, and base it on the IRI spec // try { // createIRI(iri); // return true; // } catch (Exception t) { // return false; // } // } // // public static IRI createIRI(String iri) { // return SimpleValueFactory.getInstance().createIRI(iri); // } // // public static Literal createLiteral(String iri) { // return SimpleValueFactory.getInstance().createLiteral(iri); // } // // public static Statement createStatement(Resource subject, IRI predicate, Value object) { // return SimpleValueFactory.getInstance().createStatement(subject, predicate, object); // } // } // // Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/model/ErrorExplanation.java // public class ErrorExplanation { // private final Type type; // private final String message; // // public enum Type { // ExternalError("external-error"), // InteractionExplired("interaction-expired"), // InternalError("internal-error"), // InvalidMessage("invalid-message"), // NotImplemented("not-implemented"), // Unavailable("unavailable"); // // private final String fipaName; // // private Type(final String fipaName) { // this.fipaName = fipaName; // } // // public String getFipaName() { // return fipaName; // } // // public static Type getByFipaName(final String fipaName) { // for (Type t : values()) { // if (t.fipaName.equals(fipaName)) { // return t; // } // } // // return null; // } // } // // public ErrorExplanation(final Type type, // final String message) { // this.type = type; // this.message = message; // // if (null == type) { // throw new IllegalArgumentException("null type"); // } // // if (null == message) { // throw new IllegalArgumentException("null message"); // } // // if (0 == message.length()) { // throw new IllegalArgumentException("empty message"); // } // } // // public Type getType() { // return type; // } // // public String getMessage() { // return message; // } // // public String toString() { // return type + " (" + message + ")"; // } // }
import jade.content.lang.sl.SLOntology; import jade.content.onto.BasicOntology; import jade.content.onto.Ontology; import jade.content.onto.OntologyException; import jade.content.schema.ConceptSchema; import jade.content.schema.ObjectSchema; import jade.content.schema.PredicateSchema; import jade.content.schema.PrimitiveSchema; import net.fortytwo.rdfagents.RDFAgents; import net.fortytwo.rdfagents.model.ErrorExplanation;
throw new ExceptionInInitializerError(e); } } public static final String DATASET = "dataset", // implicit (used only as a variable) DESCRIBES = "describes", DESCRIBES_DATASET = "dataset", // implicit (unnamed parameter) DESCRIBES_SUBJECT = "subject", // implicit (unnamed parameter) EXPLANATION = "explanation", // implicit (abstract class) -- specific errors are in ErrorExplanation EXPLANATION_MESSAGE = "message", LITERAL = "literal", LITERAL_DATATYPE = "datatype", LITERAL_LANGUAGE = "language", LITERAL_LABEL = "label", VALUE = "value", // implicit (abstract class) RESOURCE = "resource", RESOURCE_IRI = "iri"; private RDFAgentsOntology() throws OntologyException { super(RDFAgents.RDFAGENTS_ONTOLOGY_NAME, SLOntology.getInstance()); add(new PredicateSchema(DESCRIBES)); add(new ConceptSchema(DATASET)); add(new ConceptSchema(VALUE)); add(new ConceptSchema(RESOURCE)); add(new ConceptSchema(LITERAL)); add(new PredicateSchema(EXPLANATION));
// Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/RDFAgents.java // public class RDFAgents { // private static final Logger logger = Logger.getLogger(RDFAgents.class.getName()); // // // Agent profile properties // public static final String // QUERY_ANSWERING_SUPPORTED = "behavior.query.answer.supported", // QUERY_ASKING_SUPPORTED = "behavior.query.ask.supported"; // // public static final String // // TODO // BASE_IRI = "http://example.org/", // RDFAGENTS_ONTOLOGY_NAME = "rdfagents", // RDFAGENTS_ACCEPT_PARAMETER = "X-rdfagents-accept"; // // public static final String NAME_PREFIX = "urn:x-agent:"; // public static final String XMPP_URI_PREFIX = "xmpp://"; // // public enum Protocol { // Query("fipa-query"), Subscribe("fipa-subscribe"); // // private final String fipaName; // // private Protocol(final String fipaName) { // this.fipaName = fipaName; // } // // public String getFipaName() { // return fipaName; // } // // public static Protocol getByName(final String name) { // for (Protocol l : Protocol.values()) { // if (l.fipaName.equals(name)) { // return l; // } // } // // return null; // } // } // // private RDFAgents() { // } // // public static boolean isValidIRI(final String iri) { // // TODO: make this more efficient, and base it on the IRI spec // try { // createIRI(iri); // return true; // } catch (Exception t) { // return false; // } // } // // public static IRI createIRI(String iri) { // return SimpleValueFactory.getInstance().createIRI(iri); // } // // public static Literal createLiteral(String iri) { // return SimpleValueFactory.getInstance().createLiteral(iri); // } // // public static Statement createStatement(Resource subject, IRI predicate, Value object) { // return SimpleValueFactory.getInstance().createStatement(subject, predicate, object); // } // } // // Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/model/ErrorExplanation.java // public class ErrorExplanation { // private final Type type; // private final String message; // // public enum Type { // ExternalError("external-error"), // InteractionExplired("interaction-expired"), // InternalError("internal-error"), // InvalidMessage("invalid-message"), // NotImplemented("not-implemented"), // Unavailable("unavailable"); // // private final String fipaName; // // private Type(final String fipaName) { // this.fipaName = fipaName; // } // // public String getFipaName() { // return fipaName; // } // // public static Type getByFipaName(final String fipaName) { // for (Type t : values()) { // if (t.fipaName.equals(fipaName)) { // return t; // } // } // // return null; // } // } // // public ErrorExplanation(final Type type, // final String message) { // this.type = type; // this.message = message; // // if (null == type) { // throw new IllegalArgumentException("null type"); // } // // if (null == message) { // throw new IllegalArgumentException("null message"); // } // // if (0 == message.length()) { // throw new IllegalArgumentException("empty message"); // } // } // // public Type getType() { // return type; // } // // public String getMessage() { // return message; // } // // public String toString() { // return type + " (" + message + ")"; // } // } // Path: rdfagents-jade/src/main/java/net/fortytwo/rdfagents/jade/RDFAgentsOntology.java import jade.content.lang.sl.SLOntology; import jade.content.onto.BasicOntology; import jade.content.onto.Ontology; import jade.content.onto.OntologyException; import jade.content.schema.ConceptSchema; import jade.content.schema.ObjectSchema; import jade.content.schema.PredicateSchema; import jade.content.schema.PrimitiveSchema; import net.fortytwo.rdfagents.RDFAgents; import net.fortytwo.rdfagents.model.ErrorExplanation; throw new ExceptionInInitializerError(e); } } public static final String DATASET = "dataset", // implicit (used only as a variable) DESCRIBES = "describes", DESCRIBES_DATASET = "dataset", // implicit (unnamed parameter) DESCRIBES_SUBJECT = "subject", // implicit (unnamed parameter) EXPLANATION = "explanation", // implicit (abstract class) -- specific errors are in ErrorExplanation EXPLANATION_MESSAGE = "message", LITERAL = "literal", LITERAL_DATATYPE = "datatype", LITERAL_LANGUAGE = "language", LITERAL_LABEL = "label", VALUE = "value", // implicit (abstract class) RESOURCE = "resource", RESOURCE_IRI = "iri"; private RDFAgentsOntology() throws OntologyException { super(RDFAgents.RDFAGENTS_ONTOLOGY_NAME, SLOntology.getInstance()); add(new PredicateSchema(DESCRIBES)); add(new ConceptSchema(DATASET)); add(new ConceptSchema(VALUE)); add(new ConceptSchema(RESOURCE)); add(new ConceptSchema(LITERAL)); add(new PredicateSchema(EXPLANATION));
for (ErrorExplanation.Type x : ErrorExplanation.Type.values()) {
joshsh/rdfagents
rdfagents-core/src/main/java/net/fortytwo/rdfagents/messaging/subscribe/PubsubProvider.java
// Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/messaging/Commitment.java // public class Commitment { // // public enum Decision { // AGREE_AND_NOTIFY, // Query and Subscribe // AGREE_SILENTLY, // Query only // REFUSE // Query and Subscribe // } // // private final Decision decision; // private final ErrorExplanation explanation; // // public Commitment(final Decision decision, // final ErrorExplanation explanation) { // this.decision = decision; // this.explanation = explanation; // } // // public Decision getDecision() { // return decision; // } // // public ErrorExplanation getExplanation() { // return explanation; // } // } // // Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/messaging/LocalFailure.java // public class LocalFailure extends Exception { // public LocalFailure(final Throwable cause) { // super(cause); // } // // public LocalFailure(final String message) { // super(message); // } // } // // Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/messaging/Role.java // public abstract class Role { // protected final RDFAgent agent; // // public Role(final RDFAgent agent) { // this.agent = agent; // } // } // // Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/model/AgentId.java // public class AgentId { // private final String name; // private final IRI iri; // private final IRI[] transportAddresses; // // public AgentId(final String name, // final String... transportAddresses) { // this.name = name; // // this.iri = iriFromName(name); // // this.transportAddresses = new IRI[transportAddresses.length]; // for (int i = 0; i < transportAddresses.length; i++) { // this.transportAddresses[i] = SimpleValueFactory.getInstance().createIRI(transportAddresses[i]); // } // } // // public AgentId(final IRI iri, // final IRI[] transportAddresses) { // this.iri = iri; // this.name = nameFromIri(iri); // this.transportAddresses = transportAddresses; // } // // public String getName() { // return name; // } // // public IRI getIri() { // return iri; // } // // public IRI[] getTransportAddresses() { // return transportAddresses; // } // // private static IRI iriFromName(String name) { // // attempt to make the name into an IRI if it isn't one already. // // It is not always possible to pass a valid IRI as an agent identifier. // String iriStr = name; // if (!iriStr.startsWith("http://") && !iriStr.startsWith("urn:")) { // iriStr = "urn:" + iriStr; // } // // return SimpleValueFactory.getInstance().createIRI(iriStr); // } // // private static String nameFromIri(final IRI iri) { // String s = iri.stringValue(); // return s.startsWith("http://") ? s.substring(7) : s.startsWith("urn:") ? s.substring(4) : s; // } // } // // Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/model/RDFAgent.java // public abstract class RDFAgent { // protected final AgentId identity; // // public RDFAgent(final RDFAgentsPlatform platform, // final AgentId id) throws RDFAgentException { // // if (0 == id.getTransportAddresses().length) { // throw new IllegalArgumentException("at least one transport address must be specified"); // } // // identity = id; // } // // public AgentId getIdentity() { // return identity; // } // // public abstract void setQueryProvider(QueryProvider<Value, Dataset> queryProvider); // // public abstract void setPubsubProvider(PubsubProvider<Value, Dataset> pubsubProvider); // // public static class RDFAgentException extends Exception { // public RDFAgentException(final Throwable cause) { // super(cause); // } // } // // // TODO: remove/shutdown method // }
import net.fortytwo.rdfagents.messaging.Commitment; import net.fortytwo.rdfagents.messaging.LocalFailure; import net.fortytwo.rdfagents.messaging.Role; import net.fortytwo.rdfagents.model.AgentId; import net.fortytwo.rdfagents.model.RDFAgent; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.logging.Logger;
package net.fortytwo.rdfagents.messaging.subscribe; /** * The agent role of producing streams of updates based on topic-based subscriptions from other agents. * Subscriptions in RDFAgents follow FIPA's * <a href="http://www.fipa.org/specs/fipa00035/SC00035H.html">Subscribe Interaction Protocol</a>. * For more details, see <a href="http://fortytwo.net/2011/rdfagents/spec#pubsub">the specification</a>. * * @param <T> a class of topics * @param <U> a class of updates * * @author Joshua Shinavier (http://fortytwo.net) */ public abstract class PubsubProvider<T, U> extends Role { private static final Logger logger = Logger.getLogger(PubsubProvider.class.getName()); private class Subscription {
// Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/messaging/Commitment.java // public class Commitment { // // public enum Decision { // AGREE_AND_NOTIFY, // Query and Subscribe // AGREE_SILENTLY, // Query only // REFUSE // Query and Subscribe // } // // private final Decision decision; // private final ErrorExplanation explanation; // // public Commitment(final Decision decision, // final ErrorExplanation explanation) { // this.decision = decision; // this.explanation = explanation; // } // // public Decision getDecision() { // return decision; // } // // public ErrorExplanation getExplanation() { // return explanation; // } // } // // Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/messaging/LocalFailure.java // public class LocalFailure extends Exception { // public LocalFailure(final Throwable cause) { // super(cause); // } // // public LocalFailure(final String message) { // super(message); // } // } // // Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/messaging/Role.java // public abstract class Role { // protected final RDFAgent agent; // // public Role(final RDFAgent agent) { // this.agent = agent; // } // } // // Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/model/AgentId.java // public class AgentId { // private final String name; // private final IRI iri; // private final IRI[] transportAddresses; // // public AgentId(final String name, // final String... transportAddresses) { // this.name = name; // // this.iri = iriFromName(name); // // this.transportAddresses = new IRI[transportAddresses.length]; // for (int i = 0; i < transportAddresses.length; i++) { // this.transportAddresses[i] = SimpleValueFactory.getInstance().createIRI(transportAddresses[i]); // } // } // // public AgentId(final IRI iri, // final IRI[] transportAddresses) { // this.iri = iri; // this.name = nameFromIri(iri); // this.transportAddresses = transportAddresses; // } // // public String getName() { // return name; // } // // public IRI getIri() { // return iri; // } // // public IRI[] getTransportAddresses() { // return transportAddresses; // } // // private static IRI iriFromName(String name) { // // attempt to make the name into an IRI if it isn't one already. // // It is not always possible to pass a valid IRI as an agent identifier. // String iriStr = name; // if (!iriStr.startsWith("http://") && !iriStr.startsWith("urn:")) { // iriStr = "urn:" + iriStr; // } // // return SimpleValueFactory.getInstance().createIRI(iriStr); // } // // private static String nameFromIri(final IRI iri) { // String s = iri.stringValue(); // return s.startsWith("http://") ? s.substring(7) : s.startsWith("urn:") ? s.substring(4) : s; // } // } // // Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/model/RDFAgent.java // public abstract class RDFAgent { // protected final AgentId identity; // // public RDFAgent(final RDFAgentsPlatform platform, // final AgentId id) throws RDFAgentException { // // if (0 == id.getTransportAddresses().length) { // throw new IllegalArgumentException("at least one transport address must be specified"); // } // // identity = id; // } // // public AgentId getIdentity() { // return identity; // } // // public abstract void setQueryProvider(QueryProvider<Value, Dataset> queryProvider); // // public abstract void setPubsubProvider(PubsubProvider<Value, Dataset> pubsubProvider); // // public static class RDFAgentException extends Exception { // public RDFAgentException(final Throwable cause) { // super(cause); // } // } // // // TODO: remove/shutdown method // } // Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/messaging/subscribe/PubsubProvider.java import net.fortytwo.rdfagents.messaging.Commitment; import net.fortytwo.rdfagents.messaging.LocalFailure; import net.fortytwo.rdfagents.messaging.Role; import net.fortytwo.rdfagents.model.AgentId; import net.fortytwo.rdfagents.model.RDFAgent; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.logging.Logger; package net.fortytwo.rdfagents.messaging.subscribe; /** * The agent role of producing streams of updates based on topic-based subscriptions from other agents. * Subscriptions in RDFAgents follow FIPA's * <a href="http://www.fipa.org/specs/fipa00035/SC00035H.html">Subscribe Interaction Protocol</a>. * For more details, see <a href="http://fortytwo.net/2011/rdfagents/spec#pubsub">the specification</a>. * * @param <T> a class of topics * @param <U> a class of updates * * @author Joshua Shinavier (http://fortytwo.net) */ public abstract class PubsubProvider<T, U> extends Role { private static final Logger logger = Logger.getLogger(PubsubProvider.class.getName()); private class Subscription {
public final AgentId subscriber;
joshsh/rdfagents
rdfagents-core/src/main/java/net/fortytwo/rdfagents/messaging/subscribe/PubsubProvider.java
// Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/messaging/Commitment.java // public class Commitment { // // public enum Decision { // AGREE_AND_NOTIFY, // Query and Subscribe // AGREE_SILENTLY, // Query only // REFUSE // Query and Subscribe // } // // private final Decision decision; // private final ErrorExplanation explanation; // // public Commitment(final Decision decision, // final ErrorExplanation explanation) { // this.decision = decision; // this.explanation = explanation; // } // // public Decision getDecision() { // return decision; // } // // public ErrorExplanation getExplanation() { // return explanation; // } // } // // Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/messaging/LocalFailure.java // public class LocalFailure extends Exception { // public LocalFailure(final Throwable cause) { // super(cause); // } // // public LocalFailure(final String message) { // super(message); // } // } // // Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/messaging/Role.java // public abstract class Role { // protected final RDFAgent agent; // // public Role(final RDFAgent agent) { // this.agent = agent; // } // } // // Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/model/AgentId.java // public class AgentId { // private final String name; // private final IRI iri; // private final IRI[] transportAddresses; // // public AgentId(final String name, // final String... transportAddresses) { // this.name = name; // // this.iri = iriFromName(name); // // this.transportAddresses = new IRI[transportAddresses.length]; // for (int i = 0; i < transportAddresses.length; i++) { // this.transportAddresses[i] = SimpleValueFactory.getInstance().createIRI(transportAddresses[i]); // } // } // // public AgentId(final IRI iri, // final IRI[] transportAddresses) { // this.iri = iri; // this.name = nameFromIri(iri); // this.transportAddresses = transportAddresses; // } // // public String getName() { // return name; // } // // public IRI getIri() { // return iri; // } // // public IRI[] getTransportAddresses() { // return transportAddresses; // } // // private static IRI iriFromName(String name) { // // attempt to make the name into an IRI if it isn't one already. // // It is not always possible to pass a valid IRI as an agent identifier. // String iriStr = name; // if (!iriStr.startsWith("http://") && !iriStr.startsWith("urn:")) { // iriStr = "urn:" + iriStr; // } // // return SimpleValueFactory.getInstance().createIRI(iriStr); // } // // private static String nameFromIri(final IRI iri) { // String s = iri.stringValue(); // return s.startsWith("http://") ? s.substring(7) : s.startsWith("urn:") ? s.substring(4) : s; // } // } // // Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/model/RDFAgent.java // public abstract class RDFAgent { // protected final AgentId identity; // // public RDFAgent(final RDFAgentsPlatform platform, // final AgentId id) throws RDFAgentException { // // if (0 == id.getTransportAddresses().length) { // throw new IllegalArgumentException("at least one transport address must be specified"); // } // // identity = id; // } // // public AgentId getIdentity() { // return identity; // } // // public abstract void setQueryProvider(QueryProvider<Value, Dataset> queryProvider); // // public abstract void setPubsubProvider(PubsubProvider<Value, Dataset> pubsubProvider); // // public static class RDFAgentException extends Exception { // public RDFAgentException(final Throwable cause) { // super(cause); // } // } // // // TODO: remove/shutdown method // }
import net.fortytwo.rdfagents.messaging.Commitment; import net.fortytwo.rdfagents.messaging.LocalFailure; import net.fortytwo.rdfagents.messaging.Role; import net.fortytwo.rdfagents.model.AgentId; import net.fortytwo.rdfagents.model.RDFAgent; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.logging.Logger;
package net.fortytwo.rdfagents.messaging.subscribe; /** * The agent role of producing streams of updates based on topic-based subscriptions from other agents. * Subscriptions in RDFAgents follow FIPA's * <a href="http://www.fipa.org/specs/fipa00035/SC00035H.html">Subscribe Interaction Protocol</a>. * For more details, see <a href="http://fortytwo.net/2011/rdfagents/spec#pubsub">the specification</a>. * * @param <T> a class of topics * @param <U> a class of updates * * @author Joshua Shinavier (http://fortytwo.net) */ public abstract class PubsubProvider<T, U> extends Role { private static final Logger logger = Logger.getLogger(PubsubProvider.class.getName()); private class Subscription { public final AgentId subscriber; public final T topic; public final UpdateHandler<U> handler; public Subscription(final AgentId subscriber, final T topic, final UpdateHandler<U> handler) { this.subscriber = subscriber; this.topic = topic; this.handler = handler; } } private final Map<T, Set<String>> idsByTopic; private final Map<String, Subscription> subscriptionsById; private final Object mutex = "";
// Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/messaging/Commitment.java // public class Commitment { // // public enum Decision { // AGREE_AND_NOTIFY, // Query and Subscribe // AGREE_SILENTLY, // Query only // REFUSE // Query and Subscribe // } // // private final Decision decision; // private final ErrorExplanation explanation; // // public Commitment(final Decision decision, // final ErrorExplanation explanation) { // this.decision = decision; // this.explanation = explanation; // } // // public Decision getDecision() { // return decision; // } // // public ErrorExplanation getExplanation() { // return explanation; // } // } // // Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/messaging/LocalFailure.java // public class LocalFailure extends Exception { // public LocalFailure(final Throwable cause) { // super(cause); // } // // public LocalFailure(final String message) { // super(message); // } // } // // Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/messaging/Role.java // public abstract class Role { // protected final RDFAgent agent; // // public Role(final RDFAgent agent) { // this.agent = agent; // } // } // // Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/model/AgentId.java // public class AgentId { // private final String name; // private final IRI iri; // private final IRI[] transportAddresses; // // public AgentId(final String name, // final String... transportAddresses) { // this.name = name; // // this.iri = iriFromName(name); // // this.transportAddresses = new IRI[transportAddresses.length]; // for (int i = 0; i < transportAddresses.length; i++) { // this.transportAddresses[i] = SimpleValueFactory.getInstance().createIRI(transportAddresses[i]); // } // } // // public AgentId(final IRI iri, // final IRI[] transportAddresses) { // this.iri = iri; // this.name = nameFromIri(iri); // this.transportAddresses = transportAddresses; // } // // public String getName() { // return name; // } // // public IRI getIri() { // return iri; // } // // public IRI[] getTransportAddresses() { // return transportAddresses; // } // // private static IRI iriFromName(String name) { // // attempt to make the name into an IRI if it isn't one already. // // It is not always possible to pass a valid IRI as an agent identifier. // String iriStr = name; // if (!iriStr.startsWith("http://") && !iriStr.startsWith("urn:")) { // iriStr = "urn:" + iriStr; // } // // return SimpleValueFactory.getInstance().createIRI(iriStr); // } // // private static String nameFromIri(final IRI iri) { // String s = iri.stringValue(); // return s.startsWith("http://") ? s.substring(7) : s.startsWith("urn:") ? s.substring(4) : s; // } // } // // Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/model/RDFAgent.java // public abstract class RDFAgent { // protected final AgentId identity; // // public RDFAgent(final RDFAgentsPlatform platform, // final AgentId id) throws RDFAgentException { // // if (0 == id.getTransportAddresses().length) { // throw new IllegalArgumentException("at least one transport address must be specified"); // } // // identity = id; // } // // public AgentId getIdentity() { // return identity; // } // // public abstract void setQueryProvider(QueryProvider<Value, Dataset> queryProvider); // // public abstract void setPubsubProvider(PubsubProvider<Value, Dataset> pubsubProvider); // // public static class RDFAgentException extends Exception { // public RDFAgentException(final Throwable cause) { // super(cause); // } // } // // // TODO: remove/shutdown method // } // Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/messaging/subscribe/PubsubProvider.java import net.fortytwo.rdfagents.messaging.Commitment; import net.fortytwo.rdfagents.messaging.LocalFailure; import net.fortytwo.rdfagents.messaging.Role; import net.fortytwo.rdfagents.model.AgentId; import net.fortytwo.rdfagents.model.RDFAgent; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.logging.Logger; package net.fortytwo.rdfagents.messaging.subscribe; /** * The agent role of producing streams of updates based on topic-based subscriptions from other agents. * Subscriptions in RDFAgents follow FIPA's * <a href="http://www.fipa.org/specs/fipa00035/SC00035H.html">Subscribe Interaction Protocol</a>. * For more details, see <a href="http://fortytwo.net/2011/rdfagents/spec#pubsub">the specification</a>. * * @param <T> a class of topics * @param <U> a class of updates * * @author Joshua Shinavier (http://fortytwo.net) */ public abstract class PubsubProvider<T, U> extends Role { private static final Logger logger = Logger.getLogger(PubsubProvider.class.getName()); private class Subscription { public final AgentId subscriber; public final T topic; public final UpdateHandler<U> handler; public Subscription(final AgentId subscriber, final T topic, final UpdateHandler<U> handler) { this.subscriber = subscriber; this.topic = topic; this.handler = handler; } } private final Map<T, Set<String>> idsByTopic; private final Map<String, Subscription> subscriptionsById; private final Object mutex = "";
public PubsubProvider(final RDFAgent agent) {
joshsh/rdfagents
rdfagents-jade/src/main/java/net/fortytwo/rdfagents/jade/testing/ExampleMessages.java
// Path: rdfagents-jade/src/main/java/net/fortytwo/rdfagents/jade/RDFAgentsOntology.java // public class RDFAgentsOntology extends Ontology { // private static final RDFAgentsOntology INSTANCE; // // static { // try { // INSTANCE = new RDFAgentsOntology(); // } catch (OntologyException e) { // throw new ExceptionInInitializerError(e); // } // } // // public static final String // DATASET = "dataset", // implicit (used only as a variable) // DESCRIBES = "describes", // DESCRIBES_DATASET = "dataset", // implicit (unnamed parameter) // DESCRIBES_SUBJECT = "subject", // implicit (unnamed parameter) // EXPLANATION = "explanation", // implicit (abstract class) -- specific errors are in ErrorExplanation // EXPLANATION_MESSAGE = "message", // LITERAL = "literal", // LITERAL_DATATYPE = "datatype", // LITERAL_LANGUAGE = "language", // LITERAL_LABEL = "label", // VALUE = "value", // implicit (abstract class) // RESOURCE = "resource", // RESOURCE_IRI = "iri"; // // private RDFAgentsOntology() throws OntologyException { // super(RDFAgents.RDFAGENTS_ONTOLOGY_NAME, SLOntology.getInstance()); // // add(new PredicateSchema(DESCRIBES)); // // add(new ConceptSchema(DATASET)); // add(new ConceptSchema(VALUE)); // add(new ConceptSchema(RESOURCE)); // add(new ConceptSchema(LITERAL)); // // add(new PredicateSchema(EXPLANATION)); // for (ErrorExplanation.Type x : ErrorExplanation.Type.values()) { // add(new PredicateSchema(x.getFipaName())); // } // // ConceptSchema dataset = (ConceptSchema) getSchema(DATASET); // ConceptSchema resource = (ConceptSchema) getSchema(VALUE); // ConceptSchema iri = (ConceptSchema) getSchema(RESOURCE); // ConceptSchema literal = (ConceptSchema) getSchema(LITERAL); // iri.addSuperSchema(resource); // iri.add(RESOURCE_IRI, (PrimitiveSchema) getSchema(BasicOntology.STRING)); // literal.addSuperSchema(resource); // literal.add(LITERAL_LABEL, (PrimitiveSchema) getSchema(BasicOntology.STRING)); // literal.add(LITERAL_DATATYPE, iri, ObjectSchema.OPTIONAL); // literal.add(LITERAL_LANGUAGE, (PrimitiveSchema) getSchema(BasicOntology.STRING), ObjectSchema.OPTIONAL); // // PredicateSchema describes = (PredicateSchema) getSchema(DESCRIBES); // describes.add(DESCRIBES_DATASET, dataset); // describes.add(DESCRIBES_SUBJECT, resource); // // PredicateSchema explanation = (PredicateSchema) getSchema(EXPLANATION); // explanation.add(EXPLANATION_MESSAGE, getSchema(BasicOntology.STRING)); // // for (ErrorExplanation.Type x : ErrorExplanation.Type.values()) { // PredicateSchema s = (PredicateSchema) getSchema(x.getFipaName()); // s.addSuperSchema(explanation); // } // } // // public static RDFAgentsOntology getInstance() { // return INSTANCE; // } // }
import jade.content.ContentManager; import jade.content.lang.Codec; import jade.content.lang.sl.SLCodec; import jade.content.onto.BasicOntology; import jade.core.AID; import jade.domain.FIPANames; import jade.lang.acl.ACLMessage; import jade.lang.acl.StringACLCodec; import net.fortytwo.rdfagents.jade.RDFAgentsOntology; import java.util.Random;
client.setName("http://fortytwo.net/agents/smith"); client.addAddresses("xmpp:smith@fortytwo.net"); AID server = new AID(); server.setName("http://example.org/rdfnews"); server.addAddresses("xmpp:rdfnews@example.org"); ContentManager manager = new ContentManager(); Codec codec = new SLCodec(0); manager.registerLanguage(codec); manager.registerOntology(BasicOntology.getInstance()); for (String s : manager.getLanguageNames()) { System.out.println("language: " + s); } for (String s : manager.getOntologyNames()) { System.out.println("ontology: " + s); } ACLMessage m; m = new ACLMessage(ACLMessage.INFORM); m.setSender(client); m.addReceiver(server); print(m); m = new ACLMessage(ACLMessage.QUERY_REF); m.setSender(client); m.addReceiver(server); m.setProtocol(FIPANames.InteractionProtocol.FIPA_QUERY); m.setConversationId(convId); m.setLanguage(codec.getName());
// Path: rdfagents-jade/src/main/java/net/fortytwo/rdfagents/jade/RDFAgentsOntology.java // public class RDFAgentsOntology extends Ontology { // private static final RDFAgentsOntology INSTANCE; // // static { // try { // INSTANCE = new RDFAgentsOntology(); // } catch (OntologyException e) { // throw new ExceptionInInitializerError(e); // } // } // // public static final String // DATASET = "dataset", // implicit (used only as a variable) // DESCRIBES = "describes", // DESCRIBES_DATASET = "dataset", // implicit (unnamed parameter) // DESCRIBES_SUBJECT = "subject", // implicit (unnamed parameter) // EXPLANATION = "explanation", // implicit (abstract class) -- specific errors are in ErrorExplanation // EXPLANATION_MESSAGE = "message", // LITERAL = "literal", // LITERAL_DATATYPE = "datatype", // LITERAL_LANGUAGE = "language", // LITERAL_LABEL = "label", // VALUE = "value", // implicit (abstract class) // RESOURCE = "resource", // RESOURCE_IRI = "iri"; // // private RDFAgentsOntology() throws OntologyException { // super(RDFAgents.RDFAGENTS_ONTOLOGY_NAME, SLOntology.getInstance()); // // add(new PredicateSchema(DESCRIBES)); // // add(new ConceptSchema(DATASET)); // add(new ConceptSchema(VALUE)); // add(new ConceptSchema(RESOURCE)); // add(new ConceptSchema(LITERAL)); // // add(new PredicateSchema(EXPLANATION)); // for (ErrorExplanation.Type x : ErrorExplanation.Type.values()) { // add(new PredicateSchema(x.getFipaName())); // } // // ConceptSchema dataset = (ConceptSchema) getSchema(DATASET); // ConceptSchema resource = (ConceptSchema) getSchema(VALUE); // ConceptSchema iri = (ConceptSchema) getSchema(RESOURCE); // ConceptSchema literal = (ConceptSchema) getSchema(LITERAL); // iri.addSuperSchema(resource); // iri.add(RESOURCE_IRI, (PrimitiveSchema) getSchema(BasicOntology.STRING)); // literal.addSuperSchema(resource); // literal.add(LITERAL_LABEL, (PrimitiveSchema) getSchema(BasicOntology.STRING)); // literal.add(LITERAL_DATATYPE, iri, ObjectSchema.OPTIONAL); // literal.add(LITERAL_LANGUAGE, (PrimitiveSchema) getSchema(BasicOntology.STRING), ObjectSchema.OPTIONAL); // // PredicateSchema describes = (PredicateSchema) getSchema(DESCRIBES); // describes.add(DESCRIBES_DATASET, dataset); // describes.add(DESCRIBES_SUBJECT, resource); // // PredicateSchema explanation = (PredicateSchema) getSchema(EXPLANATION); // explanation.add(EXPLANATION_MESSAGE, getSchema(BasicOntology.STRING)); // // for (ErrorExplanation.Type x : ErrorExplanation.Type.values()) { // PredicateSchema s = (PredicateSchema) getSchema(x.getFipaName()); // s.addSuperSchema(explanation); // } // } // // public static RDFAgentsOntology getInstance() { // return INSTANCE; // } // } // Path: rdfagents-jade/src/main/java/net/fortytwo/rdfagents/jade/testing/ExampleMessages.java import jade.content.ContentManager; import jade.content.lang.Codec; import jade.content.lang.sl.SLCodec; import jade.content.onto.BasicOntology; import jade.core.AID; import jade.domain.FIPANames; import jade.lang.acl.ACLMessage; import jade.lang.acl.StringACLCodec; import net.fortytwo.rdfagents.jade.RDFAgentsOntology; import java.util.Random; client.setName("http://fortytwo.net/agents/smith"); client.addAddresses("xmpp:smith@fortytwo.net"); AID server = new AID(); server.setName("http://example.org/rdfnews"); server.addAddresses("xmpp:rdfnews@example.org"); ContentManager manager = new ContentManager(); Codec codec = new SLCodec(0); manager.registerLanguage(codec); manager.registerOntology(BasicOntology.getInstance()); for (String s : manager.getLanguageNames()) { System.out.println("language: " + s); } for (String s : manager.getOntologyNames()) { System.out.println("ontology: " + s); } ACLMessage m; m = new ACLMessage(ACLMessage.INFORM); m.setSender(client); m.addReceiver(server); print(m); m = new ACLMessage(ACLMessage.QUERY_REF); m.setSender(client); m.addReceiver(server); m.setProtocol(FIPANames.InteractionProtocol.FIPA_QUERY); m.setConversationId(convId); m.setLanguage(codec.getName());
m.setOntology(RDFAgentsOntology.getInstance().getName());
joshsh/rdfagents
rdfagents-csparql/src/main/java/net/fortytwo/rdfagents/CSPARQLConsumer.java
// Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/messaging/ConsumerCallback.java // public interface ConsumerCallback<A> { // /** // * Indicates success of the query request and provides the query answer. // * // * @param answer the answer to the submitted query // */ // void success(A answer); // // /** // * Indicates that the remote participant has agreed to answer the query. // */ // void agreed(); // // /** // * Indicates that the remote participant has refused to answer the query. // * // * @param explanation an explanation of the refusal, provided by the remote participant // */ // void refused(ErrorExplanation explanation); // // /** // * Indicates that the remote participant has failed to answer the query. // * // * @param explanation an explanation of failure, provided by the remote participant // */ // void remoteFailure(ErrorExplanation explanation); // // /** // * Indicates that a local exception has caused this interaction to fail. // * // * @param e the local exception which has occurred // */ // void localFailure(LocalFailure e); // } // // Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/messaging/LocalFailure.java // public class LocalFailure extends Exception { // public LocalFailure(final Throwable cause) { // super(cause); // } // // public LocalFailure(final String message) { // super(message); // } // } // // Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/model/Dataset.java // public class Dataset { // public static final String UUID_URN_PREFIX = "urn:uuid:"; // // private final Collection<Statement> statements; // // public Dataset(Collection<Statement> statements) { // this.statements = statements; // } // // public Collection<Statement> getStatements() { // return statements; // } // } // // Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/model/ErrorExplanation.java // public class ErrorExplanation { // private final Type type; // private final String message; // // public enum Type { // ExternalError("external-error"), // InteractionExplired("interaction-expired"), // InternalError("internal-error"), // InvalidMessage("invalid-message"), // NotImplemented("not-implemented"), // Unavailable("unavailable"); // // private final String fipaName; // // private Type(final String fipaName) { // this.fipaName = fipaName; // } // // public String getFipaName() { // return fipaName; // } // // public static Type getByFipaName(final String fipaName) { // for (Type t : values()) { // if (t.fipaName.equals(fipaName)) { // return t; // } // } // // return null; // } // } // // public ErrorExplanation(final Type type, // final String message) { // this.type = type; // this.message = message; // // if (null == type) { // throw new IllegalArgumentException("null type"); // } // // if (null == message) { // throw new IllegalArgumentException("null message"); // } // // if (0 == message.length()) { // throw new IllegalArgumentException("empty message"); // } // } // // public Type getType() { // return type; // } // // public String getMessage() { // return message; // } // // public String toString() { // return type + " (" + message + ")"; // } // }
import eu.larkc.csparql.cep.api.RdfQuadruple; import eu.larkc.csparql.cep.api.RdfStream; import net.fortytwo.rdfagents.messaging.ConsumerCallback; import net.fortytwo.rdfagents.messaging.LocalFailure; import net.fortytwo.rdfagents.model.Dataset; import net.fortytwo.rdfagents.model.ErrorExplanation; import org.openrdf.model.Statement;
package net.fortytwo.rdfagents; /** * @author Joshua Shinavier (http://fortytwo.net) */ public class CSPARQLConsumer extends RdfStream implements ConsumerCallback<Dataset> { public CSPARQLConsumer(String iri) { super(iri); // TODO Auto-generated constructor stub } @Override public void agreed() { // TODO Auto-generated method stub } @Override
// Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/messaging/ConsumerCallback.java // public interface ConsumerCallback<A> { // /** // * Indicates success of the query request and provides the query answer. // * // * @param answer the answer to the submitted query // */ // void success(A answer); // // /** // * Indicates that the remote participant has agreed to answer the query. // */ // void agreed(); // // /** // * Indicates that the remote participant has refused to answer the query. // * // * @param explanation an explanation of the refusal, provided by the remote participant // */ // void refused(ErrorExplanation explanation); // // /** // * Indicates that the remote participant has failed to answer the query. // * // * @param explanation an explanation of failure, provided by the remote participant // */ // void remoteFailure(ErrorExplanation explanation); // // /** // * Indicates that a local exception has caused this interaction to fail. // * // * @param e the local exception which has occurred // */ // void localFailure(LocalFailure e); // } // // Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/messaging/LocalFailure.java // public class LocalFailure extends Exception { // public LocalFailure(final Throwable cause) { // super(cause); // } // // public LocalFailure(final String message) { // super(message); // } // } // // Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/model/Dataset.java // public class Dataset { // public static final String UUID_URN_PREFIX = "urn:uuid:"; // // private final Collection<Statement> statements; // // public Dataset(Collection<Statement> statements) { // this.statements = statements; // } // // public Collection<Statement> getStatements() { // return statements; // } // } // // Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/model/ErrorExplanation.java // public class ErrorExplanation { // private final Type type; // private final String message; // // public enum Type { // ExternalError("external-error"), // InteractionExplired("interaction-expired"), // InternalError("internal-error"), // InvalidMessage("invalid-message"), // NotImplemented("not-implemented"), // Unavailable("unavailable"); // // private final String fipaName; // // private Type(final String fipaName) { // this.fipaName = fipaName; // } // // public String getFipaName() { // return fipaName; // } // // public static Type getByFipaName(final String fipaName) { // for (Type t : values()) { // if (t.fipaName.equals(fipaName)) { // return t; // } // } // // return null; // } // } // // public ErrorExplanation(final Type type, // final String message) { // this.type = type; // this.message = message; // // if (null == type) { // throw new IllegalArgumentException("null type"); // } // // if (null == message) { // throw new IllegalArgumentException("null message"); // } // // if (0 == message.length()) { // throw new IllegalArgumentException("empty message"); // } // } // // public Type getType() { // return type; // } // // public String getMessage() { // return message; // } // // public String toString() { // return type + " (" + message + ")"; // } // } // Path: rdfagents-csparql/src/main/java/net/fortytwo/rdfagents/CSPARQLConsumer.java import eu.larkc.csparql.cep.api.RdfQuadruple; import eu.larkc.csparql.cep.api.RdfStream; import net.fortytwo.rdfagents.messaging.ConsumerCallback; import net.fortytwo.rdfagents.messaging.LocalFailure; import net.fortytwo.rdfagents.model.Dataset; import net.fortytwo.rdfagents.model.ErrorExplanation; import org.openrdf.model.Statement; package net.fortytwo.rdfagents; /** * @author Joshua Shinavier (http://fortytwo.net) */ public class CSPARQLConsumer extends RdfStream implements ConsumerCallback<Dataset> { public CSPARQLConsumer(String iri) { super(iri); // TODO Auto-generated constructor stub } @Override public void agreed() { // TODO Auto-generated method stub } @Override
public void localFailure(LocalFailure arg0) {
joshsh/rdfagents
rdfagents-csparql/src/main/java/net/fortytwo/rdfagents/CSPARQLConsumer.java
// Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/messaging/ConsumerCallback.java // public interface ConsumerCallback<A> { // /** // * Indicates success of the query request and provides the query answer. // * // * @param answer the answer to the submitted query // */ // void success(A answer); // // /** // * Indicates that the remote participant has agreed to answer the query. // */ // void agreed(); // // /** // * Indicates that the remote participant has refused to answer the query. // * // * @param explanation an explanation of the refusal, provided by the remote participant // */ // void refused(ErrorExplanation explanation); // // /** // * Indicates that the remote participant has failed to answer the query. // * // * @param explanation an explanation of failure, provided by the remote participant // */ // void remoteFailure(ErrorExplanation explanation); // // /** // * Indicates that a local exception has caused this interaction to fail. // * // * @param e the local exception which has occurred // */ // void localFailure(LocalFailure e); // } // // Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/messaging/LocalFailure.java // public class LocalFailure extends Exception { // public LocalFailure(final Throwable cause) { // super(cause); // } // // public LocalFailure(final String message) { // super(message); // } // } // // Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/model/Dataset.java // public class Dataset { // public static final String UUID_URN_PREFIX = "urn:uuid:"; // // private final Collection<Statement> statements; // // public Dataset(Collection<Statement> statements) { // this.statements = statements; // } // // public Collection<Statement> getStatements() { // return statements; // } // } // // Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/model/ErrorExplanation.java // public class ErrorExplanation { // private final Type type; // private final String message; // // public enum Type { // ExternalError("external-error"), // InteractionExplired("interaction-expired"), // InternalError("internal-error"), // InvalidMessage("invalid-message"), // NotImplemented("not-implemented"), // Unavailable("unavailable"); // // private final String fipaName; // // private Type(final String fipaName) { // this.fipaName = fipaName; // } // // public String getFipaName() { // return fipaName; // } // // public static Type getByFipaName(final String fipaName) { // for (Type t : values()) { // if (t.fipaName.equals(fipaName)) { // return t; // } // } // // return null; // } // } // // public ErrorExplanation(final Type type, // final String message) { // this.type = type; // this.message = message; // // if (null == type) { // throw new IllegalArgumentException("null type"); // } // // if (null == message) { // throw new IllegalArgumentException("null message"); // } // // if (0 == message.length()) { // throw new IllegalArgumentException("empty message"); // } // } // // public Type getType() { // return type; // } // // public String getMessage() { // return message; // } // // public String toString() { // return type + " (" + message + ")"; // } // }
import eu.larkc.csparql.cep.api.RdfQuadruple; import eu.larkc.csparql.cep.api.RdfStream; import net.fortytwo.rdfagents.messaging.ConsumerCallback; import net.fortytwo.rdfagents.messaging.LocalFailure; import net.fortytwo.rdfagents.model.Dataset; import net.fortytwo.rdfagents.model.ErrorExplanation; import org.openrdf.model.Statement;
package net.fortytwo.rdfagents; /** * @author Joshua Shinavier (http://fortytwo.net) */ public class CSPARQLConsumer extends RdfStream implements ConsumerCallback<Dataset> { public CSPARQLConsumer(String iri) { super(iri); // TODO Auto-generated constructor stub } @Override public void agreed() { // TODO Auto-generated method stub } @Override public void localFailure(LocalFailure arg0) { // TODO Auto-generated method stub } @Override
// Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/messaging/ConsumerCallback.java // public interface ConsumerCallback<A> { // /** // * Indicates success of the query request and provides the query answer. // * // * @param answer the answer to the submitted query // */ // void success(A answer); // // /** // * Indicates that the remote participant has agreed to answer the query. // */ // void agreed(); // // /** // * Indicates that the remote participant has refused to answer the query. // * // * @param explanation an explanation of the refusal, provided by the remote participant // */ // void refused(ErrorExplanation explanation); // // /** // * Indicates that the remote participant has failed to answer the query. // * // * @param explanation an explanation of failure, provided by the remote participant // */ // void remoteFailure(ErrorExplanation explanation); // // /** // * Indicates that a local exception has caused this interaction to fail. // * // * @param e the local exception which has occurred // */ // void localFailure(LocalFailure e); // } // // Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/messaging/LocalFailure.java // public class LocalFailure extends Exception { // public LocalFailure(final Throwable cause) { // super(cause); // } // // public LocalFailure(final String message) { // super(message); // } // } // // Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/model/Dataset.java // public class Dataset { // public static final String UUID_URN_PREFIX = "urn:uuid:"; // // private final Collection<Statement> statements; // // public Dataset(Collection<Statement> statements) { // this.statements = statements; // } // // public Collection<Statement> getStatements() { // return statements; // } // } // // Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/model/ErrorExplanation.java // public class ErrorExplanation { // private final Type type; // private final String message; // // public enum Type { // ExternalError("external-error"), // InteractionExplired("interaction-expired"), // InternalError("internal-error"), // InvalidMessage("invalid-message"), // NotImplemented("not-implemented"), // Unavailable("unavailable"); // // private final String fipaName; // // private Type(final String fipaName) { // this.fipaName = fipaName; // } // // public String getFipaName() { // return fipaName; // } // // public static Type getByFipaName(final String fipaName) { // for (Type t : values()) { // if (t.fipaName.equals(fipaName)) { // return t; // } // } // // return null; // } // } // // public ErrorExplanation(final Type type, // final String message) { // this.type = type; // this.message = message; // // if (null == type) { // throw new IllegalArgumentException("null type"); // } // // if (null == message) { // throw new IllegalArgumentException("null message"); // } // // if (0 == message.length()) { // throw new IllegalArgumentException("empty message"); // } // } // // public Type getType() { // return type; // } // // public String getMessage() { // return message; // } // // public String toString() { // return type + " (" + message + ")"; // } // } // Path: rdfagents-csparql/src/main/java/net/fortytwo/rdfagents/CSPARQLConsumer.java import eu.larkc.csparql.cep.api.RdfQuadruple; import eu.larkc.csparql.cep.api.RdfStream; import net.fortytwo.rdfagents.messaging.ConsumerCallback; import net.fortytwo.rdfagents.messaging.LocalFailure; import net.fortytwo.rdfagents.model.Dataset; import net.fortytwo.rdfagents.model.ErrorExplanation; import org.openrdf.model.Statement; package net.fortytwo.rdfagents; /** * @author Joshua Shinavier (http://fortytwo.net) */ public class CSPARQLConsumer extends RdfStream implements ConsumerCallback<Dataset> { public CSPARQLConsumer(String iri) { super(iri); // TODO Auto-generated constructor stub } @Override public void agreed() { // TODO Auto-generated method stub } @Override public void localFailure(LocalFailure arg0) { // TODO Auto-generated method stub } @Override
public void refused(ErrorExplanation arg0) {
joshsh/rdfagents
rdfagents-core/src/main/java/net/fortytwo/rdfagents/model/RDFAgent.java
// Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/messaging/query/QueryProvider.java // public abstract class QueryProvider<Q, A> extends Role { // // public QueryProvider(final RDFAgent agent) { // super(agent); // } // // /** // * @param conversationId the conversation of the query // * @param query the query to be answered // * @param initiator the requester of the query // * @return the commitment of this server towards answering the query // */ // public abstract Commitment considerQueryRequest(String conversationId, // Q query, // AgentId initiator); // // /** // * Evaluate a query to produce a result. // * While the query request has previously been accepted or refused based on the identity of the initiator, // * the actual query is answered independently of the initiator. // * // * @param query the query to answer // * @return the answer to the query // * @throws LocalFailure if query answering fails // */ // public abstract A answer(Q query) throws LocalFailure; // // /** // * Cancel a previously submitted query. // * // * @param conversationId the conversation of the query // * @throws LocalFailure if cancellation fails // */ // public abstract void cancel(String conversationId) throws LocalFailure; // } // // Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/messaging/subscribe/PubsubProvider.java // public abstract class PubsubProvider<T, U> extends Role { // private static final Logger logger = Logger.getLogger(PubsubProvider.class.getName()); // // private class Subscription { // public final AgentId subscriber; // public final T topic; // public final UpdateHandler<U> handler; // // public Subscription(final AgentId subscriber, // final T topic, // final UpdateHandler<U> handler) { // this.subscriber = subscriber; // this.topic = topic; // this.handler = handler; // } // } // // private final Map<T, Set<String>> idsByTopic; // private final Map<String, Subscription> subscriptionsById; // private final Object mutex = ""; // // public PubsubProvider(final RDFAgent agent) { // super(agent); // this.idsByTopic = new HashMap<>(); // this.subscriptionsById = new HashMap<>(); // } // // /** // * Renders a decision with respect to a subscription request. // * // * @param conversationId the conversation of the subscription // * @param topic the topic of the desired stream // * @param initiator the requester of the subscription // * @param handler the handler for updates, provided this subscription request is accepted // * @return the commitment of this server towards handling the subscription // * @throws LocalFailure if decision making fails // */ // public Commitment considerSubscriptionRequest(final String conversationId, // final T topic, // final AgentId initiator, // final UpdateHandler<U> handler) throws LocalFailure { // Commitment c = considerSubscriptionRequestInternal(topic, initiator); // // switch (c.getDecision()) { // case AGREE_AND_NOTIFY: // synchronized (mutex) { // Set<String> ids = idsByTopic.get(topic); // if (null == ids) { // ids = new HashSet<>(); // idsByTopic.put(topic, ids); // } // ids.add(conversationId); // // Subscription s = new Subscription(initiator, topic, handler); // subscriptionsById.put(conversationId, s); // } // // return c; // case AGREE_SILENTLY: // throw new LocalFailure("agreeing to a subscription without confirmation is not supported"); // case REFUSE: // return c; // default: // throw new LocalFailure("unexpected decision: " + c.getDecision()); // } // } // // /** // * Renders a decision with respect to a subscription request. // * // * @param topic the topic of the desired stream // * @param initiator the requester of the subscription // * @return the commitment of this server towards handling the subscription // */ // protected abstract Commitment considerSubscriptionRequestInternal(T topic, // AgentId initiator); // // /** // * Cancel a subscription. // * // * @param conversationId the conversation of the subscription // * @throws LocalFailure if cancellation fails // */ // public void cancel(String conversationId) throws LocalFailure { // synchronized (mutex) { // Subscription s = subscriptionsById.get(conversationId); // // if (null == s) { // logger.warning("attempted to cancel a Subscribe interaction which does not exist: " + conversationId); // } else { // subscriptionsById.remove(conversationId); // Set<String> ids = idsByTopic.get(s.topic); // if (null != ids) { // if (1 >= ids.size()) { // idsByTopic.remove(s.topic); // } else { // ids.remove(conversationId); // } // } // } // } // } // // /** // * Communicates an update for each matching subscription to its respective subscriber // * // * @param topic the topic of the subscription(s) // * @param update the update to communicate // * @throws LocalFailure if update communication fails // */ // protected void produceUpdate(final T topic, // final U update) throws LocalFailure { // for (String id : idsByTopic.get(topic)) { // Subscription s = subscriptionsById.get(id); // s.handler.handle(update); // } // } // // /** // * @return the set of all topics of active subscriptions // */ // protected Set<T> getTopics() { // return idsByTopic.keySet(); // } // }
import net.fortytwo.rdfagents.messaging.query.QueryProvider; import net.fortytwo.rdfagents.messaging.subscribe.PubsubProvider; import org.openrdf.model.Value;
package net.fortytwo.rdfagents.model; /** * @author Joshua Shinavier (http://fortytwo.net) */ public abstract class RDFAgent { protected final AgentId identity; public RDFAgent(final RDFAgentsPlatform platform, final AgentId id) throws RDFAgentException { if (0 == id.getTransportAddresses().length) { throw new IllegalArgumentException("at least one transport address must be specified"); } identity = id; } public AgentId getIdentity() { return identity; }
// Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/messaging/query/QueryProvider.java // public abstract class QueryProvider<Q, A> extends Role { // // public QueryProvider(final RDFAgent agent) { // super(agent); // } // // /** // * @param conversationId the conversation of the query // * @param query the query to be answered // * @param initiator the requester of the query // * @return the commitment of this server towards answering the query // */ // public abstract Commitment considerQueryRequest(String conversationId, // Q query, // AgentId initiator); // // /** // * Evaluate a query to produce a result. // * While the query request has previously been accepted or refused based on the identity of the initiator, // * the actual query is answered independently of the initiator. // * // * @param query the query to answer // * @return the answer to the query // * @throws LocalFailure if query answering fails // */ // public abstract A answer(Q query) throws LocalFailure; // // /** // * Cancel a previously submitted query. // * // * @param conversationId the conversation of the query // * @throws LocalFailure if cancellation fails // */ // public abstract void cancel(String conversationId) throws LocalFailure; // } // // Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/messaging/subscribe/PubsubProvider.java // public abstract class PubsubProvider<T, U> extends Role { // private static final Logger logger = Logger.getLogger(PubsubProvider.class.getName()); // // private class Subscription { // public final AgentId subscriber; // public final T topic; // public final UpdateHandler<U> handler; // // public Subscription(final AgentId subscriber, // final T topic, // final UpdateHandler<U> handler) { // this.subscriber = subscriber; // this.topic = topic; // this.handler = handler; // } // } // // private final Map<T, Set<String>> idsByTopic; // private final Map<String, Subscription> subscriptionsById; // private final Object mutex = ""; // // public PubsubProvider(final RDFAgent agent) { // super(agent); // this.idsByTopic = new HashMap<>(); // this.subscriptionsById = new HashMap<>(); // } // // /** // * Renders a decision with respect to a subscription request. // * // * @param conversationId the conversation of the subscription // * @param topic the topic of the desired stream // * @param initiator the requester of the subscription // * @param handler the handler for updates, provided this subscription request is accepted // * @return the commitment of this server towards handling the subscription // * @throws LocalFailure if decision making fails // */ // public Commitment considerSubscriptionRequest(final String conversationId, // final T topic, // final AgentId initiator, // final UpdateHandler<U> handler) throws LocalFailure { // Commitment c = considerSubscriptionRequestInternal(topic, initiator); // // switch (c.getDecision()) { // case AGREE_AND_NOTIFY: // synchronized (mutex) { // Set<String> ids = idsByTopic.get(topic); // if (null == ids) { // ids = new HashSet<>(); // idsByTopic.put(topic, ids); // } // ids.add(conversationId); // // Subscription s = new Subscription(initiator, topic, handler); // subscriptionsById.put(conversationId, s); // } // // return c; // case AGREE_SILENTLY: // throw new LocalFailure("agreeing to a subscription without confirmation is not supported"); // case REFUSE: // return c; // default: // throw new LocalFailure("unexpected decision: " + c.getDecision()); // } // } // // /** // * Renders a decision with respect to a subscription request. // * // * @param topic the topic of the desired stream // * @param initiator the requester of the subscription // * @return the commitment of this server towards handling the subscription // */ // protected abstract Commitment considerSubscriptionRequestInternal(T topic, // AgentId initiator); // // /** // * Cancel a subscription. // * // * @param conversationId the conversation of the subscription // * @throws LocalFailure if cancellation fails // */ // public void cancel(String conversationId) throws LocalFailure { // synchronized (mutex) { // Subscription s = subscriptionsById.get(conversationId); // // if (null == s) { // logger.warning("attempted to cancel a Subscribe interaction which does not exist: " + conversationId); // } else { // subscriptionsById.remove(conversationId); // Set<String> ids = idsByTopic.get(s.topic); // if (null != ids) { // if (1 >= ids.size()) { // idsByTopic.remove(s.topic); // } else { // ids.remove(conversationId); // } // } // } // } // } // // /** // * Communicates an update for each matching subscription to its respective subscriber // * // * @param topic the topic of the subscription(s) // * @param update the update to communicate // * @throws LocalFailure if update communication fails // */ // protected void produceUpdate(final T topic, // final U update) throws LocalFailure { // for (String id : idsByTopic.get(topic)) { // Subscription s = subscriptionsById.get(id); // s.handler.handle(update); // } // } // // /** // * @return the set of all topics of active subscriptions // */ // protected Set<T> getTopics() { // return idsByTopic.keySet(); // } // } // Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/model/RDFAgent.java import net.fortytwo.rdfagents.messaging.query.QueryProvider; import net.fortytwo.rdfagents.messaging.subscribe.PubsubProvider; import org.openrdf.model.Value; package net.fortytwo.rdfagents.model; /** * @author Joshua Shinavier (http://fortytwo.net) */ public abstract class RDFAgent { protected final AgentId identity; public RDFAgent(final RDFAgentsPlatform platform, final AgentId id) throws RDFAgentException { if (0 == id.getTransportAddresses().length) { throw new IllegalArgumentException("at least one transport address must be specified"); } identity = id; } public AgentId getIdentity() { return identity; }
public abstract void setQueryProvider(QueryProvider<Value, Dataset> queryProvider);
joshsh/rdfagents
rdfagents-core/src/main/java/net/fortytwo/rdfagents/model/RDFAgent.java
// Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/messaging/query/QueryProvider.java // public abstract class QueryProvider<Q, A> extends Role { // // public QueryProvider(final RDFAgent agent) { // super(agent); // } // // /** // * @param conversationId the conversation of the query // * @param query the query to be answered // * @param initiator the requester of the query // * @return the commitment of this server towards answering the query // */ // public abstract Commitment considerQueryRequest(String conversationId, // Q query, // AgentId initiator); // // /** // * Evaluate a query to produce a result. // * While the query request has previously been accepted or refused based on the identity of the initiator, // * the actual query is answered independently of the initiator. // * // * @param query the query to answer // * @return the answer to the query // * @throws LocalFailure if query answering fails // */ // public abstract A answer(Q query) throws LocalFailure; // // /** // * Cancel a previously submitted query. // * // * @param conversationId the conversation of the query // * @throws LocalFailure if cancellation fails // */ // public abstract void cancel(String conversationId) throws LocalFailure; // } // // Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/messaging/subscribe/PubsubProvider.java // public abstract class PubsubProvider<T, U> extends Role { // private static final Logger logger = Logger.getLogger(PubsubProvider.class.getName()); // // private class Subscription { // public final AgentId subscriber; // public final T topic; // public final UpdateHandler<U> handler; // // public Subscription(final AgentId subscriber, // final T topic, // final UpdateHandler<U> handler) { // this.subscriber = subscriber; // this.topic = topic; // this.handler = handler; // } // } // // private final Map<T, Set<String>> idsByTopic; // private final Map<String, Subscription> subscriptionsById; // private final Object mutex = ""; // // public PubsubProvider(final RDFAgent agent) { // super(agent); // this.idsByTopic = new HashMap<>(); // this.subscriptionsById = new HashMap<>(); // } // // /** // * Renders a decision with respect to a subscription request. // * // * @param conversationId the conversation of the subscription // * @param topic the topic of the desired stream // * @param initiator the requester of the subscription // * @param handler the handler for updates, provided this subscription request is accepted // * @return the commitment of this server towards handling the subscription // * @throws LocalFailure if decision making fails // */ // public Commitment considerSubscriptionRequest(final String conversationId, // final T topic, // final AgentId initiator, // final UpdateHandler<U> handler) throws LocalFailure { // Commitment c = considerSubscriptionRequestInternal(topic, initiator); // // switch (c.getDecision()) { // case AGREE_AND_NOTIFY: // synchronized (mutex) { // Set<String> ids = idsByTopic.get(topic); // if (null == ids) { // ids = new HashSet<>(); // idsByTopic.put(topic, ids); // } // ids.add(conversationId); // // Subscription s = new Subscription(initiator, topic, handler); // subscriptionsById.put(conversationId, s); // } // // return c; // case AGREE_SILENTLY: // throw new LocalFailure("agreeing to a subscription without confirmation is not supported"); // case REFUSE: // return c; // default: // throw new LocalFailure("unexpected decision: " + c.getDecision()); // } // } // // /** // * Renders a decision with respect to a subscription request. // * // * @param topic the topic of the desired stream // * @param initiator the requester of the subscription // * @return the commitment of this server towards handling the subscription // */ // protected abstract Commitment considerSubscriptionRequestInternal(T topic, // AgentId initiator); // // /** // * Cancel a subscription. // * // * @param conversationId the conversation of the subscription // * @throws LocalFailure if cancellation fails // */ // public void cancel(String conversationId) throws LocalFailure { // synchronized (mutex) { // Subscription s = subscriptionsById.get(conversationId); // // if (null == s) { // logger.warning("attempted to cancel a Subscribe interaction which does not exist: " + conversationId); // } else { // subscriptionsById.remove(conversationId); // Set<String> ids = idsByTopic.get(s.topic); // if (null != ids) { // if (1 >= ids.size()) { // idsByTopic.remove(s.topic); // } else { // ids.remove(conversationId); // } // } // } // } // } // // /** // * Communicates an update for each matching subscription to its respective subscriber // * // * @param topic the topic of the subscription(s) // * @param update the update to communicate // * @throws LocalFailure if update communication fails // */ // protected void produceUpdate(final T topic, // final U update) throws LocalFailure { // for (String id : idsByTopic.get(topic)) { // Subscription s = subscriptionsById.get(id); // s.handler.handle(update); // } // } // // /** // * @return the set of all topics of active subscriptions // */ // protected Set<T> getTopics() { // return idsByTopic.keySet(); // } // }
import net.fortytwo.rdfagents.messaging.query.QueryProvider; import net.fortytwo.rdfagents.messaging.subscribe.PubsubProvider; import org.openrdf.model.Value;
package net.fortytwo.rdfagents.model; /** * @author Joshua Shinavier (http://fortytwo.net) */ public abstract class RDFAgent { protected final AgentId identity; public RDFAgent(final RDFAgentsPlatform platform, final AgentId id) throws RDFAgentException { if (0 == id.getTransportAddresses().length) { throw new IllegalArgumentException("at least one transport address must be specified"); } identity = id; } public AgentId getIdentity() { return identity; } public abstract void setQueryProvider(QueryProvider<Value, Dataset> queryProvider);
// Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/messaging/query/QueryProvider.java // public abstract class QueryProvider<Q, A> extends Role { // // public QueryProvider(final RDFAgent agent) { // super(agent); // } // // /** // * @param conversationId the conversation of the query // * @param query the query to be answered // * @param initiator the requester of the query // * @return the commitment of this server towards answering the query // */ // public abstract Commitment considerQueryRequest(String conversationId, // Q query, // AgentId initiator); // // /** // * Evaluate a query to produce a result. // * While the query request has previously been accepted or refused based on the identity of the initiator, // * the actual query is answered independently of the initiator. // * // * @param query the query to answer // * @return the answer to the query // * @throws LocalFailure if query answering fails // */ // public abstract A answer(Q query) throws LocalFailure; // // /** // * Cancel a previously submitted query. // * // * @param conversationId the conversation of the query // * @throws LocalFailure if cancellation fails // */ // public abstract void cancel(String conversationId) throws LocalFailure; // } // // Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/messaging/subscribe/PubsubProvider.java // public abstract class PubsubProvider<T, U> extends Role { // private static final Logger logger = Logger.getLogger(PubsubProvider.class.getName()); // // private class Subscription { // public final AgentId subscriber; // public final T topic; // public final UpdateHandler<U> handler; // // public Subscription(final AgentId subscriber, // final T topic, // final UpdateHandler<U> handler) { // this.subscriber = subscriber; // this.topic = topic; // this.handler = handler; // } // } // // private final Map<T, Set<String>> idsByTopic; // private final Map<String, Subscription> subscriptionsById; // private final Object mutex = ""; // // public PubsubProvider(final RDFAgent agent) { // super(agent); // this.idsByTopic = new HashMap<>(); // this.subscriptionsById = new HashMap<>(); // } // // /** // * Renders a decision with respect to a subscription request. // * // * @param conversationId the conversation of the subscription // * @param topic the topic of the desired stream // * @param initiator the requester of the subscription // * @param handler the handler for updates, provided this subscription request is accepted // * @return the commitment of this server towards handling the subscription // * @throws LocalFailure if decision making fails // */ // public Commitment considerSubscriptionRequest(final String conversationId, // final T topic, // final AgentId initiator, // final UpdateHandler<U> handler) throws LocalFailure { // Commitment c = considerSubscriptionRequestInternal(topic, initiator); // // switch (c.getDecision()) { // case AGREE_AND_NOTIFY: // synchronized (mutex) { // Set<String> ids = idsByTopic.get(topic); // if (null == ids) { // ids = new HashSet<>(); // idsByTopic.put(topic, ids); // } // ids.add(conversationId); // // Subscription s = new Subscription(initiator, topic, handler); // subscriptionsById.put(conversationId, s); // } // // return c; // case AGREE_SILENTLY: // throw new LocalFailure("agreeing to a subscription without confirmation is not supported"); // case REFUSE: // return c; // default: // throw new LocalFailure("unexpected decision: " + c.getDecision()); // } // } // // /** // * Renders a decision with respect to a subscription request. // * // * @param topic the topic of the desired stream // * @param initiator the requester of the subscription // * @return the commitment of this server towards handling the subscription // */ // protected abstract Commitment considerSubscriptionRequestInternal(T topic, // AgentId initiator); // // /** // * Cancel a subscription. // * // * @param conversationId the conversation of the subscription // * @throws LocalFailure if cancellation fails // */ // public void cancel(String conversationId) throws LocalFailure { // synchronized (mutex) { // Subscription s = subscriptionsById.get(conversationId); // // if (null == s) { // logger.warning("attempted to cancel a Subscribe interaction which does not exist: " + conversationId); // } else { // subscriptionsById.remove(conversationId); // Set<String> ids = idsByTopic.get(s.topic); // if (null != ids) { // if (1 >= ids.size()) { // idsByTopic.remove(s.topic); // } else { // ids.remove(conversationId); // } // } // } // } // } // // /** // * Communicates an update for each matching subscription to its respective subscriber // * // * @param topic the topic of the subscription(s) // * @param update the update to communicate // * @throws LocalFailure if update communication fails // */ // protected void produceUpdate(final T topic, // final U update) throws LocalFailure { // for (String id : idsByTopic.get(topic)) { // Subscription s = subscriptionsById.get(id); // s.handler.handle(update); // } // } // // /** // * @return the set of all topics of active subscriptions // */ // protected Set<T> getTopics() { // return idsByTopic.keySet(); // } // } // Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/model/RDFAgent.java import net.fortytwo.rdfagents.messaging.query.QueryProvider; import net.fortytwo.rdfagents.messaging.subscribe.PubsubProvider; import org.openrdf.model.Value; package net.fortytwo.rdfagents.model; /** * @author Joshua Shinavier (http://fortytwo.net) */ public abstract class RDFAgent { protected final AgentId identity; public RDFAgent(final RDFAgentsPlatform platform, final AgentId id) throws RDFAgentException { if (0 == id.getTransportAddresses().length) { throw new IllegalArgumentException("at least one transport address must be specified"); } identity = id; } public AgentId getIdentity() { return identity; } public abstract void setQueryProvider(QueryProvider<Value, Dataset> queryProvider);
public abstract void setPubsubProvider(PubsubProvider<Value, Dataset> pubsubProvider);
joshsh/rdfagents
rdfagents-core/src/main/java/net/fortytwo/rdfagents/messaging/CancellationCallback.java
// Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/model/ErrorExplanation.java // public class ErrorExplanation { // private final Type type; // private final String message; // // public enum Type { // ExternalError("external-error"), // InteractionExplired("interaction-expired"), // InternalError("internal-error"), // InvalidMessage("invalid-message"), // NotImplemented("not-implemented"), // Unavailable("unavailable"); // // private final String fipaName; // // private Type(final String fipaName) { // this.fipaName = fipaName; // } // // public String getFipaName() { // return fipaName; // } // // public static Type getByFipaName(final String fipaName) { // for (Type t : values()) { // if (t.fipaName.equals(fipaName)) { // return t; // } // } // // return null; // } // } // // public ErrorExplanation(final Type type, // final String message) { // this.type = type; // this.message = message; // // if (null == type) { // throw new IllegalArgumentException("null type"); // } // // if (null == message) { // throw new IllegalArgumentException("null message"); // } // // if (0 == message.length()) { // throw new IllegalArgumentException("empty message"); // } // } // // public Type getType() { // return type; // } // // public String getMessage() { // return message; // } // // public String toString() { // return type + " (" + message + ")"; // } // }
import net.fortytwo.rdfagents.model.ErrorExplanation;
package net.fortytwo.rdfagents.messaging; /** * A handler for all possible outcomes of a query cancellation request. * * @author Joshua Shinavier (http://fortytwo.net) */ public interface CancellationCallback { /** * Indicates success of the cancellation request. */ void success(); /** * Indicates failure of the cancellation request. * * @param explanation an explanation of failure, provided by the remote participant */
// Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/model/ErrorExplanation.java // public class ErrorExplanation { // private final Type type; // private final String message; // // public enum Type { // ExternalError("external-error"), // InteractionExplired("interaction-expired"), // InternalError("internal-error"), // InvalidMessage("invalid-message"), // NotImplemented("not-implemented"), // Unavailable("unavailable"); // // private final String fipaName; // // private Type(final String fipaName) { // this.fipaName = fipaName; // } // // public String getFipaName() { // return fipaName; // } // // public static Type getByFipaName(final String fipaName) { // for (Type t : values()) { // if (t.fipaName.equals(fipaName)) { // return t; // } // } // // return null; // } // } // // public ErrorExplanation(final Type type, // final String message) { // this.type = type; // this.message = message; // // if (null == type) { // throw new IllegalArgumentException("null type"); // } // // if (null == message) { // throw new IllegalArgumentException("null message"); // } // // if (0 == message.length()) { // throw new IllegalArgumentException("empty message"); // } // } // // public Type getType() { // return type; // } // // public String getMessage() { // return message; // } // // public String toString() { // return type + " (" + message + ")"; // } // } // Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/messaging/CancellationCallback.java import net.fortytwo.rdfagents.model.ErrorExplanation; package net.fortytwo.rdfagents.messaging; /** * A handler for all possible outcomes of a query cancellation request. * * @author Joshua Shinavier (http://fortytwo.net) */ public interface CancellationCallback { /** * Indicates success of the cancellation request. */ void success(); /** * Indicates failure of the cancellation request. * * @param explanation an explanation of failure, provided by the remote participant */
void remoteFailure(ErrorExplanation explanation);
joshsh/rdfagents
rdfagents-core/src/main/java/net/fortytwo/rdfagents/data/RecursiveDescribeQuery.java
// Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/model/Dataset.java // public class Dataset { // public static final String UUID_URN_PREFIX = "urn:uuid:"; // // private final Collection<Statement> statements; // // public Dataset(Collection<Statement> statements) { // this.statements = statements; // } // // public Collection<Statement> getStatements() { // return statements; // } // }
import info.aduna.iteration.CloseableIteration; import net.fortytwo.rdfagents.model.Dataset; import org.openrdf.model.Resource; import org.openrdf.model.Statement; import org.openrdf.model.Value; import org.openrdf.sail.Sail; import org.openrdf.sail.SailConnection; import org.openrdf.sail.SailException; import java.util.Collection; import java.util.HashSet; import java.util.LinkedList; import java.util.Set; import java.util.stream.Collectors;
package net.fortytwo.rdfagents.data; /** * A simple "describes" query engine which produces a RDF Dataset of graphs describing * (containing forward or backward links to) the resource, as well as those describing * the graphs, and so on recursively. * The purpose of the recursion is to capture the provenance trail of the base description of the the resource. * * This implementation prevents duplicate statements * (i.e. two or more statements with the same subject, predicate, and object in the same graph) * * @author Joshua Shinavier (http://fortytwo.net) */ public class RecursiveDescribeQuery implements DatasetQuery { private final Sail sail; private final Value resource; /** * @param resource the resource to describe * Exactly what constitutes a description is a matter of implementation. * @param sail the storage and inference layer against which to evaluate the query */ public RecursiveDescribeQuery(final Value resource, final Sail sail) { this.resource = resource; this.sail = sail; }
// Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/model/Dataset.java // public class Dataset { // public static final String UUID_URN_PREFIX = "urn:uuid:"; // // private final Collection<Statement> statements; // // public Dataset(Collection<Statement> statements) { // this.statements = statements; // } // // public Collection<Statement> getStatements() { // return statements; // } // } // Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/data/RecursiveDescribeQuery.java import info.aduna.iteration.CloseableIteration; import net.fortytwo.rdfagents.model.Dataset; import org.openrdf.model.Resource; import org.openrdf.model.Statement; import org.openrdf.model.Value; import org.openrdf.sail.Sail; import org.openrdf.sail.SailConnection; import org.openrdf.sail.SailException; import java.util.Collection; import java.util.HashSet; import java.util.LinkedList; import java.util.Set; import java.util.stream.Collectors; package net.fortytwo.rdfagents.data; /** * A simple "describes" query engine which produces a RDF Dataset of graphs describing * (containing forward or backward links to) the resource, as well as those describing * the graphs, and so on recursively. * The purpose of the recursion is to capture the provenance trail of the base description of the the resource. * * This implementation prevents duplicate statements * (i.e. two or more statements with the same subject, predicate, and object in the same graph) * * @author Joshua Shinavier (http://fortytwo.net) */ public class RecursiveDescribeQuery implements DatasetQuery { private final Sail sail; private final Value resource; /** * @param resource the resource to describe * Exactly what constitutes a description is a matter of implementation. * @param sail the storage and inference layer against which to evaluate the query */ public RecursiveDescribeQuery(final Value resource, final Sail sail) { this.resource = resource; this.sail = sail; }
public Dataset evaluate() throws DatasetQueryException {
joshsh/rdfagents
rdfagents-core/src/main/java/net/fortytwo/rdfagents/messaging/Commitment.java
// Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/model/ErrorExplanation.java // public class ErrorExplanation { // private final Type type; // private final String message; // // public enum Type { // ExternalError("external-error"), // InteractionExplired("interaction-expired"), // InternalError("internal-error"), // InvalidMessage("invalid-message"), // NotImplemented("not-implemented"), // Unavailable("unavailable"); // // private final String fipaName; // // private Type(final String fipaName) { // this.fipaName = fipaName; // } // // public String getFipaName() { // return fipaName; // } // // public static Type getByFipaName(final String fipaName) { // for (Type t : values()) { // if (t.fipaName.equals(fipaName)) { // return t; // } // } // // return null; // } // } // // public ErrorExplanation(final Type type, // final String message) { // this.type = type; // this.message = message; // // if (null == type) { // throw new IllegalArgumentException("null type"); // } // // if (null == message) { // throw new IllegalArgumentException("null message"); // } // // if (0 == message.length()) { // throw new IllegalArgumentException("empty message"); // } // } // // public Type getType() { // return type; // } // // public String getMessage() { // return message; // } // // public String toString() { // return type + " (" + message + ")"; // } // }
import net.fortytwo.rdfagents.model.ErrorExplanation;
package net.fortytwo.rdfagents.messaging; /** * A commitment (or lack thereof) to answer a query or accept a subscription. * A query may either be answered immediately * (in which case the response to the initiator consists of the query result), * or at some later point in time * (in which case an "agree" message is first sent to the initiator, * to be followed by another message with the query result). * Subscription requests must always be met with either an "agree" or a "refuse" message, before any updates are sent. * * @author Joshua Shinavier (http://fortytwo.net) */ public class Commitment { public enum Decision { AGREE_AND_NOTIFY, // Query and Subscribe AGREE_SILENTLY, // Query only REFUSE // Query and Subscribe } private final Decision decision;
// Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/model/ErrorExplanation.java // public class ErrorExplanation { // private final Type type; // private final String message; // // public enum Type { // ExternalError("external-error"), // InteractionExplired("interaction-expired"), // InternalError("internal-error"), // InvalidMessage("invalid-message"), // NotImplemented("not-implemented"), // Unavailable("unavailable"); // // private final String fipaName; // // private Type(final String fipaName) { // this.fipaName = fipaName; // } // // public String getFipaName() { // return fipaName; // } // // public static Type getByFipaName(final String fipaName) { // for (Type t : values()) { // if (t.fipaName.equals(fipaName)) { // return t; // } // } // // return null; // } // } // // public ErrorExplanation(final Type type, // final String message) { // this.type = type; // this.message = message; // // if (null == type) { // throw new IllegalArgumentException("null type"); // } // // if (null == message) { // throw new IllegalArgumentException("null message"); // } // // if (0 == message.length()) { // throw new IllegalArgumentException("empty message"); // } // } // // public Type getType() { // return type; // } // // public String getMessage() { // return message; // } // // public String toString() { // return type + " (" + message + ")"; // } // } // Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/messaging/Commitment.java import net.fortytwo.rdfagents.model.ErrorExplanation; package net.fortytwo.rdfagents.messaging; /** * A commitment (or lack thereof) to answer a query or accept a subscription. * A query may either be answered immediately * (in which case the response to the initiator consists of the query result), * or at some later point in time * (in which case an "agree" message is first sent to the initiator, * to be followed by another message with the query result). * Subscription requests must always be met with either an "agree" or a "refuse" message, before any updates are sent. * * @author Joshua Shinavier (http://fortytwo.net) */ public class Commitment { public enum Decision { AGREE_AND_NOTIFY, // Query and Subscribe AGREE_SILENTLY, // Query only REFUSE // Query and Subscribe } private final Decision decision;
private final ErrorExplanation explanation;
joshsh/rdfagents
rdfagents-core/src/main/java/net/fortytwo/rdfagents/messaging/subscribe/old/SubscribeRequestOld.java
// Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/model/AgentId.java // public class AgentId { // private final String name; // private final IRI iri; // private final IRI[] transportAddresses; // // public AgentId(final String name, // final String... transportAddresses) { // this.name = name; // // this.iri = iriFromName(name); // // this.transportAddresses = new IRI[transportAddresses.length]; // for (int i = 0; i < transportAddresses.length; i++) { // this.transportAddresses[i] = SimpleValueFactory.getInstance().createIRI(transportAddresses[i]); // } // } // // public AgentId(final IRI iri, // final IRI[] transportAddresses) { // this.iri = iri; // this.name = nameFromIri(iri); // this.transportAddresses = transportAddresses; // } // // public String getName() { // return name; // } // // public IRI getIri() { // return iri; // } // // public IRI[] getTransportAddresses() { // return transportAddresses; // } // // private static IRI iriFromName(String name) { // // attempt to make the name into an IRI if it isn't one already. // // It is not always possible to pass a valid IRI as an agent identifier. // String iriStr = name; // if (!iriStr.startsWith("http://") && !iriStr.startsWith("urn:")) { // iriStr = "urn:" + iriStr; // } // // return SimpleValueFactory.getInstance().createIRI(iriStr); // } // // private static String nameFromIri(final IRI iri) { // String s = iri.stringValue(); // return s.startsWith("http://") ? s.substring(7) : s.startsWith("urn:") ? s.substring(4) : s; // } // }
import net.fortytwo.rdfagents.model.AgentId;
package net.fortytwo.rdfagents.messaging.subscribe.old; /** * @author Joshua Shinavier (http://fortytwo.net) */ public abstract class SubscribeRequestOld<Q> { private final Q topic;
// Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/model/AgentId.java // public class AgentId { // private final String name; // private final IRI iri; // private final IRI[] transportAddresses; // // public AgentId(final String name, // final String... transportAddresses) { // this.name = name; // // this.iri = iriFromName(name); // // this.transportAddresses = new IRI[transportAddresses.length]; // for (int i = 0; i < transportAddresses.length; i++) { // this.transportAddresses[i] = SimpleValueFactory.getInstance().createIRI(transportAddresses[i]); // } // } // // public AgentId(final IRI iri, // final IRI[] transportAddresses) { // this.iri = iri; // this.name = nameFromIri(iri); // this.transportAddresses = transportAddresses; // } // // public String getName() { // return name; // } // // public IRI getIri() { // return iri; // } // // public IRI[] getTransportAddresses() { // return transportAddresses; // } // // private static IRI iriFromName(String name) { // // attempt to make the name into an IRI if it isn't one already. // // It is not always possible to pass a valid IRI as an agent identifier. // String iriStr = name; // if (!iriStr.startsWith("http://") && !iriStr.startsWith("urn:")) { // iriStr = "urn:" + iriStr; // } // // return SimpleValueFactory.getInstance().createIRI(iriStr); // } // // private static String nameFromIri(final IRI iri) { // String s = iri.stringValue(); // return s.startsWith("http://") ? s.substring(7) : s.startsWith("urn:") ? s.substring(4) : s; // } // } // Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/messaging/subscribe/old/SubscribeRequestOld.java import net.fortytwo.rdfagents.model.AgentId; package net.fortytwo.rdfagents.messaging.subscribe.old; /** * @author Joshua Shinavier (http://fortytwo.net) */ public abstract class SubscribeRequestOld<Q> { private final Q topic;
private final AgentId remoteParticipant;
joshsh/rdfagents
rdfagents-jade/src/test/java/net/fortytwo/rdfagents/data/RecursiveDescribeQueryTest.java
// Path: rdfagents-jade/src/test/java/net/fortytwo/rdfagents/RDFAgentsTestCase.java // public abstract class RDFAgentsTestCase extends TestCase { // protected AgentId sender, receiver; // protected IRI resourceX = RDFAgents.createIRI("http://example.org/resourceX"); // protected Literal plainLiteralX = new LiteralImpl("Don't panic."); // protected Literal typedLiteralX = new LiteralImpl("Don't panic.", XMLSchema.STRING); // protected Literal languageLiteralX = new LiteralImpl("Don't panic.", "en"); // // protected static final String NS = "http://example.org/ns#"; // protected static final IRI // ARTHUR = RDFAgents.createIRI(NS + "arthur"); // // protected Sail sail; // protected DatasetFactory datasetFactory; // protected MessageFactory messageFactory; // // @Override // public void setUp() throws Exception { // IRI senderName = RDFAgents.createIRI("http://example.org/agentA"); // IRI[] senderAddresses = new IRI[]{ // RDFAgents.createIRI("mailto:agentA@example.org"), // RDFAgents.createIRI("xmpp:agentA@example.org")}; // sender = new AgentId(senderName, senderAddresses); // // IRI receiverName = RDFAgents.createIRI("http://example.org/agentB"); // IRI[] receiverAddresses = new IRI[]{ // RDFAgents.createIRI("mailto:agentB@example.org"), // RDFAgents.createIRI("xmpp:agentB@example.org")}; // receiver = new AgentId(receiverName, receiverAddresses); // // datasetFactory = new DatasetFactory(new ValueFactoryImpl()); // for (RDFContentLanguage l : RDFContentLanguage.values()) { // datasetFactory.addLanguage(l); // } // Dataset d; // try (InputStream in = RDFAgents.class.getResourceAsStream("dummyData.trig")) { // d = datasetFactory.parse(in, RDFContentLanguage.RDF_TRIG); // } // // sail = new MemoryStore(); // sail.initialize(); // datasetFactory.addToSail(d, sail); // // messageFactory = new MessageFactory(datasetFactory); // } // // @Override // public void tearDown() throws Exception { // sail.shutDown(); // } // // protected void showDataset(final Dataset d) throws Exception { // RDFWriter w = Rio.createWriter(RDFFormat.TRIG, System.out); // w.startRDF(); // d.getStatements().forEach(w::handleStatement); // w.endRDF(); // } // } // // Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/model/Dataset.java // public class Dataset { // public static final String UUID_URN_PREFIX = "urn:uuid:"; // // private final Collection<Statement> statements; // // public Dataset(Collection<Statement> statements) { // this.statements = statements; // } // // public Collection<Statement> getStatements() { // return statements; // } // }
import net.fortytwo.rdfagents.RDFAgentsTestCase; import net.fortytwo.rdfagents.model.Dataset;
package net.fortytwo.rdfagents.data; /** * @author Joshua Shinavier (http://fortytwo.net) */ public class RecursiveDescribeQueryTest extends RDFAgentsTestCase { public void testAll() throws Exception { DatasetQuery q = new RecursiveDescribeQuery(ARTHUR, sail);
// Path: rdfagents-jade/src/test/java/net/fortytwo/rdfagents/RDFAgentsTestCase.java // public abstract class RDFAgentsTestCase extends TestCase { // protected AgentId sender, receiver; // protected IRI resourceX = RDFAgents.createIRI("http://example.org/resourceX"); // protected Literal plainLiteralX = new LiteralImpl("Don't panic."); // protected Literal typedLiteralX = new LiteralImpl("Don't panic.", XMLSchema.STRING); // protected Literal languageLiteralX = new LiteralImpl("Don't panic.", "en"); // // protected static final String NS = "http://example.org/ns#"; // protected static final IRI // ARTHUR = RDFAgents.createIRI(NS + "arthur"); // // protected Sail sail; // protected DatasetFactory datasetFactory; // protected MessageFactory messageFactory; // // @Override // public void setUp() throws Exception { // IRI senderName = RDFAgents.createIRI("http://example.org/agentA"); // IRI[] senderAddresses = new IRI[]{ // RDFAgents.createIRI("mailto:agentA@example.org"), // RDFAgents.createIRI("xmpp:agentA@example.org")}; // sender = new AgentId(senderName, senderAddresses); // // IRI receiverName = RDFAgents.createIRI("http://example.org/agentB"); // IRI[] receiverAddresses = new IRI[]{ // RDFAgents.createIRI("mailto:agentB@example.org"), // RDFAgents.createIRI("xmpp:agentB@example.org")}; // receiver = new AgentId(receiverName, receiverAddresses); // // datasetFactory = new DatasetFactory(new ValueFactoryImpl()); // for (RDFContentLanguage l : RDFContentLanguage.values()) { // datasetFactory.addLanguage(l); // } // Dataset d; // try (InputStream in = RDFAgents.class.getResourceAsStream("dummyData.trig")) { // d = datasetFactory.parse(in, RDFContentLanguage.RDF_TRIG); // } // // sail = new MemoryStore(); // sail.initialize(); // datasetFactory.addToSail(d, sail); // // messageFactory = new MessageFactory(datasetFactory); // } // // @Override // public void tearDown() throws Exception { // sail.shutDown(); // } // // protected void showDataset(final Dataset d) throws Exception { // RDFWriter w = Rio.createWriter(RDFFormat.TRIG, System.out); // w.startRDF(); // d.getStatements().forEach(w::handleStatement); // w.endRDF(); // } // } // // Path: rdfagents-core/src/main/java/net/fortytwo/rdfagents/model/Dataset.java // public class Dataset { // public static final String UUID_URN_PREFIX = "urn:uuid:"; // // private final Collection<Statement> statements; // // public Dataset(Collection<Statement> statements) { // this.statements = statements; // } // // public Collection<Statement> getStatements() { // return statements; // } // } // Path: rdfagents-jade/src/test/java/net/fortytwo/rdfagents/data/RecursiveDescribeQueryTest.java import net.fortytwo.rdfagents.RDFAgentsTestCase; import net.fortytwo.rdfagents.model.Dataset; package net.fortytwo.rdfagents.data; /** * @author Joshua Shinavier (http://fortytwo.net) */ public class RecursiveDescribeQueryTest extends RDFAgentsTestCase { public void testAll() throws Exception { DatasetQuery q = new RecursiveDescribeQuery(ARTHUR, sail);
Dataset arthur = q.evaluate();
ImpactDevelopment/ClientAPI
src/main/java/clientapi/load/mixin/MixinFontRenderer.java
// Path: src/main/java/clientapi/event/defaults/game/render/RenderTextEvent.java // public final class RenderTextEvent { // // /** // * The text being rendered // */ // private String text; // // public RenderTextEvent(String text) { // this.text = text; // } // // /** // * @return The text being rendered // */ // public final String getText() { // return this.text; // } // // /** // * Sets the text being rendered // * // * @param text New text // * @return This event // */ // public final RenderTextEvent setText(String text) { // this.text = text; // return this; // } // // @Override // public String toString() { // return "TextEvent{" + // "text='" + text + '\'' + // '}'; // } // }
import clientapi.ClientAPI; import clientapi.event.defaults.game.render.RenderTextEvent; import net.minecraft.client.gui.FontRenderer; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.ModifyVariable;
/* * Copyright 2018 ImpactDevelopment * * 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 clientapi.load.mixin; /** * @author Brady * @since 4/27/2017 */ @Mixin(FontRenderer.class) public abstract class MixinFontRenderer { @ModifyVariable( method = "renderStringAtPos", at = @At("HEAD") ) private String renderStringAtPos(String text) {
// Path: src/main/java/clientapi/event/defaults/game/render/RenderTextEvent.java // public final class RenderTextEvent { // // /** // * The text being rendered // */ // private String text; // // public RenderTextEvent(String text) { // this.text = text; // } // // /** // * @return The text being rendered // */ // public final String getText() { // return this.text; // } // // /** // * Sets the text being rendered // * // * @param text New text // * @return This event // */ // public final RenderTextEvent setText(String text) { // this.text = text; // return this; // } // // @Override // public String toString() { // return "TextEvent{" + // "text='" + text + '\'' + // '}'; // } // } // Path: src/main/java/clientapi/load/mixin/MixinFontRenderer.java import clientapi.ClientAPI; import clientapi.event.defaults.game.render.RenderTextEvent; import net.minecraft.client.gui.FontRenderer; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.ModifyVariable; /* * Copyright 2018 ImpactDevelopment * * 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 clientapi.load.mixin; /** * @author Brady * @since 4/27/2017 */ @Mixin(FontRenderer.class) public abstract class MixinFontRenderer { @ModifyVariable( method = "renderStringAtPos", at = @At("HEAD") ) private String renderStringAtPos(String text) {
RenderTextEvent event = new RenderTextEvent(text);
ImpactDevelopment/ClientAPI
src/main/java/clientapi/command/executor/parser/impl/BlockParser.java
// Path: src/main/java/clientapi/command/executor/ExecutionContext.java // public interface ExecutionContext { // // /** // * @return The {@link CommandSender} responsible for the command execution // */ // CommandSender sender(); // // /** // * @return The {@link CommandHandler} that carried out command execution // */ // CommandHandler handler(); // // static ExecutionContext of(CommandSender sender, CommandHandler handler) { // return new Impl(sender, handler); // } // // /** // * Implementation of {@link ExecutionContext}, used when // * creating an instance of {@link ExecutionContext} // * from {@link ExecutionContext#of(CommandSender, CommandHandler)} // * // * @see ExecutionContext#of(CommandSender, CommandHandler) // */ // class Impl implements ExecutionContext { // // /** // * {@link CommandSender} responsible for command execution // */ // private final CommandSender sender; // // /** // * {@link CommandHandler} that carried out command execution // */ // private final CommandHandler handler; // // private Impl(CommandSender sender, CommandHandler handler) { // this.sender = sender; // this.handler = handler; // } // // @Override // public CommandSender sender() { // return this.sender; // } // // @Override // public CommandHandler handler() { // return this.handler; // } // } // }
import clientapi.command.executor.ExecutionContext; import clientapi.command.executor.parser.ArgumentParser; import net.minecraft.block.Block; import java.lang.reflect.Type;
/* * Copyright 2018 ImpactDevelopment * * 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 clientapi.command.executor.parser.impl; /** * @author Brady * @since 11/3/2017 */ public final class BlockParser implements ArgumentParser<Block> { @Override
// Path: src/main/java/clientapi/command/executor/ExecutionContext.java // public interface ExecutionContext { // // /** // * @return The {@link CommandSender} responsible for the command execution // */ // CommandSender sender(); // // /** // * @return The {@link CommandHandler} that carried out command execution // */ // CommandHandler handler(); // // static ExecutionContext of(CommandSender sender, CommandHandler handler) { // return new Impl(sender, handler); // } // // /** // * Implementation of {@link ExecutionContext}, used when // * creating an instance of {@link ExecutionContext} // * from {@link ExecutionContext#of(CommandSender, CommandHandler)} // * // * @see ExecutionContext#of(CommandSender, CommandHandler) // */ // class Impl implements ExecutionContext { // // /** // * {@link CommandSender} responsible for command execution // */ // private final CommandSender sender; // // /** // * {@link CommandHandler} that carried out command execution // */ // private final CommandHandler handler; // // private Impl(CommandSender sender, CommandHandler handler) { // this.sender = sender; // this.handler = handler; // } // // @Override // public CommandSender sender() { // return this.sender; // } // // @Override // public CommandHandler handler() { // return this.handler; // } // } // } // Path: src/main/java/clientapi/command/executor/parser/impl/BlockParser.java import clientapi.command.executor.ExecutionContext; import clientapi.command.executor.parser.ArgumentParser; import net.minecraft.block.Block; import java.lang.reflect.Type; /* * Copyright 2018 ImpactDevelopment * * 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 clientapi.command.executor.parser.impl; /** * @author Brady * @since 11/3/2017 */ public final class BlockParser implements ArgumentParser<Block> { @Override
public final Block parse(ExecutionContext context, Type type, String raw) {
ImpactDevelopment/ClientAPI
src/main/java/clientapi/command/executor/parser/impl/NumberParser.java
// Path: src/main/java/clientapi/command/executor/ExecutionContext.java // public interface ExecutionContext { // // /** // * @return The {@link CommandSender} responsible for the command execution // */ // CommandSender sender(); // // /** // * @return The {@link CommandHandler} that carried out command execution // */ // CommandHandler handler(); // // static ExecutionContext of(CommandSender sender, CommandHandler handler) { // return new Impl(sender, handler); // } // // /** // * Implementation of {@link ExecutionContext}, used when // * creating an instance of {@link ExecutionContext} // * from {@link ExecutionContext#of(CommandSender, CommandHandler)} // * // * @see ExecutionContext#of(CommandSender, CommandHandler) // */ // class Impl implements ExecutionContext { // // /** // * {@link CommandSender} responsible for command execution // */ // private final CommandSender sender; // // /** // * {@link CommandHandler} that carried out command execution // */ // private final CommandHandler handler; // // private Impl(CommandSender sender, CommandHandler handler) { // this.sender = sender; // this.handler = handler; // } // // @Override // public CommandSender sender() { // return this.sender; // } // // @Override // public CommandHandler handler() { // return this.handler; // } // } // }
import clientapi.command.executor.ExecutionContext; import clientapi.command.executor.parser.ArgumentParser; import org.apache.commons.lang3.math.NumberUtils; import java.lang.reflect.Type; import java.math.BigDecimal; import java.math.BigInteger;
/* * Copyright 2018 ImpactDevelopment * * 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 clientapi.command.executor.parser.impl; /** * @author Brady * @since 10/20/2017 */ public final class NumberParser implements ArgumentParser<Number> { @Override
// Path: src/main/java/clientapi/command/executor/ExecutionContext.java // public interface ExecutionContext { // // /** // * @return The {@link CommandSender} responsible for the command execution // */ // CommandSender sender(); // // /** // * @return The {@link CommandHandler} that carried out command execution // */ // CommandHandler handler(); // // static ExecutionContext of(CommandSender sender, CommandHandler handler) { // return new Impl(sender, handler); // } // // /** // * Implementation of {@link ExecutionContext}, used when // * creating an instance of {@link ExecutionContext} // * from {@link ExecutionContext#of(CommandSender, CommandHandler)} // * // * @see ExecutionContext#of(CommandSender, CommandHandler) // */ // class Impl implements ExecutionContext { // // /** // * {@link CommandSender} responsible for command execution // */ // private final CommandSender sender; // // /** // * {@link CommandHandler} that carried out command execution // */ // private final CommandHandler handler; // // private Impl(CommandSender sender, CommandHandler handler) { // this.sender = sender; // this.handler = handler; // } // // @Override // public CommandSender sender() { // return this.sender; // } // // @Override // public CommandHandler handler() { // return this.handler; // } // } // } // Path: src/main/java/clientapi/command/executor/parser/impl/NumberParser.java import clientapi.command.executor.ExecutionContext; import clientapi.command.executor.parser.ArgumentParser; import org.apache.commons.lang3.math.NumberUtils; import java.lang.reflect.Type; import java.math.BigDecimal; import java.math.BigInteger; /* * Copyright 2018 ImpactDevelopment * * 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 clientapi.command.executor.parser.impl; /** * @author Brady * @since 10/20/2017 */ public final class NumberParser implements ArgumentParser<Number> { @Override
public final Number parse(ExecutionContext context, Type type, String raw) {
ImpactDevelopment/ClientAPI
src/example/java/me/zero/example/mod/mods/Fly.java
// Path: src/main/java/clientapi/event/defaults/game/entity/local/UpdateEvent.java // public final class UpdateEvent extends LocalPlayerEvent.Cancellable { // // private final EventState state; // // public UpdateEvent(EntityPlayerSP player, EventState state) { // super(player); // this.state = state; // } // // public EventState getState() { // return this.state; // } // // @Override // public String toString() { // return "UpdateEvent{" + // "state=" + state + // '}'; // } // } // // Path: src/example/java/me/zero/example/mod/category/IMovement.java // @Category(name = "Movement") // public interface IMovement {}
import clientapi.event.defaults.game.entity.local.UpdateEvent; import clientapi.module.Module; import clientapi.module.annotation.Mod; import me.zero.alpine.listener.EventHandler; import me.zero.alpine.listener.Listener; import me.zero.example.mod.category.IMovement; import org.lwjgl.input.Keyboard;
/* * Copyright 2018 ImpactDevelopment * * 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 me.zero.example.mod.mods; /** * @author Brady * @since 2/8/2017 12:00 PM */ @Mod(name = "Fly", description = "Allows you to fly", bind = Keyboard.KEY_F) public final class Fly extends Module implements IMovement { @EventHandler
// Path: src/main/java/clientapi/event/defaults/game/entity/local/UpdateEvent.java // public final class UpdateEvent extends LocalPlayerEvent.Cancellable { // // private final EventState state; // // public UpdateEvent(EntityPlayerSP player, EventState state) { // super(player); // this.state = state; // } // // public EventState getState() { // return this.state; // } // // @Override // public String toString() { // return "UpdateEvent{" + // "state=" + state + // '}'; // } // } // // Path: src/example/java/me/zero/example/mod/category/IMovement.java // @Category(name = "Movement") // public interface IMovement {} // Path: src/example/java/me/zero/example/mod/mods/Fly.java import clientapi.event.defaults.game.entity.local.UpdateEvent; import clientapi.module.Module; import clientapi.module.annotation.Mod; import me.zero.alpine.listener.EventHandler; import me.zero.alpine.listener.Listener; import me.zero.example.mod.category.IMovement; import org.lwjgl.input.Keyboard; /* * Copyright 2018 ImpactDevelopment * * 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 me.zero.example.mod.mods; /** * @author Brady * @since 2/8/2017 12:00 PM */ @Mod(name = "Fly", description = "Allows you to fly", bind = Keyboard.KEY_F) public final class Fly extends Module implements IMovement { @EventHandler
private Listener<UpdateEvent> updateListener = new Listener<>(event ->
ImpactDevelopment/ClientAPI
src/main/java/clientapi/command/exception/InvalidArgumentException.java
// Path: src/main/java/clientapi/command/Command.java // public class Command implements ICommand { // // /** // * A list of this command's child commands // */ // private final List<ChildCommand> children = new ArrayList<>(); // // /** // * A list of handles used to execute this command // */ // private String[] handles; // // /** // * A description of this command's usage // */ // private String description; // // public Command() { // if (!this.getClass().isAnnotationPresent(Cmd.class)) // throw new CommandInitException(this, "@Cmd annotation must be present if required parameters aren't passed through constructor"); // // Cmd data = this.getClass().getAnnotation(Cmd.class); // setup(data.handles(), data.description()); // } // // public Command(String[] handles, String description) { // setup(handles, description); // } // // private void setup(String[] handles, String description) { // this.handles = handles; // this.description = description; // // for (Method method : this.getClass().getDeclaredMethods()) { // int parameters = method.getParameterCount(); // if (parameters == 0 || !method.getParameterTypes()[0].equals(ExecutionContext.class) || !method.isAnnotationPresent(Sub.class)) // continue; // // // Ensure that there is only one optional at most, and that it is the last parameter // int optionals = 0; // for (int i = 0; i < parameters; i++) { // if (method.getParameterTypes()[i].isAssignableFrom(Optional.class)) { // if (i != parameters - 1) // throw new CommandInitException(this, "Optionals must be defined as the last parameter"); // if (++optionals > 1) // throw new CommandInitException(this, "More than one optional parameter is not supported"); // } // } // // // Create the child command // children.add(new ChildCommand(this, method)); // } // // if (ClientAPIUtils.containsNull(handles, description)) // throw new NullPointerException("One or more Command members were null!"); // } // // @Override // public final void execute(ExecutionContext context, String[] arguments) throws CommandException { // Optional<ChildCommand> sub = CommandInputParser.INSTANCE.findChild(this, arguments, true); // if (!sub.isPresent()) // throw new UnknownSubCommandException(this, arguments); // // // If the child was found by it's header, then remove the first argument. // if (sub.get().getHandles().length > 0 && arguments.length > 0) { // String[] newArgs = new String[arguments.length - 1]; // System.arraycopy(arguments, 1, newArgs, 0, arguments.length - 1); // arguments = newArgs; // } // // sub.get().execute(context, arguments); // } // // @Override // public final String[] getHandles() { // return this.handles; // } // // @Override // public final String getDescription() { // return this.description; // } // // /** // * @return A list of this command's child commands. // */ // public final List<ChildCommand> getChildren() { // return this.children; // } // }
import clientapi.command.ChildCommand; import clientapi.command.Command; import java.lang.reflect.Type;
/* * Copyright 2018 ImpactDevelopment * * 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 clientapi.command.exception; /** * Thrown when an argument that was passed to the command * was not the expected type. For example, a number was expected * but the number was unable to be parsed. * * @author Brady * @since 6/7/2017 */ public final class InvalidArgumentException extends CommandException { /** * The child command involved in the exception */ private final ChildCommand child; /** * Array of inputted arguments */ private final String[] args; /** * Index of the bag argument */ private final int badArg; /** * Expected type */ private final Type expected;
// Path: src/main/java/clientapi/command/Command.java // public class Command implements ICommand { // // /** // * A list of this command's child commands // */ // private final List<ChildCommand> children = new ArrayList<>(); // // /** // * A list of handles used to execute this command // */ // private String[] handles; // // /** // * A description of this command's usage // */ // private String description; // // public Command() { // if (!this.getClass().isAnnotationPresent(Cmd.class)) // throw new CommandInitException(this, "@Cmd annotation must be present if required parameters aren't passed through constructor"); // // Cmd data = this.getClass().getAnnotation(Cmd.class); // setup(data.handles(), data.description()); // } // // public Command(String[] handles, String description) { // setup(handles, description); // } // // private void setup(String[] handles, String description) { // this.handles = handles; // this.description = description; // // for (Method method : this.getClass().getDeclaredMethods()) { // int parameters = method.getParameterCount(); // if (parameters == 0 || !method.getParameterTypes()[0].equals(ExecutionContext.class) || !method.isAnnotationPresent(Sub.class)) // continue; // // // Ensure that there is only one optional at most, and that it is the last parameter // int optionals = 0; // for (int i = 0; i < parameters; i++) { // if (method.getParameterTypes()[i].isAssignableFrom(Optional.class)) { // if (i != parameters - 1) // throw new CommandInitException(this, "Optionals must be defined as the last parameter"); // if (++optionals > 1) // throw new CommandInitException(this, "More than one optional parameter is not supported"); // } // } // // // Create the child command // children.add(new ChildCommand(this, method)); // } // // if (ClientAPIUtils.containsNull(handles, description)) // throw new NullPointerException("One or more Command members were null!"); // } // // @Override // public final void execute(ExecutionContext context, String[] arguments) throws CommandException { // Optional<ChildCommand> sub = CommandInputParser.INSTANCE.findChild(this, arguments, true); // if (!sub.isPresent()) // throw new UnknownSubCommandException(this, arguments); // // // If the child was found by it's header, then remove the first argument. // if (sub.get().getHandles().length > 0 && arguments.length > 0) { // String[] newArgs = new String[arguments.length - 1]; // System.arraycopy(arguments, 1, newArgs, 0, arguments.length - 1); // arguments = newArgs; // } // // sub.get().execute(context, arguments); // } // // @Override // public final String[] getHandles() { // return this.handles; // } // // @Override // public final String getDescription() { // return this.description; // } // // /** // * @return A list of this command's child commands. // */ // public final List<ChildCommand> getChildren() { // return this.children; // } // } // Path: src/main/java/clientapi/command/exception/InvalidArgumentException.java import clientapi.command.ChildCommand; import clientapi.command.Command; import java.lang.reflect.Type; /* * Copyright 2018 ImpactDevelopment * * 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 clientapi.command.exception; /** * Thrown when an argument that was passed to the command * was not the expected type. For example, a number was expected * but the number was unable to be parsed. * * @author Brady * @since 6/7/2017 */ public final class InvalidArgumentException extends CommandException { /** * The child command involved in the exception */ private final ChildCommand child; /** * Array of inputted arguments */ private final String[] args; /** * Index of the bag argument */ private final int badArg; /** * Expected type */ private final Type expected;
public InvalidArgumentException(Command command, ChildCommand child, String[] args, int badArg, Type expected) {
ImpactDevelopment/ClientAPI
src/example/java/me/zero/example/command/commands/TestCommand.java
// Path: src/main/java/clientapi/command/Command.java // public class Command implements ICommand { // // /** // * A list of this command's child commands // */ // private final List<ChildCommand> children = new ArrayList<>(); // // /** // * A list of handles used to execute this command // */ // private String[] handles; // // /** // * A description of this command's usage // */ // private String description; // // public Command() { // if (!this.getClass().isAnnotationPresent(Cmd.class)) // throw new CommandInitException(this, "@Cmd annotation must be present if required parameters aren't passed through constructor"); // // Cmd data = this.getClass().getAnnotation(Cmd.class); // setup(data.handles(), data.description()); // } // // public Command(String[] handles, String description) { // setup(handles, description); // } // // private void setup(String[] handles, String description) { // this.handles = handles; // this.description = description; // // for (Method method : this.getClass().getDeclaredMethods()) { // int parameters = method.getParameterCount(); // if (parameters == 0 || !method.getParameterTypes()[0].equals(ExecutionContext.class) || !method.isAnnotationPresent(Sub.class)) // continue; // // // Ensure that there is only one optional at most, and that it is the last parameter // int optionals = 0; // for (int i = 0; i < parameters; i++) { // if (method.getParameterTypes()[i].isAssignableFrom(Optional.class)) { // if (i != parameters - 1) // throw new CommandInitException(this, "Optionals must be defined as the last parameter"); // if (++optionals > 1) // throw new CommandInitException(this, "More than one optional parameter is not supported"); // } // } // // // Create the child command // children.add(new ChildCommand(this, method)); // } // // if (ClientAPIUtils.containsNull(handles, description)) // throw new NullPointerException("One or more Command members were null!"); // } // // @Override // public final void execute(ExecutionContext context, String[] arguments) throws CommandException { // Optional<ChildCommand> sub = CommandInputParser.INSTANCE.findChild(this, arguments, true); // if (!sub.isPresent()) // throw new UnknownSubCommandException(this, arguments); // // // If the child was found by it's header, then remove the first argument. // if (sub.get().getHandles().length > 0 && arguments.length > 0) { // String[] newArgs = new String[arguments.length - 1]; // System.arraycopy(arguments, 1, newArgs, 0, arguments.length - 1); // arguments = newArgs; // } // // sub.get().execute(context, arguments); // } // // @Override // public final String[] getHandles() { // return this.handles; // } // // @Override // public final String getDescription() { // return this.description; // } // // /** // * @return A list of this command's child commands. // */ // public final List<ChildCommand> getChildren() { // return this.children; // } // } // // Path: src/main/java/clientapi/command/executor/ExecutionContext.java // public interface ExecutionContext { // // /** // * @return The {@link CommandSender} responsible for the command execution // */ // CommandSender sender(); // // /** // * @return The {@link CommandHandler} that carried out command execution // */ // CommandHandler handler(); // // static ExecutionContext of(CommandSender sender, CommandHandler handler) { // return new Impl(sender, handler); // } // // /** // * Implementation of {@link ExecutionContext}, used when // * creating an instance of {@link ExecutionContext} // * from {@link ExecutionContext#of(CommandSender, CommandHandler)} // * // * @see ExecutionContext#of(CommandSender, CommandHandler) // */ // class Impl implements ExecutionContext { // // /** // * {@link CommandSender} responsible for command execution // */ // private final CommandSender sender; // // /** // * {@link CommandHandler} that carried out command execution // */ // private final CommandHandler handler; // // private Impl(CommandSender sender, CommandHandler handler) { // this.sender = sender; // this.handler = handler; // } // // @Override // public CommandSender sender() { // return this.sender; // } // // @Override // public CommandHandler handler() { // return this.handler; // } // } // }
import clientapi.command.Command; import clientapi.command.annotation.Cmd; import clientapi.command.annotation.Sub; import clientapi.command.executor.ExecutionContext; import clientapi.util.builder.impl.ChatBuilder; import net.minecraft.util.text.TextFormatting; import java.util.Optional;
/* * Copyright 2018 ImpactDevelopment * * 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 me.zero.example.command.commands; /** * @author Brady * @since 5/31/2017 6:18 PM */ @Cmd(handles = { "test", "example"}, description = "Test Command") public final class TestCommand extends Command { /** * Sub command with no defining header, that takes * in any arguments that are passed to the command, * indicated by the vararg. * * @param context Context behind command execution * @param argument Arguments */ @Sub
// Path: src/main/java/clientapi/command/Command.java // public class Command implements ICommand { // // /** // * A list of this command's child commands // */ // private final List<ChildCommand> children = new ArrayList<>(); // // /** // * A list of handles used to execute this command // */ // private String[] handles; // // /** // * A description of this command's usage // */ // private String description; // // public Command() { // if (!this.getClass().isAnnotationPresent(Cmd.class)) // throw new CommandInitException(this, "@Cmd annotation must be present if required parameters aren't passed through constructor"); // // Cmd data = this.getClass().getAnnotation(Cmd.class); // setup(data.handles(), data.description()); // } // // public Command(String[] handles, String description) { // setup(handles, description); // } // // private void setup(String[] handles, String description) { // this.handles = handles; // this.description = description; // // for (Method method : this.getClass().getDeclaredMethods()) { // int parameters = method.getParameterCount(); // if (parameters == 0 || !method.getParameterTypes()[0].equals(ExecutionContext.class) || !method.isAnnotationPresent(Sub.class)) // continue; // // // Ensure that there is only one optional at most, and that it is the last parameter // int optionals = 0; // for (int i = 0; i < parameters; i++) { // if (method.getParameterTypes()[i].isAssignableFrom(Optional.class)) { // if (i != parameters - 1) // throw new CommandInitException(this, "Optionals must be defined as the last parameter"); // if (++optionals > 1) // throw new CommandInitException(this, "More than one optional parameter is not supported"); // } // } // // // Create the child command // children.add(new ChildCommand(this, method)); // } // // if (ClientAPIUtils.containsNull(handles, description)) // throw new NullPointerException("One or more Command members were null!"); // } // // @Override // public final void execute(ExecutionContext context, String[] arguments) throws CommandException { // Optional<ChildCommand> sub = CommandInputParser.INSTANCE.findChild(this, arguments, true); // if (!sub.isPresent()) // throw new UnknownSubCommandException(this, arguments); // // // If the child was found by it's header, then remove the first argument. // if (sub.get().getHandles().length > 0 && arguments.length > 0) { // String[] newArgs = new String[arguments.length - 1]; // System.arraycopy(arguments, 1, newArgs, 0, arguments.length - 1); // arguments = newArgs; // } // // sub.get().execute(context, arguments); // } // // @Override // public final String[] getHandles() { // return this.handles; // } // // @Override // public final String getDescription() { // return this.description; // } // // /** // * @return A list of this command's child commands. // */ // public final List<ChildCommand> getChildren() { // return this.children; // } // } // // Path: src/main/java/clientapi/command/executor/ExecutionContext.java // public interface ExecutionContext { // // /** // * @return The {@link CommandSender} responsible for the command execution // */ // CommandSender sender(); // // /** // * @return The {@link CommandHandler} that carried out command execution // */ // CommandHandler handler(); // // static ExecutionContext of(CommandSender sender, CommandHandler handler) { // return new Impl(sender, handler); // } // // /** // * Implementation of {@link ExecutionContext}, used when // * creating an instance of {@link ExecutionContext} // * from {@link ExecutionContext#of(CommandSender, CommandHandler)} // * // * @see ExecutionContext#of(CommandSender, CommandHandler) // */ // class Impl implements ExecutionContext { // // /** // * {@link CommandSender} responsible for command execution // */ // private final CommandSender sender; // // /** // * {@link CommandHandler} that carried out command execution // */ // private final CommandHandler handler; // // private Impl(CommandSender sender, CommandHandler handler) { // this.sender = sender; // this.handler = handler; // } // // @Override // public CommandSender sender() { // return this.sender; // } // // @Override // public CommandHandler handler() { // return this.handler; // } // } // } // Path: src/example/java/me/zero/example/command/commands/TestCommand.java import clientapi.command.Command; import clientapi.command.annotation.Cmd; import clientapi.command.annotation.Sub; import clientapi.command.executor.ExecutionContext; import clientapi.util.builder.impl.ChatBuilder; import net.minecraft.util.text.TextFormatting; import java.util.Optional; /* * Copyright 2018 ImpactDevelopment * * 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 me.zero.example.command.commands; /** * @author Brady * @since 5/31/2017 6:18 PM */ @Cmd(handles = { "test", "example"}, description = "Test Command") public final class TestCommand extends Command { /** * Sub command with no defining header, that takes * in any arguments that are passed to the command, * indicated by the vararg. * * @param context Context behind command execution * @param argument Arguments */ @Sub
private void handle(ExecutionContext context, Optional<String> argument) {
ImpactDevelopment/ClientAPI
src/main/java/clientapi/command/Command.java
// Path: src/main/java/clientapi/command/exception/CommandInitException.java // public final class CommandInitException extends CommandException { // // public CommandInitException(Command command, String message) { // super(command, message); // } // } // // Path: src/main/java/clientapi/command/executor/ExecutionContext.java // public interface ExecutionContext { // // /** // * @return The {@link CommandSender} responsible for the command execution // */ // CommandSender sender(); // // /** // * @return The {@link CommandHandler} that carried out command execution // */ // CommandHandler handler(); // // static ExecutionContext of(CommandSender sender, CommandHandler handler) { // return new Impl(sender, handler); // } // // /** // * Implementation of {@link ExecutionContext}, used when // * creating an instance of {@link ExecutionContext} // * from {@link ExecutionContext#of(CommandSender, CommandHandler)} // * // * @see ExecutionContext#of(CommandSender, CommandHandler) // */ // class Impl implements ExecutionContext { // // /** // * {@link CommandSender} responsible for command execution // */ // private final CommandSender sender; // // /** // * {@link CommandHandler} that carried out command execution // */ // private final CommandHandler handler; // // private Impl(CommandSender sender, CommandHandler handler) { // this.sender = sender; // this.handler = handler; // } // // @Override // public CommandSender sender() { // return this.sender; // } // // @Override // public CommandHandler handler() { // return this.handler; // } // } // }
import clientapi.command.annotation.Cmd; import clientapi.command.annotation.Sub; import clientapi.command.exception.CommandException; import clientapi.command.exception.CommandInitException; import clientapi.command.exception.UnknownSubCommandException; import clientapi.command.executor.ExecutionContext; import clientapi.command.executor.parser.CommandInputParser; import clientapi.util.ClientAPIUtils; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import java.util.Optional;
/* * Copyright 2018 ImpactDevelopment * * 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 clientapi.command; /** * Implementation of {@link ICommand} * * @author Brady * @since 5/31/2017 */ public class Command implements ICommand { /** * A list of this command's child commands */ private final List<ChildCommand> children = new ArrayList<>(); /** * A list of handles used to execute this command */ private String[] handles; /** * A description of this command's usage */ private String description; public Command() { if (!this.getClass().isAnnotationPresent(Cmd.class))
// Path: src/main/java/clientapi/command/exception/CommandInitException.java // public final class CommandInitException extends CommandException { // // public CommandInitException(Command command, String message) { // super(command, message); // } // } // // Path: src/main/java/clientapi/command/executor/ExecutionContext.java // public interface ExecutionContext { // // /** // * @return The {@link CommandSender} responsible for the command execution // */ // CommandSender sender(); // // /** // * @return The {@link CommandHandler} that carried out command execution // */ // CommandHandler handler(); // // static ExecutionContext of(CommandSender sender, CommandHandler handler) { // return new Impl(sender, handler); // } // // /** // * Implementation of {@link ExecutionContext}, used when // * creating an instance of {@link ExecutionContext} // * from {@link ExecutionContext#of(CommandSender, CommandHandler)} // * // * @see ExecutionContext#of(CommandSender, CommandHandler) // */ // class Impl implements ExecutionContext { // // /** // * {@link CommandSender} responsible for command execution // */ // private final CommandSender sender; // // /** // * {@link CommandHandler} that carried out command execution // */ // private final CommandHandler handler; // // private Impl(CommandSender sender, CommandHandler handler) { // this.sender = sender; // this.handler = handler; // } // // @Override // public CommandSender sender() { // return this.sender; // } // // @Override // public CommandHandler handler() { // return this.handler; // } // } // } // Path: src/main/java/clientapi/command/Command.java import clientapi.command.annotation.Cmd; import clientapi.command.annotation.Sub; import clientapi.command.exception.CommandException; import clientapi.command.exception.CommandInitException; import clientapi.command.exception.UnknownSubCommandException; import clientapi.command.executor.ExecutionContext; import clientapi.command.executor.parser.CommandInputParser; import clientapi.util.ClientAPIUtils; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import java.util.Optional; /* * Copyright 2018 ImpactDevelopment * * 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 clientapi.command; /** * Implementation of {@link ICommand} * * @author Brady * @since 5/31/2017 */ public class Command implements ICommand { /** * A list of this command's child commands */ private final List<ChildCommand> children = new ArrayList<>(); /** * A list of handles used to execute this command */ private String[] handles; /** * A description of this command's usage */ private String description; public Command() { if (!this.getClass().isAnnotationPresent(Cmd.class))
throw new CommandInitException(this, "@Cmd annotation must be present if required parameters aren't passed through constructor");
ImpactDevelopment/ClientAPI
src/main/java/clientapi/command/Command.java
// Path: src/main/java/clientapi/command/exception/CommandInitException.java // public final class CommandInitException extends CommandException { // // public CommandInitException(Command command, String message) { // super(command, message); // } // } // // Path: src/main/java/clientapi/command/executor/ExecutionContext.java // public interface ExecutionContext { // // /** // * @return The {@link CommandSender} responsible for the command execution // */ // CommandSender sender(); // // /** // * @return The {@link CommandHandler} that carried out command execution // */ // CommandHandler handler(); // // static ExecutionContext of(CommandSender sender, CommandHandler handler) { // return new Impl(sender, handler); // } // // /** // * Implementation of {@link ExecutionContext}, used when // * creating an instance of {@link ExecutionContext} // * from {@link ExecutionContext#of(CommandSender, CommandHandler)} // * // * @see ExecutionContext#of(CommandSender, CommandHandler) // */ // class Impl implements ExecutionContext { // // /** // * {@link CommandSender} responsible for command execution // */ // private final CommandSender sender; // // /** // * {@link CommandHandler} that carried out command execution // */ // private final CommandHandler handler; // // private Impl(CommandSender sender, CommandHandler handler) { // this.sender = sender; // this.handler = handler; // } // // @Override // public CommandSender sender() { // return this.sender; // } // // @Override // public CommandHandler handler() { // return this.handler; // } // } // }
import clientapi.command.annotation.Cmd; import clientapi.command.annotation.Sub; import clientapi.command.exception.CommandException; import clientapi.command.exception.CommandInitException; import clientapi.command.exception.UnknownSubCommandException; import clientapi.command.executor.ExecutionContext; import clientapi.command.executor.parser.CommandInputParser; import clientapi.util.ClientAPIUtils; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import java.util.Optional;
/* * Copyright 2018 ImpactDevelopment * * 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 clientapi.command; /** * Implementation of {@link ICommand} * * @author Brady * @since 5/31/2017 */ public class Command implements ICommand { /** * A list of this command's child commands */ private final List<ChildCommand> children = new ArrayList<>(); /** * A list of handles used to execute this command */ private String[] handles; /** * A description of this command's usage */ private String description; public Command() { if (!this.getClass().isAnnotationPresent(Cmd.class)) throw new CommandInitException(this, "@Cmd annotation must be present if required parameters aren't passed through constructor"); Cmd data = this.getClass().getAnnotation(Cmd.class); setup(data.handles(), data.description()); } public Command(String[] handles, String description) { setup(handles, description); } private void setup(String[] handles, String description) { this.handles = handles; this.description = description; for (Method method : this.getClass().getDeclaredMethods()) { int parameters = method.getParameterCount();
// Path: src/main/java/clientapi/command/exception/CommandInitException.java // public final class CommandInitException extends CommandException { // // public CommandInitException(Command command, String message) { // super(command, message); // } // } // // Path: src/main/java/clientapi/command/executor/ExecutionContext.java // public interface ExecutionContext { // // /** // * @return The {@link CommandSender} responsible for the command execution // */ // CommandSender sender(); // // /** // * @return The {@link CommandHandler} that carried out command execution // */ // CommandHandler handler(); // // static ExecutionContext of(CommandSender sender, CommandHandler handler) { // return new Impl(sender, handler); // } // // /** // * Implementation of {@link ExecutionContext}, used when // * creating an instance of {@link ExecutionContext} // * from {@link ExecutionContext#of(CommandSender, CommandHandler)} // * // * @see ExecutionContext#of(CommandSender, CommandHandler) // */ // class Impl implements ExecutionContext { // // /** // * {@link CommandSender} responsible for command execution // */ // private final CommandSender sender; // // /** // * {@link CommandHandler} that carried out command execution // */ // private final CommandHandler handler; // // private Impl(CommandSender sender, CommandHandler handler) { // this.sender = sender; // this.handler = handler; // } // // @Override // public CommandSender sender() { // return this.sender; // } // // @Override // public CommandHandler handler() { // return this.handler; // } // } // } // Path: src/main/java/clientapi/command/Command.java import clientapi.command.annotation.Cmd; import clientapi.command.annotation.Sub; import clientapi.command.exception.CommandException; import clientapi.command.exception.CommandInitException; import clientapi.command.exception.UnknownSubCommandException; import clientapi.command.executor.ExecutionContext; import clientapi.command.executor.parser.CommandInputParser; import clientapi.util.ClientAPIUtils; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import java.util.Optional; /* * Copyright 2018 ImpactDevelopment * * 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 clientapi.command; /** * Implementation of {@link ICommand} * * @author Brady * @since 5/31/2017 */ public class Command implements ICommand { /** * A list of this command's child commands */ private final List<ChildCommand> children = new ArrayList<>(); /** * A list of handles used to execute this command */ private String[] handles; /** * A description of this command's usage */ private String description; public Command() { if (!this.getClass().isAnnotationPresent(Cmd.class)) throw new CommandInitException(this, "@Cmd annotation must be present if required parameters aren't passed through constructor"); Cmd data = this.getClass().getAnnotation(Cmd.class); setup(data.handles(), data.description()); } public Command(String[] handles, String description) { setup(handles, description); } private void setup(String[] handles, String description) { this.handles = handles; this.description = description; for (Method method : this.getClass().getDeclaredMethods()) { int parameters = method.getParameterCount();
if (parameters == 0 || !method.getParameterTypes()[0].equals(ExecutionContext.class) || !method.isAnnotationPresent(Sub.class))
ImpactDevelopment/ClientAPI
src/main/java/clientapi/load/mixin/MixinGuiSpectator.java
// Path: src/main/java/clientapi/event/defaults/game/render/HudOverlayEvent.java // public final class HudOverlayEvent extends Cancellable { // // /** // * The type of overlay that is being rendered // */ // private final Type type; // // public HudOverlayEvent(Type type) { // this.type = type; // } // // /** // * @return The type of overlay that is being rendered // */ // public final Type getType() { // return this.type; // } // // public enum Type { // /** // * Rendered when the player is in water and their eye height is under the water level // */ // WATER, // // /** // * Rendered when the player is in lava and their eye height is under the lava level // */ // LAVA, // // /** // * Rendered when the player has a pumpkin on their head // */ // PUMPKIN, // // /** // * Transformation to the screen when the player takes damage // */ // HURTCAM, // // /** // * The scoreboard that is displayed on the right side of the screen // */ // SCOREBOARD, // // /** // * Rendered when the player is on fire // */ // FIRE, // // /** // * The entire stat bar // */ // STAT_ALL, // // /** // * The stat bar displaying the health level of the player // */ // STAT_HEALTH, // // /** // * The stat bar displaying the food level of the player // */ // STAT_FOOD, // // /** // * The stat bar displaying the armor level of the player // */ // STAT_ARMOR, // // /** // * The stat bar displaying the remaining air that the player has when underwater // */ // STAT_AIR, // // /** // * The boss bar rendered at the top of the screen showing the boss health // */ // BOSS_BAR, // // /** // * The bar displaying the current player experience level // */ // EXP_BAR, // // /** // * The vignette effect overlayed over the game // */ // VIGNETTE, // // /** // * The crosshair // */ // CROSSHAIR, // // /** // * The attack indicator displaying the remaining time until the player's attack is fully charged // */ // ATTACK_INDICATOR, // // /** // * The horse jump bar // */ // JUMP_BAR, // // /** // * The health of the currently mounted entity // */ // MOUNT_HEALTH, // // /** // * The overlay rendered when the player is inside of a nether portal // */ // PORTAL, // // /** // * The tooltip displayed over the hotbar when a new item is selected // */ // SELECTED_ITEM_TOOLTIP, // // /** // * The list of potion effects in the top right of the screen // */ // POTION_EFFECTS // } // // @Override // public String toString() { // return "HudOverlayEvent{" + // "type=" + type + // '}'; // } // }
import clientapi.ClientAPI; import clientapi.event.defaults.game.render.HudOverlayEvent; import net.minecraft.client.gui.GuiSpectator; import net.minecraft.client.gui.ScaledResolution; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
/* * Copyright 2018 ImpactDevelopment * * 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 clientapi.load.mixin; /** * @author Brady * @since 5/24/2018 */ @Mixin(GuiSpectator.class) public class MixinGuiSpectator { @Inject( method = "renderSelectedItem", at = @At("HEAD"), cancellable = true ) private void renderSelectedItem(ScaledResolution scaledRes, CallbackInfo ci) {
// Path: src/main/java/clientapi/event/defaults/game/render/HudOverlayEvent.java // public final class HudOverlayEvent extends Cancellable { // // /** // * The type of overlay that is being rendered // */ // private final Type type; // // public HudOverlayEvent(Type type) { // this.type = type; // } // // /** // * @return The type of overlay that is being rendered // */ // public final Type getType() { // return this.type; // } // // public enum Type { // /** // * Rendered when the player is in water and their eye height is under the water level // */ // WATER, // // /** // * Rendered when the player is in lava and their eye height is under the lava level // */ // LAVA, // // /** // * Rendered when the player has a pumpkin on their head // */ // PUMPKIN, // // /** // * Transformation to the screen when the player takes damage // */ // HURTCAM, // // /** // * The scoreboard that is displayed on the right side of the screen // */ // SCOREBOARD, // // /** // * Rendered when the player is on fire // */ // FIRE, // // /** // * The entire stat bar // */ // STAT_ALL, // // /** // * The stat bar displaying the health level of the player // */ // STAT_HEALTH, // // /** // * The stat bar displaying the food level of the player // */ // STAT_FOOD, // // /** // * The stat bar displaying the armor level of the player // */ // STAT_ARMOR, // // /** // * The stat bar displaying the remaining air that the player has when underwater // */ // STAT_AIR, // // /** // * The boss bar rendered at the top of the screen showing the boss health // */ // BOSS_BAR, // // /** // * The bar displaying the current player experience level // */ // EXP_BAR, // // /** // * The vignette effect overlayed over the game // */ // VIGNETTE, // // /** // * The crosshair // */ // CROSSHAIR, // // /** // * The attack indicator displaying the remaining time until the player's attack is fully charged // */ // ATTACK_INDICATOR, // // /** // * The horse jump bar // */ // JUMP_BAR, // // /** // * The health of the currently mounted entity // */ // MOUNT_HEALTH, // // /** // * The overlay rendered when the player is inside of a nether portal // */ // PORTAL, // // /** // * The tooltip displayed over the hotbar when a new item is selected // */ // SELECTED_ITEM_TOOLTIP, // // /** // * The list of potion effects in the top right of the screen // */ // POTION_EFFECTS // } // // @Override // public String toString() { // return "HudOverlayEvent{" + // "type=" + type + // '}'; // } // } // Path: src/main/java/clientapi/load/mixin/MixinGuiSpectator.java import clientapi.ClientAPI; import clientapi.event.defaults.game.render.HudOverlayEvent; import net.minecraft.client.gui.GuiSpectator; import net.minecraft.client.gui.ScaledResolution; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; /* * Copyright 2018 ImpactDevelopment * * 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 clientapi.load.mixin; /** * @author Brady * @since 5/24/2018 */ @Mixin(GuiSpectator.class) public class MixinGuiSpectator { @Inject( method = "renderSelectedItem", at = @At("HEAD"), cancellable = true ) private void renderSelectedItem(ScaledResolution scaledRes, CallbackInfo ci) {
HudOverlayEvent event = new HudOverlayEvent(HudOverlayEvent.Type.SELECTED_ITEM_TOOLTIP);
ImpactDevelopment/ClientAPI
src/main/java/clientapi/command/executor/parser/impl/ItemParser.java
// Path: src/main/java/clientapi/command/executor/ExecutionContext.java // public interface ExecutionContext { // // /** // * @return The {@link CommandSender} responsible for the command execution // */ // CommandSender sender(); // // /** // * @return The {@link CommandHandler} that carried out command execution // */ // CommandHandler handler(); // // static ExecutionContext of(CommandSender sender, CommandHandler handler) { // return new Impl(sender, handler); // } // // /** // * Implementation of {@link ExecutionContext}, used when // * creating an instance of {@link ExecutionContext} // * from {@link ExecutionContext#of(CommandSender, CommandHandler)} // * // * @see ExecutionContext#of(CommandSender, CommandHandler) // */ // class Impl implements ExecutionContext { // // /** // * {@link CommandSender} responsible for command execution // */ // private final CommandSender sender; // // /** // * {@link CommandHandler} that carried out command execution // */ // private final CommandHandler handler; // // private Impl(CommandSender sender, CommandHandler handler) { // this.sender = sender; // this.handler = handler; // } // // @Override // public CommandSender sender() { // return this.sender; // } // // @Override // public CommandHandler handler() { // return this.handler; // } // } // }
import clientapi.command.executor.ExecutionContext; import clientapi.command.executor.parser.ArgumentParser; import net.minecraft.item.Item; import java.lang.reflect.Type;
/* * Copyright 2018 ImpactDevelopment * * 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 clientapi.command.executor.parser.impl; /** * @author Brady * @since 4/19/2018 */ public final class ItemParser implements ArgumentParser<Item> { @Override
// Path: src/main/java/clientapi/command/executor/ExecutionContext.java // public interface ExecutionContext { // // /** // * @return The {@link CommandSender} responsible for the command execution // */ // CommandSender sender(); // // /** // * @return The {@link CommandHandler} that carried out command execution // */ // CommandHandler handler(); // // static ExecutionContext of(CommandSender sender, CommandHandler handler) { // return new Impl(sender, handler); // } // // /** // * Implementation of {@link ExecutionContext}, used when // * creating an instance of {@link ExecutionContext} // * from {@link ExecutionContext#of(CommandSender, CommandHandler)} // * // * @see ExecutionContext#of(CommandSender, CommandHandler) // */ // class Impl implements ExecutionContext { // // /** // * {@link CommandSender} responsible for command execution // */ // private final CommandSender sender; // // /** // * {@link CommandHandler} that carried out command execution // */ // private final CommandHandler handler; // // private Impl(CommandSender sender, CommandHandler handler) { // this.sender = sender; // this.handler = handler; // } // // @Override // public CommandSender sender() { // return this.sender; // } // // @Override // public CommandHandler handler() { // return this.handler; // } // } // } // Path: src/main/java/clientapi/command/executor/parser/impl/ItemParser.java import clientapi.command.executor.ExecutionContext; import clientapi.command.executor.parser.ArgumentParser; import net.minecraft.item.Item; import java.lang.reflect.Type; /* * Copyright 2018 ImpactDevelopment * * 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 clientapi.command.executor.parser.impl; /** * @author Brady * @since 4/19/2018 */ public final class ItemParser implements ArgumentParser<Item> { @Override
public final Item parse(ExecutionContext context, Type type, String raw) {
ImpactDevelopment/ClientAPI
src/main/java/clientapi/load/mixin/MixinWorldClient.java
// Path: src/main/java/clientapi/event/defaults/game/network/ServerEvent.java // public class ServerEvent { // // /** // * Server being connected/disconnected to/from // */ // private final ServerData serverData; // // ServerEvent(ServerData serverData) { // this.serverData = serverData; // } // // /** // * @return Server being connected/disconnected to/from // */ // public final ServerData getServerData() { // return this.serverData; // } // // /** // * Called when the client user connects to a server // */ // public static class Connect extends ServerEvent { // // /** // * State of the event // * // * @see State // */ // private final State state; // // public Connect(State state, ServerData serverData) { // super(serverData); // this.state = state; // } // // /** // * @return The state of the event // */ // public final State getState() { // return this.state; // } // // public enum State { // // /** // * Called before the connection attempt // */ // PRE, // // /** // * Indicates that the connection attempt was successful // */ // CONNECT, // // /** // * Indicates that an exception occurred when trying to connect to the target server. // * This will be followed by an instance of {@link ServerEvent.Disconnect} being posted. // */ // FAILED // } // } // // /** // * Called when the client user disconnects from a server // */ // public static class Disconnect extends ServerEvent { // // /** // * State of the event. PRE if before the disconnect processing. // * POST if disconnect processing has already been executed. // */ // private final EventState state; // // /** // * Whether or not the connection was forcefully closed. True if the // * server called for the client to be disconnected. False if the // * client manually disconnected through {@link GuiIngameMenu}. // */ // private final boolean forced; // // public Disconnect(EventState state, boolean forced, ServerData serverData) { // super(serverData); // this.state = state; // this.forced = forced; // } // // /** // * @return The state of the event // */ // public final EventState getState() { // return this.state; // } // // /** // * @return Whether or not the connection was forcefully closed // */ // public final boolean isForced() { // return this.forced; // } // } // // @Override // public String toString() { // return "ServerEvent{" + // "serverData=" + serverData + // '}'; // } // }
import clientapi.ClientAPI; import clientapi.event.defaults.game.network.ServerEvent; import me.zero.alpine.event.EventState; import net.minecraft.client.Minecraft; import net.minecraft.client.multiplayer.WorldClient; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
/* * Copyright 2018 ImpactDevelopment * * 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 clientapi.load.mixin; /** * @author Brady * @since 9/7/2017 */ @Mixin(WorldClient.class) public class MixinWorldClient { @Shadow @Final private Minecraft mc; @Inject( method = "sendQuittingDisconnectingPacket", at = @At("HEAD") ) private void preSendQuittingDisconnectingPacket(CallbackInfo ci) {
// Path: src/main/java/clientapi/event/defaults/game/network/ServerEvent.java // public class ServerEvent { // // /** // * Server being connected/disconnected to/from // */ // private final ServerData serverData; // // ServerEvent(ServerData serverData) { // this.serverData = serverData; // } // // /** // * @return Server being connected/disconnected to/from // */ // public final ServerData getServerData() { // return this.serverData; // } // // /** // * Called when the client user connects to a server // */ // public static class Connect extends ServerEvent { // // /** // * State of the event // * // * @see State // */ // private final State state; // // public Connect(State state, ServerData serverData) { // super(serverData); // this.state = state; // } // // /** // * @return The state of the event // */ // public final State getState() { // return this.state; // } // // public enum State { // // /** // * Called before the connection attempt // */ // PRE, // // /** // * Indicates that the connection attempt was successful // */ // CONNECT, // // /** // * Indicates that an exception occurred when trying to connect to the target server. // * This will be followed by an instance of {@link ServerEvent.Disconnect} being posted. // */ // FAILED // } // } // // /** // * Called when the client user disconnects from a server // */ // public static class Disconnect extends ServerEvent { // // /** // * State of the event. PRE if before the disconnect processing. // * POST if disconnect processing has already been executed. // */ // private final EventState state; // // /** // * Whether or not the connection was forcefully closed. True if the // * server called for the client to be disconnected. False if the // * client manually disconnected through {@link GuiIngameMenu}. // */ // private final boolean forced; // // public Disconnect(EventState state, boolean forced, ServerData serverData) { // super(serverData); // this.state = state; // this.forced = forced; // } // // /** // * @return The state of the event // */ // public final EventState getState() { // return this.state; // } // // /** // * @return Whether or not the connection was forcefully closed // */ // public final boolean isForced() { // return this.forced; // } // } // // @Override // public String toString() { // return "ServerEvent{" + // "serverData=" + serverData + // '}'; // } // } // Path: src/main/java/clientapi/load/mixin/MixinWorldClient.java import clientapi.ClientAPI; import clientapi.event.defaults.game.network.ServerEvent; import me.zero.alpine.event.EventState; import net.minecraft.client.Minecraft; import net.minecraft.client.multiplayer.WorldClient; import org.spongepowered.asm.mixin.Final; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; /* * Copyright 2018 ImpactDevelopment * * 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 clientapi.load.mixin; /** * @author Brady * @since 9/7/2017 */ @Mixin(WorldClient.class) public class MixinWorldClient { @Shadow @Final private Minecraft mc; @Inject( method = "sendQuittingDisconnectingPacket", at = @At("HEAD") ) private void preSendQuittingDisconnectingPacket(CallbackInfo ci) {
ClientAPI.EVENT_BUS.post(new ServerEvent.Disconnect(EventState.PRE, false, this.mc.getCurrentServerData()));
ImpactDevelopment/ClientAPI
src/main/java/clientapi/load/mixin/MixinGuiIngame.java
// Path: src/main/java/clientapi/event/defaults/game/render/HudOverlayEvent.java // public final class HudOverlayEvent extends Cancellable { // // /** // * The type of overlay that is being rendered // */ // private final Type type; // // public HudOverlayEvent(Type type) { // this.type = type; // } // // /** // * @return The type of overlay that is being rendered // */ // public final Type getType() { // return this.type; // } // // public enum Type { // /** // * Rendered when the player is in water and their eye height is under the water level // */ // WATER, // // /** // * Rendered when the player is in lava and their eye height is under the lava level // */ // LAVA, // // /** // * Rendered when the player has a pumpkin on their head // */ // PUMPKIN, // // /** // * Transformation to the screen when the player takes damage // */ // HURTCAM, // // /** // * The scoreboard that is displayed on the right side of the screen // */ // SCOREBOARD, // // /** // * Rendered when the player is on fire // */ // FIRE, // // /** // * The entire stat bar // */ // STAT_ALL, // // /** // * The stat bar displaying the health level of the player // */ // STAT_HEALTH, // // /** // * The stat bar displaying the food level of the player // */ // STAT_FOOD, // // /** // * The stat bar displaying the armor level of the player // */ // STAT_ARMOR, // // /** // * The stat bar displaying the remaining air that the player has when underwater // */ // STAT_AIR, // // /** // * The boss bar rendered at the top of the screen showing the boss health // */ // BOSS_BAR, // // /** // * The bar displaying the current player experience level // */ // EXP_BAR, // // /** // * The vignette effect overlayed over the game // */ // VIGNETTE, // // /** // * The crosshair // */ // CROSSHAIR, // // /** // * The attack indicator displaying the remaining time until the player's attack is fully charged // */ // ATTACK_INDICATOR, // // /** // * The horse jump bar // */ // JUMP_BAR, // // /** // * The health of the currently mounted entity // */ // MOUNT_HEALTH, // // /** // * The overlay rendered when the player is inside of a nether portal // */ // PORTAL, // // /** // * The tooltip displayed over the hotbar when a new item is selected // */ // SELECTED_ITEM_TOOLTIP, // // /** // * The list of potion effects in the top right of the screen // */ // POTION_EFFECTS // } // // @Override // public String toString() { // return "HudOverlayEvent{" + // "type=" + type + // '}'; // } // }
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import static org.spongepowered.asm.lib.Opcodes.GETFIELD; import clientapi.ClientAPI; import clientapi.event.defaults.game.render.HudOverlayEvent; import net.minecraft.block.material.Material; import net.minecraft.client.gui.GuiIngame; import net.minecraft.client.gui.ScaledResolution; import net.minecraft.client.settings.GameSettings; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.scoreboard.ScoreObjective; import net.minecraft.util.math.MathHelper; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.Redirect;
/* * Copyright 2018 ImpactDevelopment * * 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 clientapi.load.mixin; /** * @author Brady * @since 5/24/2018 */ @Mixin(GuiIngame.class) public class MixinGuiIngame { @Inject( method = "renderPumpkinOverlay", at = @At("HEAD"), cancellable = true ) private void renderPumpkinOverlay(ScaledResolution scaledRes, CallbackInfo ci) {
// Path: src/main/java/clientapi/event/defaults/game/render/HudOverlayEvent.java // public final class HudOverlayEvent extends Cancellable { // // /** // * The type of overlay that is being rendered // */ // private final Type type; // // public HudOverlayEvent(Type type) { // this.type = type; // } // // /** // * @return The type of overlay that is being rendered // */ // public final Type getType() { // return this.type; // } // // public enum Type { // /** // * Rendered when the player is in water and their eye height is under the water level // */ // WATER, // // /** // * Rendered when the player is in lava and their eye height is under the lava level // */ // LAVA, // // /** // * Rendered when the player has a pumpkin on their head // */ // PUMPKIN, // // /** // * Transformation to the screen when the player takes damage // */ // HURTCAM, // // /** // * The scoreboard that is displayed on the right side of the screen // */ // SCOREBOARD, // // /** // * Rendered when the player is on fire // */ // FIRE, // // /** // * The entire stat bar // */ // STAT_ALL, // // /** // * The stat bar displaying the health level of the player // */ // STAT_HEALTH, // // /** // * The stat bar displaying the food level of the player // */ // STAT_FOOD, // // /** // * The stat bar displaying the armor level of the player // */ // STAT_ARMOR, // // /** // * The stat bar displaying the remaining air that the player has when underwater // */ // STAT_AIR, // // /** // * The boss bar rendered at the top of the screen showing the boss health // */ // BOSS_BAR, // // /** // * The bar displaying the current player experience level // */ // EXP_BAR, // // /** // * The vignette effect overlayed over the game // */ // VIGNETTE, // // /** // * The crosshair // */ // CROSSHAIR, // // /** // * The attack indicator displaying the remaining time until the player's attack is fully charged // */ // ATTACK_INDICATOR, // // /** // * The horse jump bar // */ // JUMP_BAR, // // /** // * The health of the currently mounted entity // */ // MOUNT_HEALTH, // // /** // * The overlay rendered when the player is inside of a nether portal // */ // PORTAL, // // /** // * The tooltip displayed over the hotbar when a new item is selected // */ // SELECTED_ITEM_TOOLTIP, // // /** // * The list of potion effects in the top right of the screen // */ // POTION_EFFECTS // } // // @Override // public String toString() { // return "HudOverlayEvent{" + // "type=" + type + // '}'; // } // } // Path: src/main/java/clientapi/load/mixin/MixinGuiIngame.java import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import static org.spongepowered.asm.lib.Opcodes.GETFIELD; import clientapi.ClientAPI; import clientapi.event.defaults.game.render.HudOverlayEvent; import net.minecraft.block.material.Material; import net.minecraft.client.gui.GuiIngame; import net.minecraft.client.gui.ScaledResolution; import net.minecraft.client.settings.GameSettings; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.scoreboard.ScoreObjective; import net.minecraft.util.math.MathHelper; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.Redirect; /* * Copyright 2018 ImpactDevelopment * * 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 clientapi.load.mixin; /** * @author Brady * @since 5/24/2018 */ @Mixin(GuiIngame.class) public class MixinGuiIngame { @Inject( method = "renderPumpkinOverlay", at = @At("HEAD"), cancellable = true ) private void renderPumpkinOverlay(ScaledResolution scaledRes, CallbackInfo ci) {
HudOverlayEvent event = new HudOverlayEvent(HudOverlayEvent.Type.PUMPKIN);
ImpactDevelopment/ClientAPI
src/main/java/clientapi/gui/widget/Widget.java
// Path: src/main/java/clientapi/gui/widget/data/WidgetAlignment.java // public interface WidgetAlignment { // // float getValue(); // }
import clientapi.gui.widget.data.WidgetAlignment; import clientapi.gui.widget.data.WidgetPos; import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.gui.ScaledResolution;
/* * Copyright 2018 ImpactDevelopment * * 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 clientapi.gui.widget; /** * A widget, an element rendered on your HUD * * @author Brady * @since 5/28/2017 */ public interface Widget { /** * Renders this widget on a screen with the specified * scaled resolution using the specified font renderer. * * @param font The font that used to render text * @param sr The screen size */ void render(FontRenderer font, ScaledResolution sr); /** * Sets this widget's position on the screen * * @param pos The new position * @return This widget */ Widget setPos(WidgetPos pos); /** * Sets this widget's horizontal alignment * * @param alignment The new alignment * @return This widget */
// Path: src/main/java/clientapi/gui/widget/data/WidgetAlignment.java // public interface WidgetAlignment { // // float getValue(); // } // Path: src/main/java/clientapi/gui/widget/Widget.java import clientapi.gui.widget.data.WidgetAlignment; import clientapi.gui.widget.data.WidgetPos; import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.gui.ScaledResolution; /* * Copyright 2018 ImpactDevelopment * * 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 clientapi.gui.widget; /** * A widget, an element rendered on your HUD * * @author Brady * @since 5/28/2017 */ public interface Widget { /** * Renders this widget on a screen with the specified * scaled resolution using the specified font renderer. * * @param font The font that used to render text * @param sr The screen size */ void render(FontRenderer font, ScaledResolution sr); /** * Sets this widget's position on the screen * * @param pos The new position * @return This widget */ Widget setPos(WidgetPos pos); /** * Sets this widget's horizontal alignment * * @param alignment The new alignment * @return This widget */
Widget setAlignment(WidgetAlignment alignment);
ImpactDevelopment/ClientAPI
src/main/java/clientapi/gui/widget/impl/AbstractWidget.java
// Path: src/main/java/clientapi/gui/widget/Widget.java // public interface Widget { // // /** // * Renders this widget on a screen with the specified // * scaled resolution using the specified font renderer. // * // * @param font The font that used to render text // * @param sr The screen size // */ // void render(FontRenderer font, ScaledResolution sr); // // /** // * Sets this widget's position on the screen // * // * @param pos The new position // * @return This widget // */ // Widget setPos(WidgetPos pos); // // /** // * Sets this widget's horizontal alignment // * // * @param alignment The new alignment // * @return This widget // */ // Widget setAlignment(WidgetAlignment alignment); // // /** // * Sets the width of the widget. This should be // * called after the widget has been rendered to // * let the handler know the updated bounds of the // * widget. // * // * @param width The new width // * @return This widget // */ // Widget setWidth(float width); // // /** // * Sets the height of the widget. This should be // * called after the widget has been rendered to // * let the handler know the updated bounds of the // * widget. // * // * @param height The new height // * @return This widget // */ // Widget setHeight(float height); // // /** // * Sets the visibility flag of the widget. If // * this is set to false, then the widget isn't // * rendered. // * // * @param visible The new visibility flag // * @return This widget // */ // Widget setVisible(boolean visible); // // /** // * @return The position of this widget // */ // WidgetPos getPos(); // // /** // * @return The horizontal alignment of this widdget // */ // WidgetAlignment getAlignment(); // // /** // * @return The width of the widget // */ // float getWidth(); // // /** // * @return The height of the widget // */ // float getHeight(); // // /** // * @return The visibility flag of the widget // */ // boolean isVisible(); // } // // Path: src/main/java/clientapi/gui/widget/data/WidgetAlignment.java // public interface WidgetAlignment { // // float getValue(); // }
import clientapi.gui.widget.Widget; import clientapi.gui.widget.data.WidgetAlignment; import clientapi.gui.widget.data.WidgetPos;
/* * Copyright 2018 ImpactDevelopment * * 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 clientapi.gui.widget.impl; /** * Implementation of Widget * * @see Widget * * @author Brady * @since 5/28/2017 */ public abstract class AbstractWidget implements Widget { /** * Position of this widget */ private WidgetPos pos; /** * Alignment of this widget */
// Path: src/main/java/clientapi/gui/widget/Widget.java // public interface Widget { // // /** // * Renders this widget on a screen with the specified // * scaled resolution using the specified font renderer. // * // * @param font The font that used to render text // * @param sr The screen size // */ // void render(FontRenderer font, ScaledResolution sr); // // /** // * Sets this widget's position on the screen // * // * @param pos The new position // * @return This widget // */ // Widget setPos(WidgetPos pos); // // /** // * Sets this widget's horizontal alignment // * // * @param alignment The new alignment // * @return This widget // */ // Widget setAlignment(WidgetAlignment alignment); // // /** // * Sets the width of the widget. This should be // * called after the widget has been rendered to // * let the handler know the updated bounds of the // * widget. // * // * @param width The new width // * @return This widget // */ // Widget setWidth(float width); // // /** // * Sets the height of the widget. This should be // * called after the widget has been rendered to // * let the handler know the updated bounds of the // * widget. // * // * @param height The new height // * @return This widget // */ // Widget setHeight(float height); // // /** // * Sets the visibility flag of the widget. If // * this is set to false, then the widget isn't // * rendered. // * // * @param visible The new visibility flag // * @return This widget // */ // Widget setVisible(boolean visible); // // /** // * @return The position of this widget // */ // WidgetPos getPos(); // // /** // * @return The horizontal alignment of this widdget // */ // WidgetAlignment getAlignment(); // // /** // * @return The width of the widget // */ // float getWidth(); // // /** // * @return The height of the widget // */ // float getHeight(); // // /** // * @return The visibility flag of the widget // */ // boolean isVisible(); // } // // Path: src/main/java/clientapi/gui/widget/data/WidgetAlignment.java // public interface WidgetAlignment { // // float getValue(); // } // Path: src/main/java/clientapi/gui/widget/impl/AbstractWidget.java import clientapi.gui.widget.Widget; import clientapi.gui.widget.data.WidgetAlignment; import clientapi.gui.widget.data.WidgetPos; /* * Copyright 2018 ImpactDevelopment * * 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 clientapi.gui.widget.impl; /** * Implementation of Widget * * @see Widget * * @author Brady * @since 5/28/2017 */ public abstract class AbstractWidget implements Widget { /** * Position of this widget */ private WidgetPos pos; /** * Alignment of this widget */
private WidgetAlignment alignment;
ImpactDevelopment/ClientAPI
src/main/java/clientapi/command/executor/parser/impl/CharParser.java
// Path: src/main/java/clientapi/command/executor/ExecutionContext.java // public interface ExecutionContext { // // /** // * @return The {@link CommandSender} responsible for the command execution // */ // CommandSender sender(); // // /** // * @return The {@link CommandHandler} that carried out command execution // */ // CommandHandler handler(); // // static ExecutionContext of(CommandSender sender, CommandHandler handler) { // return new Impl(sender, handler); // } // // /** // * Implementation of {@link ExecutionContext}, used when // * creating an instance of {@link ExecutionContext} // * from {@link ExecutionContext#of(CommandSender, CommandHandler)} // * // * @see ExecutionContext#of(CommandSender, CommandHandler) // */ // class Impl implements ExecutionContext { // // /** // * {@link CommandSender} responsible for command execution // */ // private final CommandSender sender; // // /** // * {@link CommandHandler} that carried out command execution // */ // private final CommandHandler handler; // // private Impl(CommandSender sender, CommandHandler handler) { // this.sender = sender; // this.handler = handler; // } // // @Override // public CommandSender sender() { // return this.sender; // } // // @Override // public CommandHandler handler() { // return this.handler; // } // } // }
import clientapi.command.executor.ExecutionContext; import clientapi.command.executor.parser.ArgumentParser; import java.lang.reflect.Type;
/* * Copyright 2018 ImpactDevelopment * * 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 clientapi.command.executor.parser.impl; /** * @author Brady * @since 10/20/2017 */ public final class CharParser implements ArgumentParser<Character> { @Override
// Path: src/main/java/clientapi/command/executor/ExecutionContext.java // public interface ExecutionContext { // // /** // * @return The {@link CommandSender} responsible for the command execution // */ // CommandSender sender(); // // /** // * @return The {@link CommandHandler} that carried out command execution // */ // CommandHandler handler(); // // static ExecutionContext of(CommandSender sender, CommandHandler handler) { // return new Impl(sender, handler); // } // // /** // * Implementation of {@link ExecutionContext}, used when // * creating an instance of {@link ExecutionContext} // * from {@link ExecutionContext#of(CommandSender, CommandHandler)} // * // * @see ExecutionContext#of(CommandSender, CommandHandler) // */ // class Impl implements ExecutionContext { // // /** // * {@link CommandSender} responsible for command execution // */ // private final CommandSender sender; // // /** // * {@link CommandHandler} that carried out command execution // */ // private final CommandHandler handler; // // private Impl(CommandSender sender, CommandHandler handler) { // this.sender = sender; // this.handler = handler; // } // // @Override // public CommandSender sender() { // return this.sender; // } // // @Override // public CommandHandler handler() { // return this.handler; // } // } // } // Path: src/main/java/clientapi/command/executor/parser/impl/CharParser.java import clientapi.command.executor.ExecutionContext; import clientapi.command.executor.parser.ArgumentParser; import java.lang.reflect.Type; /* * Copyright 2018 ImpactDevelopment * * 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 clientapi.command.executor.parser.impl; /** * @author Brady * @since 10/20/2017 */ public final class CharParser implements ArgumentParser<Character> { @Override
public final Character parse(ExecutionContext context, Type type, String raw) {
ImpactDevelopment/ClientAPI
src/main/java/clientapi/load/mixin/MixinItemRenderer.java
// Path: src/main/java/clientapi/event/defaults/game/render/HudOverlayEvent.java // public final class HudOverlayEvent extends Cancellable { // // /** // * The type of overlay that is being rendered // */ // private final Type type; // // public HudOverlayEvent(Type type) { // this.type = type; // } // // /** // * @return The type of overlay that is being rendered // */ // public final Type getType() { // return this.type; // } // // public enum Type { // /** // * Rendered when the player is in water and their eye height is under the water level // */ // WATER, // // /** // * Rendered when the player is in lava and their eye height is under the lava level // */ // LAVA, // // /** // * Rendered when the player has a pumpkin on their head // */ // PUMPKIN, // // /** // * Transformation to the screen when the player takes damage // */ // HURTCAM, // // /** // * The scoreboard that is displayed on the right side of the screen // */ // SCOREBOARD, // // /** // * Rendered when the player is on fire // */ // FIRE, // // /** // * The entire stat bar // */ // STAT_ALL, // // /** // * The stat bar displaying the health level of the player // */ // STAT_HEALTH, // // /** // * The stat bar displaying the food level of the player // */ // STAT_FOOD, // // /** // * The stat bar displaying the armor level of the player // */ // STAT_ARMOR, // // /** // * The stat bar displaying the remaining air that the player has when underwater // */ // STAT_AIR, // // /** // * The boss bar rendered at the top of the screen showing the boss health // */ // BOSS_BAR, // // /** // * The bar displaying the current player experience level // */ // EXP_BAR, // // /** // * The vignette effect overlayed over the game // */ // VIGNETTE, // // /** // * The crosshair // */ // CROSSHAIR, // // /** // * The attack indicator displaying the remaining time until the player's attack is fully charged // */ // ATTACK_INDICATOR, // // /** // * The horse jump bar // */ // JUMP_BAR, // // /** // * The health of the currently mounted entity // */ // MOUNT_HEALTH, // // /** // * The overlay rendered when the player is inside of a nether portal // */ // PORTAL, // // /** // * The tooltip displayed over the hotbar when a new item is selected // */ // SELECTED_ITEM_TOOLTIP, // // /** // * The list of potion effects in the top right of the screen // */ // POTION_EFFECTS // } // // @Override // public String toString() { // return "HudOverlayEvent{" + // "type=" + type + // '}'; // } // }
import clientapi.ClientAPI; import clientapi.event.defaults.game.render.HudOverlayEvent; import clientapi.event.defaults.game.render.RenderItemEvent; import net.minecraft.client.entity.AbstractClientPlayer; import net.minecraft.client.renderer.ItemRenderer; import net.minecraft.item.ItemStack; import net.minecraft.util.EnumHand; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
/* * Copyright 2018 ImpactDevelopment * * 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 clientapi.load.mixin; /** * @author Brady * @since 4/27/2017 */ @Mixin(ItemRenderer.class) public abstract class MixinItemRenderer { @Inject( method = "renderItemInFirstPerson(Lnet/minecraft/client/entity/AbstractClientPlayer;FFLnet/minecraft/util/EnumHand;FLnet/minecraft/item/ItemStack;F)V", at = @At("HEAD"), cancellable = true ) private void renderItemInFirstPerson(AbstractClientPlayer p_187457_1_, float partialTicks, float pitch, EnumHand hand, float swingProgress, ItemStack stack, float rechargeProgress, CallbackInfo ci) { RenderItemEvent event = new RenderItemEvent((ItemRenderer) (Object) this, partialTicks, hand, swingProgress, stack, rechargeProgress); ClientAPI.EVENT_BUS.post(event); if (event.isCancelled()) ci.cancel(); } @Inject( method = "renderFireInFirstPerson", at = @At("HEAD"), cancellable = true ) private void renderFireInFirstPerson(CallbackInfo ci) {
// Path: src/main/java/clientapi/event/defaults/game/render/HudOverlayEvent.java // public final class HudOverlayEvent extends Cancellable { // // /** // * The type of overlay that is being rendered // */ // private final Type type; // // public HudOverlayEvent(Type type) { // this.type = type; // } // // /** // * @return The type of overlay that is being rendered // */ // public final Type getType() { // return this.type; // } // // public enum Type { // /** // * Rendered when the player is in water and their eye height is under the water level // */ // WATER, // // /** // * Rendered when the player is in lava and their eye height is under the lava level // */ // LAVA, // // /** // * Rendered when the player has a pumpkin on their head // */ // PUMPKIN, // // /** // * Transformation to the screen when the player takes damage // */ // HURTCAM, // // /** // * The scoreboard that is displayed on the right side of the screen // */ // SCOREBOARD, // // /** // * Rendered when the player is on fire // */ // FIRE, // // /** // * The entire stat bar // */ // STAT_ALL, // // /** // * The stat bar displaying the health level of the player // */ // STAT_HEALTH, // // /** // * The stat bar displaying the food level of the player // */ // STAT_FOOD, // // /** // * The stat bar displaying the armor level of the player // */ // STAT_ARMOR, // // /** // * The stat bar displaying the remaining air that the player has when underwater // */ // STAT_AIR, // // /** // * The boss bar rendered at the top of the screen showing the boss health // */ // BOSS_BAR, // // /** // * The bar displaying the current player experience level // */ // EXP_BAR, // // /** // * The vignette effect overlayed over the game // */ // VIGNETTE, // // /** // * The crosshair // */ // CROSSHAIR, // // /** // * The attack indicator displaying the remaining time until the player's attack is fully charged // */ // ATTACK_INDICATOR, // // /** // * The horse jump bar // */ // JUMP_BAR, // // /** // * The health of the currently mounted entity // */ // MOUNT_HEALTH, // // /** // * The overlay rendered when the player is inside of a nether portal // */ // PORTAL, // // /** // * The tooltip displayed over the hotbar when a new item is selected // */ // SELECTED_ITEM_TOOLTIP, // // /** // * The list of potion effects in the top right of the screen // */ // POTION_EFFECTS // } // // @Override // public String toString() { // return "HudOverlayEvent{" + // "type=" + type + // '}'; // } // } // Path: src/main/java/clientapi/load/mixin/MixinItemRenderer.java import clientapi.ClientAPI; import clientapi.event.defaults.game.render.HudOverlayEvent; import clientapi.event.defaults.game.render.RenderItemEvent; import net.minecraft.client.entity.AbstractClientPlayer; import net.minecraft.client.renderer.ItemRenderer; import net.minecraft.item.ItemStack; import net.minecraft.util.EnumHand; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; /* * Copyright 2018 ImpactDevelopment * * 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 clientapi.load.mixin; /** * @author Brady * @since 4/27/2017 */ @Mixin(ItemRenderer.class) public abstract class MixinItemRenderer { @Inject( method = "renderItemInFirstPerson(Lnet/minecraft/client/entity/AbstractClientPlayer;FFLnet/minecraft/util/EnumHand;FLnet/minecraft/item/ItemStack;F)V", at = @At("HEAD"), cancellable = true ) private void renderItemInFirstPerson(AbstractClientPlayer p_187457_1_, float partialTicks, float pitch, EnumHand hand, float swingProgress, ItemStack stack, float rechargeProgress, CallbackInfo ci) { RenderItemEvent event = new RenderItemEvent((ItemRenderer) (Object) this, partialTicks, hand, swingProgress, stack, rechargeProgress); ClientAPI.EVENT_BUS.post(event); if (event.isCancelled()) ci.cancel(); } @Inject( method = "renderFireInFirstPerson", at = @At("HEAD"), cancellable = true ) private void renderFireInFirstPerson(CallbackInfo ci) {
HudOverlayEvent event = new HudOverlayEvent(HudOverlayEvent.Type.FIRE);
ImpactDevelopment/ClientAPI
src/main/java/clientapi/util/render/gl/GLUtils.java
// Path: src/main/java/clientapi/event/defaults/game/render/RenderWorldEvent.java // public final class RenderWorldEvent extends RenderEvent { // // /** // * The Render pass this event was called from // */ // private final Pass pass; // // public RenderWorldEvent(float partialTicks, int pass) { // super(partialTicks); // this.pass = Pass.values()[pass]; // } // // /** // * @return The render pass that this event was called from // */ // public final Pass getPass() { // return this.pass; // } // // public enum Pass { // ANAGLYPH_CYAN, ANAGLYPH_RED, NORMAL // } // // @Override // public String toString() { // return "RenderWorldEvent{" + // "pass=" + pass + // ", partialTicks=" + partialTicks + // '}'; // } // }
import clientapi.ClientAPI; import clientapi.event.defaults.game.render.RenderWorldEvent; import clientapi.util.math.Vec3; import clientapi.util.render.Colors; import me.zero.alpine.listener.Listener; import net.minecraft.client.renderer.GlStateManager; import org.lwjgl.BufferUtils; import org.lwjgl.opengl.Display; import org.lwjgl.util.glu.GLU; import java.nio.FloatBuffer; import java.nio.IntBuffer; import static org.lwjgl.opengl.GL11.*;
/* * Copyright 2018 ImpactDevelopment * * 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 clientapi.util.render.gl; /** * OpenGL utils * * @author Brady * @since 2/20/2017 */ public final class GLUtils { private GLUtils() {} private static final FloatBuffer MODELVIEW = BufferUtils.createFloatBuffer(16); private static final FloatBuffer PROJECTION = BufferUtils.createFloatBuffer(16); private static final IntBuffer VIEWPORT = BufferUtils.createIntBuffer(16); private static final FloatBuffer TO_SCREEN_BUFFER = BufferUtils.createFloatBuffer(3); private static final FloatBuffer TO_WORLD_BUFFER = BufferUtils.createFloatBuffer(3); public static void init() {
// Path: src/main/java/clientapi/event/defaults/game/render/RenderWorldEvent.java // public final class RenderWorldEvent extends RenderEvent { // // /** // * The Render pass this event was called from // */ // private final Pass pass; // // public RenderWorldEvent(float partialTicks, int pass) { // super(partialTicks); // this.pass = Pass.values()[pass]; // } // // /** // * @return The render pass that this event was called from // */ // public final Pass getPass() { // return this.pass; // } // // public enum Pass { // ANAGLYPH_CYAN, ANAGLYPH_RED, NORMAL // } // // @Override // public String toString() { // return "RenderWorldEvent{" + // "pass=" + pass + // ", partialTicks=" + partialTicks + // '}'; // } // } // Path: src/main/java/clientapi/util/render/gl/GLUtils.java import clientapi.ClientAPI; import clientapi.event.defaults.game.render.RenderWorldEvent; import clientapi.util.math.Vec3; import clientapi.util.render.Colors; import me.zero.alpine.listener.Listener; import net.minecraft.client.renderer.GlStateManager; import org.lwjgl.BufferUtils; import org.lwjgl.opengl.Display; import org.lwjgl.util.glu.GLU; import java.nio.FloatBuffer; import java.nio.IntBuffer; import static org.lwjgl.opengl.GL11.*; /* * Copyright 2018 ImpactDevelopment * * 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 clientapi.util.render.gl; /** * OpenGL utils * * @author Brady * @since 2/20/2017 */ public final class GLUtils { private GLUtils() {} private static final FloatBuffer MODELVIEW = BufferUtils.createFloatBuffer(16); private static final FloatBuffer PROJECTION = BufferUtils.createFloatBuffer(16); private static final IntBuffer VIEWPORT = BufferUtils.createIntBuffer(16); private static final FloatBuffer TO_SCREEN_BUFFER = BufferUtils.createFloatBuffer(3); private static final FloatBuffer TO_WORLD_BUFFER = BufferUtils.createFloatBuffer(3); public static void init() {
ClientAPI.EVENT_BUS.subscribe(new Listener<RenderWorldEvent>(event -> {
ImpactDevelopment/ClientAPI
src/main/java/clientapi/command/exception/ParserException.java
// Path: src/main/java/clientapi/command/Command.java // public class Command implements ICommand { // // /** // * A list of this command's child commands // */ // private final List<ChildCommand> children = new ArrayList<>(); // // /** // * A list of handles used to execute this command // */ // private String[] handles; // // /** // * A description of this command's usage // */ // private String description; // // public Command() { // if (!this.getClass().isAnnotationPresent(Cmd.class)) // throw new CommandInitException(this, "@Cmd annotation must be present if required parameters aren't passed through constructor"); // // Cmd data = this.getClass().getAnnotation(Cmd.class); // setup(data.handles(), data.description()); // } // // public Command(String[] handles, String description) { // setup(handles, description); // } // // private void setup(String[] handles, String description) { // this.handles = handles; // this.description = description; // // for (Method method : this.getClass().getDeclaredMethods()) { // int parameters = method.getParameterCount(); // if (parameters == 0 || !method.getParameterTypes()[0].equals(ExecutionContext.class) || !method.isAnnotationPresent(Sub.class)) // continue; // // // Ensure that there is only one optional at most, and that it is the last parameter // int optionals = 0; // for (int i = 0; i < parameters; i++) { // if (method.getParameterTypes()[i].isAssignableFrom(Optional.class)) { // if (i != parameters - 1) // throw new CommandInitException(this, "Optionals must be defined as the last parameter"); // if (++optionals > 1) // throw new CommandInitException(this, "More than one optional parameter is not supported"); // } // } // // // Create the child command // children.add(new ChildCommand(this, method)); // } // // if (ClientAPIUtils.containsNull(handles, description)) // throw new NullPointerException("One or more Command members were null!"); // } // // @Override // public final void execute(ExecutionContext context, String[] arguments) throws CommandException { // Optional<ChildCommand> sub = CommandInputParser.INSTANCE.findChild(this, arguments, true); // if (!sub.isPresent()) // throw new UnknownSubCommandException(this, arguments); // // // If the child was found by it's header, then remove the first argument. // if (sub.get().getHandles().length > 0 && arguments.length > 0) { // String[] newArgs = new String[arguments.length - 1]; // System.arraycopy(arguments, 1, newArgs, 0, arguments.length - 1); // arguments = newArgs; // } // // sub.get().execute(context, arguments); // } // // @Override // public final String[] getHandles() { // return this.handles; // } // // @Override // public final String getDescription() { // return this.description; // } // // /** // * @return A list of this command's child commands. // */ // public final List<ChildCommand> getChildren() { // return this.children; // } // }
import clientapi.command.ChildCommand; import clientapi.command.Command; import clientapi.command.executor.parser.ArgumentParser; import java.lang.reflect.Type;
/* * Copyright 2018 ImpactDevelopment * * 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 clientapi.command.exception; /** * @author Brady * @since 10/18/2017 */ public final class ParserException extends CommandException { /** * The child command involved in the exception */ private final ChildCommand child; /** * The parser involved */ private final ArgumentParser<?> parser; /** * The raw data that was passed to the parser */ private final String raw; /** * The type that was expected to be returned */ private final Type expected; /** * The type that the parser returned */ private final Class<?> returned;
// Path: src/main/java/clientapi/command/Command.java // public class Command implements ICommand { // // /** // * A list of this command's child commands // */ // private final List<ChildCommand> children = new ArrayList<>(); // // /** // * A list of handles used to execute this command // */ // private String[] handles; // // /** // * A description of this command's usage // */ // private String description; // // public Command() { // if (!this.getClass().isAnnotationPresent(Cmd.class)) // throw new CommandInitException(this, "@Cmd annotation must be present if required parameters aren't passed through constructor"); // // Cmd data = this.getClass().getAnnotation(Cmd.class); // setup(data.handles(), data.description()); // } // // public Command(String[] handles, String description) { // setup(handles, description); // } // // private void setup(String[] handles, String description) { // this.handles = handles; // this.description = description; // // for (Method method : this.getClass().getDeclaredMethods()) { // int parameters = method.getParameterCount(); // if (parameters == 0 || !method.getParameterTypes()[0].equals(ExecutionContext.class) || !method.isAnnotationPresent(Sub.class)) // continue; // // // Ensure that there is only one optional at most, and that it is the last parameter // int optionals = 0; // for (int i = 0; i < parameters; i++) { // if (method.getParameterTypes()[i].isAssignableFrom(Optional.class)) { // if (i != parameters - 1) // throw new CommandInitException(this, "Optionals must be defined as the last parameter"); // if (++optionals > 1) // throw new CommandInitException(this, "More than one optional parameter is not supported"); // } // } // // // Create the child command // children.add(new ChildCommand(this, method)); // } // // if (ClientAPIUtils.containsNull(handles, description)) // throw new NullPointerException("One or more Command members were null!"); // } // // @Override // public final void execute(ExecutionContext context, String[] arguments) throws CommandException { // Optional<ChildCommand> sub = CommandInputParser.INSTANCE.findChild(this, arguments, true); // if (!sub.isPresent()) // throw new UnknownSubCommandException(this, arguments); // // // If the child was found by it's header, then remove the first argument. // if (sub.get().getHandles().length > 0 && arguments.length > 0) { // String[] newArgs = new String[arguments.length - 1]; // System.arraycopy(arguments, 1, newArgs, 0, arguments.length - 1); // arguments = newArgs; // } // // sub.get().execute(context, arguments); // } // // @Override // public final String[] getHandles() { // return this.handles; // } // // @Override // public final String getDescription() { // return this.description; // } // // /** // * @return A list of this command's child commands. // */ // public final List<ChildCommand> getChildren() { // return this.children; // } // } // Path: src/main/java/clientapi/command/exception/ParserException.java import clientapi.command.ChildCommand; import clientapi.command.Command; import clientapi.command.executor.parser.ArgumentParser; import java.lang.reflect.Type; /* * Copyright 2018 ImpactDevelopment * * 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 clientapi.command.exception; /** * @author Brady * @since 10/18/2017 */ public final class ParserException extends CommandException { /** * The child command involved in the exception */ private final ChildCommand child; /** * The parser involved */ private final ArgumentParser<?> parser; /** * The raw data that was passed to the parser */ private final String raw; /** * The type that was expected to be returned */ private final Type expected; /** * The type that the parser returned */ private final Class<?> returned;
public ParserException(Command command, ChildCommand child, ArgumentParser<?> parser, String raw, Type expected, Class<?> returned) {
cescoffier/vertx-kubernetes-workshop
currency-service/src/main/java/io/vertx/workshop/currency/CurrencyServiceProxy.java
// Path: portfolio-service/src/main/generated/io/vertx/workshop/portfolio/reactivex/PortfolioService.java // @io.vertx.lang.reactivex.RxGen(io.vertx.workshop.portfolio.PortfolioService.class) // public class PortfolioService { // // public static final io.vertx.lang.reactivex.TypeArg<PortfolioService> __TYPE_ARG = new io.vertx.lang.reactivex.TypeArg<>( // obj -> new PortfolioService((io.vertx.workshop.portfolio.PortfolioService) obj), // PortfolioService::getDelegate // ); // // private final io.vertx.workshop.portfolio.PortfolioService delegate; // // public PortfolioService(io.vertx.workshop.portfolio.PortfolioService delegate) { // this.delegate = delegate; // } // // public io.vertx.workshop.portfolio.PortfolioService getDelegate() { // return delegate; // } // // /** // * Gets the portfolio. // * @param resultHandler the result handler called when the portfolio has been retrieved. The async result indicates whether the call was successful or not. // */ // public void getPortfolio(Handler<AsyncResult<Portfolio>> resultHandler) { // delegate.getPortfolio(resultHandler); // } // // /** // * Gets the portfolio. // * @return // */ // public Single<Portfolio> rxGetPortfolio() { // return new io.vertx.reactivex.core.impl.AsyncResultSingle<Portfolio>(handler -> { // getPortfolio(handler); // }); // } // // /** // * Buy `amount` shares of the given shares (quote). // * @param amount the amount // * @param quote the last quote // * @param resultHandler the result handler with the updated portfolio. If the action cannot be executed, the async result is market as a failure (not enough money, not enough shares available...) // */ // public void buy(int amount, JsonObject quote, Handler<AsyncResult<Portfolio>> resultHandler) { // delegate.buy(amount, quote, resultHandler); // } // // /** // * Buy `amount` shares of the given shares (quote). // * @param amount the amount // * @param quote the last quote // * @return // */ // public Single<Portfolio> rxBuy(int amount, JsonObject quote) { // return new io.vertx.reactivex.core.impl.AsyncResultSingle<Portfolio>(handler -> { // buy(amount, quote, handler); // }); // } // // /** // * Sell `amount` shares of the given shares (quote). // * @param amount the amount // * @param quote the last quote // * @param resultHandler the result handler with the updated portfolio. If the action cannot be executed, the async result is market as a failure (not enough share...) // */ // public void sell(int amount, JsonObject quote, Handler<AsyncResult<Portfolio>> resultHandler) { // delegate.sell(amount, quote, resultHandler); // } // // /** // * Sell `amount` shares of the given shares (quote). // * @param amount the amount // * @param quote the last quote // * @return // */ // public Single<Portfolio> rxSell(int amount, JsonObject quote) { // return new io.vertx.reactivex.core.impl.AsyncResultSingle<Portfolio>(handler -> { // sell(amount, quote, handler); // }); // } // // /** // * Evaluates the current value of the portfolio. // * @param resultHandler the result handler with the valuation // */ // public void evaluate(Handler<AsyncResult<Double>> resultHandler) { // delegate.evaluate(resultHandler); // } // // /** // * Evaluates the current value of the portfolio. // * @return // */ // public Single<Double> rxEvaluate() { // return new io.vertx.reactivex.core.impl.AsyncResultSingle<Double>(handler -> { // evaluate(handler); // }); // } // // // public static PortfolioService newInstance(io.vertx.workshop.portfolio.PortfolioService arg) { // return arg != null ? new PortfolioService(arg) : null; // } // } // // Path: currency-service/src/main/solution/io/vertx/workshop/currency/Helpers.java // public static SingleObserver<JsonObject> toObserver(Future<JsonObject> future) { // return new SingleObserver<JsonObject>() { // public void onSubscribe(@NonNull Disposable d) { // } // // public void onSuccess(@NonNull JsonObject item) { // future.tryComplete(item); // } // // public void onError(Throwable error) { // future.tryFail(error); // } // }; // }
import io.reactivex.Single; import io.vertx.circuitbreaker.CircuitBreakerOptions; import io.vertx.core.json.JsonObject; import io.vertx.reactivex.circuitbreaker.CircuitBreaker; import io.vertx.reactivex.core.AbstractVerticle; import io.vertx.reactivex.core.buffer.Buffer; import io.vertx.reactivex.ext.web.Router; import io.vertx.reactivex.ext.web.RoutingContext; import io.vertx.reactivex.ext.web.client.HttpResponse; import io.vertx.reactivex.ext.web.handler.BodyHandler; import io.vertx.reactivex.servicediscovery.ServiceDiscovery; import io.vertx.reactivex.servicediscovery.types.EventBusService; import io.vertx.reactivex.servicediscovery.types.HttpEndpoint; import io.vertx.workshop.portfolio.reactivex.PortfolioService; import static io.vertx.workshop.currency.Helpers.toObserver;
// method as example. // ----- return Single.just(new JsonObject().put("amount", 0.0).put("currency", "N/A")); }) // ---- .map(JsonObject::toBuffer) .map(Buffer::new) .subscribe(toObserver(rc)); } /** * Example of method not using a circuit breaker. * * @param rc the routing context */ private void delegate(RoutingContext rc) { HttpEndpoint.rxGetWebClient(discovery, svc -> svc.getName().equals("currency-3rdparty-service")) .flatMap(client -> client.post("/").rxSendJsonObject(rc.getBodyAsJson())) .map(HttpResponse::bodyAsBuffer) .subscribe(toObserver(rc)); } /** * Method to check the proxy requesting to convert the current portfolio to EUR. * * @param rc the routing context */ private void convertPortfolioToEuro(RoutingContext rc) {
// Path: portfolio-service/src/main/generated/io/vertx/workshop/portfolio/reactivex/PortfolioService.java // @io.vertx.lang.reactivex.RxGen(io.vertx.workshop.portfolio.PortfolioService.class) // public class PortfolioService { // // public static final io.vertx.lang.reactivex.TypeArg<PortfolioService> __TYPE_ARG = new io.vertx.lang.reactivex.TypeArg<>( // obj -> new PortfolioService((io.vertx.workshop.portfolio.PortfolioService) obj), // PortfolioService::getDelegate // ); // // private final io.vertx.workshop.portfolio.PortfolioService delegate; // // public PortfolioService(io.vertx.workshop.portfolio.PortfolioService delegate) { // this.delegate = delegate; // } // // public io.vertx.workshop.portfolio.PortfolioService getDelegate() { // return delegate; // } // // /** // * Gets the portfolio. // * @param resultHandler the result handler called when the portfolio has been retrieved. The async result indicates whether the call was successful or not. // */ // public void getPortfolio(Handler<AsyncResult<Portfolio>> resultHandler) { // delegate.getPortfolio(resultHandler); // } // // /** // * Gets the portfolio. // * @return // */ // public Single<Portfolio> rxGetPortfolio() { // return new io.vertx.reactivex.core.impl.AsyncResultSingle<Portfolio>(handler -> { // getPortfolio(handler); // }); // } // // /** // * Buy `amount` shares of the given shares (quote). // * @param amount the amount // * @param quote the last quote // * @param resultHandler the result handler with the updated portfolio. If the action cannot be executed, the async result is market as a failure (not enough money, not enough shares available...) // */ // public void buy(int amount, JsonObject quote, Handler<AsyncResult<Portfolio>> resultHandler) { // delegate.buy(amount, quote, resultHandler); // } // // /** // * Buy `amount` shares of the given shares (quote). // * @param amount the amount // * @param quote the last quote // * @return // */ // public Single<Portfolio> rxBuy(int amount, JsonObject quote) { // return new io.vertx.reactivex.core.impl.AsyncResultSingle<Portfolio>(handler -> { // buy(amount, quote, handler); // }); // } // // /** // * Sell `amount` shares of the given shares (quote). // * @param amount the amount // * @param quote the last quote // * @param resultHandler the result handler with the updated portfolio. If the action cannot be executed, the async result is market as a failure (not enough share...) // */ // public void sell(int amount, JsonObject quote, Handler<AsyncResult<Portfolio>> resultHandler) { // delegate.sell(amount, quote, resultHandler); // } // // /** // * Sell `amount` shares of the given shares (quote). // * @param amount the amount // * @param quote the last quote // * @return // */ // public Single<Portfolio> rxSell(int amount, JsonObject quote) { // return new io.vertx.reactivex.core.impl.AsyncResultSingle<Portfolio>(handler -> { // sell(amount, quote, handler); // }); // } // // /** // * Evaluates the current value of the portfolio. // * @param resultHandler the result handler with the valuation // */ // public void evaluate(Handler<AsyncResult<Double>> resultHandler) { // delegate.evaluate(resultHandler); // } // // /** // * Evaluates the current value of the portfolio. // * @return // */ // public Single<Double> rxEvaluate() { // return new io.vertx.reactivex.core.impl.AsyncResultSingle<Double>(handler -> { // evaluate(handler); // }); // } // // // public static PortfolioService newInstance(io.vertx.workshop.portfolio.PortfolioService arg) { // return arg != null ? new PortfolioService(arg) : null; // } // } // // Path: currency-service/src/main/solution/io/vertx/workshop/currency/Helpers.java // public static SingleObserver<JsonObject> toObserver(Future<JsonObject> future) { // return new SingleObserver<JsonObject>() { // public void onSubscribe(@NonNull Disposable d) { // } // // public void onSuccess(@NonNull JsonObject item) { // future.tryComplete(item); // } // // public void onError(Throwable error) { // future.tryFail(error); // } // }; // } // Path: currency-service/src/main/java/io/vertx/workshop/currency/CurrencyServiceProxy.java import io.reactivex.Single; import io.vertx.circuitbreaker.CircuitBreakerOptions; import io.vertx.core.json.JsonObject; import io.vertx.reactivex.circuitbreaker.CircuitBreaker; import io.vertx.reactivex.core.AbstractVerticle; import io.vertx.reactivex.core.buffer.Buffer; import io.vertx.reactivex.ext.web.Router; import io.vertx.reactivex.ext.web.RoutingContext; import io.vertx.reactivex.ext.web.client.HttpResponse; import io.vertx.reactivex.ext.web.handler.BodyHandler; import io.vertx.reactivex.servicediscovery.ServiceDiscovery; import io.vertx.reactivex.servicediscovery.types.EventBusService; import io.vertx.reactivex.servicediscovery.types.HttpEndpoint; import io.vertx.workshop.portfolio.reactivex.PortfolioService; import static io.vertx.workshop.currency.Helpers.toObserver; // method as example. // ----- return Single.just(new JsonObject().put("amount", 0.0).put("currency", "N/A")); }) // ---- .map(JsonObject::toBuffer) .map(Buffer::new) .subscribe(toObserver(rc)); } /** * Example of method not using a circuit breaker. * * @param rc the routing context */ private void delegate(RoutingContext rc) { HttpEndpoint.rxGetWebClient(discovery, svc -> svc.getName().equals("currency-3rdparty-service")) .flatMap(client -> client.post("/").rxSendJsonObject(rc.getBodyAsJson())) .map(HttpResponse::bodyAsBuffer) .subscribe(toObserver(rc)); } /** * Method to check the proxy requesting to convert the current portfolio to EUR. * * @param rc the routing context */ private void convertPortfolioToEuro(RoutingContext rc) {
EventBusService.getServiceProxy(discovery, svc -> svc.getName().equals("portfolio"), PortfolioService.class,
cescoffier/vertx-kubernetes-workshop
currency-service/src/main/solution/io/vertx/workshop/currency/CurrencyServiceProxy.java
// Path: portfolio-service/src/main/generated/io/vertx/workshop/portfolio/reactivex/PortfolioService.java // @io.vertx.lang.reactivex.RxGen(io.vertx.workshop.portfolio.PortfolioService.class) // public class PortfolioService { // // public static final io.vertx.lang.reactivex.TypeArg<PortfolioService> __TYPE_ARG = new io.vertx.lang.reactivex.TypeArg<>( // obj -> new PortfolioService((io.vertx.workshop.portfolio.PortfolioService) obj), // PortfolioService::getDelegate // ); // // private final io.vertx.workshop.portfolio.PortfolioService delegate; // // public PortfolioService(io.vertx.workshop.portfolio.PortfolioService delegate) { // this.delegate = delegate; // } // // public io.vertx.workshop.portfolio.PortfolioService getDelegate() { // return delegate; // } // // /** // * Gets the portfolio. // * @param resultHandler the result handler called when the portfolio has been retrieved. The async result indicates whether the call was successful or not. // */ // public void getPortfolio(Handler<AsyncResult<Portfolio>> resultHandler) { // delegate.getPortfolio(resultHandler); // } // // /** // * Gets the portfolio. // * @return // */ // public Single<Portfolio> rxGetPortfolio() { // return new io.vertx.reactivex.core.impl.AsyncResultSingle<Portfolio>(handler -> { // getPortfolio(handler); // }); // } // // /** // * Buy `amount` shares of the given shares (quote). // * @param amount the amount // * @param quote the last quote // * @param resultHandler the result handler with the updated portfolio. If the action cannot be executed, the async result is market as a failure (not enough money, not enough shares available...) // */ // public void buy(int amount, JsonObject quote, Handler<AsyncResult<Portfolio>> resultHandler) { // delegate.buy(amount, quote, resultHandler); // } // // /** // * Buy `amount` shares of the given shares (quote). // * @param amount the amount // * @param quote the last quote // * @return // */ // public Single<Portfolio> rxBuy(int amount, JsonObject quote) { // return new io.vertx.reactivex.core.impl.AsyncResultSingle<Portfolio>(handler -> { // buy(amount, quote, handler); // }); // } // // /** // * Sell `amount` shares of the given shares (quote). // * @param amount the amount // * @param quote the last quote // * @param resultHandler the result handler with the updated portfolio. If the action cannot be executed, the async result is market as a failure (not enough share...) // */ // public void sell(int amount, JsonObject quote, Handler<AsyncResult<Portfolio>> resultHandler) { // delegate.sell(amount, quote, resultHandler); // } // // /** // * Sell `amount` shares of the given shares (quote). // * @param amount the amount // * @param quote the last quote // * @return // */ // public Single<Portfolio> rxSell(int amount, JsonObject quote) { // return new io.vertx.reactivex.core.impl.AsyncResultSingle<Portfolio>(handler -> { // sell(amount, quote, handler); // }); // } // // /** // * Evaluates the current value of the portfolio. // * @param resultHandler the result handler with the valuation // */ // public void evaluate(Handler<AsyncResult<Double>> resultHandler) { // delegate.evaluate(resultHandler); // } // // /** // * Evaluates the current value of the portfolio. // * @return // */ // public Single<Double> rxEvaluate() { // return new io.vertx.reactivex.core.impl.AsyncResultSingle<Double>(handler -> { // evaluate(handler); // }); // } // // // public static PortfolioService newInstance(io.vertx.workshop.portfolio.PortfolioService arg) { // return arg != null ? new PortfolioService(arg) : null; // } // } // // Path: currency-service/src/main/solution/io/vertx/workshop/currency/Helpers.java // public static SingleObserver<JsonObject> toObserver(Future<JsonObject> future) { // return new SingleObserver<JsonObject>() { // public void onSubscribe(@NonNull Disposable d) { // } // // public void onSuccess(@NonNull JsonObject item) { // future.tryComplete(item); // } // // public void onError(Throwable error) { // future.tryFail(error); // } // }; // }
import io.vertx.circuitbreaker.CircuitBreakerOptions; import io.vertx.core.json.JsonObject; import io.vertx.reactivex.circuitbreaker.CircuitBreaker; import io.vertx.reactivex.core.AbstractVerticle; import io.vertx.reactivex.core.buffer.Buffer; import io.vertx.reactivex.ext.web.Router; import io.vertx.reactivex.ext.web.RoutingContext; import io.vertx.reactivex.ext.web.client.HttpResponse; import io.vertx.reactivex.ext.web.handler.BodyHandler; import io.vertx.reactivex.servicediscovery.ServiceDiscovery; import io.vertx.reactivex.servicediscovery.types.EventBusService; import io.vertx.reactivex.servicediscovery.types.HttpEndpoint; import io.vertx.workshop.portfolio.reactivex.PortfolioService; import static io.vertx.workshop.currency.Helpers.toObserver;
err -> new JsonObject() .put("amount", rc.getBodyAsJson().getDouble("amount")) .put("currency", "USD"))) // ---- .map(JsonObject::toBuffer) .map(Buffer::new) .subscribe(toObserver(rc)); } /** * Example of method not using a circuit breaker. * * @param rc the routing context */ private void delegate(RoutingContext rc) { HttpEndpoint.rxGetWebClient(discovery, svc -> svc.getName().equals("currency-3rdparty-service")) .flatMap(client -> client.post("/").rxSendJsonObject(rc.getBodyAsJson())) .map(HttpResponse::bodyAsBuffer) .subscribe(toObserver(rc)); } /** * Method to check the proxy requesting to convert the current portfolio to EUR. * * @param rc the routing context */ private void convertPortfolioToEuro(RoutingContext rc) {
// Path: portfolio-service/src/main/generated/io/vertx/workshop/portfolio/reactivex/PortfolioService.java // @io.vertx.lang.reactivex.RxGen(io.vertx.workshop.portfolio.PortfolioService.class) // public class PortfolioService { // // public static final io.vertx.lang.reactivex.TypeArg<PortfolioService> __TYPE_ARG = new io.vertx.lang.reactivex.TypeArg<>( // obj -> new PortfolioService((io.vertx.workshop.portfolio.PortfolioService) obj), // PortfolioService::getDelegate // ); // // private final io.vertx.workshop.portfolio.PortfolioService delegate; // // public PortfolioService(io.vertx.workshop.portfolio.PortfolioService delegate) { // this.delegate = delegate; // } // // public io.vertx.workshop.portfolio.PortfolioService getDelegate() { // return delegate; // } // // /** // * Gets the portfolio. // * @param resultHandler the result handler called when the portfolio has been retrieved. The async result indicates whether the call was successful or not. // */ // public void getPortfolio(Handler<AsyncResult<Portfolio>> resultHandler) { // delegate.getPortfolio(resultHandler); // } // // /** // * Gets the portfolio. // * @return // */ // public Single<Portfolio> rxGetPortfolio() { // return new io.vertx.reactivex.core.impl.AsyncResultSingle<Portfolio>(handler -> { // getPortfolio(handler); // }); // } // // /** // * Buy `amount` shares of the given shares (quote). // * @param amount the amount // * @param quote the last quote // * @param resultHandler the result handler with the updated portfolio. If the action cannot be executed, the async result is market as a failure (not enough money, not enough shares available...) // */ // public void buy(int amount, JsonObject quote, Handler<AsyncResult<Portfolio>> resultHandler) { // delegate.buy(amount, quote, resultHandler); // } // // /** // * Buy `amount` shares of the given shares (quote). // * @param amount the amount // * @param quote the last quote // * @return // */ // public Single<Portfolio> rxBuy(int amount, JsonObject quote) { // return new io.vertx.reactivex.core.impl.AsyncResultSingle<Portfolio>(handler -> { // buy(amount, quote, handler); // }); // } // // /** // * Sell `amount` shares of the given shares (quote). // * @param amount the amount // * @param quote the last quote // * @param resultHandler the result handler with the updated portfolio. If the action cannot be executed, the async result is market as a failure (not enough share...) // */ // public void sell(int amount, JsonObject quote, Handler<AsyncResult<Portfolio>> resultHandler) { // delegate.sell(amount, quote, resultHandler); // } // // /** // * Sell `amount` shares of the given shares (quote). // * @param amount the amount // * @param quote the last quote // * @return // */ // public Single<Portfolio> rxSell(int amount, JsonObject quote) { // return new io.vertx.reactivex.core.impl.AsyncResultSingle<Portfolio>(handler -> { // sell(amount, quote, handler); // }); // } // // /** // * Evaluates the current value of the portfolio. // * @param resultHandler the result handler with the valuation // */ // public void evaluate(Handler<AsyncResult<Double>> resultHandler) { // delegate.evaluate(resultHandler); // } // // /** // * Evaluates the current value of the portfolio. // * @return // */ // public Single<Double> rxEvaluate() { // return new io.vertx.reactivex.core.impl.AsyncResultSingle<Double>(handler -> { // evaluate(handler); // }); // } // // // public static PortfolioService newInstance(io.vertx.workshop.portfolio.PortfolioService arg) { // return arg != null ? new PortfolioService(arg) : null; // } // } // // Path: currency-service/src/main/solution/io/vertx/workshop/currency/Helpers.java // public static SingleObserver<JsonObject> toObserver(Future<JsonObject> future) { // return new SingleObserver<JsonObject>() { // public void onSubscribe(@NonNull Disposable d) { // } // // public void onSuccess(@NonNull JsonObject item) { // future.tryComplete(item); // } // // public void onError(Throwable error) { // future.tryFail(error); // } // }; // } // Path: currency-service/src/main/solution/io/vertx/workshop/currency/CurrencyServiceProxy.java import io.vertx.circuitbreaker.CircuitBreakerOptions; import io.vertx.core.json.JsonObject; import io.vertx.reactivex.circuitbreaker.CircuitBreaker; import io.vertx.reactivex.core.AbstractVerticle; import io.vertx.reactivex.core.buffer.Buffer; import io.vertx.reactivex.ext.web.Router; import io.vertx.reactivex.ext.web.RoutingContext; import io.vertx.reactivex.ext.web.client.HttpResponse; import io.vertx.reactivex.ext.web.handler.BodyHandler; import io.vertx.reactivex.servicediscovery.ServiceDiscovery; import io.vertx.reactivex.servicediscovery.types.EventBusService; import io.vertx.reactivex.servicediscovery.types.HttpEndpoint; import io.vertx.workshop.portfolio.reactivex.PortfolioService; import static io.vertx.workshop.currency.Helpers.toObserver; err -> new JsonObject() .put("amount", rc.getBodyAsJson().getDouble("amount")) .put("currency", "USD"))) // ---- .map(JsonObject::toBuffer) .map(Buffer::new) .subscribe(toObserver(rc)); } /** * Example of method not using a circuit breaker. * * @param rc the routing context */ private void delegate(RoutingContext rc) { HttpEndpoint.rxGetWebClient(discovery, svc -> svc.getName().equals("currency-3rdparty-service")) .flatMap(client -> client.post("/").rxSendJsonObject(rc.getBodyAsJson())) .map(HttpResponse::bodyAsBuffer) .subscribe(toObserver(rc)); } /** * Method to check the proxy requesting to convert the current portfolio to EUR. * * @param rc the routing context */ private void convertPortfolioToEuro(RoutingContext rc) {
EventBusService.getServiceProxy(discovery, svc -> svc.getName().equals("portfolio"), PortfolioService.class,
cescoffier/vertx-kubernetes-workshop
compulsive-traders/src/main/java/io/vertx/workshop/trader/impl/RXCompulsiveTraderVerticle.java
// Path: portfolio-service/src/main/generated/io/vertx/workshop/portfolio/reactivex/PortfolioService.java // @io.vertx.lang.reactivex.RxGen(io.vertx.workshop.portfolio.PortfolioService.class) // public class PortfolioService { // // public static final io.vertx.lang.reactivex.TypeArg<PortfolioService> __TYPE_ARG = new io.vertx.lang.reactivex.TypeArg<>( // obj -> new PortfolioService((io.vertx.workshop.portfolio.PortfolioService) obj), // PortfolioService::getDelegate // ); // // private final io.vertx.workshop.portfolio.PortfolioService delegate; // // public PortfolioService(io.vertx.workshop.portfolio.PortfolioService delegate) { // this.delegate = delegate; // } // // public io.vertx.workshop.portfolio.PortfolioService getDelegate() { // return delegate; // } // // /** // * Gets the portfolio. // * @param resultHandler the result handler called when the portfolio has been retrieved. The async result indicates whether the call was successful or not. // */ // public void getPortfolio(Handler<AsyncResult<Portfolio>> resultHandler) { // delegate.getPortfolio(resultHandler); // } // // /** // * Gets the portfolio. // * @return // */ // public Single<Portfolio> rxGetPortfolio() { // return new io.vertx.reactivex.core.impl.AsyncResultSingle<Portfolio>(handler -> { // getPortfolio(handler); // }); // } // // /** // * Buy `amount` shares of the given shares (quote). // * @param amount the amount // * @param quote the last quote // * @param resultHandler the result handler with the updated portfolio. If the action cannot be executed, the async result is market as a failure (not enough money, not enough shares available...) // */ // public void buy(int amount, JsonObject quote, Handler<AsyncResult<Portfolio>> resultHandler) { // delegate.buy(amount, quote, resultHandler); // } // // /** // * Buy `amount` shares of the given shares (quote). // * @param amount the amount // * @param quote the last quote // * @return // */ // public Single<Portfolio> rxBuy(int amount, JsonObject quote) { // return new io.vertx.reactivex.core.impl.AsyncResultSingle<Portfolio>(handler -> { // buy(amount, quote, handler); // }); // } // // /** // * Sell `amount` shares of the given shares (quote). // * @param amount the amount // * @param quote the last quote // * @param resultHandler the result handler with the updated portfolio. If the action cannot be executed, the async result is market as a failure (not enough share...) // */ // public void sell(int amount, JsonObject quote, Handler<AsyncResult<Portfolio>> resultHandler) { // delegate.sell(amount, quote, resultHandler); // } // // /** // * Sell `amount` shares of the given shares (quote). // * @param amount the amount // * @param quote the last quote // * @return // */ // public Single<Portfolio> rxSell(int amount, JsonObject quote) { // return new io.vertx.reactivex.core.impl.AsyncResultSingle<Portfolio>(handler -> { // sell(amount, quote, handler); // }); // } // // /** // * Evaluates the current value of the portfolio. // * @param resultHandler the result handler with the valuation // */ // public void evaluate(Handler<AsyncResult<Double>> resultHandler) { // delegate.evaluate(resultHandler); // } // // /** // * Evaluates the current value of the portfolio. // * @return // */ // public Single<Double> rxEvaluate() { // return new io.vertx.reactivex.core.impl.AsyncResultSingle<Double>(handler -> { // evaluate(handler); // }); // } // // // public static PortfolioService newInstance(io.vertx.workshop.portfolio.PortfolioService arg) { // return arg != null ? new PortfolioService(arg) : null; // } // }
import io.reactivex.Single; import io.vertx.core.Future; import io.vertx.core.json.JsonObject; import io.vertx.reactivex.core.AbstractVerticle; import io.vertx.reactivex.core.eventbus.MessageConsumer; import io.vertx.reactivex.servicediscovery.ServiceDiscovery; import io.vertx.reactivex.servicediscovery.types.MessageSource; import io.vertx.workshop.portfolio.reactivex.PortfolioService;
package io.vertx.workshop.trader.impl; /** * A compulsive trader developed with RX Java 2. */ public class RXCompulsiveTraderVerticle extends AbstractVerticle { @Override public void start(Future<Void> future) { String company = TraderUtils.pickACompany(); int numberOfShares = TraderUtils.pickANumber(); System.out.println("Java-RX compulsive trader configured for company " + company + " and shares: " + numberOfShares); ServiceDiscovery.create(vertx, discovery -> {
// Path: portfolio-service/src/main/generated/io/vertx/workshop/portfolio/reactivex/PortfolioService.java // @io.vertx.lang.reactivex.RxGen(io.vertx.workshop.portfolio.PortfolioService.class) // public class PortfolioService { // // public static final io.vertx.lang.reactivex.TypeArg<PortfolioService> __TYPE_ARG = new io.vertx.lang.reactivex.TypeArg<>( // obj -> new PortfolioService((io.vertx.workshop.portfolio.PortfolioService) obj), // PortfolioService::getDelegate // ); // // private final io.vertx.workshop.portfolio.PortfolioService delegate; // // public PortfolioService(io.vertx.workshop.portfolio.PortfolioService delegate) { // this.delegate = delegate; // } // // public io.vertx.workshop.portfolio.PortfolioService getDelegate() { // return delegate; // } // // /** // * Gets the portfolio. // * @param resultHandler the result handler called when the portfolio has been retrieved. The async result indicates whether the call was successful or not. // */ // public void getPortfolio(Handler<AsyncResult<Portfolio>> resultHandler) { // delegate.getPortfolio(resultHandler); // } // // /** // * Gets the portfolio. // * @return // */ // public Single<Portfolio> rxGetPortfolio() { // return new io.vertx.reactivex.core.impl.AsyncResultSingle<Portfolio>(handler -> { // getPortfolio(handler); // }); // } // // /** // * Buy `amount` shares of the given shares (quote). // * @param amount the amount // * @param quote the last quote // * @param resultHandler the result handler with the updated portfolio. If the action cannot be executed, the async result is market as a failure (not enough money, not enough shares available...) // */ // public void buy(int amount, JsonObject quote, Handler<AsyncResult<Portfolio>> resultHandler) { // delegate.buy(amount, quote, resultHandler); // } // // /** // * Buy `amount` shares of the given shares (quote). // * @param amount the amount // * @param quote the last quote // * @return // */ // public Single<Portfolio> rxBuy(int amount, JsonObject quote) { // return new io.vertx.reactivex.core.impl.AsyncResultSingle<Portfolio>(handler -> { // buy(amount, quote, handler); // }); // } // // /** // * Sell `amount` shares of the given shares (quote). // * @param amount the amount // * @param quote the last quote // * @param resultHandler the result handler with the updated portfolio. If the action cannot be executed, the async result is market as a failure (not enough share...) // */ // public void sell(int amount, JsonObject quote, Handler<AsyncResult<Portfolio>> resultHandler) { // delegate.sell(amount, quote, resultHandler); // } // // /** // * Sell `amount` shares of the given shares (quote). // * @param amount the amount // * @param quote the last quote // * @return // */ // public Single<Portfolio> rxSell(int amount, JsonObject quote) { // return new io.vertx.reactivex.core.impl.AsyncResultSingle<Portfolio>(handler -> { // sell(amount, quote, handler); // }); // } // // /** // * Evaluates the current value of the portfolio. // * @param resultHandler the result handler with the valuation // */ // public void evaluate(Handler<AsyncResult<Double>> resultHandler) { // delegate.evaluate(resultHandler); // } // // /** // * Evaluates the current value of the portfolio. // * @return // */ // public Single<Double> rxEvaluate() { // return new io.vertx.reactivex.core.impl.AsyncResultSingle<Double>(handler -> { // evaluate(handler); // }); // } // // // public static PortfolioService newInstance(io.vertx.workshop.portfolio.PortfolioService arg) { // return arg != null ? new PortfolioService(arg) : null; // } // } // Path: compulsive-traders/src/main/java/io/vertx/workshop/trader/impl/RXCompulsiveTraderVerticle.java import io.reactivex.Single; import io.vertx.core.Future; import io.vertx.core.json.JsonObject; import io.vertx.reactivex.core.AbstractVerticle; import io.vertx.reactivex.core.eventbus.MessageConsumer; import io.vertx.reactivex.servicediscovery.ServiceDiscovery; import io.vertx.reactivex.servicediscovery.types.MessageSource; import io.vertx.workshop.portfolio.reactivex.PortfolioService; package io.vertx.workshop.trader.impl; /** * A compulsive trader developed with RX Java 2. */ public class RXCompulsiveTraderVerticle extends AbstractVerticle { @Override public void start(Future<Void> future) { String company = TraderUtils.pickACompany(); int numberOfShares = TraderUtils.pickANumber(); System.out.println("Java-RX compulsive trader configured for company " + company + " and shares: " + numberOfShares); ServiceDiscovery.create(vertx, discovery -> {
Single<PortfolioService> retrieveThePortfolioService = RXEventBusService.rxGetProxy(discovery, PortfolioService.class,
cescoffier/vertx-kubernetes-workshop
compulsive-traders/src/main/solution/io/vertx/workshop/trader/impl/RXCompulsiveTraderVerticle.java
// Path: portfolio-service/src/main/generated/io/vertx/workshop/portfolio/reactivex/PortfolioService.java // @io.vertx.lang.reactivex.RxGen(io.vertx.workshop.portfolio.PortfolioService.class) // public class PortfolioService { // // public static final io.vertx.lang.reactivex.TypeArg<PortfolioService> __TYPE_ARG = new io.vertx.lang.reactivex.TypeArg<>( // obj -> new PortfolioService((io.vertx.workshop.portfolio.PortfolioService) obj), // PortfolioService::getDelegate // ); // // private final io.vertx.workshop.portfolio.PortfolioService delegate; // // public PortfolioService(io.vertx.workshop.portfolio.PortfolioService delegate) { // this.delegate = delegate; // } // // public io.vertx.workshop.portfolio.PortfolioService getDelegate() { // return delegate; // } // // /** // * Gets the portfolio. // * @param resultHandler the result handler called when the portfolio has been retrieved. The async result indicates whether the call was successful or not. // */ // public void getPortfolio(Handler<AsyncResult<Portfolio>> resultHandler) { // delegate.getPortfolio(resultHandler); // } // // /** // * Gets the portfolio. // * @return // */ // public Single<Portfolio> rxGetPortfolio() { // return new io.vertx.reactivex.core.impl.AsyncResultSingle<Portfolio>(handler -> { // getPortfolio(handler); // }); // } // // /** // * Buy `amount` shares of the given shares (quote). // * @param amount the amount // * @param quote the last quote // * @param resultHandler the result handler with the updated portfolio. If the action cannot be executed, the async result is market as a failure (not enough money, not enough shares available...) // */ // public void buy(int amount, JsonObject quote, Handler<AsyncResult<Portfolio>> resultHandler) { // delegate.buy(amount, quote, resultHandler); // } // // /** // * Buy `amount` shares of the given shares (quote). // * @param amount the amount // * @param quote the last quote // * @return // */ // public Single<Portfolio> rxBuy(int amount, JsonObject quote) { // return new io.vertx.reactivex.core.impl.AsyncResultSingle<Portfolio>(handler -> { // buy(amount, quote, handler); // }); // } // // /** // * Sell `amount` shares of the given shares (quote). // * @param amount the amount // * @param quote the last quote // * @param resultHandler the result handler with the updated portfolio. If the action cannot be executed, the async result is market as a failure (not enough share...) // */ // public void sell(int amount, JsonObject quote, Handler<AsyncResult<Portfolio>> resultHandler) { // delegate.sell(amount, quote, resultHandler); // } // // /** // * Sell `amount` shares of the given shares (quote). // * @param amount the amount // * @param quote the last quote // * @return // */ // public Single<Portfolio> rxSell(int amount, JsonObject quote) { // return new io.vertx.reactivex.core.impl.AsyncResultSingle<Portfolio>(handler -> { // sell(amount, quote, handler); // }); // } // // /** // * Evaluates the current value of the portfolio. // * @param resultHandler the result handler with the valuation // */ // public void evaluate(Handler<AsyncResult<Double>> resultHandler) { // delegate.evaluate(resultHandler); // } // // /** // * Evaluates the current value of the portfolio. // * @return // */ // public Single<Double> rxEvaluate() { // return new io.vertx.reactivex.core.impl.AsyncResultSingle<Double>(handler -> { // evaluate(handler); // }); // } // // // public static PortfolioService newInstance(io.vertx.workshop.portfolio.PortfolioService arg) { // return arg != null ? new PortfolioService(arg) : null; // } // }
import io.reactivex.Single; import io.vertx.core.Future; import io.vertx.core.json.JsonObject; import io.vertx.reactivex.CompletableHelper; import io.vertx.reactivex.core.AbstractVerticle; import io.vertx.reactivex.core.eventbus.MessageConsumer; import io.vertx.reactivex.servicediscovery.ServiceDiscovery; import io.vertx.reactivex.servicediscovery.types.MessageSource; import io.vertx.workshop.portfolio.reactivex.PortfolioService;
package io.vertx.workshop.trader.impl; /** * A compulsive trader developed with RX Java 2. */ public class RXCompulsiveTraderVerticle extends AbstractVerticle { @Override public void start(Future<Void> future) { String company = TraderUtils.pickACompany(); int numberOfShares = TraderUtils.pickANumber(); System.out.println("Java-RX compulsive trader configured for company " + company + " and shares: " + numberOfShares); ServiceDiscovery.create(vertx, discovery -> {
// Path: portfolio-service/src/main/generated/io/vertx/workshop/portfolio/reactivex/PortfolioService.java // @io.vertx.lang.reactivex.RxGen(io.vertx.workshop.portfolio.PortfolioService.class) // public class PortfolioService { // // public static final io.vertx.lang.reactivex.TypeArg<PortfolioService> __TYPE_ARG = new io.vertx.lang.reactivex.TypeArg<>( // obj -> new PortfolioService((io.vertx.workshop.portfolio.PortfolioService) obj), // PortfolioService::getDelegate // ); // // private final io.vertx.workshop.portfolio.PortfolioService delegate; // // public PortfolioService(io.vertx.workshop.portfolio.PortfolioService delegate) { // this.delegate = delegate; // } // // public io.vertx.workshop.portfolio.PortfolioService getDelegate() { // return delegate; // } // // /** // * Gets the portfolio. // * @param resultHandler the result handler called when the portfolio has been retrieved. The async result indicates whether the call was successful or not. // */ // public void getPortfolio(Handler<AsyncResult<Portfolio>> resultHandler) { // delegate.getPortfolio(resultHandler); // } // // /** // * Gets the portfolio. // * @return // */ // public Single<Portfolio> rxGetPortfolio() { // return new io.vertx.reactivex.core.impl.AsyncResultSingle<Portfolio>(handler -> { // getPortfolio(handler); // }); // } // // /** // * Buy `amount` shares of the given shares (quote). // * @param amount the amount // * @param quote the last quote // * @param resultHandler the result handler with the updated portfolio. If the action cannot be executed, the async result is market as a failure (not enough money, not enough shares available...) // */ // public void buy(int amount, JsonObject quote, Handler<AsyncResult<Portfolio>> resultHandler) { // delegate.buy(amount, quote, resultHandler); // } // // /** // * Buy `amount` shares of the given shares (quote). // * @param amount the amount // * @param quote the last quote // * @return // */ // public Single<Portfolio> rxBuy(int amount, JsonObject quote) { // return new io.vertx.reactivex.core.impl.AsyncResultSingle<Portfolio>(handler -> { // buy(amount, quote, handler); // }); // } // // /** // * Sell `amount` shares of the given shares (quote). // * @param amount the amount // * @param quote the last quote // * @param resultHandler the result handler with the updated portfolio. If the action cannot be executed, the async result is market as a failure (not enough share...) // */ // public void sell(int amount, JsonObject quote, Handler<AsyncResult<Portfolio>> resultHandler) { // delegate.sell(amount, quote, resultHandler); // } // // /** // * Sell `amount` shares of the given shares (quote). // * @param amount the amount // * @param quote the last quote // * @return // */ // public Single<Portfolio> rxSell(int amount, JsonObject quote) { // return new io.vertx.reactivex.core.impl.AsyncResultSingle<Portfolio>(handler -> { // sell(amount, quote, handler); // }); // } // // /** // * Evaluates the current value of the portfolio. // * @param resultHandler the result handler with the valuation // */ // public void evaluate(Handler<AsyncResult<Double>> resultHandler) { // delegate.evaluate(resultHandler); // } // // /** // * Evaluates the current value of the portfolio. // * @return // */ // public Single<Double> rxEvaluate() { // return new io.vertx.reactivex.core.impl.AsyncResultSingle<Double>(handler -> { // evaluate(handler); // }); // } // // // public static PortfolioService newInstance(io.vertx.workshop.portfolio.PortfolioService arg) { // return arg != null ? new PortfolioService(arg) : null; // } // } // Path: compulsive-traders/src/main/solution/io/vertx/workshop/trader/impl/RXCompulsiveTraderVerticle.java import io.reactivex.Single; import io.vertx.core.Future; import io.vertx.core.json.JsonObject; import io.vertx.reactivex.CompletableHelper; import io.vertx.reactivex.core.AbstractVerticle; import io.vertx.reactivex.core.eventbus.MessageConsumer; import io.vertx.reactivex.servicediscovery.ServiceDiscovery; import io.vertx.reactivex.servicediscovery.types.MessageSource; import io.vertx.workshop.portfolio.reactivex.PortfolioService; package io.vertx.workshop.trader.impl; /** * A compulsive trader developed with RX Java 2. */ public class RXCompulsiveTraderVerticle extends AbstractVerticle { @Override public void start(Future<Void> future) { String company = TraderUtils.pickACompany(); int numberOfShares = TraderUtils.pickANumber(); System.out.println("Java-RX compulsive trader configured for company " + company + " and shares: " + numberOfShares); ServiceDiscovery.create(vertx, discovery -> {
Single<PortfolioService> retrieveThePortfolioService = RXEventBusService.rxGetProxy(discovery, PortfolioService.class,
jvdb/derric
src/org/derric_lang/validator/interpreter/structure/ReadValue.java
// Path: src/org/derric_lang/validator/ByteOrder.java // public enum ByteOrder { // BIG_ENDIAN { // public void apply(byte[] b) { // } // }, // LITTLE_ENDIAN { // public void apply(byte[] b) { // for (int i = 0; i < b.length / 2; i++) { // byte tmp = b[i]; // b[i] = b[(b.length - 1) - i]; // b[(b.length - 1) - i] = tmp; // } // } // }; // // public abstract void apply(byte[] b); // } // // Path: src/org/derric_lang/validator/ValidatorInputStream.java // public abstract class ValidatorInputStream extends InputStream { // // public abstract boolean isByteAligned(); // public abstract boolean atEOF() throws IOException; // // public abstract long lastLocation(); // public abstract long lastRead(); // public abstract void mark(); // public abstract void reset() throws IOException; // // public abstract boolean skipBits(long bits) throws IOException; // public abstract long skip(long bytes) throws IOException; // // public abstract ValidatorInputStream bitOrder(BitOrder order); // public abstract ValidatorInputStream byteOrder(ByteOrder order); // public abstract ValidatorInputStream signed(); // public abstract ValidatorInputStream unsigned(); // public abstract long readInteger(long bits) throws IOException; // // public abstract ValidatorInputStream includeMarker(boolean includeMarker); // public abstract Content readUntil(long bits, ValueSet values) throws IOException; // // public abstract Content validateContent(long size, String name, Map<String, String> configuration, Map<String, List<Object>> arguments, boolean allowEOF) throws IOException; // } // // Path: src/org/derric_lang/validator/interpreter/Sentence.java // public class Sentence { // // private final URI _inputFile; // // private String _structureName; // private ISourceLocation _sequenceLocation; // private ISourceLocation _structureLocation; // private ISourceLocation _inputLocation; // // private List<StructureMatch> _matches; // private List<StructureMatch> _sub; // private List<FieldMatch> _fields; // // public Sentence(URI inputFile) { // _inputFile = inputFile; // _matches = new ArrayList<StructureMatch>(); // _sub = new ArrayList<StructureMatch>(); // _fields = new ArrayList<FieldMatch>(); // } // // public void setStructureName(String name) { // _structureName = name; // } // // public void setSequenceLocation(ISourceLocation location) { // _sequenceLocation = location; // } // // public void setStructureLocation(ISourceLocation location) { // _structureLocation = location; // } // // public void setStructureInputLocation(int offset, int length) { // _inputLocation = new SourceLocation(_inputFile, offset, length); // } // // public void addFieldLocation(String name, ISourceLocation sourceLocation, int offset, int length) { // boolean dup = false; // int index = 0; // for (int i = 0; i < _fields.size(); i++) { // if (_fields.get(i).sourceLocation.getOffset() == sourceLocation.getOffset() && _fields.get(i).sourceLocation.getLength() == sourceLocation.getLength()) { // dup = true; // index = i; // String fName = _fields.get(i).name.length() > name.length() ? name : _fields.get(i).name; // int fOffset = _fields.get(i).inputLocation.getOffset() > offset ? offset : _fields.get(i).inputLocation.getOffset(); // int fLength = ((_fields.get(i).inputLocation.getOffset() + _fields.get(i).inputLocation.getLength()) > (offset + length) ? _fields.get(i).inputLocation.getOffset() + _fields.get(i).inputLocation.getLength() : offset + length) - fOffset; // FieldMatch fm = new FieldMatch(fName, sourceLocation, new SourceLocation(_inputFile, fOffset, fLength)); // _fields.add(index, fm); // _fields.remove(index + 1); // break; // } // } // if (!dup) { // _fields.add(new FieldMatch(name, sourceLocation, new SourceLocation(_inputFile, offset, length))); // } // } // // public void subMatch() { // List<FieldMatch> fieldMatches = new ArrayList<FieldMatch>(); // fieldMatches.addAll(_fields); // _sub.add(new StructureMatch(_structureName, _sequenceLocation, _structureLocation, _inputLocation, fieldMatches)); // _fields.clear(); // } // // public void fullMatch() { // _matches.addAll(_sub); // clearSub(); // } // // public void clearSub() { // _sub.clear(); // _fields.clear(); // } // // @Override // public String toString() { // String out = ""; // boolean first = true; // for (StructureMatch s : _matches) { // if (first) { // first = false; // } else { // out += " "; // } // out += s.name; // } // return out; // } // // public List<StructureMatch> getMatches() { // return _matches; // } // // }
import java.io.IOException; import java.util.Map; import org.derric_lang.validator.ByteOrder; import org.derric_lang.validator.ValidatorInputStream; import org.derric_lang.validator.interpreter.Sentence;
package org.derric_lang.validator.interpreter.structure; public class ReadValue extends Statement { private final Integer _type; private final String _name; public ReadValue(Type type, String name) { _type = (Integer)type; _name = name; } @Override
// Path: src/org/derric_lang/validator/ByteOrder.java // public enum ByteOrder { // BIG_ENDIAN { // public void apply(byte[] b) { // } // }, // LITTLE_ENDIAN { // public void apply(byte[] b) { // for (int i = 0; i < b.length / 2; i++) { // byte tmp = b[i]; // b[i] = b[(b.length - 1) - i]; // b[(b.length - 1) - i] = tmp; // } // } // }; // // public abstract void apply(byte[] b); // } // // Path: src/org/derric_lang/validator/ValidatorInputStream.java // public abstract class ValidatorInputStream extends InputStream { // // public abstract boolean isByteAligned(); // public abstract boolean atEOF() throws IOException; // // public abstract long lastLocation(); // public abstract long lastRead(); // public abstract void mark(); // public abstract void reset() throws IOException; // // public abstract boolean skipBits(long bits) throws IOException; // public abstract long skip(long bytes) throws IOException; // // public abstract ValidatorInputStream bitOrder(BitOrder order); // public abstract ValidatorInputStream byteOrder(ByteOrder order); // public abstract ValidatorInputStream signed(); // public abstract ValidatorInputStream unsigned(); // public abstract long readInteger(long bits) throws IOException; // // public abstract ValidatorInputStream includeMarker(boolean includeMarker); // public abstract Content readUntil(long bits, ValueSet values) throws IOException; // // public abstract Content validateContent(long size, String name, Map<String, String> configuration, Map<String, List<Object>> arguments, boolean allowEOF) throws IOException; // } // // Path: src/org/derric_lang/validator/interpreter/Sentence.java // public class Sentence { // // private final URI _inputFile; // // private String _structureName; // private ISourceLocation _sequenceLocation; // private ISourceLocation _structureLocation; // private ISourceLocation _inputLocation; // // private List<StructureMatch> _matches; // private List<StructureMatch> _sub; // private List<FieldMatch> _fields; // // public Sentence(URI inputFile) { // _inputFile = inputFile; // _matches = new ArrayList<StructureMatch>(); // _sub = new ArrayList<StructureMatch>(); // _fields = new ArrayList<FieldMatch>(); // } // // public void setStructureName(String name) { // _structureName = name; // } // // public void setSequenceLocation(ISourceLocation location) { // _sequenceLocation = location; // } // // public void setStructureLocation(ISourceLocation location) { // _structureLocation = location; // } // // public void setStructureInputLocation(int offset, int length) { // _inputLocation = new SourceLocation(_inputFile, offset, length); // } // // public void addFieldLocation(String name, ISourceLocation sourceLocation, int offset, int length) { // boolean dup = false; // int index = 0; // for (int i = 0; i < _fields.size(); i++) { // if (_fields.get(i).sourceLocation.getOffset() == sourceLocation.getOffset() && _fields.get(i).sourceLocation.getLength() == sourceLocation.getLength()) { // dup = true; // index = i; // String fName = _fields.get(i).name.length() > name.length() ? name : _fields.get(i).name; // int fOffset = _fields.get(i).inputLocation.getOffset() > offset ? offset : _fields.get(i).inputLocation.getOffset(); // int fLength = ((_fields.get(i).inputLocation.getOffset() + _fields.get(i).inputLocation.getLength()) > (offset + length) ? _fields.get(i).inputLocation.getOffset() + _fields.get(i).inputLocation.getLength() : offset + length) - fOffset; // FieldMatch fm = new FieldMatch(fName, sourceLocation, new SourceLocation(_inputFile, fOffset, fLength)); // _fields.add(index, fm); // _fields.remove(index + 1); // break; // } // } // if (!dup) { // _fields.add(new FieldMatch(name, sourceLocation, new SourceLocation(_inputFile, offset, length))); // } // } // // public void subMatch() { // List<FieldMatch> fieldMatches = new ArrayList<FieldMatch>(); // fieldMatches.addAll(_fields); // _sub.add(new StructureMatch(_structureName, _sequenceLocation, _structureLocation, _inputLocation, fieldMatches)); // _fields.clear(); // } // // public void fullMatch() { // _matches.addAll(_sub); // clearSub(); // } // // public void clearSub() { // _sub.clear(); // _fields.clear(); // } // // @Override // public String toString() { // String out = ""; // boolean first = true; // for (StructureMatch s : _matches) { // if (first) { // first = false; // } else { // out += " "; // } // out += s.name; // } // return out; // } // // public List<StructureMatch> getMatches() { // return _matches; // } // // } // Path: src/org/derric_lang/validator/interpreter/structure/ReadValue.java import java.io.IOException; import java.util.Map; import org.derric_lang.validator.ByteOrder; import org.derric_lang.validator.ValidatorInputStream; import org.derric_lang.validator.interpreter.Sentence; package org.derric_lang.validator.interpreter.structure; public class ReadValue extends Statement { private final Integer _type; private final String _name; public ReadValue(Type type, String name) { _type = (Integer)type; _name = name; } @Override
public boolean eval(ValidatorInputStream input, Map<String, Type> globals, Map<String, Type> locals, Sentence current) throws IOException {
jvdb/derric
src/org/derric_lang/validator/interpreter/structure/ReadValue.java
// Path: src/org/derric_lang/validator/ByteOrder.java // public enum ByteOrder { // BIG_ENDIAN { // public void apply(byte[] b) { // } // }, // LITTLE_ENDIAN { // public void apply(byte[] b) { // for (int i = 0; i < b.length / 2; i++) { // byte tmp = b[i]; // b[i] = b[(b.length - 1) - i]; // b[(b.length - 1) - i] = tmp; // } // } // }; // // public abstract void apply(byte[] b); // } // // Path: src/org/derric_lang/validator/ValidatorInputStream.java // public abstract class ValidatorInputStream extends InputStream { // // public abstract boolean isByteAligned(); // public abstract boolean atEOF() throws IOException; // // public abstract long lastLocation(); // public abstract long lastRead(); // public abstract void mark(); // public abstract void reset() throws IOException; // // public abstract boolean skipBits(long bits) throws IOException; // public abstract long skip(long bytes) throws IOException; // // public abstract ValidatorInputStream bitOrder(BitOrder order); // public abstract ValidatorInputStream byteOrder(ByteOrder order); // public abstract ValidatorInputStream signed(); // public abstract ValidatorInputStream unsigned(); // public abstract long readInteger(long bits) throws IOException; // // public abstract ValidatorInputStream includeMarker(boolean includeMarker); // public abstract Content readUntil(long bits, ValueSet values) throws IOException; // // public abstract Content validateContent(long size, String name, Map<String, String> configuration, Map<String, List<Object>> arguments, boolean allowEOF) throws IOException; // } // // Path: src/org/derric_lang/validator/interpreter/Sentence.java // public class Sentence { // // private final URI _inputFile; // // private String _structureName; // private ISourceLocation _sequenceLocation; // private ISourceLocation _structureLocation; // private ISourceLocation _inputLocation; // // private List<StructureMatch> _matches; // private List<StructureMatch> _sub; // private List<FieldMatch> _fields; // // public Sentence(URI inputFile) { // _inputFile = inputFile; // _matches = new ArrayList<StructureMatch>(); // _sub = new ArrayList<StructureMatch>(); // _fields = new ArrayList<FieldMatch>(); // } // // public void setStructureName(String name) { // _structureName = name; // } // // public void setSequenceLocation(ISourceLocation location) { // _sequenceLocation = location; // } // // public void setStructureLocation(ISourceLocation location) { // _structureLocation = location; // } // // public void setStructureInputLocation(int offset, int length) { // _inputLocation = new SourceLocation(_inputFile, offset, length); // } // // public void addFieldLocation(String name, ISourceLocation sourceLocation, int offset, int length) { // boolean dup = false; // int index = 0; // for (int i = 0; i < _fields.size(); i++) { // if (_fields.get(i).sourceLocation.getOffset() == sourceLocation.getOffset() && _fields.get(i).sourceLocation.getLength() == sourceLocation.getLength()) { // dup = true; // index = i; // String fName = _fields.get(i).name.length() > name.length() ? name : _fields.get(i).name; // int fOffset = _fields.get(i).inputLocation.getOffset() > offset ? offset : _fields.get(i).inputLocation.getOffset(); // int fLength = ((_fields.get(i).inputLocation.getOffset() + _fields.get(i).inputLocation.getLength()) > (offset + length) ? _fields.get(i).inputLocation.getOffset() + _fields.get(i).inputLocation.getLength() : offset + length) - fOffset; // FieldMatch fm = new FieldMatch(fName, sourceLocation, new SourceLocation(_inputFile, fOffset, fLength)); // _fields.add(index, fm); // _fields.remove(index + 1); // break; // } // } // if (!dup) { // _fields.add(new FieldMatch(name, sourceLocation, new SourceLocation(_inputFile, offset, length))); // } // } // // public void subMatch() { // List<FieldMatch> fieldMatches = new ArrayList<FieldMatch>(); // fieldMatches.addAll(_fields); // _sub.add(new StructureMatch(_structureName, _sequenceLocation, _structureLocation, _inputLocation, fieldMatches)); // _fields.clear(); // } // // public void fullMatch() { // _matches.addAll(_sub); // clearSub(); // } // // public void clearSub() { // _sub.clear(); // _fields.clear(); // } // // @Override // public String toString() { // String out = ""; // boolean first = true; // for (StructureMatch s : _matches) { // if (first) { // first = false; // } else { // out += " "; // } // out += s.name; // } // return out; // } // // public List<StructureMatch> getMatches() { // return _matches; // } // // }
import java.io.IOException; import java.util.Map; import org.derric_lang.validator.ByteOrder; import org.derric_lang.validator.ValidatorInputStream; import org.derric_lang.validator.interpreter.Sentence;
package org.derric_lang.validator.interpreter.structure; public class ReadValue extends Statement { private final Integer _type; private final String _name; public ReadValue(Type type, String name) { _type = (Integer)type; _name = name; } @Override
// Path: src/org/derric_lang/validator/ByteOrder.java // public enum ByteOrder { // BIG_ENDIAN { // public void apply(byte[] b) { // } // }, // LITTLE_ENDIAN { // public void apply(byte[] b) { // for (int i = 0; i < b.length / 2; i++) { // byte tmp = b[i]; // b[i] = b[(b.length - 1) - i]; // b[(b.length - 1) - i] = tmp; // } // } // }; // // public abstract void apply(byte[] b); // } // // Path: src/org/derric_lang/validator/ValidatorInputStream.java // public abstract class ValidatorInputStream extends InputStream { // // public abstract boolean isByteAligned(); // public abstract boolean atEOF() throws IOException; // // public abstract long lastLocation(); // public abstract long lastRead(); // public abstract void mark(); // public abstract void reset() throws IOException; // // public abstract boolean skipBits(long bits) throws IOException; // public abstract long skip(long bytes) throws IOException; // // public abstract ValidatorInputStream bitOrder(BitOrder order); // public abstract ValidatorInputStream byteOrder(ByteOrder order); // public abstract ValidatorInputStream signed(); // public abstract ValidatorInputStream unsigned(); // public abstract long readInteger(long bits) throws IOException; // // public abstract ValidatorInputStream includeMarker(boolean includeMarker); // public abstract Content readUntil(long bits, ValueSet values) throws IOException; // // public abstract Content validateContent(long size, String name, Map<String, String> configuration, Map<String, List<Object>> arguments, boolean allowEOF) throws IOException; // } // // Path: src/org/derric_lang/validator/interpreter/Sentence.java // public class Sentence { // // private final URI _inputFile; // // private String _structureName; // private ISourceLocation _sequenceLocation; // private ISourceLocation _structureLocation; // private ISourceLocation _inputLocation; // // private List<StructureMatch> _matches; // private List<StructureMatch> _sub; // private List<FieldMatch> _fields; // // public Sentence(URI inputFile) { // _inputFile = inputFile; // _matches = new ArrayList<StructureMatch>(); // _sub = new ArrayList<StructureMatch>(); // _fields = new ArrayList<FieldMatch>(); // } // // public void setStructureName(String name) { // _structureName = name; // } // // public void setSequenceLocation(ISourceLocation location) { // _sequenceLocation = location; // } // // public void setStructureLocation(ISourceLocation location) { // _structureLocation = location; // } // // public void setStructureInputLocation(int offset, int length) { // _inputLocation = new SourceLocation(_inputFile, offset, length); // } // // public void addFieldLocation(String name, ISourceLocation sourceLocation, int offset, int length) { // boolean dup = false; // int index = 0; // for (int i = 0; i < _fields.size(); i++) { // if (_fields.get(i).sourceLocation.getOffset() == sourceLocation.getOffset() && _fields.get(i).sourceLocation.getLength() == sourceLocation.getLength()) { // dup = true; // index = i; // String fName = _fields.get(i).name.length() > name.length() ? name : _fields.get(i).name; // int fOffset = _fields.get(i).inputLocation.getOffset() > offset ? offset : _fields.get(i).inputLocation.getOffset(); // int fLength = ((_fields.get(i).inputLocation.getOffset() + _fields.get(i).inputLocation.getLength()) > (offset + length) ? _fields.get(i).inputLocation.getOffset() + _fields.get(i).inputLocation.getLength() : offset + length) - fOffset; // FieldMatch fm = new FieldMatch(fName, sourceLocation, new SourceLocation(_inputFile, fOffset, fLength)); // _fields.add(index, fm); // _fields.remove(index + 1); // break; // } // } // if (!dup) { // _fields.add(new FieldMatch(name, sourceLocation, new SourceLocation(_inputFile, offset, length))); // } // } // // public void subMatch() { // List<FieldMatch> fieldMatches = new ArrayList<FieldMatch>(); // fieldMatches.addAll(_fields); // _sub.add(new StructureMatch(_structureName, _sequenceLocation, _structureLocation, _inputLocation, fieldMatches)); // _fields.clear(); // } // // public void fullMatch() { // _matches.addAll(_sub); // clearSub(); // } // // public void clearSub() { // _sub.clear(); // _fields.clear(); // } // // @Override // public String toString() { // String out = ""; // boolean first = true; // for (StructureMatch s : _matches) { // if (first) { // first = false; // } else { // out += " "; // } // out += s.name; // } // return out; // } // // public List<StructureMatch> getMatches() { // return _matches; // } // // } // Path: src/org/derric_lang/validator/interpreter/structure/ReadValue.java import java.io.IOException; import java.util.Map; import org.derric_lang.validator.ByteOrder; import org.derric_lang.validator.ValidatorInputStream; import org.derric_lang.validator.interpreter.Sentence; package org.derric_lang.validator.interpreter.structure; public class ReadValue extends Statement { private final Integer _type; private final String _name; public ReadValue(Type type, String name) { _type = (Integer)type; _name = name; } @Override
public boolean eval(ValidatorInputStream input, Map<String, Type> globals, Map<String, Type> locals, Sentence current) throws IOException {
jvdb/derric
src/org/derric_lang/validator/interpreter/structure/ReadValue.java
// Path: src/org/derric_lang/validator/ByteOrder.java // public enum ByteOrder { // BIG_ENDIAN { // public void apply(byte[] b) { // } // }, // LITTLE_ENDIAN { // public void apply(byte[] b) { // for (int i = 0; i < b.length / 2; i++) { // byte tmp = b[i]; // b[i] = b[(b.length - 1) - i]; // b[(b.length - 1) - i] = tmp; // } // } // }; // // public abstract void apply(byte[] b); // } // // Path: src/org/derric_lang/validator/ValidatorInputStream.java // public abstract class ValidatorInputStream extends InputStream { // // public abstract boolean isByteAligned(); // public abstract boolean atEOF() throws IOException; // // public abstract long lastLocation(); // public abstract long lastRead(); // public abstract void mark(); // public abstract void reset() throws IOException; // // public abstract boolean skipBits(long bits) throws IOException; // public abstract long skip(long bytes) throws IOException; // // public abstract ValidatorInputStream bitOrder(BitOrder order); // public abstract ValidatorInputStream byteOrder(ByteOrder order); // public abstract ValidatorInputStream signed(); // public abstract ValidatorInputStream unsigned(); // public abstract long readInteger(long bits) throws IOException; // // public abstract ValidatorInputStream includeMarker(boolean includeMarker); // public abstract Content readUntil(long bits, ValueSet values) throws IOException; // // public abstract Content validateContent(long size, String name, Map<String, String> configuration, Map<String, List<Object>> arguments, boolean allowEOF) throws IOException; // } // // Path: src/org/derric_lang/validator/interpreter/Sentence.java // public class Sentence { // // private final URI _inputFile; // // private String _structureName; // private ISourceLocation _sequenceLocation; // private ISourceLocation _structureLocation; // private ISourceLocation _inputLocation; // // private List<StructureMatch> _matches; // private List<StructureMatch> _sub; // private List<FieldMatch> _fields; // // public Sentence(URI inputFile) { // _inputFile = inputFile; // _matches = new ArrayList<StructureMatch>(); // _sub = new ArrayList<StructureMatch>(); // _fields = new ArrayList<FieldMatch>(); // } // // public void setStructureName(String name) { // _structureName = name; // } // // public void setSequenceLocation(ISourceLocation location) { // _sequenceLocation = location; // } // // public void setStructureLocation(ISourceLocation location) { // _structureLocation = location; // } // // public void setStructureInputLocation(int offset, int length) { // _inputLocation = new SourceLocation(_inputFile, offset, length); // } // // public void addFieldLocation(String name, ISourceLocation sourceLocation, int offset, int length) { // boolean dup = false; // int index = 0; // for (int i = 0; i < _fields.size(); i++) { // if (_fields.get(i).sourceLocation.getOffset() == sourceLocation.getOffset() && _fields.get(i).sourceLocation.getLength() == sourceLocation.getLength()) { // dup = true; // index = i; // String fName = _fields.get(i).name.length() > name.length() ? name : _fields.get(i).name; // int fOffset = _fields.get(i).inputLocation.getOffset() > offset ? offset : _fields.get(i).inputLocation.getOffset(); // int fLength = ((_fields.get(i).inputLocation.getOffset() + _fields.get(i).inputLocation.getLength()) > (offset + length) ? _fields.get(i).inputLocation.getOffset() + _fields.get(i).inputLocation.getLength() : offset + length) - fOffset; // FieldMatch fm = new FieldMatch(fName, sourceLocation, new SourceLocation(_inputFile, fOffset, fLength)); // _fields.add(index, fm); // _fields.remove(index + 1); // break; // } // } // if (!dup) { // _fields.add(new FieldMatch(name, sourceLocation, new SourceLocation(_inputFile, offset, length))); // } // } // // public void subMatch() { // List<FieldMatch> fieldMatches = new ArrayList<FieldMatch>(); // fieldMatches.addAll(_fields); // _sub.add(new StructureMatch(_structureName, _sequenceLocation, _structureLocation, _inputLocation, fieldMatches)); // _fields.clear(); // } // // public void fullMatch() { // _matches.addAll(_sub); // clearSub(); // } // // public void clearSub() { // _sub.clear(); // _fields.clear(); // } // // @Override // public String toString() { // String out = ""; // boolean first = true; // for (StructureMatch s : _matches) { // if (first) { // first = false; // } else { // out += " "; // } // out += s.name; // } // return out; // } // // public List<StructureMatch> getMatches() { // return _matches; // } // // }
import java.io.IOException; import java.util.Map; import org.derric_lang.validator.ByteOrder; import org.derric_lang.validator.ValidatorInputStream; import org.derric_lang.validator.interpreter.Sentence;
package org.derric_lang.validator.interpreter.structure; public class ReadValue extends Statement { private final Integer _type; private final String _name; public ReadValue(Type type, String name) { _type = (Integer)type; _name = name; } @Override public boolean eval(ValidatorInputStream input, Map<String, Type> globals, Map<String, Type> locals, Sentence current) throws IOException { long offset = input.lastLocation(); Integer value = Expression.getInteger(_name, globals, locals); if (_type.getSign()) { input.signed(); } else { input.unsigned(); } if (_type.isBigEndian()) {
// Path: src/org/derric_lang/validator/ByteOrder.java // public enum ByteOrder { // BIG_ENDIAN { // public void apply(byte[] b) { // } // }, // LITTLE_ENDIAN { // public void apply(byte[] b) { // for (int i = 0; i < b.length / 2; i++) { // byte tmp = b[i]; // b[i] = b[(b.length - 1) - i]; // b[(b.length - 1) - i] = tmp; // } // } // }; // // public abstract void apply(byte[] b); // } // // Path: src/org/derric_lang/validator/ValidatorInputStream.java // public abstract class ValidatorInputStream extends InputStream { // // public abstract boolean isByteAligned(); // public abstract boolean atEOF() throws IOException; // // public abstract long lastLocation(); // public abstract long lastRead(); // public abstract void mark(); // public abstract void reset() throws IOException; // // public abstract boolean skipBits(long bits) throws IOException; // public abstract long skip(long bytes) throws IOException; // // public abstract ValidatorInputStream bitOrder(BitOrder order); // public abstract ValidatorInputStream byteOrder(ByteOrder order); // public abstract ValidatorInputStream signed(); // public abstract ValidatorInputStream unsigned(); // public abstract long readInteger(long bits) throws IOException; // // public abstract ValidatorInputStream includeMarker(boolean includeMarker); // public abstract Content readUntil(long bits, ValueSet values) throws IOException; // // public abstract Content validateContent(long size, String name, Map<String, String> configuration, Map<String, List<Object>> arguments, boolean allowEOF) throws IOException; // } // // Path: src/org/derric_lang/validator/interpreter/Sentence.java // public class Sentence { // // private final URI _inputFile; // // private String _structureName; // private ISourceLocation _sequenceLocation; // private ISourceLocation _structureLocation; // private ISourceLocation _inputLocation; // // private List<StructureMatch> _matches; // private List<StructureMatch> _sub; // private List<FieldMatch> _fields; // // public Sentence(URI inputFile) { // _inputFile = inputFile; // _matches = new ArrayList<StructureMatch>(); // _sub = new ArrayList<StructureMatch>(); // _fields = new ArrayList<FieldMatch>(); // } // // public void setStructureName(String name) { // _structureName = name; // } // // public void setSequenceLocation(ISourceLocation location) { // _sequenceLocation = location; // } // // public void setStructureLocation(ISourceLocation location) { // _structureLocation = location; // } // // public void setStructureInputLocation(int offset, int length) { // _inputLocation = new SourceLocation(_inputFile, offset, length); // } // // public void addFieldLocation(String name, ISourceLocation sourceLocation, int offset, int length) { // boolean dup = false; // int index = 0; // for (int i = 0; i < _fields.size(); i++) { // if (_fields.get(i).sourceLocation.getOffset() == sourceLocation.getOffset() && _fields.get(i).sourceLocation.getLength() == sourceLocation.getLength()) { // dup = true; // index = i; // String fName = _fields.get(i).name.length() > name.length() ? name : _fields.get(i).name; // int fOffset = _fields.get(i).inputLocation.getOffset() > offset ? offset : _fields.get(i).inputLocation.getOffset(); // int fLength = ((_fields.get(i).inputLocation.getOffset() + _fields.get(i).inputLocation.getLength()) > (offset + length) ? _fields.get(i).inputLocation.getOffset() + _fields.get(i).inputLocation.getLength() : offset + length) - fOffset; // FieldMatch fm = new FieldMatch(fName, sourceLocation, new SourceLocation(_inputFile, fOffset, fLength)); // _fields.add(index, fm); // _fields.remove(index + 1); // break; // } // } // if (!dup) { // _fields.add(new FieldMatch(name, sourceLocation, new SourceLocation(_inputFile, offset, length))); // } // } // // public void subMatch() { // List<FieldMatch> fieldMatches = new ArrayList<FieldMatch>(); // fieldMatches.addAll(_fields); // _sub.add(new StructureMatch(_structureName, _sequenceLocation, _structureLocation, _inputLocation, fieldMatches)); // _fields.clear(); // } // // public void fullMatch() { // _matches.addAll(_sub); // clearSub(); // } // // public void clearSub() { // _sub.clear(); // _fields.clear(); // } // // @Override // public String toString() { // String out = ""; // boolean first = true; // for (StructureMatch s : _matches) { // if (first) { // first = false; // } else { // out += " "; // } // out += s.name; // } // return out; // } // // public List<StructureMatch> getMatches() { // return _matches; // } // // } // Path: src/org/derric_lang/validator/interpreter/structure/ReadValue.java import java.io.IOException; import java.util.Map; import org.derric_lang.validator.ByteOrder; import org.derric_lang.validator.ValidatorInputStream; import org.derric_lang.validator.interpreter.Sentence; package org.derric_lang.validator.interpreter.structure; public class ReadValue extends Statement { private final Integer _type; private final String _name; public ReadValue(Type type, String name) { _type = (Integer)type; _name = name; } @Override public boolean eval(ValidatorInputStream input, Map<String, Type> globals, Map<String, Type> locals, Sentence current) throws IOException { long offset = input.lastLocation(); Integer value = Expression.getInteger(_name, globals, locals); if (_type.getSign()) { input.signed(); } else { input.unsigned(); } if (_type.isBigEndian()) {
input.byteOrder(ByteOrder.BIG_ENDIAN);
jvdb/derric
src/org/derric_lang/validator/interpreter/symbol/Iter.java
// Path: src/org/derric_lang/validator/interpreter/Interpreter.java // public class Interpreter extends Validator { // // private final String _format; // private final List<Symbol> _sequence; // private final List<Structure> _structures; // private final Map<String, Type> _globals; // // private Sentence _current; // private URI _inputFile; // // public Interpreter(URI inputFile, String format, List<Symbol> sequence, List<Structure> structures, List<Decl> globals) { // super(format); // _inputFile = inputFile; // _format = format; // _sequence = sequence; // _structures = structures; // _globals = new HashMap<String, Type>(); // for (Decl d : globals) { // _globals.put(d.getName(), d.getType()); // } // setStream(ValidatorInputStreamFactory.create(_inputFile)); // } // // @Override // public String getExtension() { // return _format; // } // // @Override // protected ParseResult tryParseBody() throws IOException { // _current = new Sentence(_inputFile); // for (Symbol s : _sequence) { // if (!s.parse(this)) { // return new ParseResult(false, _input.lastLocation(), _input.lastRead(), s.toString(), _current.toString()); // } // _current.fullMatch(); // //System.out.println("Validated " + s.toString()); // } // return new ParseResult(true, _input.lastLocation(), _input.lastRead(), "", _current.toString()); // } // // @Override // public ParseResult findNextFooter() throws IOException { // return null; // } // // public boolean parseStructure(String name) throws IOException { // long offset = _input.lastLocation(); // for (Structure s : _structures) { // if (name.equals(s.getName())) { // if (s.parse(_input, _globals, _current)) { // _current.setStructureLocation(s.getLocation()); // _current.setStructureInputLocation((int)offset, (int)(_input.lastLocation() - offset)); // //System.out.println("Structure " + s.getName() + " matched!"); // return true; // } else { // return false; // } // } // } // throw new RuntimeException("Unknown structure requested: " + name); // } // // public ValidatorInputStream getInput() { // return _input; // } // // public Sentence getCurrent() { // return _current; // } // // }
import java.io.IOException; import org.derric_lang.validator.interpreter.Interpreter;
package org.derric_lang.validator.interpreter.symbol; public class Iter extends Symbol { private final Symbol _symbol; public Iter(Symbol symbol) { _symbol = symbol; } @Override
// Path: src/org/derric_lang/validator/interpreter/Interpreter.java // public class Interpreter extends Validator { // // private final String _format; // private final List<Symbol> _sequence; // private final List<Structure> _structures; // private final Map<String, Type> _globals; // // private Sentence _current; // private URI _inputFile; // // public Interpreter(URI inputFile, String format, List<Symbol> sequence, List<Structure> structures, List<Decl> globals) { // super(format); // _inputFile = inputFile; // _format = format; // _sequence = sequence; // _structures = structures; // _globals = new HashMap<String, Type>(); // for (Decl d : globals) { // _globals.put(d.getName(), d.getType()); // } // setStream(ValidatorInputStreamFactory.create(_inputFile)); // } // // @Override // public String getExtension() { // return _format; // } // // @Override // protected ParseResult tryParseBody() throws IOException { // _current = new Sentence(_inputFile); // for (Symbol s : _sequence) { // if (!s.parse(this)) { // return new ParseResult(false, _input.lastLocation(), _input.lastRead(), s.toString(), _current.toString()); // } // _current.fullMatch(); // //System.out.println("Validated " + s.toString()); // } // return new ParseResult(true, _input.lastLocation(), _input.lastRead(), "", _current.toString()); // } // // @Override // public ParseResult findNextFooter() throws IOException { // return null; // } // // public boolean parseStructure(String name) throws IOException { // long offset = _input.lastLocation(); // for (Structure s : _structures) { // if (name.equals(s.getName())) { // if (s.parse(_input, _globals, _current)) { // _current.setStructureLocation(s.getLocation()); // _current.setStructureInputLocation((int)offset, (int)(_input.lastLocation() - offset)); // //System.out.println("Structure " + s.getName() + " matched!"); // return true; // } else { // return false; // } // } // } // throw new RuntimeException("Unknown structure requested: " + name); // } // // public ValidatorInputStream getInput() { // return _input; // } // // public Sentence getCurrent() { // return _current; // } // // } // Path: src/org/derric_lang/validator/interpreter/symbol/Iter.java import java.io.IOException; import org.derric_lang.validator.interpreter.Interpreter; package org.derric_lang.validator.interpreter.symbol; public class Iter extends Symbol { private final Symbol _symbol; public Iter(Symbol symbol) { _symbol = symbol; } @Override
public boolean parse(Interpreter in) throws IOException {
jvdb/derric
src/org/derric_lang/validator/interpreter/structure/Statement.java
// Path: src/org/derric_lang/validator/ValidatorInputStream.java // public abstract class ValidatorInputStream extends InputStream { // // public abstract boolean isByteAligned(); // public abstract boolean atEOF() throws IOException; // // public abstract long lastLocation(); // public abstract long lastRead(); // public abstract void mark(); // public abstract void reset() throws IOException; // // public abstract boolean skipBits(long bits) throws IOException; // public abstract long skip(long bytes) throws IOException; // // public abstract ValidatorInputStream bitOrder(BitOrder order); // public abstract ValidatorInputStream byteOrder(ByteOrder order); // public abstract ValidatorInputStream signed(); // public abstract ValidatorInputStream unsigned(); // public abstract long readInteger(long bits) throws IOException; // // public abstract ValidatorInputStream includeMarker(boolean includeMarker); // public abstract Content readUntil(long bits, ValueSet values) throws IOException; // // public abstract Content validateContent(long size, String name, Map<String, String> configuration, Map<String, List<Object>> arguments, boolean allowEOF) throws IOException; // } // // Path: src/org/derric_lang/validator/interpreter/Sentence.java // public class Sentence { // // private final URI _inputFile; // // private String _structureName; // private ISourceLocation _sequenceLocation; // private ISourceLocation _structureLocation; // private ISourceLocation _inputLocation; // // private List<StructureMatch> _matches; // private List<StructureMatch> _sub; // private List<FieldMatch> _fields; // // public Sentence(URI inputFile) { // _inputFile = inputFile; // _matches = new ArrayList<StructureMatch>(); // _sub = new ArrayList<StructureMatch>(); // _fields = new ArrayList<FieldMatch>(); // } // // public void setStructureName(String name) { // _structureName = name; // } // // public void setSequenceLocation(ISourceLocation location) { // _sequenceLocation = location; // } // // public void setStructureLocation(ISourceLocation location) { // _structureLocation = location; // } // // public void setStructureInputLocation(int offset, int length) { // _inputLocation = new SourceLocation(_inputFile, offset, length); // } // // public void addFieldLocation(String name, ISourceLocation sourceLocation, int offset, int length) { // boolean dup = false; // int index = 0; // for (int i = 0; i < _fields.size(); i++) { // if (_fields.get(i).sourceLocation.getOffset() == sourceLocation.getOffset() && _fields.get(i).sourceLocation.getLength() == sourceLocation.getLength()) { // dup = true; // index = i; // String fName = _fields.get(i).name.length() > name.length() ? name : _fields.get(i).name; // int fOffset = _fields.get(i).inputLocation.getOffset() > offset ? offset : _fields.get(i).inputLocation.getOffset(); // int fLength = ((_fields.get(i).inputLocation.getOffset() + _fields.get(i).inputLocation.getLength()) > (offset + length) ? _fields.get(i).inputLocation.getOffset() + _fields.get(i).inputLocation.getLength() : offset + length) - fOffset; // FieldMatch fm = new FieldMatch(fName, sourceLocation, new SourceLocation(_inputFile, fOffset, fLength)); // _fields.add(index, fm); // _fields.remove(index + 1); // break; // } // } // if (!dup) { // _fields.add(new FieldMatch(name, sourceLocation, new SourceLocation(_inputFile, offset, length))); // } // } // // public void subMatch() { // List<FieldMatch> fieldMatches = new ArrayList<FieldMatch>(); // fieldMatches.addAll(_fields); // _sub.add(new StructureMatch(_structureName, _sequenceLocation, _structureLocation, _inputLocation, fieldMatches)); // _fields.clear(); // } // // public void fullMatch() { // _matches.addAll(_sub); // clearSub(); // } // // public void clearSub() { // _sub.clear(); // _fields.clear(); // } // // @Override // public String toString() { // String out = ""; // boolean first = true; // for (StructureMatch s : _matches) { // if (first) { // first = false; // } else { // out += " "; // } // out += s.name; // } // return out; // } // // public List<StructureMatch> getMatches() { // return _matches; // } // // }
import java.io.IOException; import java.util.Map; import org.derric_lang.validator.ValidatorInputStream; import org.derric_lang.validator.interpreter.Sentence; import org.eclipse.imp.pdb.facts.ISourceLocation;
package org.derric_lang.validator.interpreter.structure; public abstract class Statement { private ISourceLocation _location; private String _fieldName; public void setLocation(ISourceLocation location) { _location = location; } public ISourceLocation getLocation() { return _location; } public void setFieldName(String fieldName) { _fieldName = fieldName; } public String getFieldName() { return _fieldName; }
// Path: src/org/derric_lang/validator/ValidatorInputStream.java // public abstract class ValidatorInputStream extends InputStream { // // public abstract boolean isByteAligned(); // public abstract boolean atEOF() throws IOException; // // public abstract long lastLocation(); // public abstract long lastRead(); // public abstract void mark(); // public abstract void reset() throws IOException; // // public abstract boolean skipBits(long bits) throws IOException; // public abstract long skip(long bytes) throws IOException; // // public abstract ValidatorInputStream bitOrder(BitOrder order); // public abstract ValidatorInputStream byteOrder(ByteOrder order); // public abstract ValidatorInputStream signed(); // public abstract ValidatorInputStream unsigned(); // public abstract long readInteger(long bits) throws IOException; // // public abstract ValidatorInputStream includeMarker(boolean includeMarker); // public abstract Content readUntil(long bits, ValueSet values) throws IOException; // // public abstract Content validateContent(long size, String name, Map<String, String> configuration, Map<String, List<Object>> arguments, boolean allowEOF) throws IOException; // } // // Path: src/org/derric_lang/validator/interpreter/Sentence.java // public class Sentence { // // private final URI _inputFile; // // private String _structureName; // private ISourceLocation _sequenceLocation; // private ISourceLocation _structureLocation; // private ISourceLocation _inputLocation; // // private List<StructureMatch> _matches; // private List<StructureMatch> _sub; // private List<FieldMatch> _fields; // // public Sentence(URI inputFile) { // _inputFile = inputFile; // _matches = new ArrayList<StructureMatch>(); // _sub = new ArrayList<StructureMatch>(); // _fields = new ArrayList<FieldMatch>(); // } // // public void setStructureName(String name) { // _structureName = name; // } // // public void setSequenceLocation(ISourceLocation location) { // _sequenceLocation = location; // } // // public void setStructureLocation(ISourceLocation location) { // _structureLocation = location; // } // // public void setStructureInputLocation(int offset, int length) { // _inputLocation = new SourceLocation(_inputFile, offset, length); // } // // public void addFieldLocation(String name, ISourceLocation sourceLocation, int offset, int length) { // boolean dup = false; // int index = 0; // for (int i = 0; i < _fields.size(); i++) { // if (_fields.get(i).sourceLocation.getOffset() == sourceLocation.getOffset() && _fields.get(i).sourceLocation.getLength() == sourceLocation.getLength()) { // dup = true; // index = i; // String fName = _fields.get(i).name.length() > name.length() ? name : _fields.get(i).name; // int fOffset = _fields.get(i).inputLocation.getOffset() > offset ? offset : _fields.get(i).inputLocation.getOffset(); // int fLength = ((_fields.get(i).inputLocation.getOffset() + _fields.get(i).inputLocation.getLength()) > (offset + length) ? _fields.get(i).inputLocation.getOffset() + _fields.get(i).inputLocation.getLength() : offset + length) - fOffset; // FieldMatch fm = new FieldMatch(fName, sourceLocation, new SourceLocation(_inputFile, fOffset, fLength)); // _fields.add(index, fm); // _fields.remove(index + 1); // break; // } // } // if (!dup) { // _fields.add(new FieldMatch(name, sourceLocation, new SourceLocation(_inputFile, offset, length))); // } // } // // public void subMatch() { // List<FieldMatch> fieldMatches = new ArrayList<FieldMatch>(); // fieldMatches.addAll(_fields); // _sub.add(new StructureMatch(_structureName, _sequenceLocation, _structureLocation, _inputLocation, fieldMatches)); // _fields.clear(); // } // // public void fullMatch() { // _matches.addAll(_sub); // clearSub(); // } // // public void clearSub() { // _sub.clear(); // _fields.clear(); // } // // @Override // public String toString() { // String out = ""; // boolean first = true; // for (StructureMatch s : _matches) { // if (first) { // first = false; // } else { // out += " "; // } // out += s.name; // } // return out; // } // // public List<StructureMatch> getMatches() { // return _matches; // } // // } // Path: src/org/derric_lang/validator/interpreter/structure/Statement.java import java.io.IOException; import java.util.Map; import org.derric_lang.validator.ValidatorInputStream; import org.derric_lang.validator.interpreter.Sentence; import org.eclipse.imp.pdb.facts.ISourceLocation; package org.derric_lang.validator.interpreter.structure; public abstract class Statement { private ISourceLocation _location; private String _fieldName; public void setLocation(ISourceLocation location) { _location = location; } public ISourceLocation getLocation() { return _location; } public void setFieldName(String fieldName) { _fieldName = fieldName; } public String getFieldName() { return _fieldName; }
public abstract boolean eval(ValidatorInputStream input, Map<String, Type> globals, Map<String, Type> locals, Sentence current) throws IOException;
jvdb/derric
src/org/derric_lang/validator/interpreter/structure/Statement.java
// Path: src/org/derric_lang/validator/ValidatorInputStream.java // public abstract class ValidatorInputStream extends InputStream { // // public abstract boolean isByteAligned(); // public abstract boolean atEOF() throws IOException; // // public abstract long lastLocation(); // public abstract long lastRead(); // public abstract void mark(); // public abstract void reset() throws IOException; // // public abstract boolean skipBits(long bits) throws IOException; // public abstract long skip(long bytes) throws IOException; // // public abstract ValidatorInputStream bitOrder(BitOrder order); // public abstract ValidatorInputStream byteOrder(ByteOrder order); // public abstract ValidatorInputStream signed(); // public abstract ValidatorInputStream unsigned(); // public abstract long readInteger(long bits) throws IOException; // // public abstract ValidatorInputStream includeMarker(boolean includeMarker); // public abstract Content readUntil(long bits, ValueSet values) throws IOException; // // public abstract Content validateContent(long size, String name, Map<String, String> configuration, Map<String, List<Object>> arguments, boolean allowEOF) throws IOException; // } // // Path: src/org/derric_lang/validator/interpreter/Sentence.java // public class Sentence { // // private final URI _inputFile; // // private String _structureName; // private ISourceLocation _sequenceLocation; // private ISourceLocation _structureLocation; // private ISourceLocation _inputLocation; // // private List<StructureMatch> _matches; // private List<StructureMatch> _sub; // private List<FieldMatch> _fields; // // public Sentence(URI inputFile) { // _inputFile = inputFile; // _matches = new ArrayList<StructureMatch>(); // _sub = new ArrayList<StructureMatch>(); // _fields = new ArrayList<FieldMatch>(); // } // // public void setStructureName(String name) { // _structureName = name; // } // // public void setSequenceLocation(ISourceLocation location) { // _sequenceLocation = location; // } // // public void setStructureLocation(ISourceLocation location) { // _structureLocation = location; // } // // public void setStructureInputLocation(int offset, int length) { // _inputLocation = new SourceLocation(_inputFile, offset, length); // } // // public void addFieldLocation(String name, ISourceLocation sourceLocation, int offset, int length) { // boolean dup = false; // int index = 0; // for (int i = 0; i < _fields.size(); i++) { // if (_fields.get(i).sourceLocation.getOffset() == sourceLocation.getOffset() && _fields.get(i).sourceLocation.getLength() == sourceLocation.getLength()) { // dup = true; // index = i; // String fName = _fields.get(i).name.length() > name.length() ? name : _fields.get(i).name; // int fOffset = _fields.get(i).inputLocation.getOffset() > offset ? offset : _fields.get(i).inputLocation.getOffset(); // int fLength = ((_fields.get(i).inputLocation.getOffset() + _fields.get(i).inputLocation.getLength()) > (offset + length) ? _fields.get(i).inputLocation.getOffset() + _fields.get(i).inputLocation.getLength() : offset + length) - fOffset; // FieldMatch fm = new FieldMatch(fName, sourceLocation, new SourceLocation(_inputFile, fOffset, fLength)); // _fields.add(index, fm); // _fields.remove(index + 1); // break; // } // } // if (!dup) { // _fields.add(new FieldMatch(name, sourceLocation, new SourceLocation(_inputFile, offset, length))); // } // } // // public void subMatch() { // List<FieldMatch> fieldMatches = new ArrayList<FieldMatch>(); // fieldMatches.addAll(_fields); // _sub.add(new StructureMatch(_structureName, _sequenceLocation, _structureLocation, _inputLocation, fieldMatches)); // _fields.clear(); // } // // public void fullMatch() { // _matches.addAll(_sub); // clearSub(); // } // // public void clearSub() { // _sub.clear(); // _fields.clear(); // } // // @Override // public String toString() { // String out = ""; // boolean first = true; // for (StructureMatch s : _matches) { // if (first) { // first = false; // } else { // out += " "; // } // out += s.name; // } // return out; // } // // public List<StructureMatch> getMatches() { // return _matches; // } // // }
import java.io.IOException; import java.util.Map; import org.derric_lang.validator.ValidatorInputStream; import org.derric_lang.validator.interpreter.Sentence; import org.eclipse.imp.pdb.facts.ISourceLocation;
package org.derric_lang.validator.interpreter.structure; public abstract class Statement { private ISourceLocation _location; private String _fieldName; public void setLocation(ISourceLocation location) { _location = location; } public ISourceLocation getLocation() { return _location; } public void setFieldName(String fieldName) { _fieldName = fieldName; } public String getFieldName() { return _fieldName; }
// Path: src/org/derric_lang/validator/ValidatorInputStream.java // public abstract class ValidatorInputStream extends InputStream { // // public abstract boolean isByteAligned(); // public abstract boolean atEOF() throws IOException; // // public abstract long lastLocation(); // public abstract long lastRead(); // public abstract void mark(); // public abstract void reset() throws IOException; // // public abstract boolean skipBits(long bits) throws IOException; // public abstract long skip(long bytes) throws IOException; // // public abstract ValidatorInputStream bitOrder(BitOrder order); // public abstract ValidatorInputStream byteOrder(ByteOrder order); // public abstract ValidatorInputStream signed(); // public abstract ValidatorInputStream unsigned(); // public abstract long readInteger(long bits) throws IOException; // // public abstract ValidatorInputStream includeMarker(boolean includeMarker); // public abstract Content readUntil(long bits, ValueSet values) throws IOException; // // public abstract Content validateContent(long size, String name, Map<String, String> configuration, Map<String, List<Object>> arguments, boolean allowEOF) throws IOException; // } // // Path: src/org/derric_lang/validator/interpreter/Sentence.java // public class Sentence { // // private final URI _inputFile; // // private String _structureName; // private ISourceLocation _sequenceLocation; // private ISourceLocation _structureLocation; // private ISourceLocation _inputLocation; // // private List<StructureMatch> _matches; // private List<StructureMatch> _sub; // private List<FieldMatch> _fields; // // public Sentence(URI inputFile) { // _inputFile = inputFile; // _matches = new ArrayList<StructureMatch>(); // _sub = new ArrayList<StructureMatch>(); // _fields = new ArrayList<FieldMatch>(); // } // // public void setStructureName(String name) { // _structureName = name; // } // // public void setSequenceLocation(ISourceLocation location) { // _sequenceLocation = location; // } // // public void setStructureLocation(ISourceLocation location) { // _structureLocation = location; // } // // public void setStructureInputLocation(int offset, int length) { // _inputLocation = new SourceLocation(_inputFile, offset, length); // } // // public void addFieldLocation(String name, ISourceLocation sourceLocation, int offset, int length) { // boolean dup = false; // int index = 0; // for (int i = 0; i < _fields.size(); i++) { // if (_fields.get(i).sourceLocation.getOffset() == sourceLocation.getOffset() && _fields.get(i).sourceLocation.getLength() == sourceLocation.getLength()) { // dup = true; // index = i; // String fName = _fields.get(i).name.length() > name.length() ? name : _fields.get(i).name; // int fOffset = _fields.get(i).inputLocation.getOffset() > offset ? offset : _fields.get(i).inputLocation.getOffset(); // int fLength = ((_fields.get(i).inputLocation.getOffset() + _fields.get(i).inputLocation.getLength()) > (offset + length) ? _fields.get(i).inputLocation.getOffset() + _fields.get(i).inputLocation.getLength() : offset + length) - fOffset; // FieldMatch fm = new FieldMatch(fName, sourceLocation, new SourceLocation(_inputFile, fOffset, fLength)); // _fields.add(index, fm); // _fields.remove(index + 1); // break; // } // } // if (!dup) { // _fields.add(new FieldMatch(name, sourceLocation, new SourceLocation(_inputFile, offset, length))); // } // } // // public void subMatch() { // List<FieldMatch> fieldMatches = new ArrayList<FieldMatch>(); // fieldMatches.addAll(_fields); // _sub.add(new StructureMatch(_structureName, _sequenceLocation, _structureLocation, _inputLocation, fieldMatches)); // _fields.clear(); // } // // public void fullMatch() { // _matches.addAll(_sub); // clearSub(); // } // // public void clearSub() { // _sub.clear(); // _fields.clear(); // } // // @Override // public String toString() { // String out = ""; // boolean first = true; // for (StructureMatch s : _matches) { // if (first) { // first = false; // } else { // out += " "; // } // out += s.name; // } // return out; // } // // public List<StructureMatch> getMatches() { // return _matches; // } // // } // Path: src/org/derric_lang/validator/interpreter/structure/Statement.java import java.io.IOException; import java.util.Map; import org.derric_lang.validator.ValidatorInputStream; import org.derric_lang.validator.interpreter.Sentence; import org.eclipse.imp.pdb.facts.ISourceLocation; package org.derric_lang.validator.interpreter.structure; public abstract class Statement { private ISourceLocation _location; private String _fieldName; public void setLocation(ISourceLocation location) { _location = location; } public ISourceLocation getLocation() { return _location; } public void setFieldName(String fieldName) { _fieldName = fieldName; } public String getFieldName() { return _fieldName; }
public abstract boolean eval(ValidatorInputStream input, Map<String, Type> globals, Map<String, Type> locals, Sentence current) throws IOException;
jvdb/derric
src/org/derric_lang/validator/interpreter/symbol/Optional.java
// Path: src/org/derric_lang/validator/interpreter/Interpreter.java // public class Interpreter extends Validator { // // private final String _format; // private final List<Symbol> _sequence; // private final List<Structure> _structures; // private final Map<String, Type> _globals; // // private Sentence _current; // private URI _inputFile; // // public Interpreter(URI inputFile, String format, List<Symbol> sequence, List<Structure> structures, List<Decl> globals) { // super(format); // _inputFile = inputFile; // _format = format; // _sequence = sequence; // _structures = structures; // _globals = new HashMap<String, Type>(); // for (Decl d : globals) { // _globals.put(d.getName(), d.getType()); // } // setStream(ValidatorInputStreamFactory.create(_inputFile)); // } // // @Override // public String getExtension() { // return _format; // } // // @Override // protected ParseResult tryParseBody() throws IOException { // _current = new Sentence(_inputFile); // for (Symbol s : _sequence) { // if (!s.parse(this)) { // return new ParseResult(false, _input.lastLocation(), _input.lastRead(), s.toString(), _current.toString()); // } // _current.fullMatch(); // //System.out.println("Validated " + s.toString()); // } // return new ParseResult(true, _input.lastLocation(), _input.lastRead(), "", _current.toString()); // } // // @Override // public ParseResult findNextFooter() throws IOException { // return null; // } // // public boolean parseStructure(String name) throws IOException { // long offset = _input.lastLocation(); // for (Structure s : _structures) { // if (name.equals(s.getName())) { // if (s.parse(_input, _globals, _current)) { // _current.setStructureLocation(s.getLocation()); // _current.setStructureInputLocation((int)offset, (int)(_input.lastLocation() - offset)); // //System.out.println("Structure " + s.getName() + " matched!"); // return true; // } else { // return false; // } // } // } // throw new RuntimeException("Unknown structure requested: " + name); // } // // public ValidatorInputStream getInput() { // return _input; // } // // public Sentence getCurrent() { // return _current; // } // // }
import java.io.IOException; import org.derric_lang.validator.interpreter.Interpreter;
package org.derric_lang.validator.interpreter.symbol; public class Optional extends Symbol { private final Symbol _symbol; public Optional(Symbol symbol) { _symbol = symbol; } @Override
// Path: src/org/derric_lang/validator/interpreter/Interpreter.java // public class Interpreter extends Validator { // // private final String _format; // private final List<Symbol> _sequence; // private final List<Structure> _structures; // private final Map<String, Type> _globals; // // private Sentence _current; // private URI _inputFile; // // public Interpreter(URI inputFile, String format, List<Symbol> sequence, List<Structure> structures, List<Decl> globals) { // super(format); // _inputFile = inputFile; // _format = format; // _sequence = sequence; // _structures = structures; // _globals = new HashMap<String, Type>(); // for (Decl d : globals) { // _globals.put(d.getName(), d.getType()); // } // setStream(ValidatorInputStreamFactory.create(_inputFile)); // } // // @Override // public String getExtension() { // return _format; // } // // @Override // protected ParseResult tryParseBody() throws IOException { // _current = new Sentence(_inputFile); // for (Symbol s : _sequence) { // if (!s.parse(this)) { // return new ParseResult(false, _input.lastLocation(), _input.lastRead(), s.toString(), _current.toString()); // } // _current.fullMatch(); // //System.out.println("Validated " + s.toString()); // } // return new ParseResult(true, _input.lastLocation(), _input.lastRead(), "", _current.toString()); // } // // @Override // public ParseResult findNextFooter() throws IOException { // return null; // } // // public boolean parseStructure(String name) throws IOException { // long offset = _input.lastLocation(); // for (Structure s : _structures) { // if (name.equals(s.getName())) { // if (s.parse(_input, _globals, _current)) { // _current.setStructureLocation(s.getLocation()); // _current.setStructureInputLocation((int)offset, (int)(_input.lastLocation() - offset)); // //System.out.println("Structure " + s.getName() + " matched!"); // return true; // } else { // return false; // } // } // } // throw new RuntimeException("Unknown structure requested: " + name); // } // // public ValidatorInputStream getInput() { // return _input; // } // // public Sentence getCurrent() { // return _current; // } // // } // Path: src/org/derric_lang/validator/interpreter/symbol/Optional.java import java.io.IOException; import org.derric_lang.validator.interpreter.Interpreter; package org.derric_lang.validator.interpreter.symbol; public class Optional extends Symbol { private final Symbol _symbol; public Optional(Symbol symbol) { _symbol = symbol; } @Override
public boolean parse(Interpreter in) throws IOException {
jvdb/derric
src/org/derric_lang/validator/interpreter/structure/SkipValue.java
// Path: src/org/derric_lang/validator/ValidatorInputStream.java // public abstract class ValidatorInputStream extends InputStream { // // public abstract boolean isByteAligned(); // public abstract boolean atEOF() throws IOException; // // public abstract long lastLocation(); // public abstract long lastRead(); // public abstract void mark(); // public abstract void reset() throws IOException; // // public abstract boolean skipBits(long bits) throws IOException; // public abstract long skip(long bytes) throws IOException; // // public abstract ValidatorInputStream bitOrder(BitOrder order); // public abstract ValidatorInputStream byteOrder(ByteOrder order); // public abstract ValidatorInputStream signed(); // public abstract ValidatorInputStream unsigned(); // public abstract long readInteger(long bits) throws IOException; // // public abstract ValidatorInputStream includeMarker(boolean includeMarker); // public abstract Content readUntil(long bits, ValueSet values) throws IOException; // // public abstract Content validateContent(long size, String name, Map<String, String> configuration, Map<String, List<Object>> arguments, boolean allowEOF) throws IOException; // } // // Path: src/org/derric_lang/validator/interpreter/Sentence.java // public class Sentence { // // private final URI _inputFile; // // private String _structureName; // private ISourceLocation _sequenceLocation; // private ISourceLocation _structureLocation; // private ISourceLocation _inputLocation; // // private List<StructureMatch> _matches; // private List<StructureMatch> _sub; // private List<FieldMatch> _fields; // // public Sentence(URI inputFile) { // _inputFile = inputFile; // _matches = new ArrayList<StructureMatch>(); // _sub = new ArrayList<StructureMatch>(); // _fields = new ArrayList<FieldMatch>(); // } // // public void setStructureName(String name) { // _structureName = name; // } // // public void setSequenceLocation(ISourceLocation location) { // _sequenceLocation = location; // } // // public void setStructureLocation(ISourceLocation location) { // _structureLocation = location; // } // // public void setStructureInputLocation(int offset, int length) { // _inputLocation = new SourceLocation(_inputFile, offset, length); // } // // public void addFieldLocation(String name, ISourceLocation sourceLocation, int offset, int length) { // boolean dup = false; // int index = 0; // for (int i = 0; i < _fields.size(); i++) { // if (_fields.get(i).sourceLocation.getOffset() == sourceLocation.getOffset() && _fields.get(i).sourceLocation.getLength() == sourceLocation.getLength()) { // dup = true; // index = i; // String fName = _fields.get(i).name.length() > name.length() ? name : _fields.get(i).name; // int fOffset = _fields.get(i).inputLocation.getOffset() > offset ? offset : _fields.get(i).inputLocation.getOffset(); // int fLength = ((_fields.get(i).inputLocation.getOffset() + _fields.get(i).inputLocation.getLength()) > (offset + length) ? _fields.get(i).inputLocation.getOffset() + _fields.get(i).inputLocation.getLength() : offset + length) - fOffset; // FieldMatch fm = new FieldMatch(fName, sourceLocation, new SourceLocation(_inputFile, fOffset, fLength)); // _fields.add(index, fm); // _fields.remove(index + 1); // break; // } // } // if (!dup) { // _fields.add(new FieldMatch(name, sourceLocation, new SourceLocation(_inputFile, offset, length))); // } // } // // public void subMatch() { // List<FieldMatch> fieldMatches = new ArrayList<FieldMatch>(); // fieldMatches.addAll(_fields); // _sub.add(new StructureMatch(_structureName, _sequenceLocation, _structureLocation, _inputLocation, fieldMatches)); // _fields.clear(); // } // // public void fullMatch() { // _matches.addAll(_sub); // clearSub(); // } // // public void clearSub() { // _sub.clear(); // _fields.clear(); // } // // @Override // public String toString() { // String out = ""; // boolean first = true; // for (StructureMatch s : _matches) { // if (first) { // first = false; // } else { // out += " "; // } // out += s.name; // } // return out; // } // // public List<StructureMatch> getMatches() { // return _matches; // } // // }
import java.io.IOException; import java.util.Map; import org.derric_lang.validator.ValidatorInputStream; import org.derric_lang.validator.interpreter.Sentence;
package org.derric_lang.validator.interpreter.structure; public class SkipValue extends Statement { private final Type _type; public SkipValue(Type type) { _type = type; } @Override
// Path: src/org/derric_lang/validator/ValidatorInputStream.java // public abstract class ValidatorInputStream extends InputStream { // // public abstract boolean isByteAligned(); // public abstract boolean atEOF() throws IOException; // // public abstract long lastLocation(); // public abstract long lastRead(); // public abstract void mark(); // public abstract void reset() throws IOException; // // public abstract boolean skipBits(long bits) throws IOException; // public abstract long skip(long bytes) throws IOException; // // public abstract ValidatorInputStream bitOrder(BitOrder order); // public abstract ValidatorInputStream byteOrder(ByteOrder order); // public abstract ValidatorInputStream signed(); // public abstract ValidatorInputStream unsigned(); // public abstract long readInteger(long bits) throws IOException; // // public abstract ValidatorInputStream includeMarker(boolean includeMarker); // public abstract Content readUntil(long bits, ValueSet values) throws IOException; // // public abstract Content validateContent(long size, String name, Map<String, String> configuration, Map<String, List<Object>> arguments, boolean allowEOF) throws IOException; // } // // Path: src/org/derric_lang/validator/interpreter/Sentence.java // public class Sentence { // // private final URI _inputFile; // // private String _structureName; // private ISourceLocation _sequenceLocation; // private ISourceLocation _structureLocation; // private ISourceLocation _inputLocation; // // private List<StructureMatch> _matches; // private List<StructureMatch> _sub; // private List<FieldMatch> _fields; // // public Sentence(URI inputFile) { // _inputFile = inputFile; // _matches = new ArrayList<StructureMatch>(); // _sub = new ArrayList<StructureMatch>(); // _fields = new ArrayList<FieldMatch>(); // } // // public void setStructureName(String name) { // _structureName = name; // } // // public void setSequenceLocation(ISourceLocation location) { // _sequenceLocation = location; // } // // public void setStructureLocation(ISourceLocation location) { // _structureLocation = location; // } // // public void setStructureInputLocation(int offset, int length) { // _inputLocation = new SourceLocation(_inputFile, offset, length); // } // // public void addFieldLocation(String name, ISourceLocation sourceLocation, int offset, int length) { // boolean dup = false; // int index = 0; // for (int i = 0; i < _fields.size(); i++) { // if (_fields.get(i).sourceLocation.getOffset() == sourceLocation.getOffset() && _fields.get(i).sourceLocation.getLength() == sourceLocation.getLength()) { // dup = true; // index = i; // String fName = _fields.get(i).name.length() > name.length() ? name : _fields.get(i).name; // int fOffset = _fields.get(i).inputLocation.getOffset() > offset ? offset : _fields.get(i).inputLocation.getOffset(); // int fLength = ((_fields.get(i).inputLocation.getOffset() + _fields.get(i).inputLocation.getLength()) > (offset + length) ? _fields.get(i).inputLocation.getOffset() + _fields.get(i).inputLocation.getLength() : offset + length) - fOffset; // FieldMatch fm = new FieldMatch(fName, sourceLocation, new SourceLocation(_inputFile, fOffset, fLength)); // _fields.add(index, fm); // _fields.remove(index + 1); // break; // } // } // if (!dup) { // _fields.add(new FieldMatch(name, sourceLocation, new SourceLocation(_inputFile, offset, length))); // } // } // // public void subMatch() { // List<FieldMatch> fieldMatches = new ArrayList<FieldMatch>(); // fieldMatches.addAll(_fields); // _sub.add(new StructureMatch(_structureName, _sequenceLocation, _structureLocation, _inputLocation, fieldMatches)); // _fields.clear(); // } // // public void fullMatch() { // _matches.addAll(_sub); // clearSub(); // } // // public void clearSub() { // _sub.clear(); // _fields.clear(); // } // // @Override // public String toString() { // String out = ""; // boolean first = true; // for (StructureMatch s : _matches) { // if (first) { // first = false; // } else { // out += " "; // } // out += s.name; // } // return out; // } // // public List<StructureMatch> getMatches() { // return _matches; // } // // } // Path: src/org/derric_lang/validator/interpreter/structure/SkipValue.java import java.io.IOException; import java.util.Map; import org.derric_lang.validator.ValidatorInputStream; import org.derric_lang.validator.interpreter.Sentence; package org.derric_lang.validator.interpreter.structure; public class SkipValue extends Statement { private final Type _type; public SkipValue(Type type) { _type = type; } @Override
public boolean eval(ValidatorInputStream input, Map<String, Type> globals, Map<String, Type> locals, Sentence current) throws IOException {
jvdb/derric
src/org/derric_lang/validator/interpreter/structure/SkipValue.java
// Path: src/org/derric_lang/validator/ValidatorInputStream.java // public abstract class ValidatorInputStream extends InputStream { // // public abstract boolean isByteAligned(); // public abstract boolean atEOF() throws IOException; // // public abstract long lastLocation(); // public abstract long lastRead(); // public abstract void mark(); // public abstract void reset() throws IOException; // // public abstract boolean skipBits(long bits) throws IOException; // public abstract long skip(long bytes) throws IOException; // // public abstract ValidatorInputStream bitOrder(BitOrder order); // public abstract ValidatorInputStream byteOrder(ByteOrder order); // public abstract ValidatorInputStream signed(); // public abstract ValidatorInputStream unsigned(); // public abstract long readInteger(long bits) throws IOException; // // public abstract ValidatorInputStream includeMarker(boolean includeMarker); // public abstract Content readUntil(long bits, ValueSet values) throws IOException; // // public abstract Content validateContent(long size, String name, Map<String, String> configuration, Map<String, List<Object>> arguments, boolean allowEOF) throws IOException; // } // // Path: src/org/derric_lang/validator/interpreter/Sentence.java // public class Sentence { // // private final URI _inputFile; // // private String _structureName; // private ISourceLocation _sequenceLocation; // private ISourceLocation _structureLocation; // private ISourceLocation _inputLocation; // // private List<StructureMatch> _matches; // private List<StructureMatch> _sub; // private List<FieldMatch> _fields; // // public Sentence(URI inputFile) { // _inputFile = inputFile; // _matches = new ArrayList<StructureMatch>(); // _sub = new ArrayList<StructureMatch>(); // _fields = new ArrayList<FieldMatch>(); // } // // public void setStructureName(String name) { // _structureName = name; // } // // public void setSequenceLocation(ISourceLocation location) { // _sequenceLocation = location; // } // // public void setStructureLocation(ISourceLocation location) { // _structureLocation = location; // } // // public void setStructureInputLocation(int offset, int length) { // _inputLocation = new SourceLocation(_inputFile, offset, length); // } // // public void addFieldLocation(String name, ISourceLocation sourceLocation, int offset, int length) { // boolean dup = false; // int index = 0; // for (int i = 0; i < _fields.size(); i++) { // if (_fields.get(i).sourceLocation.getOffset() == sourceLocation.getOffset() && _fields.get(i).sourceLocation.getLength() == sourceLocation.getLength()) { // dup = true; // index = i; // String fName = _fields.get(i).name.length() > name.length() ? name : _fields.get(i).name; // int fOffset = _fields.get(i).inputLocation.getOffset() > offset ? offset : _fields.get(i).inputLocation.getOffset(); // int fLength = ((_fields.get(i).inputLocation.getOffset() + _fields.get(i).inputLocation.getLength()) > (offset + length) ? _fields.get(i).inputLocation.getOffset() + _fields.get(i).inputLocation.getLength() : offset + length) - fOffset; // FieldMatch fm = new FieldMatch(fName, sourceLocation, new SourceLocation(_inputFile, fOffset, fLength)); // _fields.add(index, fm); // _fields.remove(index + 1); // break; // } // } // if (!dup) { // _fields.add(new FieldMatch(name, sourceLocation, new SourceLocation(_inputFile, offset, length))); // } // } // // public void subMatch() { // List<FieldMatch> fieldMatches = new ArrayList<FieldMatch>(); // fieldMatches.addAll(_fields); // _sub.add(new StructureMatch(_structureName, _sequenceLocation, _structureLocation, _inputLocation, fieldMatches)); // _fields.clear(); // } // // public void fullMatch() { // _matches.addAll(_sub); // clearSub(); // } // // public void clearSub() { // _sub.clear(); // _fields.clear(); // } // // @Override // public String toString() { // String out = ""; // boolean first = true; // for (StructureMatch s : _matches) { // if (first) { // first = false; // } else { // out += " "; // } // out += s.name; // } // return out; // } // // public List<StructureMatch> getMatches() { // return _matches; // } // // }
import java.io.IOException; import java.util.Map; import org.derric_lang.validator.ValidatorInputStream; import org.derric_lang.validator.interpreter.Sentence;
package org.derric_lang.validator.interpreter.structure; public class SkipValue extends Statement { private final Type _type; public SkipValue(Type type) { _type = type; } @Override
// Path: src/org/derric_lang/validator/ValidatorInputStream.java // public abstract class ValidatorInputStream extends InputStream { // // public abstract boolean isByteAligned(); // public abstract boolean atEOF() throws IOException; // // public abstract long lastLocation(); // public abstract long lastRead(); // public abstract void mark(); // public abstract void reset() throws IOException; // // public abstract boolean skipBits(long bits) throws IOException; // public abstract long skip(long bytes) throws IOException; // // public abstract ValidatorInputStream bitOrder(BitOrder order); // public abstract ValidatorInputStream byteOrder(ByteOrder order); // public abstract ValidatorInputStream signed(); // public abstract ValidatorInputStream unsigned(); // public abstract long readInteger(long bits) throws IOException; // // public abstract ValidatorInputStream includeMarker(boolean includeMarker); // public abstract Content readUntil(long bits, ValueSet values) throws IOException; // // public abstract Content validateContent(long size, String name, Map<String, String> configuration, Map<String, List<Object>> arguments, boolean allowEOF) throws IOException; // } // // Path: src/org/derric_lang/validator/interpreter/Sentence.java // public class Sentence { // // private final URI _inputFile; // // private String _structureName; // private ISourceLocation _sequenceLocation; // private ISourceLocation _structureLocation; // private ISourceLocation _inputLocation; // // private List<StructureMatch> _matches; // private List<StructureMatch> _sub; // private List<FieldMatch> _fields; // // public Sentence(URI inputFile) { // _inputFile = inputFile; // _matches = new ArrayList<StructureMatch>(); // _sub = new ArrayList<StructureMatch>(); // _fields = new ArrayList<FieldMatch>(); // } // // public void setStructureName(String name) { // _structureName = name; // } // // public void setSequenceLocation(ISourceLocation location) { // _sequenceLocation = location; // } // // public void setStructureLocation(ISourceLocation location) { // _structureLocation = location; // } // // public void setStructureInputLocation(int offset, int length) { // _inputLocation = new SourceLocation(_inputFile, offset, length); // } // // public void addFieldLocation(String name, ISourceLocation sourceLocation, int offset, int length) { // boolean dup = false; // int index = 0; // for (int i = 0; i < _fields.size(); i++) { // if (_fields.get(i).sourceLocation.getOffset() == sourceLocation.getOffset() && _fields.get(i).sourceLocation.getLength() == sourceLocation.getLength()) { // dup = true; // index = i; // String fName = _fields.get(i).name.length() > name.length() ? name : _fields.get(i).name; // int fOffset = _fields.get(i).inputLocation.getOffset() > offset ? offset : _fields.get(i).inputLocation.getOffset(); // int fLength = ((_fields.get(i).inputLocation.getOffset() + _fields.get(i).inputLocation.getLength()) > (offset + length) ? _fields.get(i).inputLocation.getOffset() + _fields.get(i).inputLocation.getLength() : offset + length) - fOffset; // FieldMatch fm = new FieldMatch(fName, sourceLocation, new SourceLocation(_inputFile, fOffset, fLength)); // _fields.add(index, fm); // _fields.remove(index + 1); // break; // } // } // if (!dup) { // _fields.add(new FieldMatch(name, sourceLocation, new SourceLocation(_inputFile, offset, length))); // } // } // // public void subMatch() { // List<FieldMatch> fieldMatches = new ArrayList<FieldMatch>(); // fieldMatches.addAll(_fields); // _sub.add(new StructureMatch(_structureName, _sequenceLocation, _structureLocation, _inputLocation, fieldMatches)); // _fields.clear(); // } // // public void fullMatch() { // _matches.addAll(_sub); // clearSub(); // } // // public void clearSub() { // _sub.clear(); // _fields.clear(); // } // // @Override // public String toString() { // String out = ""; // boolean first = true; // for (StructureMatch s : _matches) { // if (first) { // first = false; // } else { // out += " "; // } // out += s.name; // } // return out; // } // // public List<StructureMatch> getMatches() { // return _matches; // } // // } // Path: src/org/derric_lang/validator/interpreter/structure/SkipValue.java import java.io.IOException; import java.util.Map; import org.derric_lang.validator.ValidatorInputStream; import org.derric_lang.validator.interpreter.Sentence; package org.derric_lang.validator.interpreter.structure; public class SkipValue extends Statement { private final Type _type; public SkipValue(Type type) { _type = type; } @Override
public boolean eval(ValidatorInputStream input, Map<String, Type> globals, Map<String, Type> locals, Sentence current) throws IOException {
jvdb/derric
src/org/derric_lang/validator/interpreter/structure/Not.java
// Path: src/org/derric_lang/validator/ValueSet.java // public class ValueSet implements ValueComparer { // // private ArrayList<ValueComparer> _values = new ArrayList<ValueComparer>(); // // public void addEquals(long value) { // _values.add(new Value(value, true)); // } // // public void addNot(long value) { // _values.add(new Value(value, false)); // } // // public void addEquals(long lower, long upper) { // _values.add(new Range(lower, upper, true)); // } // // public void addNot(long lower, long upper) { // _values.add(new Range(lower, upper, false)); // } // // @Override // public boolean equals(long value) { // for (ValueComparer vc : _values) { // if (vc.equals(value)) // return true; // } // return false; // } // // class Value implements ValueComparer { // public long value; // public boolean equals; // // public Value(long value, boolean equals) { // this.value = value; // this.equals = equals; // } // // @Override // public boolean equals(long value) { // return (this.value == value) == equals; // } // } // // class Range implements ValueComparer { // public long lower; // public long upper; // public boolean equals; // // public Range(long lower, long upper, boolean equals) { // this.lower = lower; // this.upper = upper; // this.equals = equals; // } // // @Override // public boolean equals(long value) { // return (lower <= value && upper >= value) == equals; // } // } // }
import java.util.Map; import org.derric_lang.validator.ValueSet;
package org.derric_lang.validator.interpreter.structure; public class Not extends ValueSetExpression { private final ValueSetExpression _exp; public Not(ValueSetExpression exp) { _exp = exp; } @Override
// Path: src/org/derric_lang/validator/ValueSet.java // public class ValueSet implements ValueComparer { // // private ArrayList<ValueComparer> _values = new ArrayList<ValueComparer>(); // // public void addEquals(long value) { // _values.add(new Value(value, true)); // } // // public void addNot(long value) { // _values.add(new Value(value, false)); // } // // public void addEquals(long lower, long upper) { // _values.add(new Range(lower, upper, true)); // } // // public void addNot(long lower, long upper) { // _values.add(new Range(lower, upper, false)); // } // // @Override // public boolean equals(long value) { // for (ValueComparer vc : _values) { // if (vc.equals(value)) // return true; // } // return false; // } // // class Value implements ValueComparer { // public long value; // public boolean equals; // // public Value(long value, boolean equals) { // this.value = value; // this.equals = equals; // } // // @Override // public boolean equals(long value) { // return (this.value == value) == equals; // } // } // // class Range implements ValueComparer { // public long lower; // public long upper; // public boolean equals; // // public Range(long lower, long upper, boolean equals) { // this.lower = lower; // this.upper = upper; // this.equals = equals; // } // // @Override // public boolean equals(long value) { // return (lower <= value && upper >= value) == equals; // } // } // } // Path: src/org/derric_lang/validator/interpreter/structure/Not.java import java.util.Map; import org.derric_lang.validator.ValueSet; package org.derric_lang.validator.interpreter.structure; public class Not extends ValueSetExpression { private final ValueSetExpression _exp; public Not(ValueSetExpression exp) { _exp = exp; } @Override
public ValueSet eval(ValueSet vs, Map<String, Type> globals, Map<String, Type> locals) {
jvdb/derric
src/org/derric_lang/validator/interpreter/structure/SkipBuffer.java
// Path: src/org/derric_lang/validator/ValidatorInputStream.java // public abstract class ValidatorInputStream extends InputStream { // // public abstract boolean isByteAligned(); // public abstract boolean atEOF() throws IOException; // // public abstract long lastLocation(); // public abstract long lastRead(); // public abstract void mark(); // public abstract void reset() throws IOException; // // public abstract boolean skipBits(long bits) throws IOException; // public abstract long skip(long bytes) throws IOException; // // public abstract ValidatorInputStream bitOrder(BitOrder order); // public abstract ValidatorInputStream byteOrder(ByteOrder order); // public abstract ValidatorInputStream signed(); // public abstract ValidatorInputStream unsigned(); // public abstract long readInteger(long bits) throws IOException; // // public abstract ValidatorInputStream includeMarker(boolean includeMarker); // public abstract Content readUntil(long bits, ValueSet values) throws IOException; // // public abstract Content validateContent(long size, String name, Map<String, String> configuration, Map<String, List<Object>> arguments, boolean allowEOF) throws IOException; // } // // Path: src/org/derric_lang/validator/interpreter/Sentence.java // public class Sentence { // // private final URI _inputFile; // // private String _structureName; // private ISourceLocation _sequenceLocation; // private ISourceLocation _structureLocation; // private ISourceLocation _inputLocation; // // private List<StructureMatch> _matches; // private List<StructureMatch> _sub; // private List<FieldMatch> _fields; // // public Sentence(URI inputFile) { // _inputFile = inputFile; // _matches = new ArrayList<StructureMatch>(); // _sub = new ArrayList<StructureMatch>(); // _fields = new ArrayList<FieldMatch>(); // } // // public void setStructureName(String name) { // _structureName = name; // } // // public void setSequenceLocation(ISourceLocation location) { // _sequenceLocation = location; // } // // public void setStructureLocation(ISourceLocation location) { // _structureLocation = location; // } // // public void setStructureInputLocation(int offset, int length) { // _inputLocation = new SourceLocation(_inputFile, offset, length); // } // // public void addFieldLocation(String name, ISourceLocation sourceLocation, int offset, int length) { // boolean dup = false; // int index = 0; // for (int i = 0; i < _fields.size(); i++) { // if (_fields.get(i).sourceLocation.getOffset() == sourceLocation.getOffset() && _fields.get(i).sourceLocation.getLength() == sourceLocation.getLength()) { // dup = true; // index = i; // String fName = _fields.get(i).name.length() > name.length() ? name : _fields.get(i).name; // int fOffset = _fields.get(i).inputLocation.getOffset() > offset ? offset : _fields.get(i).inputLocation.getOffset(); // int fLength = ((_fields.get(i).inputLocation.getOffset() + _fields.get(i).inputLocation.getLength()) > (offset + length) ? _fields.get(i).inputLocation.getOffset() + _fields.get(i).inputLocation.getLength() : offset + length) - fOffset; // FieldMatch fm = new FieldMatch(fName, sourceLocation, new SourceLocation(_inputFile, fOffset, fLength)); // _fields.add(index, fm); // _fields.remove(index + 1); // break; // } // } // if (!dup) { // _fields.add(new FieldMatch(name, sourceLocation, new SourceLocation(_inputFile, offset, length))); // } // } // // public void subMatch() { // List<FieldMatch> fieldMatches = new ArrayList<FieldMatch>(); // fieldMatches.addAll(_fields); // _sub.add(new StructureMatch(_structureName, _sequenceLocation, _structureLocation, _inputLocation, fieldMatches)); // _fields.clear(); // } // // public void fullMatch() { // _matches.addAll(_sub); // clearSub(); // } // // public void clearSub() { // _sub.clear(); // _fields.clear(); // } // // @Override // public String toString() { // String out = ""; // boolean first = true; // for (StructureMatch s : _matches) { // if (first) { // first = false; // } else { // out += " "; // } // out += s.name; // } // return out; // } // // public List<StructureMatch> getMatches() { // return _matches; // } // // }
import java.io.IOException; import java.util.Map; import org.derric_lang.validator.ValidatorInputStream; import org.derric_lang.validator.interpreter.Sentence;
package org.derric_lang.validator.interpreter.structure; public class SkipBuffer extends Statement { private final String _sizeVar; public SkipBuffer(String sizeVar) { _sizeVar = sizeVar; } @Override
// Path: src/org/derric_lang/validator/ValidatorInputStream.java // public abstract class ValidatorInputStream extends InputStream { // // public abstract boolean isByteAligned(); // public abstract boolean atEOF() throws IOException; // // public abstract long lastLocation(); // public abstract long lastRead(); // public abstract void mark(); // public abstract void reset() throws IOException; // // public abstract boolean skipBits(long bits) throws IOException; // public abstract long skip(long bytes) throws IOException; // // public abstract ValidatorInputStream bitOrder(BitOrder order); // public abstract ValidatorInputStream byteOrder(ByteOrder order); // public abstract ValidatorInputStream signed(); // public abstract ValidatorInputStream unsigned(); // public abstract long readInteger(long bits) throws IOException; // // public abstract ValidatorInputStream includeMarker(boolean includeMarker); // public abstract Content readUntil(long bits, ValueSet values) throws IOException; // // public abstract Content validateContent(long size, String name, Map<String, String> configuration, Map<String, List<Object>> arguments, boolean allowEOF) throws IOException; // } // // Path: src/org/derric_lang/validator/interpreter/Sentence.java // public class Sentence { // // private final URI _inputFile; // // private String _structureName; // private ISourceLocation _sequenceLocation; // private ISourceLocation _structureLocation; // private ISourceLocation _inputLocation; // // private List<StructureMatch> _matches; // private List<StructureMatch> _sub; // private List<FieldMatch> _fields; // // public Sentence(URI inputFile) { // _inputFile = inputFile; // _matches = new ArrayList<StructureMatch>(); // _sub = new ArrayList<StructureMatch>(); // _fields = new ArrayList<FieldMatch>(); // } // // public void setStructureName(String name) { // _structureName = name; // } // // public void setSequenceLocation(ISourceLocation location) { // _sequenceLocation = location; // } // // public void setStructureLocation(ISourceLocation location) { // _structureLocation = location; // } // // public void setStructureInputLocation(int offset, int length) { // _inputLocation = new SourceLocation(_inputFile, offset, length); // } // // public void addFieldLocation(String name, ISourceLocation sourceLocation, int offset, int length) { // boolean dup = false; // int index = 0; // for (int i = 0; i < _fields.size(); i++) { // if (_fields.get(i).sourceLocation.getOffset() == sourceLocation.getOffset() && _fields.get(i).sourceLocation.getLength() == sourceLocation.getLength()) { // dup = true; // index = i; // String fName = _fields.get(i).name.length() > name.length() ? name : _fields.get(i).name; // int fOffset = _fields.get(i).inputLocation.getOffset() > offset ? offset : _fields.get(i).inputLocation.getOffset(); // int fLength = ((_fields.get(i).inputLocation.getOffset() + _fields.get(i).inputLocation.getLength()) > (offset + length) ? _fields.get(i).inputLocation.getOffset() + _fields.get(i).inputLocation.getLength() : offset + length) - fOffset; // FieldMatch fm = new FieldMatch(fName, sourceLocation, new SourceLocation(_inputFile, fOffset, fLength)); // _fields.add(index, fm); // _fields.remove(index + 1); // break; // } // } // if (!dup) { // _fields.add(new FieldMatch(name, sourceLocation, new SourceLocation(_inputFile, offset, length))); // } // } // // public void subMatch() { // List<FieldMatch> fieldMatches = new ArrayList<FieldMatch>(); // fieldMatches.addAll(_fields); // _sub.add(new StructureMatch(_structureName, _sequenceLocation, _structureLocation, _inputLocation, fieldMatches)); // _fields.clear(); // } // // public void fullMatch() { // _matches.addAll(_sub); // clearSub(); // } // // public void clearSub() { // _sub.clear(); // _fields.clear(); // } // // @Override // public String toString() { // String out = ""; // boolean first = true; // for (StructureMatch s : _matches) { // if (first) { // first = false; // } else { // out += " "; // } // out += s.name; // } // return out; // } // // public List<StructureMatch> getMatches() { // return _matches; // } // // } // Path: src/org/derric_lang/validator/interpreter/structure/SkipBuffer.java import java.io.IOException; import java.util.Map; import org.derric_lang.validator.ValidatorInputStream; import org.derric_lang.validator.interpreter.Sentence; package org.derric_lang.validator.interpreter.structure; public class SkipBuffer extends Statement { private final String _sizeVar; public SkipBuffer(String sizeVar) { _sizeVar = sizeVar; } @Override
public boolean eval(ValidatorInputStream input, Map<String, Type> globals, Map<String, Type> locals, Sentence current) throws IOException {
jvdb/derric
src/org/derric_lang/validator/interpreter/structure/SkipBuffer.java
// Path: src/org/derric_lang/validator/ValidatorInputStream.java // public abstract class ValidatorInputStream extends InputStream { // // public abstract boolean isByteAligned(); // public abstract boolean atEOF() throws IOException; // // public abstract long lastLocation(); // public abstract long lastRead(); // public abstract void mark(); // public abstract void reset() throws IOException; // // public abstract boolean skipBits(long bits) throws IOException; // public abstract long skip(long bytes) throws IOException; // // public abstract ValidatorInputStream bitOrder(BitOrder order); // public abstract ValidatorInputStream byteOrder(ByteOrder order); // public abstract ValidatorInputStream signed(); // public abstract ValidatorInputStream unsigned(); // public abstract long readInteger(long bits) throws IOException; // // public abstract ValidatorInputStream includeMarker(boolean includeMarker); // public abstract Content readUntil(long bits, ValueSet values) throws IOException; // // public abstract Content validateContent(long size, String name, Map<String, String> configuration, Map<String, List<Object>> arguments, boolean allowEOF) throws IOException; // } // // Path: src/org/derric_lang/validator/interpreter/Sentence.java // public class Sentence { // // private final URI _inputFile; // // private String _structureName; // private ISourceLocation _sequenceLocation; // private ISourceLocation _structureLocation; // private ISourceLocation _inputLocation; // // private List<StructureMatch> _matches; // private List<StructureMatch> _sub; // private List<FieldMatch> _fields; // // public Sentence(URI inputFile) { // _inputFile = inputFile; // _matches = new ArrayList<StructureMatch>(); // _sub = new ArrayList<StructureMatch>(); // _fields = new ArrayList<FieldMatch>(); // } // // public void setStructureName(String name) { // _structureName = name; // } // // public void setSequenceLocation(ISourceLocation location) { // _sequenceLocation = location; // } // // public void setStructureLocation(ISourceLocation location) { // _structureLocation = location; // } // // public void setStructureInputLocation(int offset, int length) { // _inputLocation = new SourceLocation(_inputFile, offset, length); // } // // public void addFieldLocation(String name, ISourceLocation sourceLocation, int offset, int length) { // boolean dup = false; // int index = 0; // for (int i = 0; i < _fields.size(); i++) { // if (_fields.get(i).sourceLocation.getOffset() == sourceLocation.getOffset() && _fields.get(i).sourceLocation.getLength() == sourceLocation.getLength()) { // dup = true; // index = i; // String fName = _fields.get(i).name.length() > name.length() ? name : _fields.get(i).name; // int fOffset = _fields.get(i).inputLocation.getOffset() > offset ? offset : _fields.get(i).inputLocation.getOffset(); // int fLength = ((_fields.get(i).inputLocation.getOffset() + _fields.get(i).inputLocation.getLength()) > (offset + length) ? _fields.get(i).inputLocation.getOffset() + _fields.get(i).inputLocation.getLength() : offset + length) - fOffset; // FieldMatch fm = new FieldMatch(fName, sourceLocation, new SourceLocation(_inputFile, fOffset, fLength)); // _fields.add(index, fm); // _fields.remove(index + 1); // break; // } // } // if (!dup) { // _fields.add(new FieldMatch(name, sourceLocation, new SourceLocation(_inputFile, offset, length))); // } // } // // public void subMatch() { // List<FieldMatch> fieldMatches = new ArrayList<FieldMatch>(); // fieldMatches.addAll(_fields); // _sub.add(new StructureMatch(_structureName, _sequenceLocation, _structureLocation, _inputLocation, fieldMatches)); // _fields.clear(); // } // // public void fullMatch() { // _matches.addAll(_sub); // clearSub(); // } // // public void clearSub() { // _sub.clear(); // _fields.clear(); // } // // @Override // public String toString() { // String out = ""; // boolean first = true; // for (StructureMatch s : _matches) { // if (first) { // first = false; // } else { // out += " "; // } // out += s.name; // } // return out; // } // // public List<StructureMatch> getMatches() { // return _matches; // } // // }
import java.io.IOException; import java.util.Map; import org.derric_lang.validator.ValidatorInputStream; import org.derric_lang.validator.interpreter.Sentence;
package org.derric_lang.validator.interpreter.structure; public class SkipBuffer extends Statement { private final String _sizeVar; public SkipBuffer(String sizeVar) { _sizeVar = sizeVar; } @Override
// Path: src/org/derric_lang/validator/ValidatorInputStream.java // public abstract class ValidatorInputStream extends InputStream { // // public abstract boolean isByteAligned(); // public abstract boolean atEOF() throws IOException; // // public abstract long lastLocation(); // public abstract long lastRead(); // public abstract void mark(); // public abstract void reset() throws IOException; // // public abstract boolean skipBits(long bits) throws IOException; // public abstract long skip(long bytes) throws IOException; // // public abstract ValidatorInputStream bitOrder(BitOrder order); // public abstract ValidatorInputStream byteOrder(ByteOrder order); // public abstract ValidatorInputStream signed(); // public abstract ValidatorInputStream unsigned(); // public abstract long readInteger(long bits) throws IOException; // // public abstract ValidatorInputStream includeMarker(boolean includeMarker); // public abstract Content readUntil(long bits, ValueSet values) throws IOException; // // public abstract Content validateContent(long size, String name, Map<String, String> configuration, Map<String, List<Object>> arguments, boolean allowEOF) throws IOException; // } // // Path: src/org/derric_lang/validator/interpreter/Sentence.java // public class Sentence { // // private final URI _inputFile; // // private String _structureName; // private ISourceLocation _sequenceLocation; // private ISourceLocation _structureLocation; // private ISourceLocation _inputLocation; // // private List<StructureMatch> _matches; // private List<StructureMatch> _sub; // private List<FieldMatch> _fields; // // public Sentence(URI inputFile) { // _inputFile = inputFile; // _matches = new ArrayList<StructureMatch>(); // _sub = new ArrayList<StructureMatch>(); // _fields = new ArrayList<FieldMatch>(); // } // // public void setStructureName(String name) { // _structureName = name; // } // // public void setSequenceLocation(ISourceLocation location) { // _sequenceLocation = location; // } // // public void setStructureLocation(ISourceLocation location) { // _structureLocation = location; // } // // public void setStructureInputLocation(int offset, int length) { // _inputLocation = new SourceLocation(_inputFile, offset, length); // } // // public void addFieldLocation(String name, ISourceLocation sourceLocation, int offset, int length) { // boolean dup = false; // int index = 0; // for (int i = 0; i < _fields.size(); i++) { // if (_fields.get(i).sourceLocation.getOffset() == sourceLocation.getOffset() && _fields.get(i).sourceLocation.getLength() == sourceLocation.getLength()) { // dup = true; // index = i; // String fName = _fields.get(i).name.length() > name.length() ? name : _fields.get(i).name; // int fOffset = _fields.get(i).inputLocation.getOffset() > offset ? offset : _fields.get(i).inputLocation.getOffset(); // int fLength = ((_fields.get(i).inputLocation.getOffset() + _fields.get(i).inputLocation.getLength()) > (offset + length) ? _fields.get(i).inputLocation.getOffset() + _fields.get(i).inputLocation.getLength() : offset + length) - fOffset; // FieldMatch fm = new FieldMatch(fName, sourceLocation, new SourceLocation(_inputFile, fOffset, fLength)); // _fields.add(index, fm); // _fields.remove(index + 1); // break; // } // } // if (!dup) { // _fields.add(new FieldMatch(name, sourceLocation, new SourceLocation(_inputFile, offset, length))); // } // } // // public void subMatch() { // List<FieldMatch> fieldMatches = new ArrayList<FieldMatch>(); // fieldMatches.addAll(_fields); // _sub.add(new StructureMatch(_structureName, _sequenceLocation, _structureLocation, _inputLocation, fieldMatches)); // _fields.clear(); // } // // public void fullMatch() { // _matches.addAll(_sub); // clearSub(); // } // // public void clearSub() { // _sub.clear(); // _fields.clear(); // } // // @Override // public String toString() { // String out = ""; // boolean first = true; // for (StructureMatch s : _matches) { // if (first) { // first = false; // } else { // out += " "; // } // out += s.name; // } // return out; // } // // public List<StructureMatch> getMatches() { // return _matches; // } // // } // Path: src/org/derric_lang/validator/interpreter/structure/SkipBuffer.java import java.io.IOException; import java.util.Map; import org.derric_lang.validator.ValidatorInputStream; import org.derric_lang.validator.interpreter.Sentence; package org.derric_lang.validator.interpreter.structure; public class SkipBuffer extends Statement { private final String _sizeVar; public SkipBuffer(String sizeVar) { _sizeVar = sizeVar; } @Override
public boolean eval(ValidatorInputStream input, Map<String, Type> globals, Map<String, Type> locals, Sentence current) throws IOException {
jvdb/derric
src/org/derric_lang/validator/interpreter/symbol/Symbol.java
// Path: src/org/derric_lang/validator/interpreter/Interpreter.java // public class Interpreter extends Validator { // // private final String _format; // private final List<Symbol> _sequence; // private final List<Structure> _structures; // private final Map<String, Type> _globals; // // private Sentence _current; // private URI _inputFile; // // public Interpreter(URI inputFile, String format, List<Symbol> sequence, List<Structure> structures, List<Decl> globals) { // super(format); // _inputFile = inputFile; // _format = format; // _sequence = sequence; // _structures = structures; // _globals = new HashMap<String, Type>(); // for (Decl d : globals) { // _globals.put(d.getName(), d.getType()); // } // setStream(ValidatorInputStreamFactory.create(_inputFile)); // } // // @Override // public String getExtension() { // return _format; // } // // @Override // protected ParseResult tryParseBody() throws IOException { // _current = new Sentence(_inputFile); // for (Symbol s : _sequence) { // if (!s.parse(this)) { // return new ParseResult(false, _input.lastLocation(), _input.lastRead(), s.toString(), _current.toString()); // } // _current.fullMatch(); // //System.out.println("Validated " + s.toString()); // } // return new ParseResult(true, _input.lastLocation(), _input.lastRead(), "", _current.toString()); // } // // @Override // public ParseResult findNextFooter() throws IOException { // return null; // } // // public boolean parseStructure(String name) throws IOException { // long offset = _input.lastLocation(); // for (Structure s : _structures) { // if (name.equals(s.getName())) { // if (s.parse(_input, _globals, _current)) { // _current.setStructureLocation(s.getLocation()); // _current.setStructureInputLocation((int)offset, (int)(_input.lastLocation() - offset)); // //System.out.println("Structure " + s.getName() + " matched!"); // return true; // } else { // return false; // } // } // } // throw new RuntimeException("Unknown structure requested: " + name); // } // // public ValidatorInputStream getInput() { // return _input; // } // // public Sentence getCurrent() { // return _current; // } // // }
import java.io.IOException; import org.derric_lang.validator.interpreter.Interpreter; import org.eclipse.imp.pdb.facts.ISourceLocation;
package org.derric_lang.validator.interpreter.symbol; public abstract class Symbol { protected boolean _allowEOF = false; protected boolean _allowEOFSet = false; protected ISourceLocation _location; public void setAllowEOF(boolean allowEOF) { _allowEOF = allowEOF; _allowEOFSet = true; } protected boolean allowEOFSet() { return _allowEOFSet; } public void setLocation(ISourceLocation location) { _location = location; }
// Path: src/org/derric_lang/validator/interpreter/Interpreter.java // public class Interpreter extends Validator { // // private final String _format; // private final List<Symbol> _sequence; // private final List<Structure> _structures; // private final Map<String, Type> _globals; // // private Sentence _current; // private URI _inputFile; // // public Interpreter(URI inputFile, String format, List<Symbol> sequence, List<Structure> structures, List<Decl> globals) { // super(format); // _inputFile = inputFile; // _format = format; // _sequence = sequence; // _structures = structures; // _globals = new HashMap<String, Type>(); // for (Decl d : globals) { // _globals.put(d.getName(), d.getType()); // } // setStream(ValidatorInputStreamFactory.create(_inputFile)); // } // // @Override // public String getExtension() { // return _format; // } // // @Override // protected ParseResult tryParseBody() throws IOException { // _current = new Sentence(_inputFile); // for (Symbol s : _sequence) { // if (!s.parse(this)) { // return new ParseResult(false, _input.lastLocation(), _input.lastRead(), s.toString(), _current.toString()); // } // _current.fullMatch(); // //System.out.println("Validated " + s.toString()); // } // return new ParseResult(true, _input.lastLocation(), _input.lastRead(), "", _current.toString()); // } // // @Override // public ParseResult findNextFooter() throws IOException { // return null; // } // // public boolean parseStructure(String name) throws IOException { // long offset = _input.lastLocation(); // for (Structure s : _structures) { // if (name.equals(s.getName())) { // if (s.parse(_input, _globals, _current)) { // _current.setStructureLocation(s.getLocation()); // _current.setStructureInputLocation((int)offset, (int)(_input.lastLocation() - offset)); // //System.out.println("Structure " + s.getName() + " matched!"); // return true; // } else { // return false; // } // } // } // throw new RuntimeException("Unknown structure requested: " + name); // } // // public ValidatorInputStream getInput() { // return _input; // } // // public Sentence getCurrent() { // return _current; // } // // } // Path: src/org/derric_lang/validator/interpreter/symbol/Symbol.java import java.io.IOException; import org.derric_lang.validator.interpreter.Interpreter; import org.eclipse.imp.pdb.facts.ISourceLocation; package org.derric_lang.validator.interpreter.symbol; public abstract class Symbol { protected boolean _allowEOF = false; protected boolean _allowEOFSet = false; protected ISourceLocation _location; public void setAllowEOF(boolean allowEOF) { _allowEOF = allowEOF; _allowEOFSet = true; } protected boolean allowEOFSet() { return _allowEOFSet; } public void setLocation(ISourceLocation location) { _location = location; }
public abstract boolean parse(Interpreter in) throws IOException;
jvdb/derric
src/org/derric_lang/validator/interpreter/structure/ValueExpression.java
// Path: src/org/derric_lang/validator/ValueSet.java // public class ValueSet implements ValueComparer { // // private ArrayList<ValueComparer> _values = new ArrayList<ValueComparer>(); // // public void addEquals(long value) { // _values.add(new Value(value, true)); // } // // public void addNot(long value) { // _values.add(new Value(value, false)); // } // // public void addEquals(long lower, long upper) { // _values.add(new Range(lower, upper, true)); // } // // public void addNot(long lower, long upper) { // _values.add(new Range(lower, upper, false)); // } // // @Override // public boolean equals(long value) { // for (ValueComparer vc : _values) { // if (vc.equals(value)) // return true; // } // return false; // } // // class Value implements ValueComparer { // public long value; // public boolean equals; // // public Value(long value, boolean equals) { // this.value = value; // this.equals = equals; // } // // @Override // public boolean equals(long value) { // return (this.value == value) == equals; // } // } // // class Range implements ValueComparer { // public long lower; // public long upper; // public boolean equals; // // public Range(long lower, long upper, boolean equals) { // this.lower = lower; // this.upper = upper; // this.equals = equals; // } // // @Override // public boolean equals(long value) { // return (lower <= value && upper >= value) == equals; // } // } // }
import java.util.Map; import org.derric_lang.validator.ValueSet;
package org.derric_lang.validator.interpreter.structure; public abstract class ValueExpression extends ValueSetExpression { public abstract Object eval(Map<String, Type> globals, Map<String, Type> locals);
// Path: src/org/derric_lang/validator/ValueSet.java // public class ValueSet implements ValueComparer { // // private ArrayList<ValueComparer> _values = new ArrayList<ValueComparer>(); // // public void addEquals(long value) { // _values.add(new Value(value, true)); // } // // public void addNot(long value) { // _values.add(new Value(value, false)); // } // // public void addEquals(long lower, long upper) { // _values.add(new Range(lower, upper, true)); // } // // public void addNot(long lower, long upper) { // _values.add(new Range(lower, upper, false)); // } // // @Override // public boolean equals(long value) { // for (ValueComparer vc : _values) { // if (vc.equals(value)) // return true; // } // return false; // } // // class Value implements ValueComparer { // public long value; // public boolean equals; // // public Value(long value, boolean equals) { // this.value = value; // this.equals = equals; // } // // @Override // public boolean equals(long value) { // return (this.value == value) == equals; // } // } // // class Range implements ValueComparer { // public long lower; // public long upper; // public boolean equals; // // public Range(long lower, long upper, boolean equals) { // this.lower = lower; // this.upper = upper; // this.equals = equals; // } // // @Override // public boolean equals(long value) { // return (lower <= value && upper >= value) == equals; // } // } // } // Path: src/org/derric_lang/validator/interpreter/structure/ValueExpression.java import java.util.Map; import org.derric_lang.validator.ValueSet; package org.derric_lang.validator.interpreter.structure; public abstract class ValueExpression extends ValueSetExpression { public abstract Object eval(Map<String, Type> globals, Map<String, Type> locals);
public ValueSet eval(ValueSet vs, Map<String, Type> globals, Map<String, Type> locals) {
jvdb/derric
src/org/derric_lang/validator/interpreter/structure/Structure.java
// Path: src/org/derric_lang/validator/ValidatorInputStream.java // public abstract class ValidatorInputStream extends InputStream { // // public abstract boolean isByteAligned(); // public abstract boolean atEOF() throws IOException; // // public abstract long lastLocation(); // public abstract long lastRead(); // public abstract void mark(); // public abstract void reset() throws IOException; // // public abstract boolean skipBits(long bits) throws IOException; // public abstract long skip(long bytes) throws IOException; // // public abstract ValidatorInputStream bitOrder(BitOrder order); // public abstract ValidatorInputStream byteOrder(ByteOrder order); // public abstract ValidatorInputStream signed(); // public abstract ValidatorInputStream unsigned(); // public abstract long readInteger(long bits) throws IOException; // // public abstract ValidatorInputStream includeMarker(boolean includeMarker); // public abstract Content readUntil(long bits, ValueSet values) throws IOException; // // public abstract Content validateContent(long size, String name, Map<String, String> configuration, Map<String, List<Object>> arguments, boolean allowEOF) throws IOException; // } // // Path: src/org/derric_lang/validator/interpreter/Sentence.java // public class Sentence { // // private final URI _inputFile; // // private String _structureName; // private ISourceLocation _sequenceLocation; // private ISourceLocation _structureLocation; // private ISourceLocation _inputLocation; // // private List<StructureMatch> _matches; // private List<StructureMatch> _sub; // private List<FieldMatch> _fields; // // public Sentence(URI inputFile) { // _inputFile = inputFile; // _matches = new ArrayList<StructureMatch>(); // _sub = new ArrayList<StructureMatch>(); // _fields = new ArrayList<FieldMatch>(); // } // // public void setStructureName(String name) { // _structureName = name; // } // // public void setSequenceLocation(ISourceLocation location) { // _sequenceLocation = location; // } // // public void setStructureLocation(ISourceLocation location) { // _structureLocation = location; // } // // public void setStructureInputLocation(int offset, int length) { // _inputLocation = new SourceLocation(_inputFile, offset, length); // } // // public void addFieldLocation(String name, ISourceLocation sourceLocation, int offset, int length) { // boolean dup = false; // int index = 0; // for (int i = 0; i < _fields.size(); i++) { // if (_fields.get(i).sourceLocation.getOffset() == sourceLocation.getOffset() && _fields.get(i).sourceLocation.getLength() == sourceLocation.getLength()) { // dup = true; // index = i; // String fName = _fields.get(i).name.length() > name.length() ? name : _fields.get(i).name; // int fOffset = _fields.get(i).inputLocation.getOffset() > offset ? offset : _fields.get(i).inputLocation.getOffset(); // int fLength = ((_fields.get(i).inputLocation.getOffset() + _fields.get(i).inputLocation.getLength()) > (offset + length) ? _fields.get(i).inputLocation.getOffset() + _fields.get(i).inputLocation.getLength() : offset + length) - fOffset; // FieldMatch fm = new FieldMatch(fName, sourceLocation, new SourceLocation(_inputFile, fOffset, fLength)); // _fields.add(index, fm); // _fields.remove(index + 1); // break; // } // } // if (!dup) { // _fields.add(new FieldMatch(name, sourceLocation, new SourceLocation(_inputFile, offset, length))); // } // } // // public void subMatch() { // List<FieldMatch> fieldMatches = new ArrayList<FieldMatch>(); // fieldMatches.addAll(_fields); // _sub.add(new StructureMatch(_structureName, _sequenceLocation, _structureLocation, _inputLocation, fieldMatches)); // _fields.clear(); // } // // public void fullMatch() { // _matches.addAll(_sub); // clearSub(); // } // // public void clearSub() { // _sub.clear(); // _fields.clear(); // } // // @Override // public String toString() { // String out = ""; // boolean first = true; // for (StructureMatch s : _matches) { // if (first) { // first = false; // } else { // out += " "; // } // out += s.name; // } // return out; // } // // public List<StructureMatch> getMatches() { // return _matches; // } // // }
import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.derric_lang.validator.ValidatorInputStream; import org.derric_lang.validator.interpreter.Sentence; import org.eclipse.imp.pdb.facts.ISourceLocation;
package org.derric_lang.validator.interpreter.structure; public class Structure { private final String _name; private final Map<String, Type> _locals; private final List<Statement> _statements; private ISourceLocation _location; public Structure(String name, ArrayList<Statement> statements) { _name = name; _locals = new HashMap<String, Type>(); _statements = new ArrayList<Statement>(); for (Statement s : statements) { if (s instanceof Decl) { _locals.put(((Decl)s).getName(), ((Decl)s).getType()); } else { _statements.add(s); } } } public void setLocation(ISourceLocation location) { _location = location; } public ISourceLocation getLocation() { return _location; } public String getName() { return _name; }
// Path: src/org/derric_lang/validator/ValidatorInputStream.java // public abstract class ValidatorInputStream extends InputStream { // // public abstract boolean isByteAligned(); // public abstract boolean atEOF() throws IOException; // // public abstract long lastLocation(); // public abstract long lastRead(); // public abstract void mark(); // public abstract void reset() throws IOException; // // public abstract boolean skipBits(long bits) throws IOException; // public abstract long skip(long bytes) throws IOException; // // public abstract ValidatorInputStream bitOrder(BitOrder order); // public abstract ValidatorInputStream byteOrder(ByteOrder order); // public abstract ValidatorInputStream signed(); // public abstract ValidatorInputStream unsigned(); // public abstract long readInteger(long bits) throws IOException; // // public abstract ValidatorInputStream includeMarker(boolean includeMarker); // public abstract Content readUntil(long bits, ValueSet values) throws IOException; // // public abstract Content validateContent(long size, String name, Map<String, String> configuration, Map<String, List<Object>> arguments, boolean allowEOF) throws IOException; // } // // Path: src/org/derric_lang/validator/interpreter/Sentence.java // public class Sentence { // // private final URI _inputFile; // // private String _structureName; // private ISourceLocation _sequenceLocation; // private ISourceLocation _structureLocation; // private ISourceLocation _inputLocation; // // private List<StructureMatch> _matches; // private List<StructureMatch> _sub; // private List<FieldMatch> _fields; // // public Sentence(URI inputFile) { // _inputFile = inputFile; // _matches = new ArrayList<StructureMatch>(); // _sub = new ArrayList<StructureMatch>(); // _fields = new ArrayList<FieldMatch>(); // } // // public void setStructureName(String name) { // _structureName = name; // } // // public void setSequenceLocation(ISourceLocation location) { // _sequenceLocation = location; // } // // public void setStructureLocation(ISourceLocation location) { // _structureLocation = location; // } // // public void setStructureInputLocation(int offset, int length) { // _inputLocation = new SourceLocation(_inputFile, offset, length); // } // // public void addFieldLocation(String name, ISourceLocation sourceLocation, int offset, int length) { // boolean dup = false; // int index = 0; // for (int i = 0; i < _fields.size(); i++) { // if (_fields.get(i).sourceLocation.getOffset() == sourceLocation.getOffset() && _fields.get(i).sourceLocation.getLength() == sourceLocation.getLength()) { // dup = true; // index = i; // String fName = _fields.get(i).name.length() > name.length() ? name : _fields.get(i).name; // int fOffset = _fields.get(i).inputLocation.getOffset() > offset ? offset : _fields.get(i).inputLocation.getOffset(); // int fLength = ((_fields.get(i).inputLocation.getOffset() + _fields.get(i).inputLocation.getLength()) > (offset + length) ? _fields.get(i).inputLocation.getOffset() + _fields.get(i).inputLocation.getLength() : offset + length) - fOffset; // FieldMatch fm = new FieldMatch(fName, sourceLocation, new SourceLocation(_inputFile, fOffset, fLength)); // _fields.add(index, fm); // _fields.remove(index + 1); // break; // } // } // if (!dup) { // _fields.add(new FieldMatch(name, sourceLocation, new SourceLocation(_inputFile, offset, length))); // } // } // // public void subMatch() { // List<FieldMatch> fieldMatches = new ArrayList<FieldMatch>(); // fieldMatches.addAll(_fields); // _sub.add(new StructureMatch(_structureName, _sequenceLocation, _structureLocation, _inputLocation, fieldMatches)); // _fields.clear(); // } // // public void fullMatch() { // _matches.addAll(_sub); // clearSub(); // } // // public void clearSub() { // _sub.clear(); // _fields.clear(); // } // // @Override // public String toString() { // String out = ""; // boolean first = true; // for (StructureMatch s : _matches) { // if (first) { // first = false; // } else { // out += " "; // } // out += s.name; // } // return out; // } // // public List<StructureMatch> getMatches() { // return _matches; // } // // } // Path: src/org/derric_lang/validator/interpreter/structure/Structure.java import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.derric_lang.validator.ValidatorInputStream; import org.derric_lang.validator.interpreter.Sentence; import org.eclipse.imp.pdb.facts.ISourceLocation; package org.derric_lang.validator.interpreter.structure; public class Structure { private final String _name; private final Map<String, Type> _locals; private final List<Statement> _statements; private ISourceLocation _location; public Structure(String name, ArrayList<Statement> statements) { _name = name; _locals = new HashMap<String, Type>(); _statements = new ArrayList<Statement>(); for (Statement s : statements) { if (s instanceof Decl) { _locals.put(((Decl)s).getName(), ((Decl)s).getType()); } else { _statements.add(s); } } } public void setLocation(ISourceLocation location) { _location = location; } public ISourceLocation getLocation() { return _location; } public String getName() { return _name; }
public boolean parse(ValidatorInputStream input, Map<String, Type> globals, Sentence current) throws IOException {
jvdb/derric
src/org/derric_lang/validator/interpreter/structure/Structure.java
// Path: src/org/derric_lang/validator/ValidatorInputStream.java // public abstract class ValidatorInputStream extends InputStream { // // public abstract boolean isByteAligned(); // public abstract boolean atEOF() throws IOException; // // public abstract long lastLocation(); // public abstract long lastRead(); // public abstract void mark(); // public abstract void reset() throws IOException; // // public abstract boolean skipBits(long bits) throws IOException; // public abstract long skip(long bytes) throws IOException; // // public abstract ValidatorInputStream bitOrder(BitOrder order); // public abstract ValidatorInputStream byteOrder(ByteOrder order); // public abstract ValidatorInputStream signed(); // public abstract ValidatorInputStream unsigned(); // public abstract long readInteger(long bits) throws IOException; // // public abstract ValidatorInputStream includeMarker(boolean includeMarker); // public abstract Content readUntil(long bits, ValueSet values) throws IOException; // // public abstract Content validateContent(long size, String name, Map<String, String> configuration, Map<String, List<Object>> arguments, boolean allowEOF) throws IOException; // } // // Path: src/org/derric_lang/validator/interpreter/Sentence.java // public class Sentence { // // private final URI _inputFile; // // private String _structureName; // private ISourceLocation _sequenceLocation; // private ISourceLocation _structureLocation; // private ISourceLocation _inputLocation; // // private List<StructureMatch> _matches; // private List<StructureMatch> _sub; // private List<FieldMatch> _fields; // // public Sentence(URI inputFile) { // _inputFile = inputFile; // _matches = new ArrayList<StructureMatch>(); // _sub = new ArrayList<StructureMatch>(); // _fields = new ArrayList<FieldMatch>(); // } // // public void setStructureName(String name) { // _structureName = name; // } // // public void setSequenceLocation(ISourceLocation location) { // _sequenceLocation = location; // } // // public void setStructureLocation(ISourceLocation location) { // _structureLocation = location; // } // // public void setStructureInputLocation(int offset, int length) { // _inputLocation = new SourceLocation(_inputFile, offset, length); // } // // public void addFieldLocation(String name, ISourceLocation sourceLocation, int offset, int length) { // boolean dup = false; // int index = 0; // for (int i = 0; i < _fields.size(); i++) { // if (_fields.get(i).sourceLocation.getOffset() == sourceLocation.getOffset() && _fields.get(i).sourceLocation.getLength() == sourceLocation.getLength()) { // dup = true; // index = i; // String fName = _fields.get(i).name.length() > name.length() ? name : _fields.get(i).name; // int fOffset = _fields.get(i).inputLocation.getOffset() > offset ? offset : _fields.get(i).inputLocation.getOffset(); // int fLength = ((_fields.get(i).inputLocation.getOffset() + _fields.get(i).inputLocation.getLength()) > (offset + length) ? _fields.get(i).inputLocation.getOffset() + _fields.get(i).inputLocation.getLength() : offset + length) - fOffset; // FieldMatch fm = new FieldMatch(fName, sourceLocation, new SourceLocation(_inputFile, fOffset, fLength)); // _fields.add(index, fm); // _fields.remove(index + 1); // break; // } // } // if (!dup) { // _fields.add(new FieldMatch(name, sourceLocation, new SourceLocation(_inputFile, offset, length))); // } // } // // public void subMatch() { // List<FieldMatch> fieldMatches = new ArrayList<FieldMatch>(); // fieldMatches.addAll(_fields); // _sub.add(new StructureMatch(_structureName, _sequenceLocation, _structureLocation, _inputLocation, fieldMatches)); // _fields.clear(); // } // // public void fullMatch() { // _matches.addAll(_sub); // clearSub(); // } // // public void clearSub() { // _sub.clear(); // _fields.clear(); // } // // @Override // public String toString() { // String out = ""; // boolean first = true; // for (StructureMatch s : _matches) { // if (first) { // first = false; // } else { // out += " "; // } // out += s.name; // } // return out; // } // // public List<StructureMatch> getMatches() { // return _matches; // } // // }
import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.derric_lang.validator.ValidatorInputStream; import org.derric_lang.validator.interpreter.Sentence; import org.eclipse.imp.pdb.facts.ISourceLocation;
package org.derric_lang.validator.interpreter.structure; public class Structure { private final String _name; private final Map<String, Type> _locals; private final List<Statement> _statements; private ISourceLocation _location; public Structure(String name, ArrayList<Statement> statements) { _name = name; _locals = new HashMap<String, Type>(); _statements = new ArrayList<Statement>(); for (Statement s : statements) { if (s instanceof Decl) { _locals.put(((Decl)s).getName(), ((Decl)s).getType()); } else { _statements.add(s); } } } public void setLocation(ISourceLocation location) { _location = location; } public ISourceLocation getLocation() { return _location; } public String getName() { return _name; }
// Path: src/org/derric_lang/validator/ValidatorInputStream.java // public abstract class ValidatorInputStream extends InputStream { // // public abstract boolean isByteAligned(); // public abstract boolean atEOF() throws IOException; // // public abstract long lastLocation(); // public abstract long lastRead(); // public abstract void mark(); // public abstract void reset() throws IOException; // // public abstract boolean skipBits(long bits) throws IOException; // public abstract long skip(long bytes) throws IOException; // // public abstract ValidatorInputStream bitOrder(BitOrder order); // public abstract ValidatorInputStream byteOrder(ByteOrder order); // public abstract ValidatorInputStream signed(); // public abstract ValidatorInputStream unsigned(); // public abstract long readInteger(long bits) throws IOException; // // public abstract ValidatorInputStream includeMarker(boolean includeMarker); // public abstract Content readUntil(long bits, ValueSet values) throws IOException; // // public abstract Content validateContent(long size, String name, Map<String, String> configuration, Map<String, List<Object>> arguments, boolean allowEOF) throws IOException; // } // // Path: src/org/derric_lang/validator/interpreter/Sentence.java // public class Sentence { // // private final URI _inputFile; // // private String _structureName; // private ISourceLocation _sequenceLocation; // private ISourceLocation _structureLocation; // private ISourceLocation _inputLocation; // // private List<StructureMatch> _matches; // private List<StructureMatch> _sub; // private List<FieldMatch> _fields; // // public Sentence(URI inputFile) { // _inputFile = inputFile; // _matches = new ArrayList<StructureMatch>(); // _sub = new ArrayList<StructureMatch>(); // _fields = new ArrayList<FieldMatch>(); // } // // public void setStructureName(String name) { // _structureName = name; // } // // public void setSequenceLocation(ISourceLocation location) { // _sequenceLocation = location; // } // // public void setStructureLocation(ISourceLocation location) { // _structureLocation = location; // } // // public void setStructureInputLocation(int offset, int length) { // _inputLocation = new SourceLocation(_inputFile, offset, length); // } // // public void addFieldLocation(String name, ISourceLocation sourceLocation, int offset, int length) { // boolean dup = false; // int index = 0; // for (int i = 0; i < _fields.size(); i++) { // if (_fields.get(i).sourceLocation.getOffset() == sourceLocation.getOffset() && _fields.get(i).sourceLocation.getLength() == sourceLocation.getLength()) { // dup = true; // index = i; // String fName = _fields.get(i).name.length() > name.length() ? name : _fields.get(i).name; // int fOffset = _fields.get(i).inputLocation.getOffset() > offset ? offset : _fields.get(i).inputLocation.getOffset(); // int fLength = ((_fields.get(i).inputLocation.getOffset() + _fields.get(i).inputLocation.getLength()) > (offset + length) ? _fields.get(i).inputLocation.getOffset() + _fields.get(i).inputLocation.getLength() : offset + length) - fOffset; // FieldMatch fm = new FieldMatch(fName, sourceLocation, new SourceLocation(_inputFile, fOffset, fLength)); // _fields.add(index, fm); // _fields.remove(index + 1); // break; // } // } // if (!dup) { // _fields.add(new FieldMatch(name, sourceLocation, new SourceLocation(_inputFile, offset, length))); // } // } // // public void subMatch() { // List<FieldMatch> fieldMatches = new ArrayList<FieldMatch>(); // fieldMatches.addAll(_fields); // _sub.add(new StructureMatch(_structureName, _sequenceLocation, _structureLocation, _inputLocation, fieldMatches)); // _fields.clear(); // } // // public void fullMatch() { // _matches.addAll(_sub); // clearSub(); // } // // public void clearSub() { // _sub.clear(); // _fields.clear(); // } // // @Override // public String toString() { // String out = ""; // boolean first = true; // for (StructureMatch s : _matches) { // if (first) { // first = false; // } else { // out += " "; // } // out += s.name; // } // return out; // } // // public List<StructureMatch> getMatches() { // return _matches; // } // // } // Path: src/org/derric_lang/validator/interpreter/structure/Structure.java import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.derric_lang.validator.ValidatorInputStream; import org.derric_lang.validator.interpreter.Sentence; import org.eclipse.imp.pdb.facts.ISourceLocation; package org.derric_lang.validator.interpreter.structure; public class Structure { private final String _name; private final Map<String, Type> _locals; private final List<Statement> _statements; private ISourceLocation _location; public Structure(String name, ArrayList<Statement> statements) { _name = name; _locals = new HashMap<String, Type>(); _statements = new ArrayList<Statement>(); for (Statement s : statements) { if (s instanceof Decl) { _locals.put(((Decl)s).getName(), ((Decl)s).getType()); } else { _statements.add(s); } } } public void setLocation(ISourceLocation location) { _location = location; } public ISourceLocation getLocation() { return _location; } public String getName() { return _name; }
public boolean parse(ValidatorInputStream input, Map<String, Type> globals, Sentence current) throws IOException {
jvdb/derric
src/org/derric_lang/validator/interpreter/structure/ReadBuffer.java
// Path: src/org/derric_lang/validator/ValidatorInputStream.java // public abstract class ValidatorInputStream extends InputStream { // // public abstract boolean isByteAligned(); // public abstract boolean atEOF() throws IOException; // // public abstract long lastLocation(); // public abstract long lastRead(); // public abstract void mark(); // public abstract void reset() throws IOException; // // public abstract boolean skipBits(long bits) throws IOException; // public abstract long skip(long bytes) throws IOException; // // public abstract ValidatorInputStream bitOrder(BitOrder order); // public abstract ValidatorInputStream byteOrder(ByteOrder order); // public abstract ValidatorInputStream signed(); // public abstract ValidatorInputStream unsigned(); // public abstract long readInteger(long bits) throws IOException; // // public abstract ValidatorInputStream includeMarker(boolean includeMarker); // public abstract Content readUntil(long bits, ValueSet values) throws IOException; // // public abstract Content validateContent(long size, String name, Map<String, String> configuration, Map<String, List<Object>> arguments, boolean allowEOF) throws IOException; // } // // Path: src/org/derric_lang/validator/interpreter/Sentence.java // public class Sentence { // // private final URI _inputFile; // // private String _structureName; // private ISourceLocation _sequenceLocation; // private ISourceLocation _structureLocation; // private ISourceLocation _inputLocation; // // private List<StructureMatch> _matches; // private List<StructureMatch> _sub; // private List<FieldMatch> _fields; // // public Sentence(URI inputFile) { // _inputFile = inputFile; // _matches = new ArrayList<StructureMatch>(); // _sub = new ArrayList<StructureMatch>(); // _fields = new ArrayList<FieldMatch>(); // } // // public void setStructureName(String name) { // _structureName = name; // } // // public void setSequenceLocation(ISourceLocation location) { // _sequenceLocation = location; // } // // public void setStructureLocation(ISourceLocation location) { // _structureLocation = location; // } // // public void setStructureInputLocation(int offset, int length) { // _inputLocation = new SourceLocation(_inputFile, offset, length); // } // // public void addFieldLocation(String name, ISourceLocation sourceLocation, int offset, int length) { // boolean dup = false; // int index = 0; // for (int i = 0; i < _fields.size(); i++) { // if (_fields.get(i).sourceLocation.getOffset() == sourceLocation.getOffset() && _fields.get(i).sourceLocation.getLength() == sourceLocation.getLength()) { // dup = true; // index = i; // String fName = _fields.get(i).name.length() > name.length() ? name : _fields.get(i).name; // int fOffset = _fields.get(i).inputLocation.getOffset() > offset ? offset : _fields.get(i).inputLocation.getOffset(); // int fLength = ((_fields.get(i).inputLocation.getOffset() + _fields.get(i).inputLocation.getLength()) > (offset + length) ? _fields.get(i).inputLocation.getOffset() + _fields.get(i).inputLocation.getLength() : offset + length) - fOffset; // FieldMatch fm = new FieldMatch(fName, sourceLocation, new SourceLocation(_inputFile, fOffset, fLength)); // _fields.add(index, fm); // _fields.remove(index + 1); // break; // } // } // if (!dup) { // _fields.add(new FieldMatch(name, sourceLocation, new SourceLocation(_inputFile, offset, length))); // } // } // // public void subMatch() { // List<FieldMatch> fieldMatches = new ArrayList<FieldMatch>(); // fieldMatches.addAll(_fields); // _sub.add(new StructureMatch(_structureName, _sequenceLocation, _structureLocation, _inputLocation, fieldMatches)); // _fields.clear(); // } // // public void fullMatch() { // _matches.addAll(_sub); // clearSub(); // } // // public void clearSub() { // _sub.clear(); // _fields.clear(); // } // // @Override // public String toString() { // String out = ""; // boolean first = true; // for (StructureMatch s : _matches) { // if (first) { // first = false; // } else { // out += " "; // } // out += s.name; // } // return out; // } // // public List<StructureMatch> getMatches() { // return _matches; // } // // }
import java.io.IOException; import java.util.Map; import org.derric_lang.validator.ValidatorInputStream; import org.derric_lang.validator.interpreter.Sentence;
package org.derric_lang.validator.interpreter.structure; public class ReadBuffer extends Statement { private final String _sizeVar; private final String _name; public ReadBuffer(String sizeVar, String name) { _sizeVar = sizeVar; _name = name; } @Override
// Path: src/org/derric_lang/validator/ValidatorInputStream.java // public abstract class ValidatorInputStream extends InputStream { // // public abstract boolean isByteAligned(); // public abstract boolean atEOF() throws IOException; // // public abstract long lastLocation(); // public abstract long lastRead(); // public abstract void mark(); // public abstract void reset() throws IOException; // // public abstract boolean skipBits(long bits) throws IOException; // public abstract long skip(long bytes) throws IOException; // // public abstract ValidatorInputStream bitOrder(BitOrder order); // public abstract ValidatorInputStream byteOrder(ByteOrder order); // public abstract ValidatorInputStream signed(); // public abstract ValidatorInputStream unsigned(); // public abstract long readInteger(long bits) throws IOException; // // public abstract ValidatorInputStream includeMarker(boolean includeMarker); // public abstract Content readUntil(long bits, ValueSet values) throws IOException; // // public abstract Content validateContent(long size, String name, Map<String, String> configuration, Map<String, List<Object>> arguments, boolean allowEOF) throws IOException; // } // // Path: src/org/derric_lang/validator/interpreter/Sentence.java // public class Sentence { // // private final URI _inputFile; // // private String _structureName; // private ISourceLocation _sequenceLocation; // private ISourceLocation _structureLocation; // private ISourceLocation _inputLocation; // // private List<StructureMatch> _matches; // private List<StructureMatch> _sub; // private List<FieldMatch> _fields; // // public Sentence(URI inputFile) { // _inputFile = inputFile; // _matches = new ArrayList<StructureMatch>(); // _sub = new ArrayList<StructureMatch>(); // _fields = new ArrayList<FieldMatch>(); // } // // public void setStructureName(String name) { // _structureName = name; // } // // public void setSequenceLocation(ISourceLocation location) { // _sequenceLocation = location; // } // // public void setStructureLocation(ISourceLocation location) { // _structureLocation = location; // } // // public void setStructureInputLocation(int offset, int length) { // _inputLocation = new SourceLocation(_inputFile, offset, length); // } // // public void addFieldLocation(String name, ISourceLocation sourceLocation, int offset, int length) { // boolean dup = false; // int index = 0; // for (int i = 0; i < _fields.size(); i++) { // if (_fields.get(i).sourceLocation.getOffset() == sourceLocation.getOffset() && _fields.get(i).sourceLocation.getLength() == sourceLocation.getLength()) { // dup = true; // index = i; // String fName = _fields.get(i).name.length() > name.length() ? name : _fields.get(i).name; // int fOffset = _fields.get(i).inputLocation.getOffset() > offset ? offset : _fields.get(i).inputLocation.getOffset(); // int fLength = ((_fields.get(i).inputLocation.getOffset() + _fields.get(i).inputLocation.getLength()) > (offset + length) ? _fields.get(i).inputLocation.getOffset() + _fields.get(i).inputLocation.getLength() : offset + length) - fOffset; // FieldMatch fm = new FieldMatch(fName, sourceLocation, new SourceLocation(_inputFile, fOffset, fLength)); // _fields.add(index, fm); // _fields.remove(index + 1); // break; // } // } // if (!dup) { // _fields.add(new FieldMatch(name, sourceLocation, new SourceLocation(_inputFile, offset, length))); // } // } // // public void subMatch() { // List<FieldMatch> fieldMatches = new ArrayList<FieldMatch>(); // fieldMatches.addAll(_fields); // _sub.add(new StructureMatch(_structureName, _sequenceLocation, _structureLocation, _inputLocation, fieldMatches)); // _fields.clear(); // } // // public void fullMatch() { // _matches.addAll(_sub); // clearSub(); // } // // public void clearSub() { // _sub.clear(); // _fields.clear(); // } // // @Override // public String toString() { // String out = ""; // boolean first = true; // for (StructureMatch s : _matches) { // if (first) { // first = false; // } else { // out += " "; // } // out += s.name; // } // return out; // } // // public List<StructureMatch> getMatches() { // return _matches; // } // // } // Path: src/org/derric_lang/validator/interpreter/structure/ReadBuffer.java import java.io.IOException; import java.util.Map; import org.derric_lang.validator.ValidatorInputStream; import org.derric_lang.validator.interpreter.Sentence; package org.derric_lang.validator.interpreter.structure; public class ReadBuffer extends Statement { private final String _sizeVar; private final String _name; public ReadBuffer(String sizeVar, String name) { _sizeVar = sizeVar; _name = name; } @Override
public boolean eval(ValidatorInputStream input, Map<String, Type> globals, Map<String, Type> locals, Sentence current) throws IOException {
jvdb/derric
src/org/derric_lang/validator/interpreter/structure/ReadBuffer.java
// Path: src/org/derric_lang/validator/ValidatorInputStream.java // public abstract class ValidatorInputStream extends InputStream { // // public abstract boolean isByteAligned(); // public abstract boolean atEOF() throws IOException; // // public abstract long lastLocation(); // public abstract long lastRead(); // public abstract void mark(); // public abstract void reset() throws IOException; // // public abstract boolean skipBits(long bits) throws IOException; // public abstract long skip(long bytes) throws IOException; // // public abstract ValidatorInputStream bitOrder(BitOrder order); // public abstract ValidatorInputStream byteOrder(ByteOrder order); // public abstract ValidatorInputStream signed(); // public abstract ValidatorInputStream unsigned(); // public abstract long readInteger(long bits) throws IOException; // // public abstract ValidatorInputStream includeMarker(boolean includeMarker); // public abstract Content readUntil(long bits, ValueSet values) throws IOException; // // public abstract Content validateContent(long size, String name, Map<String, String> configuration, Map<String, List<Object>> arguments, boolean allowEOF) throws IOException; // } // // Path: src/org/derric_lang/validator/interpreter/Sentence.java // public class Sentence { // // private final URI _inputFile; // // private String _structureName; // private ISourceLocation _sequenceLocation; // private ISourceLocation _structureLocation; // private ISourceLocation _inputLocation; // // private List<StructureMatch> _matches; // private List<StructureMatch> _sub; // private List<FieldMatch> _fields; // // public Sentence(URI inputFile) { // _inputFile = inputFile; // _matches = new ArrayList<StructureMatch>(); // _sub = new ArrayList<StructureMatch>(); // _fields = new ArrayList<FieldMatch>(); // } // // public void setStructureName(String name) { // _structureName = name; // } // // public void setSequenceLocation(ISourceLocation location) { // _sequenceLocation = location; // } // // public void setStructureLocation(ISourceLocation location) { // _structureLocation = location; // } // // public void setStructureInputLocation(int offset, int length) { // _inputLocation = new SourceLocation(_inputFile, offset, length); // } // // public void addFieldLocation(String name, ISourceLocation sourceLocation, int offset, int length) { // boolean dup = false; // int index = 0; // for (int i = 0; i < _fields.size(); i++) { // if (_fields.get(i).sourceLocation.getOffset() == sourceLocation.getOffset() && _fields.get(i).sourceLocation.getLength() == sourceLocation.getLength()) { // dup = true; // index = i; // String fName = _fields.get(i).name.length() > name.length() ? name : _fields.get(i).name; // int fOffset = _fields.get(i).inputLocation.getOffset() > offset ? offset : _fields.get(i).inputLocation.getOffset(); // int fLength = ((_fields.get(i).inputLocation.getOffset() + _fields.get(i).inputLocation.getLength()) > (offset + length) ? _fields.get(i).inputLocation.getOffset() + _fields.get(i).inputLocation.getLength() : offset + length) - fOffset; // FieldMatch fm = new FieldMatch(fName, sourceLocation, new SourceLocation(_inputFile, fOffset, fLength)); // _fields.add(index, fm); // _fields.remove(index + 1); // break; // } // } // if (!dup) { // _fields.add(new FieldMatch(name, sourceLocation, new SourceLocation(_inputFile, offset, length))); // } // } // // public void subMatch() { // List<FieldMatch> fieldMatches = new ArrayList<FieldMatch>(); // fieldMatches.addAll(_fields); // _sub.add(new StructureMatch(_structureName, _sequenceLocation, _structureLocation, _inputLocation, fieldMatches)); // _fields.clear(); // } // // public void fullMatch() { // _matches.addAll(_sub); // clearSub(); // } // // public void clearSub() { // _sub.clear(); // _fields.clear(); // } // // @Override // public String toString() { // String out = ""; // boolean first = true; // for (StructureMatch s : _matches) { // if (first) { // first = false; // } else { // out += " "; // } // out += s.name; // } // return out; // } // // public List<StructureMatch> getMatches() { // return _matches; // } // // }
import java.io.IOException; import java.util.Map; import org.derric_lang.validator.ValidatorInputStream; import org.derric_lang.validator.interpreter.Sentence;
package org.derric_lang.validator.interpreter.structure; public class ReadBuffer extends Statement { private final String _sizeVar; private final String _name; public ReadBuffer(String sizeVar, String name) { _sizeVar = sizeVar; _name = name; } @Override
// Path: src/org/derric_lang/validator/ValidatorInputStream.java // public abstract class ValidatorInputStream extends InputStream { // // public abstract boolean isByteAligned(); // public abstract boolean atEOF() throws IOException; // // public abstract long lastLocation(); // public abstract long lastRead(); // public abstract void mark(); // public abstract void reset() throws IOException; // // public abstract boolean skipBits(long bits) throws IOException; // public abstract long skip(long bytes) throws IOException; // // public abstract ValidatorInputStream bitOrder(BitOrder order); // public abstract ValidatorInputStream byteOrder(ByteOrder order); // public abstract ValidatorInputStream signed(); // public abstract ValidatorInputStream unsigned(); // public abstract long readInteger(long bits) throws IOException; // // public abstract ValidatorInputStream includeMarker(boolean includeMarker); // public abstract Content readUntil(long bits, ValueSet values) throws IOException; // // public abstract Content validateContent(long size, String name, Map<String, String> configuration, Map<String, List<Object>> arguments, boolean allowEOF) throws IOException; // } // // Path: src/org/derric_lang/validator/interpreter/Sentence.java // public class Sentence { // // private final URI _inputFile; // // private String _structureName; // private ISourceLocation _sequenceLocation; // private ISourceLocation _structureLocation; // private ISourceLocation _inputLocation; // // private List<StructureMatch> _matches; // private List<StructureMatch> _sub; // private List<FieldMatch> _fields; // // public Sentence(URI inputFile) { // _inputFile = inputFile; // _matches = new ArrayList<StructureMatch>(); // _sub = new ArrayList<StructureMatch>(); // _fields = new ArrayList<FieldMatch>(); // } // // public void setStructureName(String name) { // _structureName = name; // } // // public void setSequenceLocation(ISourceLocation location) { // _sequenceLocation = location; // } // // public void setStructureLocation(ISourceLocation location) { // _structureLocation = location; // } // // public void setStructureInputLocation(int offset, int length) { // _inputLocation = new SourceLocation(_inputFile, offset, length); // } // // public void addFieldLocation(String name, ISourceLocation sourceLocation, int offset, int length) { // boolean dup = false; // int index = 0; // for (int i = 0; i < _fields.size(); i++) { // if (_fields.get(i).sourceLocation.getOffset() == sourceLocation.getOffset() && _fields.get(i).sourceLocation.getLength() == sourceLocation.getLength()) { // dup = true; // index = i; // String fName = _fields.get(i).name.length() > name.length() ? name : _fields.get(i).name; // int fOffset = _fields.get(i).inputLocation.getOffset() > offset ? offset : _fields.get(i).inputLocation.getOffset(); // int fLength = ((_fields.get(i).inputLocation.getOffset() + _fields.get(i).inputLocation.getLength()) > (offset + length) ? _fields.get(i).inputLocation.getOffset() + _fields.get(i).inputLocation.getLength() : offset + length) - fOffset; // FieldMatch fm = new FieldMatch(fName, sourceLocation, new SourceLocation(_inputFile, fOffset, fLength)); // _fields.add(index, fm); // _fields.remove(index + 1); // break; // } // } // if (!dup) { // _fields.add(new FieldMatch(name, sourceLocation, new SourceLocation(_inputFile, offset, length))); // } // } // // public void subMatch() { // List<FieldMatch> fieldMatches = new ArrayList<FieldMatch>(); // fieldMatches.addAll(_fields); // _sub.add(new StructureMatch(_structureName, _sequenceLocation, _structureLocation, _inputLocation, fieldMatches)); // _fields.clear(); // } // // public void fullMatch() { // _matches.addAll(_sub); // clearSub(); // } // // public void clearSub() { // _sub.clear(); // _fields.clear(); // } // // @Override // public String toString() { // String out = ""; // boolean first = true; // for (StructureMatch s : _matches) { // if (first) { // first = false; // } else { // out += " "; // } // out += s.name; // } // return out; // } // // public List<StructureMatch> getMatches() { // return _matches; // } // // } // Path: src/org/derric_lang/validator/interpreter/structure/ReadBuffer.java import java.io.IOException; import java.util.Map; import org.derric_lang.validator.ValidatorInputStream; import org.derric_lang.validator.interpreter.Sentence; package org.derric_lang.validator.interpreter.structure; public class ReadBuffer extends Statement { private final String _sizeVar; private final String _name; public ReadBuffer(String sizeVar, String name) { _sizeVar = sizeVar; _name = name; } @Override
public boolean eval(ValidatorInputStream input, Map<String, Type> globals, Map<String, Type> locals, Sentence current) throws IOException {