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
TakWolf/CNode-Material-Design
app/src/main/java/org/cnodejs/android/md/model/api/ForegroundCallback.java
// Path: app/src/main/java/org/cnodejs/android/md/model/entity/ErrorResult.java // public class ErrorResult extends Result { // // @NonNull // public static ErrorResult from(@NonNull Response response) { // ErrorResult errorResult = null; // ResponseBody errorBody = response.errorBody(); // if (errorBody != null) { // try { // errorResult = EntityUtils.gson.fromJson(errorBody.string(), ErrorResult.class); // } catch (Throwable ignored) {} // } // if (errorResult == null) { // errorResult = new ErrorResult(); // errorResult.setSuccess(false); // switch (response.code()) { // case 400: // errorResult.setMessage("非法请求"); // break; // case 403: // errorResult.setMessage("非法行为"); // break; // case 404: // errorResult.setMessage("未找到资源"); // break; // case 405: // errorResult.setMessage("非法请求方式"); // break; // case 408: // errorResult.setMessage("请求超时"); // break; // case 500: // errorResult.setMessage("服务器内部错误"); // break; // case 502: // errorResult.setMessage("服务器网关错误"); // break; // case 504: // errorResult.setMessage("服务器网关超时"); // break; // default: // errorResult.setMessage("未知响应:" + response.message()); // break; // } // } // return errorResult; // } // // @NonNull // public static ErrorResult from(@NonNull Throwable t) { // ErrorResult errorResult = new ErrorResult(); // errorResult.setSuccess(false); // if (t instanceof UnknownHostException || t instanceof ConnectException) { // errorResult.setMessage("网络无法连接"); // } else if (t instanceof NoRouteToHostException) { // errorResult.setMessage("无法访问网络"); // } else if (t instanceof SocketTimeoutException) { // errorResult.setMessage("网络访问超时"); // } else if (t instanceof JsonSyntaxException) { // errorResult.setMessage("响应数据格式错误"); // } else { // errorResult.setMessage("未知错误:" + t.getLocalizedMessage()); // } // return errorResult; // } // // @SerializedName("error_msg") // private String message; // // public String getMessage() { // return message; // } // // public void setMessage(String message) { // this.message = message; // } // // } // // Path: app/src/main/java/org/cnodejs/android/md/model/entity/Result.java // public class Result { // // private boolean success; // // public boolean isSuccess() { // return success; // } // // public void setSuccess(boolean success) { // this.success = success; // } // // } // // Path: app/src/main/java/org/cnodejs/android/md/ui/util/ActivityUtils.java // public final class ActivityUtils { // // private ActivityUtils() {} // // public static boolean isAlive(@Nullable Activity activity) { // return activity != null && !(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 && activity.isDestroyed()) && !activity.isFinishing(); // } // // }
import android.app.Activity; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import org.cnodejs.android.md.model.entity.ErrorResult; import org.cnodejs.android.md.model.entity.Result; import org.cnodejs.android.md.ui.util.ActivityUtils; import java.lang.ref.WeakReference; import okhttp3.Headers; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response;
package org.cnodejs.android.md.model.api; public class ForegroundCallback<T extends Result> implements Callback<T>, CallbackLifecycle<T> { private final WeakReference<Activity> activityWeakReference; public ForegroundCallback(@NonNull Activity activity) { activityWeakReference = new WeakReference<>(activity); } @Nullable protected final Activity getActivity() { return activityWeakReference.get(); } @Override public final void onResponse(@NonNull Call<T> call, @NonNull Response<T> response) { Activity activity = getActivity(); if (ActivityUtils.isAlive(activity)) { boolean interrupt; if (response.isSuccessful()) { interrupt = onResultOk(response.code(), response.headers(), response.body()); } else {
// Path: app/src/main/java/org/cnodejs/android/md/model/entity/ErrorResult.java // public class ErrorResult extends Result { // // @NonNull // public static ErrorResult from(@NonNull Response response) { // ErrorResult errorResult = null; // ResponseBody errorBody = response.errorBody(); // if (errorBody != null) { // try { // errorResult = EntityUtils.gson.fromJson(errorBody.string(), ErrorResult.class); // } catch (Throwable ignored) {} // } // if (errorResult == null) { // errorResult = new ErrorResult(); // errorResult.setSuccess(false); // switch (response.code()) { // case 400: // errorResult.setMessage("非法请求"); // break; // case 403: // errorResult.setMessage("非法行为"); // break; // case 404: // errorResult.setMessage("未找到资源"); // break; // case 405: // errorResult.setMessage("非法请求方式"); // break; // case 408: // errorResult.setMessage("请求超时"); // break; // case 500: // errorResult.setMessage("服务器内部错误"); // break; // case 502: // errorResult.setMessage("服务器网关错误"); // break; // case 504: // errorResult.setMessage("服务器网关超时"); // break; // default: // errorResult.setMessage("未知响应:" + response.message()); // break; // } // } // return errorResult; // } // // @NonNull // public static ErrorResult from(@NonNull Throwable t) { // ErrorResult errorResult = new ErrorResult(); // errorResult.setSuccess(false); // if (t instanceof UnknownHostException || t instanceof ConnectException) { // errorResult.setMessage("网络无法连接"); // } else if (t instanceof NoRouteToHostException) { // errorResult.setMessage("无法访问网络"); // } else if (t instanceof SocketTimeoutException) { // errorResult.setMessage("网络访问超时"); // } else if (t instanceof JsonSyntaxException) { // errorResult.setMessage("响应数据格式错误"); // } else { // errorResult.setMessage("未知错误:" + t.getLocalizedMessage()); // } // return errorResult; // } // // @SerializedName("error_msg") // private String message; // // public String getMessage() { // return message; // } // // public void setMessage(String message) { // this.message = message; // } // // } // // Path: app/src/main/java/org/cnodejs/android/md/model/entity/Result.java // public class Result { // // private boolean success; // // public boolean isSuccess() { // return success; // } // // public void setSuccess(boolean success) { // this.success = success; // } // // } // // Path: app/src/main/java/org/cnodejs/android/md/ui/util/ActivityUtils.java // public final class ActivityUtils { // // private ActivityUtils() {} // // public static boolean isAlive(@Nullable Activity activity) { // return activity != null && !(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 && activity.isDestroyed()) && !activity.isFinishing(); // } // // } // Path: app/src/main/java/org/cnodejs/android/md/model/api/ForegroundCallback.java import android.app.Activity; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import org.cnodejs.android.md.model.entity.ErrorResult; import org.cnodejs.android.md.model.entity.Result; import org.cnodejs.android.md.ui.util.ActivityUtils; import java.lang.ref.WeakReference; import okhttp3.Headers; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; package org.cnodejs.android.md.model.api; public class ForegroundCallback<T extends Result> implements Callback<T>, CallbackLifecycle<T> { private final WeakReference<Activity> activityWeakReference; public ForegroundCallback(@NonNull Activity activity) { activityWeakReference = new WeakReference<>(activity); } @Nullable protected final Activity getActivity() { return activityWeakReference.get(); } @Override public final void onResponse(@NonNull Call<T> call, @NonNull Response<T> response) { Activity activity = getActivity(); if (ActivityUtils.isAlive(activity)) { boolean interrupt; if (response.isSuccessful()) { interrupt = onResultOk(response.code(), response.headers(), response.body()); } else {
interrupt = onResultError(response.code(), response.headers(), ErrorResult.from(response));
TakWolf/CNode-Material-Design
app/src/main/java/org/cnodejs/android/md/ui/jsbridge/ImageJavascriptInterface.java
// Path: app/src/main/java/org/cnodejs/android/md/ui/activity/ImagePreviewActivity.java // public class ImagePreviewActivity extends StatusBarActivity { // // private static final String EXTRA_IMAGE_URL = "imageUrl"; // // public static void start(@NonNull Context context, String imageUrl) { // Intent intent = new Intent(context, ImagePreviewActivity.class); // intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // intent.putExtra(EXTRA_IMAGE_URL, imageUrl); // context.startActivity(intent); // } // // @BindView(R.id.toolbar) // Toolbar toolbar; // // @BindView(R.id.photo_view) // PhotoView photoView; // // @BindView(R.id.progress_wheel) // ProgressWheel progressWheel; // // @Override // protected void onCreate(@Nullable Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_image_preview); // ButterKnife.bind(this); // // toolbar.setNavigationOnClickListener(new NavigationFinishClickListener(this)); // // loadImageAsyncTask(); // } // // private void loadImageAsyncTask() { // progressWheel.spin(); // GlideApp.with(this).load(getIntent().getStringExtra(EXTRA_IMAGE_URL)).error(R.drawable.image_error).listener(new RequestListener<Drawable>() { // // @Override // public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) { // progressWheel.stopSpinning(); // return false; // } // // @Override // public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) { // progressWheel.stopSpinning(); // return false; // } // // }).into(photoView); // } // // }
import android.content.Context; import android.support.annotation.NonNull; import android.webkit.JavascriptInterface; import org.cnodejs.android.md.ui.activity.ImagePreviewActivity;
package org.cnodejs.android.md.ui.jsbridge; public final class ImageJavascriptInterface { public static final String NAME = "imageBridge"; private final Context context; public ImageJavascriptInterface(@NonNull Context context) { this.context = context.getApplicationContext(); } @JavascriptInterface public void openImage(String imageUrl) {
// Path: app/src/main/java/org/cnodejs/android/md/ui/activity/ImagePreviewActivity.java // public class ImagePreviewActivity extends StatusBarActivity { // // private static final String EXTRA_IMAGE_URL = "imageUrl"; // // public static void start(@NonNull Context context, String imageUrl) { // Intent intent = new Intent(context, ImagePreviewActivity.class); // intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // intent.putExtra(EXTRA_IMAGE_URL, imageUrl); // context.startActivity(intent); // } // // @BindView(R.id.toolbar) // Toolbar toolbar; // // @BindView(R.id.photo_view) // PhotoView photoView; // // @BindView(R.id.progress_wheel) // ProgressWheel progressWheel; // // @Override // protected void onCreate(@Nullable Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // setContentView(R.layout.activity_image_preview); // ButterKnife.bind(this); // // toolbar.setNavigationOnClickListener(new NavigationFinishClickListener(this)); // // loadImageAsyncTask(); // } // // private void loadImageAsyncTask() { // progressWheel.spin(); // GlideApp.with(this).load(getIntent().getStringExtra(EXTRA_IMAGE_URL)).error(R.drawable.image_error).listener(new RequestListener<Drawable>() { // // @Override // public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) { // progressWheel.stopSpinning(); // return false; // } // // @Override // public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) { // progressWheel.stopSpinning(); // return false; // } // // }).into(photoView); // } // // } // Path: app/src/main/java/org/cnodejs/android/md/ui/jsbridge/ImageJavascriptInterface.java import android.content.Context; import android.support.annotation.NonNull; import android.webkit.JavascriptInterface; import org.cnodejs.android.md.ui.activity.ImagePreviewActivity; package org.cnodejs.android.md.ui.jsbridge; public final class ImageJavascriptInterface { public static final String NAME = "imageBridge"; private final Context context; public ImageJavascriptInterface(@NonNull Context context) { this.context = context.getApplicationContext(); } @JavascriptInterface public void openImage(String imageUrl) {
ImagePreviewActivity.start(context, imageUrl);
TakWolf/CNode-Material-Design
app/src/main/java/org/cnodejs/android/md/ui/util/ThemeUtils.java
// Path: app/src/main/java/org/cnodejs/android/md/model/storage/SettingShared.java // public final class SettingShared { // // private SettingShared() {} // // private static final String TAG = "SettingShared"; // // private static final String KEY_ENABLE_NOTIFICATION = "enableNotification"; // private static final String KEY_ENABLE_THEME_DARK = "enableThemeDark"; // private static final String KEY_ENABLE_TOPIC_DRAFT = "enableTopicDraft"; // private static final String KEY_ENABLE_TOPIC_SIGN = "enableTopicSign"; // private static final String KEY_TOPIC_SIGN_CONTENT = "topicSignContent"; // private static final String KEY_ENABLE_TOPIC_RENDER_COMPAT = "enableTopicRenderCompat"; // private static final String KEY_SHOW_TOPIC_RENDER_COMPAT_TIP = "showTopicRenderCompatTip"; // // public static final String DEFAULT_TOPIC_SIGN_CONTENT = "来自酷炫的 [CNodeMD](https://github.com/TakWolf/CNode-Material-Design)"; // // public static boolean isEnableNotification(@NonNull Context context) { // return SharedUtils.with(context, TAG).getBoolean(KEY_ENABLE_NOTIFICATION, true); // } // // public static void setEnableNotification(@NonNull Context context, boolean enable) { // SharedUtils.with(context, TAG).setBoolean(KEY_ENABLE_NOTIFICATION, enable); // } // // public static boolean isEnableThemeDark(@NonNull Context context) { // return SharedUtils.with(context, TAG).getBoolean(KEY_ENABLE_THEME_DARK, false); // } // // public static void setEnableThemeDark(@NonNull Context context, boolean enable) { // SharedUtils.with(context, TAG).setBoolean(KEY_ENABLE_THEME_DARK, enable); // } // // public static boolean isEnableTopicDraft(@NonNull Context context) { // return SharedUtils.with(context, TAG).getBoolean(KEY_ENABLE_TOPIC_DRAFT, true); // } // // public static void setEnableTopicDraft(@NonNull Context context, boolean enable) { // SharedUtils.with(context, TAG).setBoolean(KEY_ENABLE_TOPIC_DRAFT, enable); // } // // public static boolean isEnableTopicSign(@NonNull Context context) { // return SharedUtils.with(context, TAG).getBoolean(KEY_ENABLE_TOPIC_SIGN, true); // } // // public static void setEnableTopicSign(@NonNull Context context, boolean enable) { // SharedUtils.with(context, TAG).setBoolean(KEY_ENABLE_TOPIC_SIGN, enable); // } // // public static String getTopicSignContent(@NonNull Context context) { // return SharedUtils.with(context, TAG).getString(KEY_TOPIC_SIGN_CONTENT, DEFAULT_TOPIC_SIGN_CONTENT); // } // // public static void setTopicSignContent(@NonNull Context context, @Nullable String content) { // SharedUtils.with(context, TAG).setString(KEY_TOPIC_SIGN_CONTENT, content); // } // // public static boolean isEnableTopicRenderCompat(@NonNull Context context) { // return SharedUtils.with(context, TAG).getBoolean(KEY_ENABLE_TOPIC_RENDER_COMPAT, true); // } // // public static void setEnableTopicRenderCompat(@NonNull Context context, boolean enable) { // SharedUtils.with(context, TAG).setBoolean(KEY_ENABLE_TOPIC_RENDER_COMPAT, enable); // } // // public static boolean isShowTopicRenderCompatTip(@NonNull Context context) { // return SharedUtils.with(context, TAG).getBoolean(KEY_SHOW_TOPIC_RENDER_COMPAT_TIP, true); // } // // public static void markShowTopicRenderCompatTip(@NonNull Context context) { // SharedUtils.with(context, TAG).setBoolean(KEY_SHOW_TOPIC_RENDER_COMPAT_TIP, false); // } // // } // // Path: app/src/main/java/org/cnodejs/android/md/util/HandlerUtils.java // public final class HandlerUtils { // // private HandlerUtils() {} // // public static final Handler handler = new Handler(Looper.getMainLooper()); // // }
import android.app.Activity; import android.support.annotation.NonNull; import android.support.annotation.StyleRes; import org.cnodejs.android.md.model.storage.SettingShared; import org.cnodejs.android.md.util.HandlerUtils;
package org.cnodejs.android.md.ui.util; public final class ThemeUtils { private ThemeUtils() {} public static boolean configThemeBeforeOnCreate(@NonNull Activity activity, @StyleRes int light, @StyleRes int dark) {
// Path: app/src/main/java/org/cnodejs/android/md/model/storage/SettingShared.java // public final class SettingShared { // // private SettingShared() {} // // private static final String TAG = "SettingShared"; // // private static final String KEY_ENABLE_NOTIFICATION = "enableNotification"; // private static final String KEY_ENABLE_THEME_DARK = "enableThemeDark"; // private static final String KEY_ENABLE_TOPIC_DRAFT = "enableTopicDraft"; // private static final String KEY_ENABLE_TOPIC_SIGN = "enableTopicSign"; // private static final String KEY_TOPIC_SIGN_CONTENT = "topicSignContent"; // private static final String KEY_ENABLE_TOPIC_RENDER_COMPAT = "enableTopicRenderCompat"; // private static final String KEY_SHOW_TOPIC_RENDER_COMPAT_TIP = "showTopicRenderCompatTip"; // // public static final String DEFAULT_TOPIC_SIGN_CONTENT = "来自酷炫的 [CNodeMD](https://github.com/TakWolf/CNode-Material-Design)"; // // public static boolean isEnableNotification(@NonNull Context context) { // return SharedUtils.with(context, TAG).getBoolean(KEY_ENABLE_NOTIFICATION, true); // } // // public static void setEnableNotification(@NonNull Context context, boolean enable) { // SharedUtils.with(context, TAG).setBoolean(KEY_ENABLE_NOTIFICATION, enable); // } // // public static boolean isEnableThemeDark(@NonNull Context context) { // return SharedUtils.with(context, TAG).getBoolean(KEY_ENABLE_THEME_DARK, false); // } // // public static void setEnableThemeDark(@NonNull Context context, boolean enable) { // SharedUtils.with(context, TAG).setBoolean(KEY_ENABLE_THEME_DARK, enable); // } // // public static boolean isEnableTopicDraft(@NonNull Context context) { // return SharedUtils.with(context, TAG).getBoolean(KEY_ENABLE_TOPIC_DRAFT, true); // } // // public static void setEnableTopicDraft(@NonNull Context context, boolean enable) { // SharedUtils.with(context, TAG).setBoolean(KEY_ENABLE_TOPIC_DRAFT, enable); // } // // public static boolean isEnableTopicSign(@NonNull Context context) { // return SharedUtils.with(context, TAG).getBoolean(KEY_ENABLE_TOPIC_SIGN, true); // } // // public static void setEnableTopicSign(@NonNull Context context, boolean enable) { // SharedUtils.with(context, TAG).setBoolean(KEY_ENABLE_TOPIC_SIGN, enable); // } // // public static String getTopicSignContent(@NonNull Context context) { // return SharedUtils.with(context, TAG).getString(KEY_TOPIC_SIGN_CONTENT, DEFAULT_TOPIC_SIGN_CONTENT); // } // // public static void setTopicSignContent(@NonNull Context context, @Nullable String content) { // SharedUtils.with(context, TAG).setString(KEY_TOPIC_SIGN_CONTENT, content); // } // // public static boolean isEnableTopicRenderCompat(@NonNull Context context) { // return SharedUtils.with(context, TAG).getBoolean(KEY_ENABLE_TOPIC_RENDER_COMPAT, true); // } // // public static void setEnableTopicRenderCompat(@NonNull Context context, boolean enable) { // SharedUtils.with(context, TAG).setBoolean(KEY_ENABLE_TOPIC_RENDER_COMPAT, enable); // } // // public static boolean isShowTopicRenderCompatTip(@NonNull Context context) { // return SharedUtils.with(context, TAG).getBoolean(KEY_SHOW_TOPIC_RENDER_COMPAT_TIP, true); // } // // public static void markShowTopicRenderCompatTip(@NonNull Context context) { // SharedUtils.with(context, TAG).setBoolean(KEY_SHOW_TOPIC_RENDER_COMPAT_TIP, false); // } // // } // // Path: app/src/main/java/org/cnodejs/android/md/util/HandlerUtils.java // public final class HandlerUtils { // // private HandlerUtils() {} // // public static final Handler handler = new Handler(Looper.getMainLooper()); // // } // Path: app/src/main/java/org/cnodejs/android/md/ui/util/ThemeUtils.java import android.app.Activity; import android.support.annotation.NonNull; import android.support.annotation.StyleRes; import org.cnodejs.android.md.model.storage.SettingShared; import org.cnodejs.android.md.util.HandlerUtils; package org.cnodejs.android.md.ui.util; public final class ThemeUtils { private ThemeUtils() {} public static boolean configThemeBeforeOnCreate(@NonNull Activity activity, @StyleRes int light, @StyleRes int dark) {
boolean enable = SettingShared.isEnableThemeDark(activity);
TakWolf/CNode-Material-Design
app/src/main/java/org/cnodejs/android/md/ui/util/ThemeUtils.java
// Path: app/src/main/java/org/cnodejs/android/md/model/storage/SettingShared.java // public final class SettingShared { // // private SettingShared() {} // // private static final String TAG = "SettingShared"; // // private static final String KEY_ENABLE_NOTIFICATION = "enableNotification"; // private static final String KEY_ENABLE_THEME_DARK = "enableThemeDark"; // private static final String KEY_ENABLE_TOPIC_DRAFT = "enableTopicDraft"; // private static final String KEY_ENABLE_TOPIC_SIGN = "enableTopicSign"; // private static final String KEY_TOPIC_SIGN_CONTENT = "topicSignContent"; // private static final String KEY_ENABLE_TOPIC_RENDER_COMPAT = "enableTopicRenderCompat"; // private static final String KEY_SHOW_TOPIC_RENDER_COMPAT_TIP = "showTopicRenderCompatTip"; // // public static final String DEFAULT_TOPIC_SIGN_CONTENT = "来自酷炫的 [CNodeMD](https://github.com/TakWolf/CNode-Material-Design)"; // // public static boolean isEnableNotification(@NonNull Context context) { // return SharedUtils.with(context, TAG).getBoolean(KEY_ENABLE_NOTIFICATION, true); // } // // public static void setEnableNotification(@NonNull Context context, boolean enable) { // SharedUtils.with(context, TAG).setBoolean(KEY_ENABLE_NOTIFICATION, enable); // } // // public static boolean isEnableThemeDark(@NonNull Context context) { // return SharedUtils.with(context, TAG).getBoolean(KEY_ENABLE_THEME_DARK, false); // } // // public static void setEnableThemeDark(@NonNull Context context, boolean enable) { // SharedUtils.with(context, TAG).setBoolean(KEY_ENABLE_THEME_DARK, enable); // } // // public static boolean isEnableTopicDraft(@NonNull Context context) { // return SharedUtils.with(context, TAG).getBoolean(KEY_ENABLE_TOPIC_DRAFT, true); // } // // public static void setEnableTopicDraft(@NonNull Context context, boolean enable) { // SharedUtils.with(context, TAG).setBoolean(KEY_ENABLE_TOPIC_DRAFT, enable); // } // // public static boolean isEnableTopicSign(@NonNull Context context) { // return SharedUtils.with(context, TAG).getBoolean(KEY_ENABLE_TOPIC_SIGN, true); // } // // public static void setEnableTopicSign(@NonNull Context context, boolean enable) { // SharedUtils.with(context, TAG).setBoolean(KEY_ENABLE_TOPIC_SIGN, enable); // } // // public static String getTopicSignContent(@NonNull Context context) { // return SharedUtils.with(context, TAG).getString(KEY_TOPIC_SIGN_CONTENT, DEFAULT_TOPIC_SIGN_CONTENT); // } // // public static void setTopicSignContent(@NonNull Context context, @Nullable String content) { // SharedUtils.with(context, TAG).setString(KEY_TOPIC_SIGN_CONTENT, content); // } // // public static boolean isEnableTopicRenderCompat(@NonNull Context context) { // return SharedUtils.with(context, TAG).getBoolean(KEY_ENABLE_TOPIC_RENDER_COMPAT, true); // } // // public static void setEnableTopicRenderCompat(@NonNull Context context, boolean enable) { // SharedUtils.with(context, TAG).setBoolean(KEY_ENABLE_TOPIC_RENDER_COMPAT, enable); // } // // public static boolean isShowTopicRenderCompatTip(@NonNull Context context) { // return SharedUtils.with(context, TAG).getBoolean(KEY_SHOW_TOPIC_RENDER_COMPAT_TIP, true); // } // // public static void markShowTopicRenderCompatTip(@NonNull Context context) { // SharedUtils.with(context, TAG).setBoolean(KEY_SHOW_TOPIC_RENDER_COMPAT_TIP, false); // } // // } // // Path: app/src/main/java/org/cnodejs/android/md/util/HandlerUtils.java // public final class HandlerUtils { // // private HandlerUtils() {} // // public static final Handler handler = new Handler(Looper.getMainLooper()); // // }
import android.app.Activity; import android.support.annotation.NonNull; import android.support.annotation.StyleRes; import org.cnodejs.android.md.model.storage.SettingShared; import org.cnodejs.android.md.util.HandlerUtils;
package org.cnodejs.android.md.ui.util; public final class ThemeUtils { private ThemeUtils() {} public static boolean configThemeBeforeOnCreate(@NonNull Activity activity, @StyleRes int light, @StyleRes int dark) { boolean enable = SettingShared.isEnableThemeDark(activity); activity.setTheme(enable ? dark : light); return enable; } public static void notifyThemeApply(@NonNull final Activity activity) {
// Path: app/src/main/java/org/cnodejs/android/md/model/storage/SettingShared.java // public final class SettingShared { // // private SettingShared() {} // // private static final String TAG = "SettingShared"; // // private static final String KEY_ENABLE_NOTIFICATION = "enableNotification"; // private static final String KEY_ENABLE_THEME_DARK = "enableThemeDark"; // private static final String KEY_ENABLE_TOPIC_DRAFT = "enableTopicDraft"; // private static final String KEY_ENABLE_TOPIC_SIGN = "enableTopicSign"; // private static final String KEY_TOPIC_SIGN_CONTENT = "topicSignContent"; // private static final String KEY_ENABLE_TOPIC_RENDER_COMPAT = "enableTopicRenderCompat"; // private static final String KEY_SHOW_TOPIC_RENDER_COMPAT_TIP = "showTopicRenderCompatTip"; // // public static final String DEFAULT_TOPIC_SIGN_CONTENT = "来自酷炫的 [CNodeMD](https://github.com/TakWolf/CNode-Material-Design)"; // // public static boolean isEnableNotification(@NonNull Context context) { // return SharedUtils.with(context, TAG).getBoolean(KEY_ENABLE_NOTIFICATION, true); // } // // public static void setEnableNotification(@NonNull Context context, boolean enable) { // SharedUtils.with(context, TAG).setBoolean(KEY_ENABLE_NOTIFICATION, enable); // } // // public static boolean isEnableThemeDark(@NonNull Context context) { // return SharedUtils.with(context, TAG).getBoolean(KEY_ENABLE_THEME_DARK, false); // } // // public static void setEnableThemeDark(@NonNull Context context, boolean enable) { // SharedUtils.with(context, TAG).setBoolean(KEY_ENABLE_THEME_DARK, enable); // } // // public static boolean isEnableTopicDraft(@NonNull Context context) { // return SharedUtils.with(context, TAG).getBoolean(KEY_ENABLE_TOPIC_DRAFT, true); // } // // public static void setEnableTopicDraft(@NonNull Context context, boolean enable) { // SharedUtils.with(context, TAG).setBoolean(KEY_ENABLE_TOPIC_DRAFT, enable); // } // // public static boolean isEnableTopicSign(@NonNull Context context) { // return SharedUtils.with(context, TAG).getBoolean(KEY_ENABLE_TOPIC_SIGN, true); // } // // public static void setEnableTopicSign(@NonNull Context context, boolean enable) { // SharedUtils.with(context, TAG).setBoolean(KEY_ENABLE_TOPIC_SIGN, enable); // } // // public static String getTopicSignContent(@NonNull Context context) { // return SharedUtils.with(context, TAG).getString(KEY_TOPIC_SIGN_CONTENT, DEFAULT_TOPIC_SIGN_CONTENT); // } // // public static void setTopicSignContent(@NonNull Context context, @Nullable String content) { // SharedUtils.with(context, TAG).setString(KEY_TOPIC_SIGN_CONTENT, content); // } // // public static boolean isEnableTopicRenderCompat(@NonNull Context context) { // return SharedUtils.with(context, TAG).getBoolean(KEY_ENABLE_TOPIC_RENDER_COMPAT, true); // } // // public static void setEnableTopicRenderCompat(@NonNull Context context, boolean enable) { // SharedUtils.with(context, TAG).setBoolean(KEY_ENABLE_TOPIC_RENDER_COMPAT, enable); // } // // public static boolean isShowTopicRenderCompatTip(@NonNull Context context) { // return SharedUtils.with(context, TAG).getBoolean(KEY_SHOW_TOPIC_RENDER_COMPAT_TIP, true); // } // // public static void markShowTopicRenderCompatTip(@NonNull Context context) { // SharedUtils.with(context, TAG).setBoolean(KEY_SHOW_TOPIC_RENDER_COMPAT_TIP, false); // } // // } // // Path: app/src/main/java/org/cnodejs/android/md/util/HandlerUtils.java // public final class HandlerUtils { // // private HandlerUtils() {} // // public static final Handler handler = new Handler(Looper.getMainLooper()); // // } // Path: app/src/main/java/org/cnodejs/android/md/ui/util/ThemeUtils.java import android.app.Activity; import android.support.annotation.NonNull; import android.support.annotation.StyleRes; import org.cnodejs.android.md.model.storage.SettingShared; import org.cnodejs.android.md.util.HandlerUtils; package org.cnodejs.android.md.ui.util; public final class ThemeUtils { private ThemeUtils() {} public static boolean configThemeBeforeOnCreate(@NonNull Activity activity, @StyleRes int light, @StyleRes int dark) { boolean enable = SettingShared.isEnableThemeDark(activity); activity.setTheme(enable ? dark : light); return enable; } public static void notifyThemeApply(@NonNull final Activity activity) {
HandlerUtils.handler.post(new Runnable() {
TakWolf/CNode-Material-Design
app/src/main/java/org/cnodejs/android/md/model/api/ApiClient.java
// Path: app/src/main/java/org/cnodejs/android/md/model/util/EntityUtils.java // public final class EntityUtils { // // private EntityUtils() {} // // public static final Gson gson = new GsonBuilder() // .registerTypeAdapter(DateTime.class, new DateTimeTypeAdapter()) // .create(); // // private static class DateTimeTypeAdapter extends TypeAdapter<DateTime> { // // @Override // public void write(JsonWriter out, DateTime dateTime) throws IOException { // if (dateTime == null) { // out.nullValue(); // } else { // out.value(dateTime.toString()); // } // } // // @Override // public DateTime read(JsonReader in) throws IOException { // if (in.peek() == JsonToken.NULL) { // in.nextNull(); // return null; // } else { // return new DateTime(in.nextString()); // } // } // // } // // }
import android.support.annotation.NonNull; import org.cnodejs.android.md.BuildConfig; import org.cnodejs.android.md.model.util.EntityUtils; import java.io.IOException; import okhttp3.Interceptor; import okhttp3.OkHttpClient; import okhttp3.OkHttpHackUtils; import okhttp3.Request; import okhttp3.Response; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory;
package org.cnodejs.android.md.model.api; public final class ApiClient { private ApiClient() {} public static final ApiService service = new Retrofit.Builder() .baseUrl(ApiDefine.API_BASE_URL) .client(new OkHttpClient.Builder() .addInterceptor(createUserAgentInterceptor()) .addInterceptor(createHttpLoggingInterceptor()) .build())
// Path: app/src/main/java/org/cnodejs/android/md/model/util/EntityUtils.java // public final class EntityUtils { // // private EntityUtils() {} // // public static final Gson gson = new GsonBuilder() // .registerTypeAdapter(DateTime.class, new DateTimeTypeAdapter()) // .create(); // // private static class DateTimeTypeAdapter extends TypeAdapter<DateTime> { // // @Override // public void write(JsonWriter out, DateTime dateTime) throws IOException { // if (dateTime == null) { // out.nullValue(); // } else { // out.value(dateTime.toString()); // } // } // // @Override // public DateTime read(JsonReader in) throws IOException { // if (in.peek() == JsonToken.NULL) { // in.nextNull(); // return null; // } else { // return new DateTime(in.nextString()); // } // } // // } // // } // Path: app/src/main/java/org/cnodejs/android/md/model/api/ApiClient.java import android.support.annotation.NonNull; import org.cnodejs.android.md.BuildConfig; import org.cnodejs.android.md.model.util.EntityUtils; import java.io.IOException; import okhttp3.Interceptor; import okhttp3.OkHttpClient; import okhttp3.OkHttpHackUtils; import okhttp3.Request; import okhttp3.Response; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; package org.cnodejs.android.md.model.api; public final class ApiClient { private ApiClient() {} public static final ApiService service = new Retrofit.Builder() .baseUrl(ApiDefine.API_BASE_URL) .client(new OkHttpClient.Builder() .addInterceptor(createUserAgentInterceptor()) .addInterceptor(createHttpLoggingInterceptor()) .build())
.addConverterFactory(GsonConverterFactory.create(EntityUtils.gson))
TakWolf/CNode-Material-Design
app/src/main/java/org/cnodejs/android/md/util/FormatUtils.java
// Path: app/src/main/java/org/cnodejs/android/md/model/api/ApiDefine.java // public final class ApiDefine { // // private ApiDefine() {} // // public static final String HOST_BASE_URL = "https://cnodejs.org"; // public static final String API_BASE_URL = HOST_BASE_URL + "/api/v1/"; // public static final String USER_PATH_PREFIX = "/user/"; // public static final String USER_LINK_URL_PREFIX = HOST_BASE_URL + USER_PATH_PREFIX; // public static final String TOPIC_PATH_PREFIX = "/topic/"; // public static final String TOPIC_LINK_URL_PREFIX = HOST_BASE_URL + TOPIC_PATH_PREFIX; // // public static final String USER_AGENT = "CNodeMD/" + BuildConfig.VERSION_NAME + " (Android " + Build.VERSION.RELEASE + "; " + Build.MODEL + "; " + Build.MANUFACTURER + ")"; // // public static final boolean MD_RENDER = true; // 使用服务端Markdown渲染可以轻微提升性能 // // }
import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.text.TextUtils; import org.cnodejs.android.md.model.api.ApiDefine; import org.joda.time.DateTime; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.safety.Cleaner; import org.jsoup.safety.Whitelist; import org.tautua.markdownpapers.Markdown; import org.tautua.markdownpapers.parser.ParseException; import java.io.StringReader; import java.io.StringWriter; import java.util.UUID;
public static boolean isAccessToken(String accessToken) { if (TextUtils.isEmpty(accessToken)) { return false; } else { try { //noinspection ResultOfMethodCallIgnored UUID.fromString(accessToken); return true; } catch (Exception e) { return false; } } } /** * 修复头像地址的历史遗留问题 */ public static String getCompatAvatarUrl(String avatarUrl) { if (!TextUtils.isEmpty(avatarUrl) && avatarUrl.startsWith("//gravatar.com/avatar/")) { return "http:" + avatarUrl; } else { return avatarUrl; } } /** * 标准URL检测 */ public static boolean isUserLinkUrl(String url) {
// Path: app/src/main/java/org/cnodejs/android/md/model/api/ApiDefine.java // public final class ApiDefine { // // private ApiDefine() {} // // public static final String HOST_BASE_URL = "https://cnodejs.org"; // public static final String API_BASE_URL = HOST_BASE_URL + "/api/v1/"; // public static final String USER_PATH_PREFIX = "/user/"; // public static final String USER_LINK_URL_PREFIX = HOST_BASE_URL + USER_PATH_PREFIX; // public static final String TOPIC_PATH_PREFIX = "/topic/"; // public static final String TOPIC_LINK_URL_PREFIX = HOST_BASE_URL + TOPIC_PATH_PREFIX; // // public static final String USER_AGENT = "CNodeMD/" + BuildConfig.VERSION_NAME + " (Android " + Build.VERSION.RELEASE + "; " + Build.MODEL + "; " + Build.MANUFACTURER + ")"; // // public static final boolean MD_RENDER = true; // 使用服务端Markdown渲染可以轻微提升性能 // // } // Path: app/src/main/java/org/cnodejs/android/md/util/FormatUtils.java import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.text.TextUtils; import org.cnodejs.android.md.model.api.ApiDefine; import org.joda.time.DateTime; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.safety.Cleaner; import org.jsoup.safety.Whitelist; import org.tautua.markdownpapers.Markdown; import org.tautua.markdownpapers.parser.ParseException; import java.io.StringReader; import java.io.StringWriter; import java.util.UUID; public static boolean isAccessToken(String accessToken) { if (TextUtils.isEmpty(accessToken)) { return false; } else { try { //noinspection ResultOfMethodCallIgnored UUID.fromString(accessToken); return true; } catch (Exception e) { return false; } } } /** * 修复头像地址的历史遗留问题 */ public static String getCompatAvatarUrl(String avatarUrl) { if (!TextUtils.isEmpty(avatarUrl) && avatarUrl.startsWith("//gravatar.com/avatar/")) { return "http:" + avatarUrl; } else { return avatarUrl; } } /** * 标准URL检测 */ public static boolean isUserLinkUrl(String url) {
return !TextUtils.isEmpty(url) && url.startsWith(ApiDefine.USER_LINK_URL_PREFIX);
TakWolf/CNode-Material-Design
app/src/main/java/org/cnodejs/android/md/model/util/SharedUtils.java
// Path: app/src/main/java/org/cnodejs/android/md/util/DigestUtils.java // public final class DigestUtils { // // public static final DigestUtils sha256 = new DigestUtils("SHA-256"); // // private final String algorithm; // // private DigestUtils(@NonNull String algorithm) { // this.algorithm = algorithm; // } // // @NonNull // public byte[] getRaw(@NonNull byte[] data) { // try { // return MessageDigest.getInstance(algorithm).digest(data); // } catch (NoSuchAlgorithmException e) { // throw new RuntimeException(e); // } // } // // @NonNull // public byte[] getRaw(@NonNull String data) { // return getRaw(data.getBytes(StandardCharsets.UTF_8)); // } // // @NonNull // public String getHex(@NonNull byte[] data) { // StringBuilder sb = new StringBuilder(); // for (byte b : getRaw(data)) { // sb.append(String.format("%02x", 0xFF & b)); // } // return sb.toString(); // } // // @NonNull // public String getHex(@NonNull String data) { // return getHex(data.getBytes(StandardCharsets.UTF_8)); // } // // }
import android.content.Context; import android.content.SharedPreferences; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.Log; import com.google.gson.JsonParseException; import org.cnodejs.android.md.util.DigestUtils; import java.lang.reflect.Type;
package org.cnodejs.android.md.model.util; public final class SharedUtils { private SharedUtils() {} private static final String TAG = "SharedUtils"; @NonNull public static SharedPreferencesWrapper with(@NonNull Context context, @NonNull String name) {
// Path: app/src/main/java/org/cnodejs/android/md/util/DigestUtils.java // public final class DigestUtils { // // public static final DigestUtils sha256 = new DigestUtils("SHA-256"); // // private final String algorithm; // // private DigestUtils(@NonNull String algorithm) { // this.algorithm = algorithm; // } // // @NonNull // public byte[] getRaw(@NonNull byte[] data) { // try { // return MessageDigest.getInstance(algorithm).digest(data); // } catch (NoSuchAlgorithmException e) { // throw new RuntimeException(e); // } // } // // @NonNull // public byte[] getRaw(@NonNull String data) { // return getRaw(data.getBytes(StandardCharsets.UTF_8)); // } // // @NonNull // public String getHex(@NonNull byte[] data) { // StringBuilder sb = new StringBuilder(); // for (byte b : getRaw(data)) { // sb.append(String.format("%02x", 0xFF & b)); // } // return sb.toString(); // } // // @NonNull // public String getHex(@NonNull String data) { // return getHex(data.getBytes(StandardCharsets.UTF_8)); // } // // } // Path: app/src/main/java/org/cnodejs/android/md/model/util/SharedUtils.java import android.content.Context; import android.content.SharedPreferences; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.Log; import com.google.gson.JsonParseException; import org.cnodejs.android.md.util.DigestUtils; import java.lang.reflect.Type; package org.cnodejs.android.md.model.util; public final class SharedUtils { private SharedUtils() {} private static final String TAG = "SharedUtils"; @NonNull public static SharedPreferencesWrapper with(@NonNull Context context, @NonNull String name) {
return new SharedPreferencesWrapper(context.getSharedPreferences(DigestUtils.sha256.getHex(name), Context.MODE_PRIVATE));
TakWolf/CNode-Material-Design
app/src/main/java/org/cnodejs/android/md/ui/widget/NotificationWebView.java
// Path: app/src/main/java/org/cnodejs/android/md/model/entity/Message.java // public class Message { // // public enum Type { // reply, // at // } // // private String id; // // private Type type; // // @SerializedName("has_read") // private boolean read; // // private Author author; // // private TopicSimple topic; // 这里不含Author字段,注意 // // private Reply reply; // 这里不含Author字段,注意 // // @SerializedName("create_at") // private DateTime createAt; // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // @NonNull // public Type getType() { // return type == null ? Type.reply : type; // 保证返回不为空 // } // // public void setType(Type type) { // this.type = type; // } // // public boolean isRead() { // return read; // } // // public void setRead(boolean read) { // this.read = read; // } // // public Author getAuthor() { // return author; // } // // public void setAuthor(Author author) { // this.author = author; // } // // public TopicSimple getTopic() { // return topic; // } // // public void setTopic(TopicSimple topic) { // this.topic = topic; // } // // public Reply getReply() { // return reply; // } // // public void setReply(Reply reply) { // this.reply = reply; // } // // public DateTime getCreateAt() { // return createAt; // } // // public void setCreateAt(DateTime createAt) { // this.createAt = createAt; // } // // } // // Path: app/src/main/java/org/cnodejs/android/md/model/util/EntityUtils.java // public final class EntityUtils { // // private EntityUtils() {} // // public static final Gson gson = new GsonBuilder() // .registerTypeAdapter(DateTime.class, new DateTimeTypeAdapter()) // .create(); // // private static class DateTimeTypeAdapter extends TypeAdapter<DateTime> { // // @Override // public void write(JsonWriter out, DateTime dateTime) throws IOException { // if (dateTime == null) { // out.nullValue(); // } else { // out.value(dateTime.toString()); // } // } // // @Override // public DateTime read(JsonReader in) throws IOException { // if (in.peek() == JsonToken.NULL) { // in.nextNull(); // return null; // } else { // return new DateTime(in.nextString()); // } // } // // } // // } // // Path: app/src/main/java/org/cnodejs/android/md/ui/jsbridge/FormatJavascriptInterface.java // public final class FormatJavascriptInterface { // // public static final String NAME = "formatBridge"; // // @JavascriptInterface // public String getRelativeTimeSpanString(String time) { // return FormatUtils.getRelativeTimeSpanString(new DateTime(time)); // } // // } // // Path: app/src/main/java/org/cnodejs/android/md/ui/jsbridge/ImageJavascriptInterface.java // public final class ImageJavascriptInterface { // // public static final String NAME = "imageBridge"; // // private final Context context; // // public ImageJavascriptInterface(@NonNull Context context) { // this.context = context.getApplicationContext(); // } // // @JavascriptInterface // public void openImage(String imageUrl) { // ImagePreviewActivity.start(context, imageUrl); // } // // } // // Path: app/src/main/java/org/cnodejs/android/md/ui/jsbridge/NotificationJavascriptInterface.java // public final class NotificationJavascriptInterface { // // public static final String NAME = "notificationBridge"; // // private final Context context; // // public NotificationJavascriptInterface(@NonNull Context context) { // this.context = context.getApplicationContext(); // } // // @JavascriptInterface // public void openTopic(String topicId) { // Navigator.TopicWithAutoCompat.start(context, topicId); // } // // @JavascriptInterface // public void openUser(String loginName) { // UserDetailActivity.start(context, loginName); // } // // } // // Path: app/src/main/java/org/cnodejs/android/md/ui/view/IBackToContentTopView.java // public interface IBackToContentTopView { // // void backToContentTop(); // // }
import android.annotation.SuppressLint; import android.content.Context; import android.os.Build; import android.support.annotation.AttrRes; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.annotation.RequiresApi; import android.support.annotation.StyleRes; import android.util.AttributeSet; import org.cnodejs.android.md.model.entity.Message; import org.cnodejs.android.md.model.util.EntityUtils; import org.cnodejs.android.md.ui.jsbridge.FormatJavascriptInterface; import org.cnodejs.android.md.ui.jsbridge.ImageJavascriptInterface; import org.cnodejs.android.md.ui.jsbridge.NotificationJavascriptInterface; import org.cnodejs.android.md.ui.view.IBackToContentTopView; import java.util.List;
package org.cnodejs.android.md.ui.widget; public class NotificationWebView extends CNodeWebView implements IBackToContentTopView { private static final String LIGHT_THEME_PATH = "file:///android_asset/notification_light.html"; private static final String DARK_THEME_PATH = "file:///android_asset/notification_dark.html"; private boolean pageLoaded = false;
// Path: app/src/main/java/org/cnodejs/android/md/model/entity/Message.java // public class Message { // // public enum Type { // reply, // at // } // // private String id; // // private Type type; // // @SerializedName("has_read") // private boolean read; // // private Author author; // // private TopicSimple topic; // 这里不含Author字段,注意 // // private Reply reply; // 这里不含Author字段,注意 // // @SerializedName("create_at") // private DateTime createAt; // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // @NonNull // public Type getType() { // return type == null ? Type.reply : type; // 保证返回不为空 // } // // public void setType(Type type) { // this.type = type; // } // // public boolean isRead() { // return read; // } // // public void setRead(boolean read) { // this.read = read; // } // // public Author getAuthor() { // return author; // } // // public void setAuthor(Author author) { // this.author = author; // } // // public TopicSimple getTopic() { // return topic; // } // // public void setTopic(TopicSimple topic) { // this.topic = topic; // } // // public Reply getReply() { // return reply; // } // // public void setReply(Reply reply) { // this.reply = reply; // } // // public DateTime getCreateAt() { // return createAt; // } // // public void setCreateAt(DateTime createAt) { // this.createAt = createAt; // } // // } // // Path: app/src/main/java/org/cnodejs/android/md/model/util/EntityUtils.java // public final class EntityUtils { // // private EntityUtils() {} // // public static final Gson gson = new GsonBuilder() // .registerTypeAdapter(DateTime.class, new DateTimeTypeAdapter()) // .create(); // // private static class DateTimeTypeAdapter extends TypeAdapter<DateTime> { // // @Override // public void write(JsonWriter out, DateTime dateTime) throws IOException { // if (dateTime == null) { // out.nullValue(); // } else { // out.value(dateTime.toString()); // } // } // // @Override // public DateTime read(JsonReader in) throws IOException { // if (in.peek() == JsonToken.NULL) { // in.nextNull(); // return null; // } else { // return new DateTime(in.nextString()); // } // } // // } // // } // // Path: app/src/main/java/org/cnodejs/android/md/ui/jsbridge/FormatJavascriptInterface.java // public final class FormatJavascriptInterface { // // public static final String NAME = "formatBridge"; // // @JavascriptInterface // public String getRelativeTimeSpanString(String time) { // return FormatUtils.getRelativeTimeSpanString(new DateTime(time)); // } // // } // // Path: app/src/main/java/org/cnodejs/android/md/ui/jsbridge/ImageJavascriptInterface.java // public final class ImageJavascriptInterface { // // public static final String NAME = "imageBridge"; // // private final Context context; // // public ImageJavascriptInterface(@NonNull Context context) { // this.context = context.getApplicationContext(); // } // // @JavascriptInterface // public void openImage(String imageUrl) { // ImagePreviewActivity.start(context, imageUrl); // } // // } // // Path: app/src/main/java/org/cnodejs/android/md/ui/jsbridge/NotificationJavascriptInterface.java // public final class NotificationJavascriptInterface { // // public static final String NAME = "notificationBridge"; // // private final Context context; // // public NotificationJavascriptInterface(@NonNull Context context) { // this.context = context.getApplicationContext(); // } // // @JavascriptInterface // public void openTopic(String topicId) { // Navigator.TopicWithAutoCompat.start(context, topicId); // } // // @JavascriptInterface // public void openUser(String loginName) { // UserDetailActivity.start(context, loginName); // } // // } // // Path: app/src/main/java/org/cnodejs/android/md/ui/view/IBackToContentTopView.java // public interface IBackToContentTopView { // // void backToContentTop(); // // } // Path: app/src/main/java/org/cnodejs/android/md/ui/widget/NotificationWebView.java import android.annotation.SuppressLint; import android.content.Context; import android.os.Build; import android.support.annotation.AttrRes; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.annotation.RequiresApi; import android.support.annotation.StyleRes; import android.util.AttributeSet; import org.cnodejs.android.md.model.entity.Message; import org.cnodejs.android.md.model.util.EntityUtils; import org.cnodejs.android.md.ui.jsbridge.FormatJavascriptInterface; import org.cnodejs.android.md.ui.jsbridge.ImageJavascriptInterface; import org.cnodejs.android.md.ui.jsbridge.NotificationJavascriptInterface; import org.cnodejs.android.md.ui.view.IBackToContentTopView; import java.util.List; package org.cnodejs.android.md.ui.widget; public class NotificationWebView extends CNodeWebView implements IBackToContentTopView { private static final String LIGHT_THEME_PATH = "file:///android_asset/notification_light.html"; private static final String DARK_THEME_PATH = "file:///android_asset/notification_dark.html"; private boolean pageLoaded = false;
private List<Message> messageList = null;
TakWolf/CNode-Material-Design
app/src/main/java/org/cnodejs/android/md/ui/adapter/TabSpinnerAdapter.java
// Path: app/src/main/java/org/cnodejs/android/md/model/entity/Tab.java // public enum Tab { // // all(R.string.app_name), // // good(R.string.tab_good), // // unknown(R.string.tab_unknown), // // share(R.string.tab_share), // // ask(R.string.tab_ask), // // job(R.string.tab_job), // // dev(R.string.tab_dev); // // @StringRes // private final int nameId; // // Tab(@StringRes int nameId) { // this.nameId = nameId; // } // // @StringRes // public int getNameId() { // return nameId; // } // // public static List<Tab> getPublishableTabList() { // List<Tab> tabList = new ArrayList<>(); // if (BuildConfig.DEBUG) { // tabList.add(dev); // } // tabList.add(share); // tabList.add(ask); // tabList.add(job); // return tabList; // } // // }
import android.content.Context; import android.support.annotation.LayoutRes; import android.support.annotation.NonNull; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import org.cnodejs.android.md.model.entity.Tab; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife;
package org.cnodejs.android.md.ui.adapter; public class TabSpinnerAdapter extends BaseAdapter { private final LayoutInflater inflater;
// Path: app/src/main/java/org/cnodejs/android/md/model/entity/Tab.java // public enum Tab { // // all(R.string.app_name), // // good(R.string.tab_good), // // unknown(R.string.tab_unknown), // // share(R.string.tab_share), // // ask(R.string.tab_ask), // // job(R.string.tab_job), // // dev(R.string.tab_dev); // // @StringRes // private final int nameId; // // Tab(@StringRes int nameId) { // this.nameId = nameId; // } // // @StringRes // public int getNameId() { // return nameId; // } // // public static List<Tab> getPublishableTabList() { // List<Tab> tabList = new ArrayList<>(); // if (BuildConfig.DEBUG) { // tabList.add(dev); // } // tabList.add(share); // tabList.add(ask); // tabList.add(job); // return tabList; // } // // } // Path: app/src/main/java/org/cnodejs/android/md/ui/adapter/TabSpinnerAdapter.java import android.content.Context; import android.support.annotation.LayoutRes; import android.support.annotation.NonNull; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import org.cnodejs.android.md.model.entity.Tab; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; package org.cnodejs.android.md.ui.adapter; public class TabSpinnerAdapter extends BaseAdapter { private final LayoutInflater inflater;
private final List<Tab> tabList = new ArrayList<>();
TakWolf/CNode-Material-Design
app/src/main/java/org/cnodejs/android/md/ui/activity/ScanQRCodeActivity.java
// Path: app/src/main/java/org/cnodejs/android/md/ui/dialog/AlertDialogUtils.java // public final class AlertDialogUtils { // // private AlertDialogUtils() {} // // public static AlertDialog.Builder createBuilderWithAutoTheme(@NonNull Activity activity) { // return new AlertDialog.Builder(activity, SettingShared.isEnableThemeDark(activity) ? R.style.AppDialogDark_Alert : R.style.AppDialogLight_Alert); // } // // } // // Path: app/src/main/java/org/cnodejs/android/md/ui/listener/NavigationFinishClickListener.java // public class NavigationFinishClickListener implements View.OnClickListener { // // private final Activity activity; // // public NavigationFinishClickListener(@NonNull Activity activity) { // this.activity = activity; // } // // @Override // public void onClick(View v) { // ActivityCompat.finishAfterTransition(activity); // } // // }
import android.Manifest; import android.app.Activity; import android.content.DialogInterface; import android.content.Intent; import android.graphics.PointF; import android.net.Uri; import android.os.Bundle; import android.provider.Settings; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.annotation.RequiresPermission; import android.support.v4.app.ActivityCompat; import android.support.v7.widget.Toolbar; import android.view.View; import android.view.animation.AnimationUtils; import com.dlazaro66.qrcodereaderview.QRCodeReaderView; import org.cnodejs.android.md.R; import org.cnodejs.android.md.ui.dialog.AlertDialogUtils; import org.cnodejs.android.md.ui.listener.NavigationFinishClickListener; import butterknife.BindView; import butterknife.ButterKnife;
package org.cnodejs.android.md.ui.activity; public class ScanQRCodeActivity extends StatusBarActivity implements QRCodeReaderView.OnQRCodeReadListener { private static final String[] PERMISSIONS = {Manifest.permission.CAMERA}; public static final String EXTRA_QR_CODE = "qrCode"; public static void requestPermissions(@NonNull final Activity activity, final int requestCode) { if (ActivityCompat.shouldShowRequestPermissionRationale(activity, Manifest.permission.CAMERA)) {
// Path: app/src/main/java/org/cnodejs/android/md/ui/dialog/AlertDialogUtils.java // public final class AlertDialogUtils { // // private AlertDialogUtils() {} // // public static AlertDialog.Builder createBuilderWithAutoTheme(@NonNull Activity activity) { // return new AlertDialog.Builder(activity, SettingShared.isEnableThemeDark(activity) ? R.style.AppDialogDark_Alert : R.style.AppDialogLight_Alert); // } // // } // // Path: app/src/main/java/org/cnodejs/android/md/ui/listener/NavigationFinishClickListener.java // public class NavigationFinishClickListener implements View.OnClickListener { // // private final Activity activity; // // public NavigationFinishClickListener(@NonNull Activity activity) { // this.activity = activity; // } // // @Override // public void onClick(View v) { // ActivityCompat.finishAfterTransition(activity); // } // // } // Path: app/src/main/java/org/cnodejs/android/md/ui/activity/ScanQRCodeActivity.java import android.Manifest; import android.app.Activity; import android.content.DialogInterface; import android.content.Intent; import android.graphics.PointF; import android.net.Uri; import android.os.Bundle; import android.provider.Settings; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.annotation.RequiresPermission; import android.support.v4.app.ActivityCompat; import android.support.v7.widget.Toolbar; import android.view.View; import android.view.animation.AnimationUtils; import com.dlazaro66.qrcodereaderview.QRCodeReaderView; import org.cnodejs.android.md.R; import org.cnodejs.android.md.ui.dialog.AlertDialogUtils; import org.cnodejs.android.md.ui.listener.NavigationFinishClickListener; import butterknife.BindView; import butterknife.ButterKnife; package org.cnodejs.android.md.ui.activity; public class ScanQRCodeActivity extends StatusBarActivity implements QRCodeReaderView.OnQRCodeReadListener { private static final String[] PERMISSIONS = {Manifest.permission.CAMERA}; public static final String EXTRA_QR_CODE = "qrCode"; public static void requestPermissions(@NonNull final Activity activity, final int requestCode) { if (ActivityCompat.shouldShowRequestPermissionRationale(activity, Manifest.permission.CAMERA)) {
AlertDialogUtils.createBuilderWithAutoTheme(activity)
TakWolf/CNode-Material-Design
app/src/main/java/org/cnodejs/android/md/ui/activity/ScanQRCodeActivity.java
// Path: app/src/main/java/org/cnodejs/android/md/ui/dialog/AlertDialogUtils.java // public final class AlertDialogUtils { // // private AlertDialogUtils() {} // // public static AlertDialog.Builder createBuilderWithAutoTheme(@NonNull Activity activity) { // return new AlertDialog.Builder(activity, SettingShared.isEnableThemeDark(activity) ? R.style.AppDialogDark_Alert : R.style.AppDialogLight_Alert); // } // // } // // Path: app/src/main/java/org/cnodejs/android/md/ui/listener/NavigationFinishClickListener.java // public class NavigationFinishClickListener implements View.OnClickListener { // // private final Activity activity; // // public NavigationFinishClickListener(@NonNull Activity activity) { // this.activity = activity; // } // // @Override // public void onClick(View v) { // ActivityCompat.finishAfterTransition(activity); // } // // }
import android.Manifest; import android.app.Activity; import android.content.DialogInterface; import android.content.Intent; import android.graphics.PointF; import android.net.Uri; import android.os.Bundle; import android.provider.Settings; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.annotation.RequiresPermission; import android.support.v4.app.ActivityCompat; import android.support.v7.widget.Toolbar; import android.view.View; import android.view.animation.AnimationUtils; import com.dlazaro66.qrcodereaderview.QRCodeReaderView; import org.cnodejs.android.md.R; import org.cnodejs.android.md.ui.dialog.AlertDialogUtils; import org.cnodejs.android.md.ui.listener.NavigationFinishClickListener; import butterknife.BindView; import butterknife.ButterKnife;
@Override public void onClick(DialogInterface dialog, int which) { activity.startActivity(new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.fromParts("package", activity.getPackageName(), null))); } }) .show(); } @RequiresPermission(Manifest.permission.CAMERA) public static void startForResult(@NonNull Activity activity, int requestCode) { activity.startActivityForResult(new Intent(activity, ScanQRCodeActivity.class), requestCode); } @BindView(R.id.toolbar) Toolbar toolbar; @BindView(R.id.qr_view) QRCodeReaderView qrCodeReaderView; @BindView(R.id.icon_line) View iconLine; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_scan_qr_code); ButterKnife.bind(this);
// Path: app/src/main/java/org/cnodejs/android/md/ui/dialog/AlertDialogUtils.java // public final class AlertDialogUtils { // // private AlertDialogUtils() {} // // public static AlertDialog.Builder createBuilderWithAutoTheme(@NonNull Activity activity) { // return new AlertDialog.Builder(activity, SettingShared.isEnableThemeDark(activity) ? R.style.AppDialogDark_Alert : R.style.AppDialogLight_Alert); // } // // } // // Path: app/src/main/java/org/cnodejs/android/md/ui/listener/NavigationFinishClickListener.java // public class NavigationFinishClickListener implements View.OnClickListener { // // private final Activity activity; // // public NavigationFinishClickListener(@NonNull Activity activity) { // this.activity = activity; // } // // @Override // public void onClick(View v) { // ActivityCompat.finishAfterTransition(activity); // } // // } // Path: app/src/main/java/org/cnodejs/android/md/ui/activity/ScanQRCodeActivity.java import android.Manifest; import android.app.Activity; import android.content.DialogInterface; import android.content.Intent; import android.graphics.PointF; import android.net.Uri; import android.os.Bundle; import android.provider.Settings; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.annotation.RequiresPermission; import android.support.v4.app.ActivityCompat; import android.support.v7.widget.Toolbar; import android.view.View; import android.view.animation.AnimationUtils; import com.dlazaro66.qrcodereaderview.QRCodeReaderView; import org.cnodejs.android.md.R; import org.cnodejs.android.md.ui.dialog.AlertDialogUtils; import org.cnodejs.android.md.ui.listener.NavigationFinishClickListener; import butterknife.BindView; import butterknife.ButterKnife; @Override public void onClick(DialogInterface dialog, int which) { activity.startActivity(new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.fromParts("package", activity.getPackageName(), null))); } }) .show(); } @RequiresPermission(Manifest.permission.CAMERA) public static void startForResult(@NonNull Activity activity, int requestCode) { activity.startActivityForResult(new Intent(activity, ScanQRCodeActivity.class), requestCode); } @BindView(R.id.toolbar) Toolbar toolbar; @BindView(R.id.qr_view) QRCodeReaderView qrCodeReaderView; @BindView(R.id.icon_line) View iconLine; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_scan_qr_code); ButterKnife.bind(this);
toolbar.setNavigationOnClickListener(new NavigationFinishClickListener(this));
TakWolf/CNode-Material-Design
app/src/main/java/org/cnodejs/android/md/ui/view/ICreateReplyView.java
// Path: app/src/main/java/org/cnodejs/android/md/model/entity/Reply.java // public class Reply { // // public enum UpAction { // up, // down // } // // private String id; // // private Author author; // // private String content; // // @SerializedName("ups") // private List<String> upList; // // @SerializedName("reply_id") // private String replyId; // // @SerializedName("create_at") // private DateTime createAt; // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public Author getAuthor() { // return author; // } // // public void setAuthor(Author author) { // this.author = author; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // cleanContentCache(); // } // // public List<String> getUpList() { // return upList; // } // // public void setUpList(List<String> upList) { // this.upList = upList; // } // // public String getReplyId() { // return replyId; // } // // public void setReplyId(String replyId) { // this.replyId = replyId; // } // // public DateTime getCreateAt() { // return createAt; // } // // public void setCreateAt(DateTime createAt) { // this.createAt = createAt; // } // // /** // * Html渲染缓存 // */ // // @SerializedName("content_html") // private String contentHtml; // // @SerializedName("content_summary") // private String contentSummary; // // public void markSureHandleContent() { // if (contentHtml == null || contentSummary == null) { // Document document; // if (ApiDefine.MD_RENDER) { // document = FormatUtils.handleHtml(content); // } else { // document = FormatUtils.handleHtml(FormatUtils.renderMarkdown(content)); // } // if (contentHtml == null) { // contentHtml = document.body().html(); // } // if (contentSummary == null) { // contentSummary = document.body().text().trim(); // } // } // } // // public void cleanContentCache() { // contentHtml = null; // contentSummary = null; // } // // public String getContentHtml() { // markSureHandleContent(); // return contentHtml; // } // // public String getContentSummary() { // markSureHandleContent(); // return contentSummary; // } // // public void setContentFromLocal(String content) { // if (ApiDefine.MD_RENDER) { // this.content = FormatUtils.renderMarkdown(content); // } else { // this.content = content; // } // cleanContentCache(); // } // // }
import android.support.annotation.NonNull; import org.cnodejs.android.md.model.entity.Reply;
package org.cnodejs.android.md.ui.view; public interface ICreateReplyView { void showWindow(); void dismissWindow();
// Path: app/src/main/java/org/cnodejs/android/md/model/entity/Reply.java // public class Reply { // // public enum UpAction { // up, // down // } // // private String id; // // private Author author; // // private String content; // // @SerializedName("ups") // private List<String> upList; // // @SerializedName("reply_id") // private String replyId; // // @SerializedName("create_at") // private DateTime createAt; // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public Author getAuthor() { // return author; // } // // public void setAuthor(Author author) { // this.author = author; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // cleanContentCache(); // } // // public List<String> getUpList() { // return upList; // } // // public void setUpList(List<String> upList) { // this.upList = upList; // } // // public String getReplyId() { // return replyId; // } // // public void setReplyId(String replyId) { // this.replyId = replyId; // } // // public DateTime getCreateAt() { // return createAt; // } // // public void setCreateAt(DateTime createAt) { // this.createAt = createAt; // } // // /** // * Html渲染缓存 // */ // // @SerializedName("content_html") // private String contentHtml; // // @SerializedName("content_summary") // private String contentSummary; // // public void markSureHandleContent() { // if (contentHtml == null || contentSummary == null) { // Document document; // if (ApiDefine.MD_RENDER) { // document = FormatUtils.handleHtml(content); // } else { // document = FormatUtils.handleHtml(FormatUtils.renderMarkdown(content)); // } // if (contentHtml == null) { // contentHtml = document.body().html(); // } // if (contentSummary == null) { // contentSummary = document.body().text().trim(); // } // } // } // // public void cleanContentCache() { // contentHtml = null; // contentSummary = null; // } // // public String getContentHtml() { // markSureHandleContent(); // return contentHtml; // } // // public String getContentSummary() { // markSureHandleContent(); // return contentSummary; // } // // public void setContentFromLocal(String content) { // if (ApiDefine.MD_RENDER) { // this.content = FormatUtils.renderMarkdown(content); // } else { // this.content = content; // } // cleanContentCache(); // } // // } // Path: app/src/main/java/org/cnodejs/android/md/ui/view/ICreateReplyView.java import android.support.annotation.NonNull; import org.cnodejs.android.md.model.entity.Reply; package org.cnodejs.android.md.ui.view; public interface ICreateReplyView { void showWindow(); void dismissWindow();
void onAt(@NonNull Reply target, @NonNull Integer targetPosition);
TakWolf/CNode-Material-Design
app/src/main/java/org/cnodejs/android/md/ui/dialog/ProgressDialog.java
// Path: app/src/main/java/org/cnodejs/android/md/model/storage/SettingShared.java // public final class SettingShared { // // private SettingShared() {} // // private static final String TAG = "SettingShared"; // // private static final String KEY_ENABLE_NOTIFICATION = "enableNotification"; // private static final String KEY_ENABLE_THEME_DARK = "enableThemeDark"; // private static final String KEY_ENABLE_TOPIC_DRAFT = "enableTopicDraft"; // private static final String KEY_ENABLE_TOPIC_SIGN = "enableTopicSign"; // private static final String KEY_TOPIC_SIGN_CONTENT = "topicSignContent"; // private static final String KEY_ENABLE_TOPIC_RENDER_COMPAT = "enableTopicRenderCompat"; // private static final String KEY_SHOW_TOPIC_RENDER_COMPAT_TIP = "showTopicRenderCompatTip"; // // public static final String DEFAULT_TOPIC_SIGN_CONTENT = "来自酷炫的 [CNodeMD](https://github.com/TakWolf/CNode-Material-Design)"; // // public static boolean isEnableNotification(@NonNull Context context) { // return SharedUtils.with(context, TAG).getBoolean(KEY_ENABLE_NOTIFICATION, true); // } // // public static void setEnableNotification(@NonNull Context context, boolean enable) { // SharedUtils.with(context, TAG).setBoolean(KEY_ENABLE_NOTIFICATION, enable); // } // // public static boolean isEnableThemeDark(@NonNull Context context) { // return SharedUtils.with(context, TAG).getBoolean(KEY_ENABLE_THEME_DARK, false); // } // // public static void setEnableThemeDark(@NonNull Context context, boolean enable) { // SharedUtils.with(context, TAG).setBoolean(KEY_ENABLE_THEME_DARK, enable); // } // // public static boolean isEnableTopicDraft(@NonNull Context context) { // return SharedUtils.with(context, TAG).getBoolean(KEY_ENABLE_TOPIC_DRAFT, true); // } // // public static void setEnableTopicDraft(@NonNull Context context, boolean enable) { // SharedUtils.with(context, TAG).setBoolean(KEY_ENABLE_TOPIC_DRAFT, enable); // } // // public static boolean isEnableTopicSign(@NonNull Context context) { // return SharedUtils.with(context, TAG).getBoolean(KEY_ENABLE_TOPIC_SIGN, true); // } // // public static void setEnableTopicSign(@NonNull Context context, boolean enable) { // SharedUtils.with(context, TAG).setBoolean(KEY_ENABLE_TOPIC_SIGN, enable); // } // // public static String getTopicSignContent(@NonNull Context context) { // return SharedUtils.with(context, TAG).getString(KEY_TOPIC_SIGN_CONTENT, DEFAULT_TOPIC_SIGN_CONTENT); // } // // public static void setTopicSignContent(@NonNull Context context, @Nullable String content) { // SharedUtils.with(context, TAG).setString(KEY_TOPIC_SIGN_CONTENT, content); // } // // public static boolean isEnableTopicRenderCompat(@NonNull Context context) { // return SharedUtils.with(context, TAG).getBoolean(KEY_ENABLE_TOPIC_RENDER_COMPAT, true); // } // // public static void setEnableTopicRenderCompat(@NonNull Context context, boolean enable) { // SharedUtils.with(context, TAG).setBoolean(KEY_ENABLE_TOPIC_RENDER_COMPAT, enable); // } // // public static boolean isShowTopicRenderCompatTip(@NonNull Context context) { // return SharedUtils.with(context, TAG).getBoolean(KEY_SHOW_TOPIC_RENDER_COMPAT_TIP, true); // } // // public static void markShowTopicRenderCompatTip(@NonNull Context context) { // SharedUtils.with(context, TAG).setBoolean(KEY_SHOW_TOPIC_RENDER_COMPAT_TIP, false); // } // // }
import android.app.Activity; import android.support.annotation.NonNull; import android.support.annotation.StyleRes; import android.support.v7.app.AppCompatDialog; import com.pnikosis.materialishprogress.ProgressWheel; import org.cnodejs.android.md.R; import org.cnodejs.android.md.model.storage.SettingShared; import butterknife.BindView; import butterknife.ButterKnife;
package org.cnodejs.android.md.ui.dialog; public class ProgressDialog extends AppCompatDialog { public static ProgressDialog createWithAutoTheme(@NonNull Activity activity) {
// Path: app/src/main/java/org/cnodejs/android/md/model/storage/SettingShared.java // public final class SettingShared { // // private SettingShared() {} // // private static final String TAG = "SettingShared"; // // private static final String KEY_ENABLE_NOTIFICATION = "enableNotification"; // private static final String KEY_ENABLE_THEME_DARK = "enableThemeDark"; // private static final String KEY_ENABLE_TOPIC_DRAFT = "enableTopicDraft"; // private static final String KEY_ENABLE_TOPIC_SIGN = "enableTopicSign"; // private static final String KEY_TOPIC_SIGN_CONTENT = "topicSignContent"; // private static final String KEY_ENABLE_TOPIC_RENDER_COMPAT = "enableTopicRenderCompat"; // private static final String KEY_SHOW_TOPIC_RENDER_COMPAT_TIP = "showTopicRenderCompatTip"; // // public static final String DEFAULT_TOPIC_SIGN_CONTENT = "来自酷炫的 [CNodeMD](https://github.com/TakWolf/CNode-Material-Design)"; // // public static boolean isEnableNotification(@NonNull Context context) { // return SharedUtils.with(context, TAG).getBoolean(KEY_ENABLE_NOTIFICATION, true); // } // // public static void setEnableNotification(@NonNull Context context, boolean enable) { // SharedUtils.with(context, TAG).setBoolean(KEY_ENABLE_NOTIFICATION, enable); // } // // public static boolean isEnableThemeDark(@NonNull Context context) { // return SharedUtils.with(context, TAG).getBoolean(KEY_ENABLE_THEME_DARK, false); // } // // public static void setEnableThemeDark(@NonNull Context context, boolean enable) { // SharedUtils.with(context, TAG).setBoolean(KEY_ENABLE_THEME_DARK, enable); // } // // public static boolean isEnableTopicDraft(@NonNull Context context) { // return SharedUtils.with(context, TAG).getBoolean(KEY_ENABLE_TOPIC_DRAFT, true); // } // // public static void setEnableTopicDraft(@NonNull Context context, boolean enable) { // SharedUtils.with(context, TAG).setBoolean(KEY_ENABLE_TOPIC_DRAFT, enable); // } // // public static boolean isEnableTopicSign(@NonNull Context context) { // return SharedUtils.with(context, TAG).getBoolean(KEY_ENABLE_TOPIC_SIGN, true); // } // // public static void setEnableTopicSign(@NonNull Context context, boolean enable) { // SharedUtils.with(context, TAG).setBoolean(KEY_ENABLE_TOPIC_SIGN, enable); // } // // public static String getTopicSignContent(@NonNull Context context) { // return SharedUtils.with(context, TAG).getString(KEY_TOPIC_SIGN_CONTENT, DEFAULT_TOPIC_SIGN_CONTENT); // } // // public static void setTopicSignContent(@NonNull Context context, @Nullable String content) { // SharedUtils.with(context, TAG).setString(KEY_TOPIC_SIGN_CONTENT, content); // } // // public static boolean isEnableTopicRenderCompat(@NonNull Context context) { // return SharedUtils.with(context, TAG).getBoolean(KEY_ENABLE_TOPIC_RENDER_COMPAT, true); // } // // public static void setEnableTopicRenderCompat(@NonNull Context context, boolean enable) { // SharedUtils.with(context, TAG).setBoolean(KEY_ENABLE_TOPIC_RENDER_COMPAT, enable); // } // // public static boolean isShowTopicRenderCompatTip(@NonNull Context context) { // return SharedUtils.with(context, TAG).getBoolean(KEY_SHOW_TOPIC_RENDER_COMPAT_TIP, true); // } // // public static void markShowTopicRenderCompatTip(@NonNull Context context) { // SharedUtils.with(context, TAG).setBoolean(KEY_SHOW_TOPIC_RENDER_COMPAT_TIP, false); // } // // } // Path: app/src/main/java/org/cnodejs/android/md/ui/dialog/ProgressDialog.java import android.app.Activity; import android.support.annotation.NonNull; import android.support.annotation.StyleRes; import android.support.v7.app.AppCompatDialog; import com.pnikosis.materialishprogress.ProgressWheel; import org.cnodejs.android.md.R; import org.cnodejs.android.md.model.storage.SettingShared; import butterknife.BindView; import butterknife.ButterKnife; package org.cnodejs.android.md.ui.dialog; public class ProgressDialog extends AppCompatDialog { public static ProgressDialog createWithAutoTheme(@NonNull Activity activity) {
return new ProgressDialog(activity, SettingShared.isEnableThemeDark(activity) ? R.style.AppDialogDark_Progress : R.style.AppDialogLight_Progress);
TakWolf/CNode-Material-Design
app/src/main/java/org/cnodejs/android/md/ui/widget/NavigationItem.java
// Path: app/src/main/java/org/cnodejs/android/md/util/ResUtils.java // public final class ResUtils { // // private ResUtils() {} // // public static int getStatusBarHeight(@NonNull Context context) { // int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android"); // return resourceId > 0 ? context.getResources().getDimensionPixelSize(resourceId) : 0; // } // // @ColorInt // public static int getThemeAttrColor(@NonNull Context context, @AttrRes int attr) { // TypedArray a = context.obtainStyledAttributes(null, new int[]{attr}); // try { // return a.getColor(0, 0); // } finally { // a.recycle(); // } // } // // public static String getRawString(@NonNull Context context, @RawRes int rawId) throws IOException { // InputStream is = context.getResources().openRawResource(rawId); // BufferedReader reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8)); // StringBuilder sb = new StringBuilder(); // String line; // while ((line = reader.readLine()) != null) { // sb.append(line).append("\n"); // } // if (sb.length() > 0) { // sb.deleteCharAt(sb.length() - 1); // } // reader.close(); // return sb.toString(); // } // // }
import android.content.Context; import android.content.res.TypedArray; import android.graphics.Color; import android.graphics.drawable.Drawable; import android.os.Build; import android.support.annotation.AttrRes; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.annotation.RequiresApi; import android.support.annotation.StyleRes; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.widget.Checkable; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.TextView; import org.cnodejs.android.md.R; import org.cnodejs.android.md.util.ResUtils; import butterknife.BindView; import butterknife.ButterKnife;
init(context, null, 0, 0); } public NavigationItem(@NonNull Context context, @Nullable AttributeSet attrs) { super(context, attrs); init(context, attrs, 0, 0); } public NavigationItem(@NonNull Context context, @Nullable AttributeSet attrs, @AttrRes int defStyleAttr) { super(context, attrs, defStyleAttr); init(context, attrs, defStyleAttr, 0); } @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) public NavigationItem(@NonNull Context context, @Nullable AttributeSet attrs, @AttrRes int defStyleAttr, @StyleRes int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); init(context, attrs, defStyleAttr, defStyleRes); } private void init(@NonNull Context context, @Nullable AttributeSet attrs, @AttrRes int defStyleAttr, @StyleRes int defStyleRes) { LayoutInflater.from(context).inflate(R.layout.widget_navigation_item, this, true); ButterKnife.bind(this, this); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.NavigationItem, defStyleAttr, defStyleRes); iconNormal = a.getDrawable(R.styleable.NavigationItem_iconNormal); iconChecked = a.getDrawable(R.styleable.NavigationItem_iconChecked); checked = a.getBoolean(R.styleable.NavigationItem_android_checked, false); imgIcon.setImageDrawable(checked ? iconChecked : iconNormal);
// Path: app/src/main/java/org/cnodejs/android/md/util/ResUtils.java // public final class ResUtils { // // private ResUtils() {} // // public static int getStatusBarHeight(@NonNull Context context) { // int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android"); // return resourceId > 0 ? context.getResources().getDimensionPixelSize(resourceId) : 0; // } // // @ColorInt // public static int getThemeAttrColor(@NonNull Context context, @AttrRes int attr) { // TypedArray a = context.obtainStyledAttributes(null, new int[]{attr}); // try { // return a.getColor(0, 0); // } finally { // a.recycle(); // } // } // // public static String getRawString(@NonNull Context context, @RawRes int rawId) throws IOException { // InputStream is = context.getResources().openRawResource(rawId); // BufferedReader reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8)); // StringBuilder sb = new StringBuilder(); // String line; // while ((line = reader.readLine()) != null) { // sb.append(line).append("\n"); // } // if (sb.length() > 0) { // sb.deleteCharAt(sb.length() - 1); // } // reader.close(); // return sb.toString(); // } // // } // Path: app/src/main/java/org/cnodejs/android/md/ui/widget/NavigationItem.java import android.content.Context; import android.content.res.TypedArray; import android.graphics.Color; import android.graphics.drawable.Drawable; import android.os.Build; import android.support.annotation.AttrRes; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.annotation.RequiresApi; import android.support.annotation.StyleRes; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.widget.Checkable; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.TextView; import org.cnodejs.android.md.R; import org.cnodejs.android.md.util.ResUtils; import butterknife.BindView; import butterknife.ButterKnife; init(context, null, 0, 0); } public NavigationItem(@NonNull Context context, @Nullable AttributeSet attrs) { super(context, attrs); init(context, attrs, 0, 0); } public NavigationItem(@NonNull Context context, @Nullable AttributeSet attrs, @AttrRes int defStyleAttr) { super(context, attrs, defStyleAttr); init(context, attrs, defStyleAttr, 0); } @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) public NavigationItem(@NonNull Context context, @Nullable AttributeSet attrs, @AttrRes int defStyleAttr, @StyleRes int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); init(context, attrs, defStyleAttr, defStyleRes); } private void init(@NonNull Context context, @Nullable AttributeSet attrs, @AttrRes int defStyleAttr, @StyleRes int defStyleRes) { LayoutInflater.from(context).inflate(R.layout.widget_navigation_item, this, true); ButterKnife.bind(this, this); TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.NavigationItem, defStyleAttr, defStyleRes); iconNormal = a.getDrawable(R.styleable.NavigationItem_iconNormal); iconChecked = a.getDrawable(R.styleable.NavigationItem_iconChecked); checked = a.getBoolean(R.styleable.NavigationItem_android_checked, false); imgIcon.setImageDrawable(checked ? iconChecked : iconNormal);
tvTitle.setTextColor(ResUtils.getThemeAttrColor(context, checked ? R.attr.colorAccent : android.R.attr.textColorPrimary));
TakWolf/CNode-Material-Design
app/src/main/java/org/cnodejs/android/md/ui/view/IUserDetailView.java
// Path: app/src/main/java/org/cnodejs/android/md/model/entity/Topic.java // public class Topic extends TopicSimple { // // @SerializedName("author_id") // private String authorId; // // private Tab tab; // // private String content; // // private boolean good; // // private boolean top; // // @SerializedName("reply_count") // private int replyCount; // // @SerializedName("visit_count") // private int visitCount; // // @SerializedName("create_at") // private DateTime createAt; // // public String getAuthorId() { // return authorId; // } // // public void setAuthorId(String authorId) { // this.authorId = authorId; // } // // @NonNull // public Tab getTab() { // return tab == null ? Tab.unknown : tab; // 接口中有些话题没有 Tab 属性,这里保证 Tab 不为空 // } // // public void setTab(Tab tab) { // this.tab = tab; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // cleanContentCache(); // } // // public boolean isGood() { // return good; // } // // public void setGood(boolean good) { // this.good = good; // } // // public boolean isTop() { // return top; // } // // public void setTop(boolean top) { // this.top = top; // } // // public int getReplyCount() { // return replyCount; // } // // public void setReplyCount(int replyCount) { // this.replyCount = replyCount; // } // // public int getVisitCount() { // return visitCount; // } // // public void setVisitCount(int visitCount) { // this.visitCount = visitCount; // } // // public DateTime getCreateAt() { // return createAt; // } // // public void setCreateAt(DateTime createAt) { // this.createAt = createAt; // } // // /** // * Html渲染缓存 // */ // // @SerializedName("content_html") // private String contentHtml; // // @SerializedName("content_summary") // private String contentSummary; // // public void markSureHandleContent() { // if (contentHtml == null || contentSummary == null) { // Document document; // if (ApiDefine.MD_RENDER) { // document = FormatUtils.handleHtml(content); // } else { // document = FormatUtils.handleHtml(FormatUtils.renderMarkdown(content)); // } // if (contentHtml == null) { // contentHtml = document.body().html(); // } // if (contentSummary == null) { // contentSummary = document.body().text().trim(); // } // } // } // // public void cleanContentCache() { // contentHtml = null; // contentSummary = null; // } // // public String getContentHtml() { // markSureHandleContent(); // return contentHtml; // } // // public String getContentSummary() { // markSureHandleContent(); // return contentSummary; // } // // } // // Path: app/src/main/java/org/cnodejs/android/md/model/entity/User.java // public class User { // // @SerializedName("loginname") // private String loginName; // // @SerializedName("avatar_url") // private String avatarUrl; // // private String githubUsername; // // @SerializedName("create_at") // private DateTime createAt; // // private int score; // // @SerializedName("recent_topics") // private List<TopicSimple> recentTopicList; // // @SerializedName("recent_replies") // private List<TopicSimple> recentReplyList; // // public String getLoginName() { // return loginName; // } // // public void setLoginName(String loginName) { // this.loginName = loginName; // } // // public String getAvatarUrl() { // 修复头像地址的历史遗留问题 // return FormatUtils.getCompatAvatarUrl(avatarUrl); // } // // public void setAvatarUrl(String avatarUrl) { // this.avatarUrl = avatarUrl; // } // // public String getGithubUsername() { // return githubUsername; // } // // public void setGithubUsername(String githubUsername) { // this.githubUsername = githubUsername; // } // // public DateTime getCreateAt() { // return createAt; // } // // public void setCreateAt(DateTime createAt) { // this.createAt = createAt; // } // // public int getScore() { // return score; // } // // public void setScore(int score) { // this.score = score; // } // // public List<TopicSimple> getRecentTopicList() { // return recentTopicList; // } // // public void setRecentTopicList(List<TopicSimple> recentTopicList) { // this.recentTopicList = recentTopicList; // } // // public List<TopicSimple> getRecentReplyList() { // return recentReplyList; // } // // public void setRecentReplyList(List<TopicSimple> recentReplyList) { // this.recentReplyList = recentReplyList; // } // // }
import android.support.annotation.NonNull; import org.cnodejs.android.md.model.entity.Topic; import org.cnodejs.android.md.model.entity.User; import java.util.List;
package org.cnodejs.android.md.ui.view; public interface IUserDetailView { void onGetUserOk(@NonNull User user);
// Path: app/src/main/java/org/cnodejs/android/md/model/entity/Topic.java // public class Topic extends TopicSimple { // // @SerializedName("author_id") // private String authorId; // // private Tab tab; // // private String content; // // private boolean good; // // private boolean top; // // @SerializedName("reply_count") // private int replyCount; // // @SerializedName("visit_count") // private int visitCount; // // @SerializedName("create_at") // private DateTime createAt; // // public String getAuthorId() { // return authorId; // } // // public void setAuthorId(String authorId) { // this.authorId = authorId; // } // // @NonNull // public Tab getTab() { // return tab == null ? Tab.unknown : tab; // 接口中有些话题没有 Tab 属性,这里保证 Tab 不为空 // } // // public void setTab(Tab tab) { // this.tab = tab; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // cleanContentCache(); // } // // public boolean isGood() { // return good; // } // // public void setGood(boolean good) { // this.good = good; // } // // public boolean isTop() { // return top; // } // // public void setTop(boolean top) { // this.top = top; // } // // public int getReplyCount() { // return replyCount; // } // // public void setReplyCount(int replyCount) { // this.replyCount = replyCount; // } // // public int getVisitCount() { // return visitCount; // } // // public void setVisitCount(int visitCount) { // this.visitCount = visitCount; // } // // public DateTime getCreateAt() { // return createAt; // } // // public void setCreateAt(DateTime createAt) { // this.createAt = createAt; // } // // /** // * Html渲染缓存 // */ // // @SerializedName("content_html") // private String contentHtml; // // @SerializedName("content_summary") // private String contentSummary; // // public void markSureHandleContent() { // if (contentHtml == null || contentSummary == null) { // Document document; // if (ApiDefine.MD_RENDER) { // document = FormatUtils.handleHtml(content); // } else { // document = FormatUtils.handleHtml(FormatUtils.renderMarkdown(content)); // } // if (contentHtml == null) { // contentHtml = document.body().html(); // } // if (contentSummary == null) { // contentSummary = document.body().text().trim(); // } // } // } // // public void cleanContentCache() { // contentHtml = null; // contentSummary = null; // } // // public String getContentHtml() { // markSureHandleContent(); // return contentHtml; // } // // public String getContentSummary() { // markSureHandleContent(); // return contentSummary; // } // // } // // Path: app/src/main/java/org/cnodejs/android/md/model/entity/User.java // public class User { // // @SerializedName("loginname") // private String loginName; // // @SerializedName("avatar_url") // private String avatarUrl; // // private String githubUsername; // // @SerializedName("create_at") // private DateTime createAt; // // private int score; // // @SerializedName("recent_topics") // private List<TopicSimple> recentTopicList; // // @SerializedName("recent_replies") // private List<TopicSimple> recentReplyList; // // public String getLoginName() { // return loginName; // } // // public void setLoginName(String loginName) { // this.loginName = loginName; // } // // public String getAvatarUrl() { // 修复头像地址的历史遗留问题 // return FormatUtils.getCompatAvatarUrl(avatarUrl); // } // // public void setAvatarUrl(String avatarUrl) { // this.avatarUrl = avatarUrl; // } // // public String getGithubUsername() { // return githubUsername; // } // // public void setGithubUsername(String githubUsername) { // this.githubUsername = githubUsername; // } // // public DateTime getCreateAt() { // return createAt; // } // // public void setCreateAt(DateTime createAt) { // this.createAt = createAt; // } // // public int getScore() { // return score; // } // // public void setScore(int score) { // this.score = score; // } // // public List<TopicSimple> getRecentTopicList() { // return recentTopicList; // } // // public void setRecentTopicList(List<TopicSimple> recentTopicList) { // this.recentTopicList = recentTopicList; // } // // public List<TopicSimple> getRecentReplyList() { // return recentReplyList; // } // // public void setRecentReplyList(List<TopicSimple> recentReplyList) { // this.recentReplyList = recentReplyList; // } // // } // Path: app/src/main/java/org/cnodejs/android/md/ui/view/IUserDetailView.java import android.support.annotation.NonNull; import org.cnodejs.android.md.model.entity.Topic; import org.cnodejs.android.md.model.entity.User; import java.util.List; package org.cnodejs.android.md.ui.view; public interface IUserDetailView { void onGetUserOk(@NonNull User user);
void onGetCollectTopicListOk(@NonNull List<Topic> topicList);
TakWolf/CNode-Material-Design
app/src/main/java/org/cnodejs/android/md/ui/view/IMainView.java
// Path: app/src/main/java/org/cnodejs/android/md/model/entity/Tab.java // public enum Tab { // // all(R.string.app_name), // // good(R.string.tab_good), // // unknown(R.string.tab_unknown), // // share(R.string.tab_share), // // ask(R.string.tab_ask), // // job(R.string.tab_job), // // dev(R.string.tab_dev); // // @StringRes // private final int nameId; // // Tab(@StringRes int nameId) { // this.nameId = nameId; // } // // @StringRes // public int getNameId() { // return nameId; // } // // public static List<Tab> getPublishableTabList() { // List<Tab> tabList = new ArrayList<>(); // if (BuildConfig.DEBUG) { // tabList.add(dev); // } // tabList.add(share); // tabList.add(ask); // tabList.add(job); // return tabList; // } // // } // // Path: app/src/main/java/org/cnodejs/android/md/model/entity/Topic.java // public class Topic extends TopicSimple { // // @SerializedName("author_id") // private String authorId; // // private Tab tab; // // private String content; // // private boolean good; // // private boolean top; // // @SerializedName("reply_count") // private int replyCount; // // @SerializedName("visit_count") // private int visitCount; // // @SerializedName("create_at") // private DateTime createAt; // // public String getAuthorId() { // return authorId; // } // // public void setAuthorId(String authorId) { // this.authorId = authorId; // } // // @NonNull // public Tab getTab() { // return tab == null ? Tab.unknown : tab; // 接口中有些话题没有 Tab 属性,这里保证 Tab 不为空 // } // // public void setTab(Tab tab) { // this.tab = tab; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // cleanContentCache(); // } // // public boolean isGood() { // return good; // } // // public void setGood(boolean good) { // this.good = good; // } // // public boolean isTop() { // return top; // } // // public void setTop(boolean top) { // this.top = top; // } // // public int getReplyCount() { // return replyCount; // } // // public void setReplyCount(int replyCount) { // this.replyCount = replyCount; // } // // public int getVisitCount() { // return visitCount; // } // // public void setVisitCount(int visitCount) { // this.visitCount = visitCount; // } // // public DateTime getCreateAt() { // return createAt; // } // // public void setCreateAt(DateTime createAt) { // this.createAt = createAt; // } // // /** // * Html渲染缓存 // */ // // @SerializedName("content_html") // private String contentHtml; // // @SerializedName("content_summary") // private String contentSummary; // // public void markSureHandleContent() { // if (contentHtml == null || contentSummary == null) { // Document document; // if (ApiDefine.MD_RENDER) { // document = FormatUtils.handleHtml(content); // } else { // document = FormatUtils.handleHtml(FormatUtils.renderMarkdown(content)); // } // if (contentHtml == null) { // contentHtml = document.body().html(); // } // if (contentSummary == null) { // contentSummary = document.body().text().trim(); // } // } // } // // public void cleanContentCache() { // contentHtml = null; // contentSummary = null; // } // // public String getContentHtml() { // markSureHandleContent(); // return contentHtml; // } // // public String getContentSummary() { // markSureHandleContent(); // return contentSummary; // } // // }
import android.support.annotation.NonNull; import org.cnodejs.android.md.model.entity.Tab; import org.cnodejs.android.md.model.entity.Topic; import java.util.List;
package org.cnodejs.android.md.ui.view; public interface IMainView { void onSwitchTabOk(@NonNull Tab tab);
// Path: app/src/main/java/org/cnodejs/android/md/model/entity/Tab.java // public enum Tab { // // all(R.string.app_name), // // good(R.string.tab_good), // // unknown(R.string.tab_unknown), // // share(R.string.tab_share), // // ask(R.string.tab_ask), // // job(R.string.tab_job), // // dev(R.string.tab_dev); // // @StringRes // private final int nameId; // // Tab(@StringRes int nameId) { // this.nameId = nameId; // } // // @StringRes // public int getNameId() { // return nameId; // } // // public static List<Tab> getPublishableTabList() { // List<Tab> tabList = new ArrayList<>(); // if (BuildConfig.DEBUG) { // tabList.add(dev); // } // tabList.add(share); // tabList.add(ask); // tabList.add(job); // return tabList; // } // // } // // Path: app/src/main/java/org/cnodejs/android/md/model/entity/Topic.java // public class Topic extends TopicSimple { // // @SerializedName("author_id") // private String authorId; // // private Tab tab; // // private String content; // // private boolean good; // // private boolean top; // // @SerializedName("reply_count") // private int replyCount; // // @SerializedName("visit_count") // private int visitCount; // // @SerializedName("create_at") // private DateTime createAt; // // public String getAuthorId() { // return authorId; // } // // public void setAuthorId(String authorId) { // this.authorId = authorId; // } // // @NonNull // public Tab getTab() { // return tab == null ? Tab.unknown : tab; // 接口中有些话题没有 Tab 属性,这里保证 Tab 不为空 // } // // public void setTab(Tab tab) { // this.tab = tab; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // cleanContentCache(); // } // // public boolean isGood() { // return good; // } // // public void setGood(boolean good) { // this.good = good; // } // // public boolean isTop() { // return top; // } // // public void setTop(boolean top) { // this.top = top; // } // // public int getReplyCount() { // return replyCount; // } // // public void setReplyCount(int replyCount) { // this.replyCount = replyCount; // } // // public int getVisitCount() { // return visitCount; // } // // public void setVisitCount(int visitCount) { // this.visitCount = visitCount; // } // // public DateTime getCreateAt() { // return createAt; // } // // public void setCreateAt(DateTime createAt) { // this.createAt = createAt; // } // // /** // * Html渲染缓存 // */ // // @SerializedName("content_html") // private String contentHtml; // // @SerializedName("content_summary") // private String contentSummary; // // public void markSureHandleContent() { // if (contentHtml == null || contentSummary == null) { // Document document; // if (ApiDefine.MD_RENDER) { // document = FormatUtils.handleHtml(content); // } else { // document = FormatUtils.handleHtml(FormatUtils.renderMarkdown(content)); // } // if (contentHtml == null) { // contentHtml = document.body().html(); // } // if (contentSummary == null) { // contentSummary = document.body().text().trim(); // } // } // } // // public void cleanContentCache() { // contentHtml = null; // contentSummary = null; // } // // public String getContentHtml() { // markSureHandleContent(); // return contentHtml; // } // // public String getContentSummary() { // markSureHandleContent(); // return contentSummary; // } // // } // Path: app/src/main/java/org/cnodejs/android/md/ui/view/IMainView.java import android.support.annotation.NonNull; import org.cnodejs.android.md.model.entity.Tab; import org.cnodejs.android.md.model.entity.Topic; import java.util.List; package org.cnodejs.android.md.ui.view; public interface IMainView { void onSwitchTabOk(@NonNull Tab tab);
void onRefreshTopicListOk(@NonNull List<Topic> topicList);
TakWolf/CNode-Material-Design
app/src/main/java/org/cnodejs/android/md/model/api/CallbackLifecycle.java
// Path: app/src/main/java/org/cnodejs/android/md/model/entity/ErrorResult.java // public class ErrorResult extends Result { // // @NonNull // public static ErrorResult from(@NonNull Response response) { // ErrorResult errorResult = null; // ResponseBody errorBody = response.errorBody(); // if (errorBody != null) { // try { // errorResult = EntityUtils.gson.fromJson(errorBody.string(), ErrorResult.class); // } catch (Throwable ignored) {} // } // if (errorResult == null) { // errorResult = new ErrorResult(); // errorResult.setSuccess(false); // switch (response.code()) { // case 400: // errorResult.setMessage("非法请求"); // break; // case 403: // errorResult.setMessage("非法行为"); // break; // case 404: // errorResult.setMessage("未找到资源"); // break; // case 405: // errorResult.setMessage("非法请求方式"); // break; // case 408: // errorResult.setMessage("请求超时"); // break; // case 500: // errorResult.setMessage("服务器内部错误"); // break; // case 502: // errorResult.setMessage("服务器网关错误"); // break; // case 504: // errorResult.setMessage("服务器网关超时"); // break; // default: // errorResult.setMessage("未知响应:" + response.message()); // break; // } // } // return errorResult; // } // // @NonNull // public static ErrorResult from(@NonNull Throwable t) { // ErrorResult errorResult = new ErrorResult(); // errorResult.setSuccess(false); // if (t instanceof UnknownHostException || t instanceof ConnectException) { // errorResult.setMessage("网络无法连接"); // } else if (t instanceof NoRouteToHostException) { // errorResult.setMessage("无法访问网络"); // } else if (t instanceof SocketTimeoutException) { // errorResult.setMessage("网络访问超时"); // } else if (t instanceof JsonSyntaxException) { // errorResult.setMessage("响应数据格式错误"); // } else { // errorResult.setMessage("未知错误:" + t.getLocalizedMessage()); // } // return errorResult; // } // // @SerializedName("error_msg") // private String message; // // public String getMessage() { // return message; // } // // public void setMessage(String message) { // this.message = message; // } // // } // // Path: app/src/main/java/org/cnodejs/android/md/model/entity/Result.java // public class Result { // // private boolean success; // // public boolean isSuccess() { // return success; // } // // public void setSuccess(boolean success) { // this.success = success; // } // // }
import org.cnodejs.android.md.model.entity.ErrorResult; import org.cnodejs.android.md.model.entity.Result; import okhttp3.Headers;
package org.cnodejs.android.md.model.api; public interface CallbackLifecycle<T extends Result> { boolean onResultOk(int code, Headers headers, T result);
// Path: app/src/main/java/org/cnodejs/android/md/model/entity/ErrorResult.java // public class ErrorResult extends Result { // // @NonNull // public static ErrorResult from(@NonNull Response response) { // ErrorResult errorResult = null; // ResponseBody errorBody = response.errorBody(); // if (errorBody != null) { // try { // errorResult = EntityUtils.gson.fromJson(errorBody.string(), ErrorResult.class); // } catch (Throwable ignored) {} // } // if (errorResult == null) { // errorResult = new ErrorResult(); // errorResult.setSuccess(false); // switch (response.code()) { // case 400: // errorResult.setMessage("非法请求"); // break; // case 403: // errorResult.setMessage("非法行为"); // break; // case 404: // errorResult.setMessage("未找到资源"); // break; // case 405: // errorResult.setMessage("非法请求方式"); // break; // case 408: // errorResult.setMessage("请求超时"); // break; // case 500: // errorResult.setMessage("服务器内部错误"); // break; // case 502: // errorResult.setMessage("服务器网关错误"); // break; // case 504: // errorResult.setMessage("服务器网关超时"); // break; // default: // errorResult.setMessage("未知响应:" + response.message()); // break; // } // } // return errorResult; // } // // @NonNull // public static ErrorResult from(@NonNull Throwable t) { // ErrorResult errorResult = new ErrorResult(); // errorResult.setSuccess(false); // if (t instanceof UnknownHostException || t instanceof ConnectException) { // errorResult.setMessage("网络无法连接"); // } else if (t instanceof NoRouteToHostException) { // errorResult.setMessage("无法访问网络"); // } else if (t instanceof SocketTimeoutException) { // errorResult.setMessage("网络访问超时"); // } else if (t instanceof JsonSyntaxException) { // errorResult.setMessage("响应数据格式错误"); // } else { // errorResult.setMessage("未知错误:" + t.getLocalizedMessage()); // } // return errorResult; // } // // @SerializedName("error_msg") // private String message; // // public String getMessage() { // return message; // } // // public void setMessage(String message) { // this.message = message; // } // // } // // Path: app/src/main/java/org/cnodejs/android/md/model/entity/Result.java // public class Result { // // private boolean success; // // public boolean isSuccess() { // return success; // } // // public void setSuccess(boolean success) { // this.success = success; // } // // } // Path: app/src/main/java/org/cnodejs/android/md/model/api/CallbackLifecycle.java import org.cnodejs.android.md.model.entity.ErrorResult; import org.cnodejs.android.md.model.entity.Result; import okhttp3.Headers; package org.cnodejs.android.md.model.api; public interface CallbackLifecycle<T extends Result> { boolean onResultOk(int code, Headers headers, T result);
boolean onResultError(int code, Headers headers, ErrorResult errorResult);
TakWolf/CNode-Material-Design
app/src/main/java/org/cnodejs/android/md/ui/activity/StatusBarActivity.java
// Path: app/src/main/java/org/cnodejs/android/md/util/ResUtils.java // public final class ResUtils { // // private ResUtils() {} // // public static int getStatusBarHeight(@NonNull Context context) { // int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android"); // return resourceId > 0 ? context.getResources().getDimensionPixelSize(resourceId) : 0; // } // // @ColorInt // public static int getThemeAttrColor(@NonNull Context context, @AttrRes int attr) { // TypedArray a = context.obtainStyledAttributes(null, new int[]{attr}); // try { // return a.getColor(0, 0); // } finally { // a.recycle(); // } // } // // public static String getRawString(@NonNull Context context, @RawRes int rawId) throws IOException { // InputStream is = context.getResources().openRawResource(rawId); // BufferedReader reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8)); // StringBuilder sb = new StringBuilder(); // String line; // while ((line = reader.readLine()) != null) { // sb.append(line).append("\n"); // } // if (sb.length() > 0) { // sb.deleteCharAt(sb.length() - 1); // } // reader.close(); // return sb.toString(); // } // // }
import android.os.Build; import android.os.Bundle; import android.support.annotation.LayoutRes; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.widget.FrameLayout; import org.cnodejs.android.md.R; import org.cnodejs.android.md.util.ResUtils;
package org.cnodejs.android.md.ui.activity; public abstract class StatusBarActivity extends BaseActivity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); } } @Override public void setContentView(@LayoutRes int layoutResId) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { FrameLayout rootView = new FrameLayout(this); rootView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); View contentView = LayoutInflater.from(this).inflate(layoutResId, rootView, false); contentView.setFitsSystemWindows(true); rootView.addView(contentView); View statusBarView = new View(this);
// Path: app/src/main/java/org/cnodejs/android/md/util/ResUtils.java // public final class ResUtils { // // private ResUtils() {} // // public static int getStatusBarHeight(@NonNull Context context) { // int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android"); // return resourceId > 0 ? context.getResources().getDimensionPixelSize(resourceId) : 0; // } // // @ColorInt // public static int getThemeAttrColor(@NonNull Context context, @AttrRes int attr) { // TypedArray a = context.obtainStyledAttributes(null, new int[]{attr}); // try { // return a.getColor(0, 0); // } finally { // a.recycle(); // } // } // // public static String getRawString(@NonNull Context context, @RawRes int rawId) throws IOException { // InputStream is = context.getResources().openRawResource(rawId); // BufferedReader reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8)); // StringBuilder sb = new StringBuilder(); // String line; // while ((line = reader.readLine()) != null) { // sb.append(line).append("\n"); // } // if (sb.length() > 0) { // sb.deleteCharAt(sb.length() - 1); // } // reader.close(); // return sb.toString(); // } // // } // Path: app/src/main/java/org/cnodejs/android/md/ui/activity/StatusBarActivity.java import android.os.Build; import android.os.Bundle; import android.support.annotation.LayoutRes; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.WindowManager; import android.widget.FrameLayout; import org.cnodejs.android.md.R; import org.cnodejs.android.md.util.ResUtils; package org.cnodejs.android.md.ui.activity; public abstract class StatusBarActivity extends BaseActivity { @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); } } @Override public void setContentView(@LayoutRes int layoutResId) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { FrameLayout rootView = new FrameLayout(this); rootView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); View contentView = LayoutInflater.from(this).inflate(layoutResId, rootView, false); contentView.setFitsSystemWindows(true); rootView.addView(contentView); View statusBarView = new View(this);
statusBarView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ResUtils.getStatusBarHeight(this)));
TakWolf/CNode-Material-Design
app/src/main/java/org/cnodejs/android/md/ui/widget/CNodeWebView.java
// Path: app/src/main/java/org/cnodejs/android/md/ui/util/Navigator.java // public final class Navigator { // // private Navigator() {} // // public static void openInMarket(@NonNull Context context) { // Intent intent = new Intent(Intent.ACTION_VIEW); // intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // intent.setData(Uri.parse("market://details?id=" + context.getPackageName())); // if (intent.resolveActivity(context.getPackageManager()) != null) { // context.startActivity(intent); // } else { // ToastUtils.with(context).show(R.string.no_market_install_in_system); // } // } // // public static void openInBrowser(@NonNull Context context, @NonNull String url) { // Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); // intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // if (intent.resolveActivity(context.getPackageManager()) != null) { // context.startActivity(intent); // } else { // ToastUtils.with(context).show(R.string.no_browser_install_in_system); // } // } // // public static void openEmail(@NonNull Context context, @NonNull String email, @NonNull String subject, @NonNull String text) { // Intent intent = new Intent(Intent.ACTION_SENDTO); // intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // intent.setData(Uri.parse("mailto:" + email)); // if (intent.resolveActivity(context.getPackageManager()) != null) { // intent.putExtra(Intent.EXTRA_SUBJECT, subject); // intent.putExtra(Intent.EXTRA_TEXT, text); // context.startActivity(intent); // } else { // ToastUtils.with(context).show(R.string.no_email_client_install_in_system); // } // } // // public static void openShare(@NonNull Context context, @NonNull String text) { // Intent intent = new Intent(Intent.ACTION_SEND); // intent.setType("text/plain"); // intent.putExtra(Intent.EXTRA_TEXT, text); // context.startActivity(Intent.createChooser(intent, context.getString(R.string.share))); // } // // public static boolean openStandardLink(@NonNull Context context, @Nullable String url) { // if (FormatUtils.isUserLinkUrl(url)) { // UserDetailActivity.start(context, Uri.parse(url).getPath().replace(ApiDefine.USER_PATH_PREFIX, "")); // return true; // } else if (FormatUtils.isTopicLinkUrl(url)) { // TopicWithAutoCompat.start(context, Uri.parse(url).getPath().replace(ApiDefine.TOPIC_PATH_PREFIX, "")); // return true; // } else { // return false; // } // } // // public static final class TopicWithAutoCompat { // // private TopicWithAutoCompat() {} // // public static final String EXTRA_TOPIC_ID = "topicId"; // public static final String EXTRA_TOPIC = "topic"; // // private static Class<?> getTargetClass(@NonNull Context context) { // return SettingShared.isEnableTopicRenderCompat(context) ? TopicCompatActivity.class : TopicActivity.class; // } // // public static void start(@NonNull Activity activity, @NonNull Topic topic) { // Intent intent = new Intent(activity, getTargetClass(activity)); // intent.putExtra(EXTRA_TOPIC_ID, topic.getId()); // intent.putExtra(EXTRA_TOPIC, EntityUtils.gson.toJson(topic)); // activity.startActivity(intent); // } // // public static void start(@NonNull Activity activity, String topicId) { // Intent intent = new Intent(activity, getTargetClass(activity)); // intent.putExtra(EXTRA_TOPIC_ID, topicId); // activity.startActivity(intent); // } // // public static void start(@NonNull Context context, String topicId) { // Intent intent = new Intent(context, getTargetClass(context)); // intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // intent.putExtra(EXTRA_TOPIC_ID, topicId); // context.startActivity(intent); // } // // } // // public static final class NotificationWithAutoCompat { // // private NotificationWithAutoCompat() {} // // private static Class<?> getTargetClass(@NonNull Context context) { // return SettingShared.isEnableTopicRenderCompat(context) ? NotificationCompatActivity.class : NotificationActivity.class; // } // // public static void start(@NonNull Activity activity) { // activity.startActivity(new Intent(activity, getTargetClass(activity))); // } // // } // // }
import android.annotation.SuppressLint; import android.content.Context; import android.content.res.TypedArray; import android.os.Build; import android.support.annotation.AttrRes; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.annotation.RequiresApi; import android.support.annotation.StyleRes; import android.text.TextUtils; import android.util.AttributeSet; import android.webkit.WebView; import android.webkit.WebViewClient; import org.cnodejs.android.md.R; import org.cnodejs.android.md.ui.util.Navigator; import java.util.ArrayList; import java.util.List;
package org.cnodejs.android.md.ui.widget; public abstract class CNodeWebView extends WebView { private final WebViewClient webViewClient = new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView webView, String url) {
// Path: app/src/main/java/org/cnodejs/android/md/ui/util/Navigator.java // public final class Navigator { // // private Navigator() {} // // public static void openInMarket(@NonNull Context context) { // Intent intent = new Intent(Intent.ACTION_VIEW); // intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // intent.setData(Uri.parse("market://details?id=" + context.getPackageName())); // if (intent.resolveActivity(context.getPackageManager()) != null) { // context.startActivity(intent); // } else { // ToastUtils.with(context).show(R.string.no_market_install_in_system); // } // } // // public static void openInBrowser(@NonNull Context context, @NonNull String url) { // Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); // intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // if (intent.resolveActivity(context.getPackageManager()) != null) { // context.startActivity(intent); // } else { // ToastUtils.with(context).show(R.string.no_browser_install_in_system); // } // } // // public static void openEmail(@NonNull Context context, @NonNull String email, @NonNull String subject, @NonNull String text) { // Intent intent = new Intent(Intent.ACTION_SENDTO); // intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // intent.setData(Uri.parse("mailto:" + email)); // if (intent.resolveActivity(context.getPackageManager()) != null) { // intent.putExtra(Intent.EXTRA_SUBJECT, subject); // intent.putExtra(Intent.EXTRA_TEXT, text); // context.startActivity(intent); // } else { // ToastUtils.with(context).show(R.string.no_email_client_install_in_system); // } // } // // public static void openShare(@NonNull Context context, @NonNull String text) { // Intent intent = new Intent(Intent.ACTION_SEND); // intent.setType("text/plain"); // intent.putExtra(Intent.EXTRA_TEXT, text); // context.startActivity(Intent.createChooser(intent, context.getString(R.string.share))); // } // // public static boolean openStandardLink(@NonNull Context context, @Nullable String url) { // if (FormatUtils.isUserLinkUrl(url)) { // UserDetailActivity.start(context, Uri.parse(url).getPath().replace(ApiDefine.USER_PATH_PREFIX, "")); // return true; // } else if (FormatUtils.isTopicLinkUrl(url)) { // TopicWithAutoCompat.start(context, Uri.parse(url).getPath().replace(ApiDefine.TOPIC_PATH_PREFIX, "")); // return true; // } else { // return false; // } // } // // public static final class TopicWithAutoCompat { // // private TopicWithAutoCompat() {} // // public static final String EXTRA_TOPIC_ID = "topicId"; // public static final String EXTRA_TOPIC = "topic"; // // private static Class<?> getTargetClass(@NonNull Context context) { // return SettingShared.isEnableTopicRenderCompat(context) ? TopicCompatActivity.class : TopicActivity.class; // } // // public static void start(@NonNull Activity activity, @NonNull Topic topic) { // Intent intent = new Intent(activity, getTargetClass(activity)); // intent.putExtra(EXTRA_TOPIC_ID, topic.getId()); // intent.putExtra(EXTRA_TOPIC, EntityUtils.gson.toJson(topic)); // activity.startActivity(intent); // } // // public static void start(@NonNull Activity activity, String topicId) { // Intent intent = new Intent(activity, getTargetClass(activity)); // intent.putExtra(EXTRA_TOPIC_ID, topicId); // activity.startActivity(intent); // } // // public static void start(@NonNull Context context, String topicId) { // Intent intent = new Intent(context, getTargetClass(context)); // intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // intent.putExtra(EXTRA_TOPIC_ID, topicId); // context.startActivity(intent); // } // // } // // public static final class NotificationWithAutoCompat { // // private NotificationWithAutoCompat() {} // // private static Class<?> getTargetClass(@NonNull Context context) { // return SettingShared.isEnableTopicRenderCompat(context) ? NotificationCompatActivity.class : NotificationActivity.class; // } // // public static void start(@NonNull Activity activity) { // activity.startActivity(new Intent(activity, getTargetClass(activity))); // } // // } // // } // Path: app/src/main/java/org/cnodejs/android/md/ui/widget/CNodeWebView.java import android.annotation.SuppressLint; import android.content.Context; import android.content.res.TypedArray; import android.os.Build; import android.support.annotation.AttrRes; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.annotation.RequiresApi; import android.support.annotation.StyleRes; import android.text.TextUtils; import android.util.AttributeSet; import android.webkit.WebView; import android.webkit.WebViewClient; import org.cnodejs.android.md.R; import org.cnodejs.android.md.ui.util.Navigator; import java.util.ArrayList; import java.util.List; package org.cnodejs.android.md.ui.widget; public abstract class CNodeWebView extends WebView { private final WebViewClient webViewClient = new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView webView, String url) {
if (!TextUtils.isEmpty(url) && !Navigator.openStandardLink(webView.getContext(), url)) {
TakWolf/CNode-Material-Design
app/src/main/java/org/cnodejs/android/md/ui/activity/ModifyTopicSignActivity.java
// Path: app/src/main/java/org/cnodejs/android/md/model/storage/SettingShared.java // public final class SettingShared { // // private SettingShared() {} // // private static final String TAG = "SettingShared"; // // private static final String KEY_ENABLE_NOTIFICATION = "enableNotification"; // private static final String KEY_ENABLE_THEME_DARK = "enableThemeDark"; // private static final String KEY_ENABLE_TOPIC_DRAFT = "enableTopicDraft"; // private static final String KEY_ENABLE_TOPIC_SIGN = "enableTopicSign"; // private static final String KEY_TOPIC_SIGN_CONTENT = "topicSignContent"; // private static final String KEY_ENABLE_TOPIC_RENDER_COMPAT = "enableTopicRenderCompat"; // private static final String KEY_SHOW_TOPIC_RENDER_COMPAT_TIP = "showTopicRenderCompatTip"; // // public static final String DEFAULT_TOPIC_SIGN_CONTENT = "来自酷炫的 [CNodeMD](https://github.com/TakWolf/CNode-Material-Design)"; // // public static boolean isEnableNotification(@NonNull Context context) { // return SharedUtils.with(context, TAG).getBoolean(KEY_ENABLE_NOTIFICATION, true); // } // // public static void setEnableNotification(@NonNull Context context, boolean enable) { // SharedUtils.with(context, TAG).setBoolean(KEY_ENABLE_NOTIFICATION, enable); // } // // public static boolean isEnableThemeDark(@NonNull Context context) { // return SharedUtils.with(context, TAG).getBoolean(KEY_ENABLE_THEME_DARK, false); // } // // public static void setEnableThemeDark(@NonNull Context context, boolean enable) { // SharedUtils.with(context, TAG).setBoolean(KEY_ENABLE_THEME_DARK, enable); // } // // public static boolean isEnableTopicDraft(@NonNull Context context) { // return SharedUtils.with(context, TAG).getBoolean(KEY_ENABLE_TOPIC_DRAFT, true); // } // // public static void setEnableTopicDraft(@NonNull Context context, boolean enable) { // SharedUtils.with(context, TAG).setBoolean(KEY_ENABLE_TOPIC_DRAFT, enable); // } // // public static boolean isEnableTopicSign(@NonNull Context context) { // return SharedUtils.with(context, TAG).getBoolean(KEY_ENABLE_TOPIC_SIGN, true); // } // // public static void setEnableTopicSign(@NonNull Context context, boolean enable) { // SharedUtils.with(context, TAG).setBoolean(KEY_ENABLE_TOPIC_SIGN, enable); // } // // public static String getTopicSignContent(@NonNull Context context) { // return SharedUtils.with(context, TAG).getString(KEY_TOPIC_SIGN_CONTENT, DEFAULT_TOPIC_SIGN_CONTENT); // } // // public static void setTopicSignContent(@NonNull Context context, @Nullable String content) { // SharedUtils.with(context, TAG).setString(KEY_TOPIC_SIGN_CONTENT, content); // } // // public static boolean isEnableTopicRenderCompat(@NonNull Context context) { // return SharedUtils.with(context, TAG).getBoolean(KEY_ENABLE_TOPIC_RENDER_COMPAT, true); // } // // public static void setEnableTopicRenderCompat(@NonNull Context context, boolean enable) { // SharedUtils.with(context, TAG).setBoolean(KEY_ENABLE_TOPIC_RENDER_COMPAT, enable); // } // // public static boolean isShowTopicRenderCompatTip(@NonNull Context context) { // return SharedUtils.with(context, TAG).getBoolean(KEY_SHOW_TOPIC_RENDER_COMPAT_TIP, true); // } // // public static void markShowTopicRenderCompatTip(@NonNull Context context) { // SharedUtils.with(context, TAG).setBoolean(KEY_SHOW_TOPIC_RENDER_COMPAT_TIP, false); // } // // } // // Path: app/src/main/java/org/cnodejs/android/md/ui/listener/NavigationFinishClickListener.java // public class NavigationFinishClickListener implements View.OnClickListener { // // private final Activity activity; // // public NavigationFinishClickListener(@NonNull Activity activity) { // this.activity = activity; // } // // @Override // public void onClick(View v) { // ActivityCompat.finishAfterTransition(activity); // } // // } // // Path: app/src/main/java/org/cnodejs/android/md/ui/util/ThemeUtils.java // public final class ThemeUtils { // // private ThemeUtils() {} // // public static boolean configThemeBeforeOnCreate(@NonNull Activity activity, @StyleRes int light, @StyleRes int dark) { // boolean enable = SettingShared.isEnableThemeDark(activity); // activity.setTheme(enable ? dark : light); // return enable; // } // // public static void notifyThemeApply(@NonNull final Activity activity) { // HandlerUtils.handler.post(new Runnable() { // // @Override // public void run() { // activity.recreate(); // } // // }); // } // // }
import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.widget.Toolbar; import android.view.MenuItem; import android.widget.EditText; import org.cnodejs.android.md.R; import org.cnodejs.android.md.model.storage.SettingShared; import org.cnodejs.android.md.ui.listener.NavigationFinishClickListener; import org.cnodejs.android.md.ui.util.ThemeUtils; import butterknife.BindView; import butterknife.ButterKnife;
package org.cnodejs.android.md.ui.activity; public class ModifyTopicSignActivity extends StatusBarActivity implements Toolbar.OnMenuItemClickListener { @BindView(R.id.toolbar) Toolbar toolbar; @BindView(R.id.edt_content) EditText edtContent; @Override protected void onCreate(@Nullable Bundle savedInstanceState) {
// Path: app/src/main/java/org/cnodejs/android/md/model/storage/SettingShared.java // public final class SettingShared { // // private SettingShared() {} // // private static final String TAG = "SettingShared"; // // private static final String KEY_ENABLE_NOTIFICATION = "enableNotification"; // private static final String KEY_ENABLE_THEME_DARK = "enableThemeDark"; // private static final String KEY_ENABLE_TOPIC_DRAFT = "enableTopicDraft"; // private static final String KEY_ENABLE_TOPIC_SIGN = "enableTopicSign"; // private static final String KEY_TOPIC_SIGN_CONTENT = "topicSignContent"; // private static final String KEY_ENABLE_TOPIC_RENDER_COMPAT = "enableTopicRenderCompat"; // private static final String KEY_SHOW_TOPIC_RENDER_COMPAT_TIP = "showTopicRenderCompatTip"; // // public static final String DEFAULT_TOPIC_SIGN_CONTENT = "来自酷炫的 [CNodeMD](https://github.com/TakWolf/CNode-Material-Design)"; // // public static boolean isEnableNotification(@NonNull Context context) { // return SharedUtils.with(context, TAG).getBoolean(KEY_ENABLE_NOTIFICATION, true); // } // // public static void setEnableNotification(@NonNull Context context, boolean enable) { // SharedUtils.with(context, TAG).setBoolean(KEY_ENABLE_NOTIFICATION, enable); // } // // public static boolean isEnableThemeDark(@NonNull Context context) { // return SharedUtils.with(context, TAG).getBoolean(KEY_ENABLE_THEME_DARK, false); // } // // public static void setEnableThemeDark(@NonNull Context context, boolean enable) { // SharedUtils.with(context, TAG).setBoolean(KEY_ENABLE_THEME_DARK, enable); // } // // public static boolean isEnableTopicDraft(@NonNull Context context) { // return SharedUtils.with(context, TAG).getBoolean(KEY_ENABLE_TOPIC_DRAFT, true); // } // // public static void setEnableTopicDraft(@NonNull Context context, boolean enable) { // SharedUtils.with(context, TAG).setBoolean(KEY_ENABLE_TOPIC_DRAFT, enable); // } // // public static boolean isEnableTopicSign(@NonNull Context context) { // return SharedUtils.with(context, TAG).getBoolean(KEY_ENABLE_TOPIC_SIGN, true); // } // // public static void setEnableTopicSign(@NonNull Context context, boolean enable) { // SharedUtils.with(context, TAG).setBoolean(KEY_ENABLE_TOPIC_SIGN, enable); // } // // public static String getTopicSignContent(@NonNull Context context) { // return SharedUtils.with(context, TAG).getString(KEY_TOPIC_SIGN_CONTENT, DEFAULT_TOPIC_SIGN_CONTENT); // } // // public static void setTopicSignContent(@NonNull Context context, @Nullable String content) { // SharedUtils.with(context, TAG).setString(KEY_TOPIC_SIGN_CONTENT, content); // } // // public static boolean isEnableTopicRenderCompat(@NonNull Context context) { // return SharedUtils.with(context, TAG).getBoolean(KEY_ENABLE_TOPIC_RENDER_COMPAT, true); // } // // public static void setEnableTopicRenderCompat(@NonNull Context context, boolean enable) { // SharedUtils.with(context, TAG).setBoolean(KEY_ENABLE_TOPIC_RENDER_COMPAT, enable); // } // // public static boolean isShowTopicRenderCompatTip(@NonNull Context context) { // return SharedUtils.with(context, TAG).getBoolean(KEY_SHOW_TOPIC_RENDER_COMPAT_TIP, true); // } // // public static void markShowTopicRenderCompatTip(@NonNull Context context) { // SharedUtils.with(context, TAG).setBoolean(KEY_SHOW_TOPIC_RENDER_COMPAT_TIP, false); // } // // } // // Path: app/src/main/java/org/cnodejs/android/md/ui/listener/NavigationFinishClickListener.java // public class NavigationFinishClickListener implements View.OnClickListener { // // private final Activity activity; // // public NavigationFinishClickListener(@NonNull Activity activity) { // this.activity = activity; // } // // @Override // public void onClick(View v) { // ActivityCompat.finishAfterTransition(activity); // } // // } // // Path: app/src/main/java/org/cnodejs/android/md/ui/util/ThemeUtils.java // public final class ThemeUtils { // // private ThemeUtils() {} // // public static boolean configThemeBeforeOnCreate(@NonNull Activity activity, @StyleRes int light, @StyleRes int dark) { // boolean enable = SettingShared.isEnableThemeDark(activity); // activity.setTheme(enable ? dark : light); // return enable; // } // // public static void notifyThemeApply(@NonNull final Activity activity) { // HandlerUtils.handler.post(new Runnable() { // // @Override // public void run() { // activity.recreate(); // } // // }); // } // // } // Path: app/src/main/java/org/cnodejs/android/md/ui/activity/ModifyTopicSignActivity.java import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.widget.Toolbar; import android.view.MenuItem; import android.widget.EditText; import org.cnodejs.android.md.R; import org.cnodejs.android.md.model.storage.SettingShared; import org.cnodejs.android.md.ui.listener.NavigationFinishClickListener; import org.cnodejs.android.md.ui.util.ThemeUtils; import butterknife.BindView; import butterknife.ButterKnife; package org.cnodejs.android.md.ui.activity; public class ModifyTopicSignActivity extends StatusBarActivity implements Toolbar.OnMenuItemClickListener { @BindView(R.id.toolbar) Toolbar toolbar; @BindView(R.id.edt_content) EditText edtContent; @Override protected void onCreate(@Nullable Bundle savedInstanceState) {
ThemeUtils.configThemeBeforeOnCreate(this, R.style.AppThemeLight, R.style.AppThemeDark);
TakWolf/CNode-Material-Design
app/src/main/java/org/cnodejs/android/md/ui/activity/ModifyTopicSignActivity.java
// Path: app/src/main/java/org/cnodejs/android/md/model/storage/SettingShared.java // public final class SettingShared { // // private SettingShared() {} // // private static final String TAG = "SettingShared"; // // private static final String KEY_ENABLE_NOTIFICATION = "enableNotification"; // private static final String KEY_ENABLE_THEME_DARK = "enableThemeDark"; // private static final String KEY_ENABLE_TOPIC_DRAFT = "enableTopicDraft"; // private static final String KEY_ENABLE_TOPIC_SIGN = "enableTopicSign"; // private static final String KEY_TOPIC_SIGN_CONTENT = "topicSignContent"; // private static final String KEY_ENABLE_TOPIC_RENDER_COMPAT = "enableTopicRenderCompat"; // private static final String KEY_SHOW_TOPIC_RENDER_COMPAT_TIP = "showTopicRenderCompatTip"; // // public static final String DEFAULT_TOPIC_SIGN_CONTENT = "来自酷炫的 [CNodeMD](https://github.com/TakWolf/CNode-Material-Design)"; // // public static boolean isEnableNotification(@NonNull Context context) { // return SharedUtils.with(context, TAG).getBoolean(KEY_ENABLE_NOTIFICATION, true); // } // // public static void setEnableNotification(@NonNull Context context, boolean enable) { // SharedUtils.with(context, TAG).setBoolean(KEY_ENABLE_NOTIFICATION, enable); // } // // public static boolean isEnableThemeDark(@NonNull Context context) { // return SharedUtils.with(context, TAG).getBoolean(KEY_ENABLE_THEME_DARK, false); // } // // public static void setEnableThemeDark(@NonNull Context context, boolean enable) { // SharedUtils.with(context, TAG).setBoolean(KEY_ENABLE_THEME_DARK, enable); // } // // public static boolean isEnableTopicDraft(@NonNull Context context) { // return SharedUtils.with(context, TAG).getBoolean(KEY_ENABLE_TOPIC_DRAFT, true); // } // // public static void setEnableTopicDraft(@NonNull Context context, boolean enable) { // SharedUtils.with(context, TAG).setBoolean(KEY_ENABLE_TOPIC_DRAFT, enable); // } // // public static boolean isEnableTopicSign(@NonNull Context context) { // return SharedUtils.with(context, TAG).getBoolean(KEY_ENABLE_TOPIC_SIGN, true); // } // // public static void setEnableTopicSign(@NonNull Context context, boolean enable) { // SharedUtils.with(context, TAG).setBoolean(KEY_ENABLE_TOPIC_SIGN, enable); // } // // public static String getTopicSignContent(@NonNull Context context) { // return SharedUtils.with(context, TAG).getString(KEY_TOPIC_SIGN_CONTENT, DEFAULT_TOPIC_SIGN_CONTENT); // } // // public static void setTopicSignContent(@NonNull Context context, @Nullable String content) { // SharedUtils.with(context, TAG).setString(KEY_TOPIC_SIGN_CONTENT, content); // } // // public static boolean isEnableTopicRenderCompat(@NonNull Context context) { // return SharedUtils.with(context, TAG).getBoolean(KEY_ENABLE_TOPIC_RENDER_COMPAT, true); // } // // public static void setEnableTopicRenderCompat(@NonNull Context context, boolean enable) { // SharedUtils.with(context, TAG).setBoolean(KEY_ENABLE_TOPIC_RENDER_COMPAT, enable); // } // // public static boolean isShowTopicRenderCompatTip(@NonNull Context context) { // return SharedUtils.with(context, TAG).getBoolean(KEY_SHOW_TOPIC_RENDER_COMPAT_TIP, true); // } // // public static void markShowTopicRenderCompatTip(@NonNull Context context) { // SharedUtils.with(context, TAG).setBoolean(KEY_SHOW_TOPIC_RENDER_COMPAT_TIP, false); // } // // } // // Path: app/src/main/java/org/cnodejs/android/md/ui/listener/NavigationFinishClickListener.java // public class NavigationFinishClickListener implements View.OnClickListener { // // private final Activity activity; // // public NavigationFinishClickListener(@NonNull Activity activity) { // this.activity = activity; // } // // @Override // public void onClick(View v) { // ActivityCompat.finishAfterTransition(activity); // } // // } // // Path: app/src/main/java/org/cnodejs/android/md/ui/util/ThemeUtils.java // public final class ThemeUtils { // // private ThemeUtils() {} // // public static boolean configThemeBeforeOnCreate(@NonNull Activity activity, @StyleRes int light, @StyleRes int dark) { // boolean enable = SettingShared.isEnableThemeDark(activity); // activity.setTheme(enable ? dark : light); // return enable; // } // // public static void notifyThemeApply(@NonNull final Activity activity) { // HandlerUtils.handler.post(new Runnable() { // // @Override // public void run() { // activity.recreate(); // } // // }); // } // // }
import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.widget.Toolbar; import android.view.MenuItem; import android.widget.EditText; import org.cnodejs.android.md.R; import org.cnodejs.android.md.model.storage.SettingShared; import org.cnodejs.android.md.ui.listener.NavigationFinishClickListener; import org.cnodejs.android.md.ui.util.ThemeUtils; import butterknife.BindView; import butterknife.ButterKnife;
package org.cnodejs.android.md.ui.activity; public class ModifyTopicSignActivity extends StatusBarActivity implements Toolbar.OnMenuItemClickListener { @BindView(R.id.toolbar) Toolbar toolbar; @BindView(R.id.edt_content) EditText edtContent; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { ThemeUtils.configThemeBeforeOnCreate(this, R.style.AppThemeLight, R.style.AppThemeDark); super.onCreate(savedInstanceState); setContentView(R.layout.activity_modify_topic_sign); ButterKnife.bind(this);
// Path: app/src/main/java/org/cnodejs/android/md/model/storage/SettingShared.java // public final class SettingShared { // // private SettingShared() {} // // private static final String TAG = "SettingShared"; // // private static final String KEY_ENABLE_NOTIFICATION = "enableNotification"; // private static final String KEY_ENABLE_THEME_DARK = "enableThemeDark"; // private static final String KEY_ENABLE_TOPIC_DRAFT = "enableTopicDraft"; // private static final String KEY_ENABLE_TOPIC_SIGN = "enableTopicSign"; // private static final String KEY_TOPIC_SIGN_CONTENT = "topicSignContent"; // private static final String KEY_ENABLE_TOPIC_RENDER_COMPAT = "enableTopicRenderCompat"; // private static final String KEY_SHOW_TOPIC_RENDER_COMPAT_TIP = "showTopicRenderCompatTip"; // // public static final String DEFAULT_TOPIC_SIGN_CONTENT = "来自酷炫的 [CNodeMD](https://github.com/TakWolf/CNode-Material-Design)"; // // public static boolean isEnableNotification(@NonNull Context context) { // return SharedUtils.with(context, TAG).getBoolean(KEY_ENABLE_NOTIFICATION, true); // } // // public static void setEnableNotification(@NonNull Context context, boolean enable) { // SharedUtils.with(context, TAG).setBoolean(KEY_ENABLE_NOTIFICATION, enable); // } // // public static boolean isEnableThemeDark(@NonNull Context context) { // return SharedUtils.with(context, TAG).getBoolean(KEY_ENABLE_THEME_DARK, false); // } // // public static void setEnableThemeDark(@NonNull Context context, boolean enable) { // SharedUtils.with(context, TAG).setBoolean(KEY_ENABLE_THEME_DARK, enable); // } // // public static boolean isEnableTopicDraft(@NonNull Context context) { // return SharedUtils.with(context, TAG).getBoolean(KEY_ENABLE_TOPIC_DRAFT, true); // } // // public static void setEnableTopicDraft(@NonNull Context context, boolean enable) { // SharedUtils.with(context, TAG).setBoolean(KEY_ENABLE_TOPIC_DRAFT, enable); // } // // public static boolean isEnableTopicSign(@NonNull Context context) { // return SharedUtils.with(context, TAG).getBoolean(KEY_ENABLE_TOPIC_SIGN, true); // } // // public static void setEnableTopicSign(@NonNull Context context, boolean enable) { // SharedUtils.with(context, TAG).setBoolean(KEY_ENABLE_TOPIC_SIGN, enable); // } // // public static String getTopicSignContent(@NonNull Context context) { // return SharedUtils.with(context, TAG).getString(KEY_TOPIC_SIGN_CONTENT, DEFAULT_TOPIC_SIGN_CONTENT); // } // // public static void setTopicSignContent(@NonNull Context context, @Nullable String content) { // SharedUtils.with(context, TAG).setString(KEY_TOPIC_SIGN_CONTENT, content); // } // // public static boolean isEnableTopicRenderCompat(@NonNull Context context) { // return SharedUtils.with(context, TAG).getBoolean(KEY_ENABLE_TOPIC_RENDER_COMPAT, true); // } // // public static void setEnableTopicRenderCompat(@NonNull Context context, boolean enable) { // SharedUtils.with(context, TAG).setBoolean(KEY_ENABLE_TOPIC_RENDER_COMPAT, enable); // } // // public static boolean isShowTopicRenderCompatTip(@NonNull Context context) { // return SharedUtils.with(context, TAG).getBoolean(KEY_SHOW_TOPIC_RENDER_COMPAT_TIP, true); // } // // public static void markShowTopicRenderCompatTip(@NonNull Context context) { // SharedUtils.with(context, TAG).setBoolean(KEY_SHOW_TOPIC_RENDER_COMPAT_TIP, false); // } // // } // // Path: app/src/main/java/org/cnodejs/android/md/ui/listener/NavigationFinishClickListener.java // public class NavigationFinishClickListener implements View.OnClickListener { // // private final Activity activity; // // public NavigationFinishClickListener(@NonNull Activity activity) { // this.activity = activity; // } // // @Override // public void onClick(View v) { // ActivityCompat.finishAfterTransition(activity); // } // // } // // Path: app/src/main/java/org/cnodejs/android/md/ui/util/ThemeUtils.java // public final class ThemeUtils { // // private ThemeUtils() {} // // public static boolean configThemeBeforeOnCreate(@NonNull Activity activity, @StyleRes int light, @StyleRes int dark) { // boolean enable = SettingShared.isEnableThemeDark(activity); // activity.setTheme(enable ? dark : light); // return enable; // } // // public static void notifyThemeApply(@NonNull final Activity activity) { // HandlerUtils.handler.post(new Runnable() { // // @Override // public void run() { // activity.recreate(); // } // // }); // } // // } // Path: app/src/main/java/org/cnodejs/android/md/ui/activity/ModifyTopicSignActivity.java import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.widget.Toolbar; import android.view.MenuItem; import android.widget.EditText; import org.cnodejs.android.md.R; import org.cnodejs.android.md.model.storage.SettingShared; import org.cnodejs.android.md.ui.listener.NavigationFinishClickListener; import org.cnodejs.android.md.ui.util.ThemeUtils; import butterknife.BindView; import butterknife.ButterKnife; package org.cnodejs.android.md.ui.activity; public class ModifyTopicSignActivity extends StatusBarActivity implements Toolbar.OnMenuItemClickListener { @BindView(R.id.toolbar) Toolbar toolbar; @BindView(R.id.edt_content) EditText edtContent; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { ThemeUtils.configThemeBeforeOnCreate(this, R.style.AppThemeLight, R.style.AppThemeDark); super.onCreate(savedInstanceState); setContentView(R.layout.activity_modify_topic_sign); ButterKnife.bind(this);
toolbar.setNavigationOnClickListener(new NavigationFinishClickListener(this));
TakWolf/CNode-Material-Design
app/src/main/java/org/cnodejs/android/md/ui/activity/ModifyTopicSignActivity.java
// Path: app/src/main/java/org/cnodejs/android/md/model/storage/SettingShared.java // public final class SettingShared { // // private SettingShared() {} // // private static final String TAG = "SettingShared"; // // private static final String KEY_ENABLE_NOTIFICATION = "enableNotification"; // private static final String KEY_ENABLE_THEME_DARK = "enableThemeDark"; // private static final String KEY_ENABLE_TOPIC_DRAFT = "enableTopicDraft"; // private static final String KEY_ENABLE_TOPIC_SIGN = "enableTopicSign"; // private static final String KEY_TOPIC_SIGN_CONTENT = "topicSignContent"; // private static final String KEY_ENABLE_TOPIC_RENDER_COMPAT = "enableTopicRenderCompat"; // private static final String KEY_SHOW_TOPIC_RENDER_COMPAT_TIP = "showTopicRenderCompatTip"; // // public static final String DEFAULT_TOPIC_SIGN_CONTENT = "来自酷炫的 [CNodeMD](https://github.com/TakWolf/CNode-Material-Design)"; // // public static boolean isEnableNotification(@NonNull Context context) { // return SharedUtils.with(context, TAG).getBoolean(KEY_ENABLE_NOTIFICATION, true); // } // // public static void setEnableNotification(@NonNull Context context, boolean enable) { // SharedUtils.with(context, TAG).setBoolean(KEY_ENABLE_NOTIFICATION, enable); // } // // public static boolean isEnableThemeDark(@NonNull Context context) { // return SharedUtils.with(context, TAG).getBoolean(KEY_ENABLE_THEME_DARK, false); // } // // public static void setEnableThemeDark(@NonNull Context context, boolean enable) { // SharedUtils.with(context, TAG).setBoolean(KEY_ENABLE_THEME_DARK, enable); // } // // public static boolean isEnableTopicDraft(@NonNull Context context) { // return SharedUtils.with(context, TAG).getBoolean(KEY_ENABLE_TOPIC_DRAFT, true); // } // // public static void setEnableTopicDraft(@NonNull Context context, boolean enable) { // SharedUtils.with(context, TAG).setBoolean(KEY_ENABLE_TOPIC_DRAFT, enable); // } // // public static boolean isEnableTopicSign(@NonNull Context context) { // return SharedUtils.with(context, TAG).getBoolean(KEY_ENABLE_TOPIC_SIGN, true); // } // // public static void setEnableTopicSign(@NonNull Context context, boolean enable) { // SharedUtils.with(context, TAG).setBoolean(KEY_ENABLE_TOPIC_SIGN, enable); // } // // public static String getTopicSignContent(@NonNull Context context) { // return SharedUtils.with(context, TAG).getString(KEY_TOPIC_SIGN_CONTENT, DEFAULT_TOPIC_SIGN_CONTENT); // } // // public static void setTopicSignContent(@NonNull Context context, @Nullable String content) { // SharedUtils.with(context, TAG).setString(KEY_TOPIC_SIGN_CONTENT, content); // } // // public static boolean isEnableTopicRenderCompat(@NonNull Context context) { // return SharedUtils.with(context, TAG).getBoolean(KEY_ENABLE_TOPIC_RENDER_COMPAT, true); // } // // public static void setEnableTopicRenderCompat(@NonNull Context context, boolean enable) { // SharedUtils.with(context, TAG).setBoolean(KEY_ENABLE_TOPIC_RENDER_COMPAT, enable); // } // // public static boolean isShowTopicRenderCompatTip(@NonNull Context context) { // return SharedUtils.with(context, TAG).getBoolean(KEY_SHOW_TOPIC_RENDER_COMPAT_TIP, true); // } // // public static void markShowTopicRenderCompatTip(@NonNull Context context) { // SharedUtils.with(context, TAG).setBoolean(KEY_SHOW_TOPIC_RENDER_COMPAT_TIP, false); // } // // } // // Path: app/src/main/java/org/cnodejs/android/md/ui/listener/NavigationFinishClickListener.java // public class NavigationFinishClickListener implements View.OnClickListener { // // private final Activity activity; // // public NavigationFinishClickListener(@NonNull Activity activity) { // this.activity = activity; // } // // @Override // public void onClick(View v) { // ActivityCompat.finishAfterTransition(activity); // } // // } // // Path: app/src/main/java/org/cnodejs/android/md/ui/util/ThemeUtils.java // public final class ThemeUtils { // // private ThemeUtils() {} // // public static boolean configThemeBeforeOnCreate(@NonNull Activity activity, @StyleRes int light, @StyleRes int dark) { // boolean enable = SettingShared.isEnableThemeDark(activity); // activity.setTheme(enable ? dark : light); // return enable; // } // // public static void notifyThemeApply(@NonNull final Activity activity) { // HandlerUtils.handler.post(new Runnable() { // // @Override // public void run() { // activity.recreate(); // } // // }); // } // // }
import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.widget.Toolbar; import android.view.MenuItem; import android.widget.EditText; import org.cnodejs.android.md.R; import org.cnodejs.android.md.model.storage.SettingShared; import org.cnodejs.android.md.ui.listener.NavigationFinishClickListener; import org.cnodejs.android.md.ui.util.ThemeUtils; import butterknife.BindView; import butterknife.ButterKnife;
package org.cnodejs.android.md.ui.activity; public class ModifyTopicSignActivity extends StatusBarActivity implements Toolbar.OnMenuItemClickListener { @BindView(R.id.toolbar) Toolbar toolbar; @BindView(R.id.edt_content) EditText edtContent; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { ThemeUtils.configThemeBeforeOnCreate(this, R.style.AppThemeLight, R.style.AppThemeDark); super.onCreate(savedInstanceState); setContentView(R.layout.activity_modify_topic_sign); ButterKnife.bind(this); toolbar.setNavigationOnClickListener(new NavigationFinishClickListener(this)); toolbar.inflateMenu(R.menu.modify_topic_sign); toolbar.setOnMenuItemClickListener(this);
// Path: app/src/main/java/org/cnodejs/android/md/model/storage/SettingShared.java // public final class SettingShared { // // private SettingShared() {} // // private static final String TAG = "SettingShared"; // // private static final String KEY_ENABLE_NOTIFICATION = "enableNotification"; // private static final String KEY_ENABLE_THEME_DARK = "enableThemeDark"; // private static final String KEY_ENABLE_TOPIC_DRAFT = "enableTopicDraft"; // private static final String KEY_ENABLE_TOPIC_SIGN = "enableTopicSign"; // private static final String KEY_TOPIC_SIGN_CONTENT = "topicSignContent"; // private static final String KEY_ENABLE_TOPIC_RENDER_COMPAT = "enableTopicRenderCompat"; // private static final String KEY_SHOW_TOPIC_RENDER_COMPAT_TIP = "showTopicRenderCompatTip"; // // public static final String DEFAULT_TOPIC_SIGN_CONTENT = "来自酷炫的 [CNodeMD](https://github.com/TakWolf/CNode-Material-Design)"; // // public static boolean isEnableNotification(@NonNull Context context) { // return SharedUtils.with(context, TAG).getBoolean(KEY_ENABLE_NOTIFICATION, true); // } // // public static void setEnableNotification(@NonNull Context context, boolean enable) { // SharedUtils.with(context, TAG).setBoolean(KEY_ENABLE_NOTIFICATION, enable); // } // // public static boolean isEnableThemeDark(@NonNull Context context) { // return SharedUtils.with(context, TAG).getBoolean(KEY_ENABLE_THEME_DARK, false); // } // // public static void setEnableThemeDark(@NonNull Context context, boolean enable) { // SharedUtils.with(context, TAG).setBoolean(KEY_ENABLE_THEME_DARK, enable); // } // // public static boolean isEnableTopicDraft(@NonNull Context context) { // return SharedUtils.with(context, TAG).getBoolean(KEY_ENABLE_TOPIC_DRAFT, true); // } // // public static void setEnableTopicDraft(@NonNull Context context, boolean enable) { // SharedUtils.with(context, TAG).setBoolean(KEY_ENABLE_TOPIC_DRAFT, enable); // } // // public static boolean isEnableTopicSign(@NonNull Context context) { // return SharedUtils.with(context, TAG).getBoolean(KEY_ENABLE_TOPIC_SIGN, true); // } // // public static void setEnableTopicSign(@NonNull Context context, boolean enable) { // SharedUtils.with(context, TAG).setBoolean(KEY_ENABLE_TOPIC_SIGN, enable); // } // // public static String getTopicSignContent(@NonNull Context context) { // return SharedUtils.with(context, TAG).getString(KEY_TOPIC_SIGN_CONTENT, DEFAULT_TOPIC_SIGN_CONTENT); // } // // public static void setTopicSignContent(@NonNull Context context, @Nullable String content) { // SharedUtils.with(context, TAG).setString(KEY_TOPIC_SIGN_CONTENT, content); // } // // public static boolean isEnableTopicRenderCompat(@NonNull Context context) { // return SharedUtils.with(context, TAG).getBoolean(KEY_ENABLE_TOPIC_RENDER_COMPAT, true); // } // // public static void setEnableTopicRenderCompat(@NonNull Context context, boolean enable) { // SharedUtils.with(context, TAG).setBoolean(KEY_ENABLE_TOPIC_RENDER_COMPAT, enable); // } // // public static boolean isShowTopicRenderCompatTip(@NonNull Context context) { // return SharedUtils.with(context, TAG).getBoolean(KEY_SHOW_TOPIC_RENDER_COMPAT_TIP, true); // } // // public static void markShowTopicRenderCompatTip(@NonNull Context context) { // SharedUtils.with(context, TAG).setBoolean(KEY_SHOW_TOPIC_RENDER_COMPAT_TIP, false); // } // // } // // Path: app/src/main/java/org/cnodejs/android/md/ui/listener/NavigationFinishClickListener.java // public class NavigationFinishClickListener implements View.OnClickListener { // // private final Activity activity; // // public NavigationFinishClickListener(@NonNull Activity activity) { // this.activity = activity; // } // // @Override // public void onClick(View v) { // ActivityCompat.finishAfterTransition(activity); // } // // } // // Path: app/src/main/java/org/cnodejs/android/md/ui/util/ThemeUtils.java // public final class ThemeUtils { // // private ThemeUtils() {} // // public static boolean configThemeBeforeOnCreate(@NonNull Activity activity, @StyleRes int light, @StyleRes int dark) { // boolean enable = SettingShared.isEnableThemeDark(activity); // activity.setTheme(enable ? dark : light); // return enable; // } // // public static void notifyThemeApply(@NonNull final Activity activity) { // HandlerUtils.handler.post(new Runnable() { // // @Override // public void run() { // activity.recreate(); // } // // }); // } // // } // Path: app/src/main/java/org/cnodejs/android/md/ui/activity/ModifyTopicSignActivity.java import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.widget.Toolbar; import android.view.MenuItem; import android.widget.EditText; import org.cnodejs.android.md.R; import org.cnodejs.android.md.model.storage.SettingShared; import org.cnodejs.android.md.ui.listener.NavigationFinishClickListener; import org.cnodejs.android.md.ui.util.ThemeUtils; import butterknife.BindView; import butterknife.ButterKnife; package org.cnodejs.android.md.ui.activity; public class ModifyTopicSignActivity extends StatusBarActivity implements Toolbar.OnMenuItemClickListener { @BindView(R.id.toolbar) Toolbar toolbar; @BindView(R.id.edt_content) EditText edtContent; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { ThemeUtils.configThemeBeforeOnCreate(this, R.style.AppThemeLight, R.style.AppThemeDark); super.onCreate(savedInstanceState); setContentView(R.layout.activity_modify_topic_sign); ButterKnife.bind(this); toolbar.setNavigationOnClickListener(new NavigationFinishClickListener(this)); toolbar.inflateMenu(R.menu.modify_topic_sign); toolbar.setOnMenuItemClickListener(this);
edtContent.setText(SettingShared.getTopicSignContent(this));
TakWolf/CNode-Material-Design
app/src/main/java/org/cnodejs/android/md/ui/jsbridge/FormatJavascriptInterface.java
// Path: app/src/main/java/org/cnodejs/android/md/util/FormatUtils.java // public final class FormatUtils { // // private FormatUtils() {} // // /** // * 获取最近时间字符串 // */ // // private static final long MINUTE = 60 * 1000; // private static final long HOUR = 60 * MINUTE; // private static final long DAY = 24 * HOUR; // private static final long WEEK = 7 * DAY; // private static final long MONTH = 31 * DAY; // private static final long YEAR = 12 * MONTH; // // public static String getRelativeTimeSpanString(@NonNull DateTime dateTime) { // long offset = System.currentTimeMillis() - dateTime.getMillis(); // if (offset > YEAR) { // return (offset / YEAR) + "年前"; // } else if (offset > MONTH) { // return (offset / MONTH) + "个月前"; // } else if (offset > WEEK) { // return (offset / WEEK) + "周前"; // } else if (offset > DAY) { // return (offset / DAY) + "天前"; // } else if (offset > HOUR) { // return (offset / HOUR) + "小时前"; // } else if (offset > MINUTE) { // return (offset / MINUTE) + "分钟前"; // } else { // return "刚刚"; // } // } // // /** // * 检测是否是用户accessToken // */ // public static boolean isAccessToken(String accessToken) { // if (TextUtils.isEmpty(accessToken)) { // return false; // } else { // try { // //noinspection ResultOfMethodCallIgnored // UUID.fromString(accessToken); // return true; // } catch (Exception e) { // return false; // } // } // } // // /** // * 修复头像地址的历史遗留问题 // */ // public static String getCompatAvatarUrl(String avatarUrl) { // if (!TextUtils.isEmpty(avatarUrl) && avatarUrl.startsWith("//gravatar.com/avatar/")) { // return "http:" + avatarUrl; // } else { // return avatarUrl; // } // } // // /** // * 标准URL检测 // */ // // public static boolean isUserLinkUrl(String url) { // return !TextUtils.isEmpty(url) && url.startsWith(ApiDefine.USER_LINK_URL_PREFIX); // } // // public static boolean isTopicLinkUrl(String url) { // return !TextUtils.isEmpty(url) && url.startsWith(ApiDefine.TOPIC_LINK_URL_PREFIX); // } // // /** // * CNode兼容性的Markdown转换 // * '@'协议转换为'/user/'相对路径 // * 解析裸链接 // * 最外层包裹'<div class="markdown-text"></div>' // * 尽可能的实现和服务端渲染相同的结果 // */ // // private static final Markdown md = new Markdown(); // // public static String renderMarkdown(String text) { // // 保证text不为null // text = TextUtils.isEmpty(text) ? "" : text; // // 解析@协议 // text = text.replaceAll("@([\\w\\-]+)\\b(?![]<.])", "[@$1](" + ApiDefine.USER_PATH_PREFIX + "$1)"); // // 解析裸链接 // text = text + " "; // text = text.replaceAll("((http|https|ftp)://[\\w\\-.:/?=&#%]+)(\\s)", "[$1]($1)$3"); // text = text.trim(); // // 渲染markdown // try { // StringWriter out = new StringWriter(); // md.transform(new StringReader(text), out); // text = out.toString(); // } catch (ParseException e) { // // nothing to do // } // // 添加样式容器 // return "<div class=\"markdown-text\">" + text + "</div>"; // } // // /** // * CNode兼容性的Html处理 // * 过滤xss // * 保留div的class属性,但是会清除其他非白名单属性 // * 通过baseUrl补全相对地址 // */ // // private static final Cleaner cleaner = new Cleaner(Whitelist.relaxed().addAttributes("div", "class")); // 主要目的是保留最外层div的markdown-text属性 // // public static Document handleHtml(String html) { // // 保证html不为null // html = TextUtils.isEmpty(html) ? "" : html; // // 过滤xss // return cleaner.clean(Jsoup.parseBodyFragment(html, ApiDefine.HOST_BASE_URL)); // } // // }
import android.webkit.JavascriptInterface; import org.cnodejs.android.md.util.FormatUtils; import org.joda.time.DateTime;
package org.cnodejs.android.md.ui.jsbridge; public final class FormatJavascriptInterface { public static final String NAME = "formatBridge"; @JavascriptInterface public String getRelativeTimeSpanString(String time) {
// Path: app/src/main/java/org/cnodejs/android/md/util/FormatUtils.java // public final class FormatUtils { // // private FormatUtils() {} // // /** // * 获取最近时间字符串 // */ // // private static final long MINUTE = 60 * 1000; // private static final long HOUR = 60 * MINUTE; // private static final long DAY = 24 * HOUR; // private static final long WEEK = 7 * DAY; // private static final long MONTH = 31 * DAY; // private static final long YEAR = 12 * MONTH; // // public static String getRelativeTimeSpanString(@NonNull DateTime dateTime) { // long offset = System.currentTimeMillis() - dateTime.getMillis(); // if (offset > YEAR) { // return (offset / YEAR) + "年前"; // } else if (offset > MONTH) { // return (offset / MONTH) + "个月前"; // } else if (offset > WEEK) { // return (offset / WEEK) + "周前"; // } else if (offset > DAY) { // return (offset / DAY) + "天前"; // } else if (offset > HOUR) { // return (offset / HOUR) + "小时前"; // } else if (offset > MINUTE) { // return (offset / MINUTE) + "分钟前"; // } else { // return "刚刚"; // } // } // // /** // * 检测是否是用户accessToken // */ // public static boolean isAccessToken(String accessToken) { // if (TextUtils.isEmpty(accessToken)) { // return false; // } else { // try { // //noinspection ResultOfMethodCallIgnored // UUID.fromString(accessToken); // return true; // } catch (Exception e) { // return false; // } // } // } // // /** // * 修复头像地址的历史遗留问题 // */ // public static String getCompatAvatarUrl(String avatarUrl) { // if (!TextUtils.isEmpty(avatarUrl) && avatarUrl.startsWith("//gravatar.com/avatar/")) { // return "http:" + avatarUrl; // } else { // return avatarUrl; // } // } // // /** // * 标准URL检测 // */ // // public static boolean isUserLinkUrl(String url) { // return !TextUtils.isEmpty(url) && url.startsWith(ApiDefine.USER_LINK_URL_PREFIX); // } // // public static boolean isTopicLinkUrl(String url) { // return !TextUtils.isEmpty(url) && url.startsWith(ApiDefine.TOPIC_LINK_URL_PREFIX); // } // // /** // * CNode兼容性的Markdown转换 // * '@'协议转换为'/user/'相对路径 // * 解析裸链接 // * 最外层包裹'<div class="markdown-text"></div>' // * 尽可能的实现和服务端渲染相同的结果 // */ // // private static final Markdown md = new Markdown(); // // public static String renderMarkdown(String text) { // // 保证text不为null // text = TextUtils.isEmpty(text) ? "" : text; // // 解析@协议 // text = text.replaceAll("@([\\w\\-]+)\\b(?![]<.])", "[@$1](" + ApiDefine.USER_PATH_PREFIX + "$1)"); // // 解析裸链接 // text = text + " "; // text = text.replaceAll("((http|https|ftp)://[\\w\\-.:/?=&#%]+)(\\s)", "[$1]($1)$3"); // text = text.trim(); // // 渲染markdown // try { // StringWriter out = new StringWriter(); // md.transform(new StringReader(text), out); // text = out.toString(); // } catch (ParseException e) { // // nothing to do // } // // 添加样式容器 // return "<div class=\"markdown-text\">" + text + "</div>"; // } // // /** // * CNode兼容性的Html处理 // * 过滤xss // * 保留div的class属性,但是会清除其他非白名单属性 // * 通过baseUrl补全相对地址 // */ // // private static final Cleaner cleaner = new Cleaner(Whitelist.relaxed().addAttributes("div", "class")); // 主要目的是保留最外层div的markdown-text属性 // // public static Document handleHtml(String html) { // // 保证html不为null // html = TextUtils.isEmpty(html) ? "" : html; // // 过滤xss // return cleaner.clean(Jsoup.parseBodyFragment(html, ApiDefine.HOST_BASE_URL)); // } // // } // Path: app/src/main/java/org/cnodejs/android/md/ui/jsbridge/FormatJavascriptInterface.java import android.webkit.JavascriptInterface; import org.cnodejs.android.md.util.FormatUtils; import org.joda.time.DateTime; package org.cnodejs.android.md.ui.jsbridge; public final class FormatJavascriptInterface { public static final String NAME = "formatBridge"; @JavascriptInterface public String getRelativeTimeSpanString(String time) {
return FormatUtils.getRelativeTimeSpanString(new DateTime(time));
jondwillis/ElectricSleep
src/com/androsz/electricsleepbeta/app/AnalyticFragment.java
// Path: src/com/androsz/electricsleepbeta/util/GoogleAnalyticsSessionHelper.java // public class GoogleAnalyticsSessionHelper { // // private static final String TAG = GoogleAnalyticsSessionHelper.class.getSimpleName(); // // private static GoogleAnalyticsSessionHelper INSTANCE; // // private final String key; // private final Application appContext; // private int sessionCount; // // private GoogleAnalyticsSessionHelper(String key, Application appContext) { // this.key = key; // this.appContext = appContext; // this.sessionCount = 0; // } // // public static GoogleAnalyticsSessionHelper getInstance(String key, Application appContext) { // // Create a new instance if it is not cached. Otherwise, use the // // cached one. // if (INSTANCE == null) { // INSTANCE = new GoogleAnalyticsSessionHelper(key, appContext); // } // return INSTANCE; // } // // public static GoogleAnalyticsSessionHelper getExistingInstance() { // return INSTANCE; // } // // public void onStartSession() { // if (sessionCount == 0) { // GoogleAnalyticsTracker.getInstance().startNewSession(key, appContext); // } // // String versionName = "?"; // try { // versionName = appContext.getPackageManager().getPackageInfo(appContext.getPackageName(), 0).versionName; // } catch (final NameNotFoundException e) { // e.printStackTrace(); // } // // GoogleAnalyticsTracker.getInstance().setProductVersion(appContext.getPackageName(), versionName); // // // I have no idea... // GoogleAnalyticsTracker.getInstance().setCustomVar(1, Integer.toString(VERSION.SDK_INT), // Build.MODEL); // GoogleAnalyticsTracker.getInstance().setCustomVar(2, versionName, // Build.MODEL + "-" + Integer.toString(VERSION.SDK_INT)); // // sessionCount++; // } // // public void onStopSession() { // sessionCount--; // if(sessionCount < 1) // { // sessionCount = 0; // //don't dispatch data to network until we stop // GoogleAnalyticsTracker.getInstance().dispatch(); // GoogleAnalyticsTracker.getInstance().stopSession(); // } // } // // public static void trackEvent(final String label, final int value) { // new AsyncTask<Void, Void, Void>() { // @Override // protected Void doInBackground(Void... params) { // try { // GoogleAnalyticsTracker.getInstance().trackEvent( // Integer.toString(VERSION.SDK_INT), Build.MODEL, label, value); // } catch (final Exception ex) { // Log.d(TAG, "Exception when attempting to track event.", ex); // } // return null; // } // }.execute(); // } // // public static void trackPageView(final String pageUrl) { // new AsyncTask<Void, Void, Void>() { // @Override // protected Void doInBackground(Void... params) { // try { // GoogleAnalyticsTracker.getInstance().trackPageView(pageUrl); // } catch (final Exception ex) { // Log.d(TAG, "Exception while attempting to track page view.", ex); // } // return null; // } // }.execute(); // } // } // // Path: src/com/androsz/electricsleepbeta/util/GoogleAnalyticsTrackerHelper.java // public interface GoogleAnalyticsTrackerHelper { // public void trackEvent(final String label, final int value); // public void trackPageView(final String pageUrl); // }
import android.os.Bundle; import com.actionbarsherlock.app.SherlockFragment; import com.androsz.electricsleepbeta.util.GoogleAnalyticsSessionHelper; import com.androsz.electricsleepbeta.util.GoogleAnalyticsTrackerHelper;
package com.androsz.electricsleepbeta.app; public abstract class AnalyticFragment extends SherlockFragment implements GoogleAnalyticsTrackerHelper { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public void onStart() { super.onStart();
// Path: src/com/androsz/electricsleepbeta/util/GoogleAnalyticsSessionHelper.java // public class GoogleAnalyticsSessionHelper { // // private static final String TAG = GoogleAnalyticsSessionHelper.class.getSimpleName(); // // private static GoogleAnalyticsSessionHelper INSTANCE; // // private final String key; // private final Application appContext; // private int sessionCount; // // private GoogleAnalyticsSessionHelper(String key, Application appContext) { // this.key = key; // this.appContext = appContext; // this.sessionCount = 0; // } // // public static GoogleAnalyticsSessionHelper getInstance(String key, Application appContext) { // // Create a new instance if it is not cached. Otherwise, use the // // cached one. // if (INSTANCE == null) { // INSTANCE = new GoogleAnalyticsSessionHelper(key, appContext); // } // return INSTANCE; // } // // public static GoogleAnalyticsSessionHelper getExistingInstance() { // return INSTANCE; // } // // public void onStartSession() { // if (sessionCount == 0) { // GoogleAnalyticsTracker.getInstance().startNewSession(key, appContext); // } // // String versionName = "?"; // try { // versionName = appContext.getPackageManager().getPackageInfo(appContext.getPackageName(), 0).versionName; // } catch (final NameNotFoundException e) { // e.printStackTrace(); // } // // GoogleAnalyticsTracker.getInstance().setProductVersion(appContext.getPackageName(), versionName); // // // I have no idea... // GoogleAnalyticsTracker.getInstance().setCustomVar(1, Integer.toString(VERSION.SDK_INT), // Build.MODEL); // GoogleAnalyticsTracker.getInstance().setCustomVar(2, versionName, // Build.MODEL + "-" + Integer.toString(VERSION.SDK_INT)); // // sessionCount++; // } // // public void onStopSession() { // sessionCount--; // if(sessionCount < 1) // { // sessionCount = 0; // //don't dispatch data to network until we stop // GoogleAnalyticsTracker.getInstance().dispatch(); // GoogleAnalyticsTracker.getInstance().stopSession(); // } // } // // public static void trackEvent(final String label, final int value) { // new AsyncTask<Void, Void, Void>() { // @Override // protected Void doInBackground(Void... params) { // try { // GoogleAnalyticsTracker.getInstance().trackEvent( // Integer.toString(VERSION.SDK_INT), Build.MODEL, label, value); // } catch (final Exception ex) { // Log.d(TAG, "Exception when attempting to track event.", ex); // } // return null; // } // }.execute(); // } // // public static void trackPageView(final String pageUrl) { // new AsyncTask<Void, Void, Void>() { // @Override // protected Void doInBackground(Void... params) { // try { // GoogleAnalyticsTracker.getInstance().trackPageView(pageUrl); // } catch (final Exception ex) { // Log.d(TAG, "Exception while attempting to track page view.", ex); // } // return null; // } // }.execute(); // } // } // // Path: src/com/androsz/electricsleepbeta/util/GoogleAnalyticsTrackerHelper.java // public interface GoogleAnalyticsTrackerHelper { // public void trackEvent(final String label, final int value); // public void trackPageView(final String pageUrl); // } // Path: src/com/androsz/electricsleepbeta/app/AnalyticFragment.java import android.os.Bundle; import com.actionbarsherlock.app.SherlockFragment; import com.androsz.electricsleepbeta.util.GoogleAnalyticsSessionHelper; import com.androsz.electricsleepbeta.util.GoogleAnalyticsTrackerHelper; package com.androsz.electricsleepbeta.app; public abstract class AnalyticFragment extends SherlockFragment implements GoogleAnalyticsTrackerHelper { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public void onStart() { super.onStart();
GoogleAnalyticsSessionHelper.getInstance(AnalyticActivity.KEY, getActivity().getApplication())
jondwillis/ElectricSleep
src/com/androsz/electricsleepbeta/app/AnalyticActivity.java
// Path: src/com/androsz/electricsleepbeta/util/GoogleAnalyticsSessionHelper.java // public class GoogleAnalyticsSessionHelper { // // private static final String TAG = GoogleAnalyticsSessionHelper.class.getSimpleName(); // // private static GoogleAnalyticsSessionHelper INSTANCE; // // private final String key; // private final Application appContext; // private int sessionCount; // // private GoogleAnalyticsSessionHelper(String key, Application appContext) { // this.key = key; // this.appContext = appContext; // this.sessionCount = 0; // } // // public static GoogleAnalyticsSessionHelper getInstance(String key, Application appContext) { // // Create a new instance if it is not cached. Otherwise, use the // // cached one. // if (INSTANCE == null) { // INSTANCE = new GoogleAnalyticsSessionHelper(key, appContext); // } // return INSTANCE; // } // // public static GoogleAnalyticsSessionHelper getExistingInstance() { // return INSTANCE; // } // // public void onStartSession() { // if (sessionCount == 0) { // GoogleAnalyticsTracker.getInstance().startNewSession(key, appContext); // } // // String versionName = "?"; // try { // versionName = appContext.getPackageManager().getPackageInfo(appContext.getPackageName(), 0).versionName; // } catch (final NameNotFoundException e) { // e.printStackTrace(); // } // // GoogleAnalyticsTracker.getInstance().setProductVersion(appContext.getPackageName(), versionName); // // // I have no idea... // GoogleAnalyticsTracker.getInstance().setCustomVar(1, Integer.toString(VERSION.SDK_INT), // Build.MODEL); // GoogleAnalyticsTracker.getInstance().setCustomVar(2, versionName, // Build.MODEL + "-" + Integer.toString(VERSION.SDK_INT)); // // sessionCount++; // } // // public void onStopSession() { // sessionCount--; // if(sessionCount < 1) // { // sessionCount = 0; // //don't dispatch data to network until we stop // GoogleAnalyticsTracker.getInstance().dispatch(); // GoogleAnalyticsTracker.getInstance().stopSession(); // } // } // // public static void trackEvent(final String label, final int value) { // new AsyncTask<Void, Void, Void>() { // @Override // protected Void doInBackground(Void... params) { // try { // GoogleAnalyticsTracker.getInstance().trackEvent( // Integer.toString(VERSION.SDK_INT), Build.MODEL, label, value); // } catch (final Exception ex) { // Log.d(TAG, "Exception when attempting to track event.", ex); // } // return null; // } // }.execute(); // } // // public static void trackPageView(final String pageUrl) { // new AsyncTask<Void, Void, Void>() { // @Override // protected Void doInBackground(Void... params) { // try { // GoogleAnalyticsTracker.getInstance().trackPageView(pageUrl); // } catch (final Exception ex) { // Log.d(TAG, "Exception while attempting to track page view.", ex); // } // return null; // } // }.execute(); // } // } // // Path: src/com/androsz/electricsleepbeta/util/GoogleAnalyticsTrackerHelper.java // public interface GoogleAnalyticsTrackerHelper { // public void trackEvent(final String label, final int value); // public void trackPageView(final String pageUrl); // }
import com.actionbarsherlock.app.SherlockFragmentActivity; import com.androsz.electricsleepbeta.util.GoogleAnalyticsSessionHelper; import com.androsz.electricsleepbeta.util.GoogleAnalyticsTrackerHelper;
package com.androsz.electricsleepbeta.app; public abstract class AnalyticActivity extends SherlockFragmentActivity implements GoogleAnalyticsTrackerHelper { public static final String KEY = "UA-19363335-1"; @Override protected void onStart() { super.onStart();
// Path: src/com/androsz/electricsleepbeta/util/GoogleAnalyticsSessionHelper.java // public class GoogleAnalyticsSessionHelper { // // private static final String TAG = GoogleAnalyticsSessionHelper.class.getSimpleName(); // // private static GoogleAnalyticsSessionHelper INSTANCE; // // private final String key; // private final Application appContext; // private int sessionCount; // // private GoogleAnalyticsSessionHelper(String key, Application appContext) { // this.key = key; // this.appContext = appContext; // this.sessionCount = 0; // } // // public static GoogleAnalyticsSessionHelper getInstance(String key, Application appContext) { // // Create a new instance if it is not cached. Otherwise, use the // // cached one. // if (INSTANCE == null) { // INSTANCE = new GoogleAnalyticsSessionHelper(key, appContext); // } // return INSTANCE; // } // // public static GoogleAnalyticsSessionHelper getExistingInstance() { // return INSTANCE; // } // // public void onStartSession() { // if (sessionCount == 0) { // GoogleAnalyticsTracker.getInstance().startNewSession(key, appContext); // } // // String versionName = "?"; // try { // versionName = appContext.getPackageManager().getPackageInfo(appContext.getPackageName(), 0).versionName; // } catch (final NameNotFoundException e) { // e.printStackTrace(); // } // // GoogleAnalyticsTracker.getInstance().setProductVersion(appContext.getPackageName(), versionName); // // // I have no idea... // GoogleAnalyticsTracker.getInstance().setCustomVar(1, Integer.toString(VERSION.SDK_INT), // Build.MODEL); // GoogleAnalyticsTracker.getInstance().setCustomVar(2, versionName, // Build.MODEL + "-" + Integer.toString(VERSION.SDK_INT)); // // sessionCount++; // } // // public void onStopSession() { // sessionCount--; // if(sessionCount < 1) // { // sessionCount = 0; // //don't dispatch data to network until we stop // GoogleAnalyticsTracker.getInstance().dispatch(); // GoogleAnalyticsTracker.getInstance().stopSession(); // } // } // // public static void trackEvent(final String label, final int value) { // new AsyncTask<Void, Void, Void>() { // @Override // protected Void doInBackground(Void... params) { // try { // GoogleAnalyticsTracker.getInstance().trackEvent( // Integer.toString(VERSION.SDK_INT), Build.MODEL, label, value); // } catch (final Exception ex) { // Log.d(TAG, "Exception when attempting to track event.", ex); // } // return null; // } // }.execute(); // } // // public static void trackPageView(final String pageUrl) { // new AsyncTask<Void, Void, Void>() { // @Override // protected Void doInBackground(Void... params) { // try { // GoogleAnalyticsTracker.getInstance().trackPageView(pageUrl); // } catch (final Exception ex) { // Log.d(TAG, "Exception while attempting to track page view.", ex); // } // return null; // } // }.execute(); // } // } // // Path: src/com/androsz/electricsleepbeta/util/GoogleAnalyticsTrackerHelper.java // public interface GoogleAnalyticsTrackerHelper { // public void trackEvent(final String label, final int value); // public void trackPageView(final String pageUrl); // } // Path: src/com/androsz/electricsleepbeta/app/AnalyticActivity.java import com.actionbarsherlock.app.SherlockFragmentActivity; import com.androsz.electricsleepbeta.util.GoogleAnalyticsSessionHelper; import com.androsz.electricsleepbeta.util.GoogleAnalyticsTrackerHelper; package com.androsz.electricsleepbeta.app; public abstract class AnalyticActivity extends SherlockFragmentActivity implements GoogleAnalyticsTrackerHelper { public static final String KEY = "UA-19363335-1"; @Override protected void onStart() { super.onStart();
GoogleAnalyticsSessionHelper.getInstance(KEY, getApplication()).onStartSession();
jondwillis/ElectricSleep
src/com/androsz/electricsleepbeta/db/SleepSession.java
// Path: src/com/androsz/electricsleepbeta/util/PointD.java // public class PointD implements Serializable { // private static final long serialVersionUID = -7526147553632397385L; // public static int BYTE_LENGTH = 16; // // public static PointD fromByteArray(final byte[] data) { // final byte[] temp = new byte[8]; // double x; // double y; // System.arraycopy(data, 0, temp, 0, 8); // x = toDouble(temp); // System.arraycopy(data, 8, temp, 0, 8); // y = toDouble(temp); // return new PointD(x, y); // } // // private static byte[] toByte(final double data) { // return toByte(Double.doubleToRawLongBits(data)); // } // // private static byte[] toByte(final long data) { // return new byte[] { (byte) (data >> 56 & 0xff), (byte) (data >> 48 & 0xff), // (byte) (data >> 40 & 0xff), (byte) (data >> 32 & 0xff), (byte) (data >> 24 & 0xff), // (byte) (data >> 16 & 0xff), (byte) (data >> 8 & 0xff), (byte) (data >> 0 & 0xff), }; // } // // public static byte[] toByteArray(final PointD point) { // final byte[] bytes = new byte[16]; // System.arraycopy(toByte(point.x), 0, bytes, 0, 8); // System.arraycopy(toByte(point.y), 0, bytes, 8, 8); // return bytes; // } // // private static double toDouble(final byte[] data) { // if (data == null || data.length != 8) { // return 0x0; // } // return Double.longBitsToDouble(toLong(data)); // } // // private static long toLong(final byte[] data) { // if (data == null || data.length != 8) { // return 0x0; // } // return (long) (0xff & data[0]) << 56 | (long) (0xff & data[1]) << 48 // | (long) (0xff & data[2]) << 40 | (long) (0xff & data[3]) << 32 // | (long) (0xff & data[4]) << 24 | (long) (0xff & data[5]) << 16 // | (long) (0xff & data[6]) << 8 | (long) (0xff & data[7]) << 0; // } // // public double x; // // public double y; // // public PointD(final double x, final double y) { // this.x = x; // this.y = y; // } // // public static List<org.achartengine.model.PointD> convertToNew(List<PointD> oldList) { // ArrayList<org.achartengine.model.PointD> newList = new ArrayList<org.achartengine.model.PointD>(oldList.size()); // for(PointD oldPoint : oldList) // { // newList.add(new org.achartengine.model.PointD(oldPoint.x, oldPoint.y)); // } // return newList; // } // } // // Path: src/com/androsz/electricsleepbeta/db/ElectricSleepProvider.java // public interface TimestampColumns { // String CREATED_ON = "created_on"; // String UPDATED_ON = "updated_on"; // }
import com.androsz.electricsleepbeta.R; import com.androsz.electricsleepbeta.util.PointD; import static com.androsz.electricsleepbeta.db.ElectricSleepProvider.TimestampColumns; import com.google.android.apps.analytics.GoogleAnalyticsTracker; import android.content.ContentValues; import android.content.Context; import android.content.res.Resources; import android.database.Cursor; import android.net.Uri; import android.os.Build.VERSION; import android.os.Build; import android.provider.BaseColumns; import android.text.format.DateUtils; import android.text.format.Time; import android.util.Log; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.StreamCorruptedException; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import java.util.TimeZone;
package com.androsz.electricsleepbeta.db; public class SleepSession implements BaseColumns, SleepSessionKeys, TimestampColumns { private static final String TAG = SleepSession.class.getSimpleName(); /** Value that marks whether or not the database row id is valid. */ private static final long ROW_INVALID = 0; /** * Path used to access sleep session both via the provider as well as the * table name. */ public static final String PATH = "sleep_sessions"; public static final Uri CONTENT_URI = ElectricSleepProvider.BASE_CONTENT_URI .buildUpon().appendPath(PATH).build(); /** * The MIME type of {@link #CONTENT_URI}. */ public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.androsz.electricsleepbeta." + PATH; /** * The MIME type of a {@link #CONTENT_URI} sub-directory of a single row. */ public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.androsz.electricsleepbeta." + PATH; public static final String DEFAULT_SORT_ORDER = START_TIMESTAMP + " DESC"; public static final String SORT_ORDER_LIMIT_60 = DEFAULT_SORT_ORDER + " LIMIT 60"; static String[] PROJECTION = new String[] { _ID, START_TIMESTAMP, START_JULIAN_DAY, END_TIMESTAMP, TIMEZONE, DATA, DURATION, NOTE, RATING, SPIKES, CALIBRATION_LEVEL, MIN, FELL_ASLEEP_TIMESTAMP, CREATED_ON, UPDATED_ON }; float mCalibrationLevel;
// Path: src/com/androsz/electricsleepbeta/util/PointD.java // public class PointD implements Serializable { // private static final long serialVersionUID = -7526147553632397385L; // public static int BYTE_LENGTH = 16; // // public static PointD fromByteArray(final byte[] data) { // final byte[] temp = new byte[8]; // double x; // double y; // System.arraycopy(data, 0, temp, 0, 8); // x = toDouble(temp); // System.arraycopy(data, 8, temp, 0, 8); // y = toDouble(temp); // return new PointD(x, y); // } // // private static byte[] toByte(final double data) { // return toByte(Double.doubleToRawLongBits(data)); // } // // private static byte[] toByte(final long data) { // return new byte[] { (byte) (data >> 56 & 0xff), (byte) (data >> 48 & 0xff), // (byte) (data >> 40 & 0xff), (byte) (data >> 32 & 0xff), (byte) (data >> 24 & 0xff), // (byte) (data >> 16 & 0xff), (byte) (data >> 8 & 0xff), (byte) (data >> 0 & 0xff), }; // } // // public static byte[] toByteArray(final PointD point) { // final byte[] bytes = new byte[16]; // System.arraycopy(toByte(point.x), 0, bytes, 0, 8); // System.arraycopy(toByte(point.y), 0, bytes, 8, 8); // return bytes; // } // // private static double toDouble(final byte[] data) { // if (data == null || data.length != 8) { // return 0x0; // } // return Double.longBitsToDouble(toLong(data)); // } // // private static long toLong(final byte[] data) { // if (data == null || data.length != 8) { // return 0x0; // } // return (long) (0xff & data[0]) << 56 | (long) (0xff & data[1]) << 48 // | (long) (0xff & data[2]) << 40 | (long) (0xff & data[3]) << 32 // | (long) (0xff & data[4]) << 24 | (long) (0xff & data[5]) << 16 // | (long) (0xff & data[6]) << 8 | (long) (0xff & data[7]) << 0; // } // // public double x; // // public double y; // // public PointD(final double x, final double y) { // this.x = x; // this.y = y; // } // // public static List<org.achartengine.model.PointD> convertToNew(List<PointD> oldList) { // ArrayList<org.achartengine.model.PointD> newList = new ArrayList<org.achartengine.model.PointD>(oldList.size()); // for(PointD oldPoint : oldList) // { // newList.add(new org.achartengine.model.PointD(oldPoint.x, oldPoint.y)); // } // return newList; // } // } // // Path: src/com/androsz/electricsleepbeta/db/ElectricSleepProvider.java // public interface TimestampColumns { // String CREATED_ON = "created_on"; // String UPDATED_ON = "updated_on"; // } // Path: src/com/androsz/electricsleepbeta/db/SleepSession.java import com.androsz.electricsleepbeta.R; import com.androsz.electricsleepbeta.util.PointD; import static com.androsz.electricsleepbeta.db.ElectricSleepProvider.TimestampColumns; import com.google.android.apps.analytics.GoogleAnalyticsTracker; import android.content.ContentValues; import android.content.Context; import android.content.res.Resources; import android.database.Cursor; import android.net.Uri; import android.os.Build.VERSION; import android.os.Build; import android.provider.BaseColumns; import android.text.format.DateUtils; import android.text.format.Time; import android.util.Log; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.StreamCorruptedException; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import java.util.TimeZone; package com.androsz.electricsleepbeta.db; public class SleepSession implements BaseColumns, SleepSessionKeys, TimestampColumns { private static final String TAG = SleepSession.class.getSimpleName(); /** Value that marks whether or not the database row id is valid. */ private static final long ROW_INVALID = 0; /** * Path used to access sleep session both via the provider as well as the * table name. */ public static final String PATH = "sleep_sessions"; public static final Uri CONTENT_URI = ElectricSleepProvider.BASE_CONTENT_URI .buildUpon().appendPath(PATH).build(); /** * The MIME type of {@link #CONTENT_URI}. */ public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.androsz.electricsleepbeta." + PATH; /** * The MIME type of a {@link #CONTENT_URI} sub-directory of a single row. */ public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.androsz.electricsleepbeta." + PATH; public static final String DEFAULT_SORT_ORDER = START_TIMESTAMP + " DESC"; public static final String SORT_ORDER_LIMIT_60 = DEFAULT_SORT_ORDER + " LIMIT 60"; static String[] PROJECTION = new String[] { _ID, START_TIMESTAMP, START_JULIAN_DAY, END_TIMESTAMP, TIMEZONE, DATA, DURATION, NOTE, RATING, SPIKES, CALIBRATION_LEVEL, MIN, FELL_ASLEEP_TIMESTAMP, CREATED_ON, UPDATED_ON }; float mCalibrationLevel;
List<PointD> mData;
jondwillis/ElectricSleep
src/com/androsz/electricsleepbeta/app/LayoutFragment.java
// Path: src/com/androsz/electricsleepbeta/util/GoogleAnalyticsSessionHelper.java // public class GoogleAnalyticsSessionHelper { // // private static final String TAG = GoogleAnalyticsSessionHelper.class.getSimpleName(); // // private static GoogleAnalyticsSessionHelper INSTANCE; // // private final String key; // private final Application appContext; // private int sessionCount; // // private GoogleAnalyticsSessionHelper(String key, Application appContext) { // this.key = key; // this.appContext = appContext; // this.sessionCount = 0; // } // // public static GoogleAnalyticsSessionHelper getInstance(String key, Application appContext) { // // Create a new instance if it is not cached. Otherwise, use the // // cached one. // if (INSTANCE == null) { // INSTANCE = new GoogleAnalyticsSessionHelper(key, appContext); // } // return INSTANCE; // } // // public static GoogleAnalyticsSessionHelper getExistingInstance() { // return INSTANCE; // } // // public void onStartSession() { // if (sessionCount == 0) { // GoogleAnalyticsTracker.getInstance().startNewSession(key, appContext); // } // // String versionName = "?"; // try { // versionName = appContext.getPackageManager().getPackageInfo(appContext.getPackageName(), 0).versionName; // } catch (final NameNotFoundException e) { // e.printStackTrace(); // } // // GoogleAnalyticsTracker.getInstance().setProductVersion(appContext.getPackageName(), versionName); // // // I have no idea... // GoogleAnalyticsTracker.getInstance().setCustomVar(1, Integer.toString(VERSION.SDK_INT), // Build.MODEL); // GoogleAnalyticsTracker.getInstance().setCustomVar(2, versionName, // Build.MODEL + "-" + Integer.toString(VERSION.SDK_INT)); // // sessionCount++; // } // // public void onStopSession() { // sessionCount--; // if(sessionCount < 1) // { // sessionCount = 0; // //don't dispatch data to network until we stop // GoogleAnalyticsTracker.getInstance().dispatch(); // GoogleAnalyticsTracker.getInstance().stopSession(); // } // } // // public static void trackEvent(final String label, final int value) { // new AsyncTask<Void, Void, Void>() { // @Override // protected Void doInBackground(Void... params) { // try { // GoogleAnalyticsTracker.getInstance().trackEvent( // Integer.toString(VERSION.SDK_INT), Build.MODEL, label, value); // } catch (final Exception ex) { // Log.d(TAG, "Exception when attempting to track event.", ex); // } // return null; // } // }.execute(); // } // // public static void trackPageView(final String pageUrl) { // new AsyncTask<Void, Void, Void>() { // @Override // protected Void doInBackground(Void... params) { // try { // GoogleAnalyticsTracker.getInstance().trackPageView(pageUrl); // } catch (final Exception ex) { // Log.d(TAG, "Exception while attempting to track page view.", ex); // } // return null; // } // }.execute(); // } // } // // Path: src/com/androsz/electricsleepbeta/util/GoogleAnalyticsTrackerHelper.java // public interface GoogleAnalyticsTrackerHelper { // public void trackEvent(final String label, final int value); // public void trackPageView(final String pageUrl); // }
import com.androsz.electricsleepbeta.util.GoogleAnalyticsSessionHelper; import com.androsz.electricsleepbeta.util.GoogleAnalyticsTrackerHelper; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup;
package com.androsz.electricsleepbeta.app; public abstract class LayoutFragment extends Fragment implements GoogleAnalyticsTrackerHelper { public void trackEvent(final String label, final int value) {
// Path: src/com/androsz/electricsleepbeta/util/GoogleAnalyticsSessionHelper.java // public class GoogleAnalyticsSessionHelper { // // private static final String TAG = GoogleAnalyticsSessionHelper.class.getSimpleName(); // // private static GoogleAnalyticsSessionHelper INSTANCE; // // private final String key; // private final Application appContext; // private int sessionCount; // // private GoogleAnalyticsSessionHelper(String key, Application appContext) { // this.key = key; // this.appContext = appContext; // this.sessionCount = 0; // } // // public static GoogleAnalyticsSessionHelper getInstance(String key, Application appContext) { // // Create a new instance if it is not cached. Otherwise, use the // // cached one. // if (INSTANCE == null) { // INSTANCE = new GoogleAnalyticsSessionHelper(key, appContext); // } // return INSTANCE; // } // // public static GoogleAnalyticsSessionHelper getExistingInstance() { // return INSTANCE; // } // // public void onStartSession() { // if (sessionCount == 0) { // GoogleAnalyticsTracker.getInstance().startNewSession(key, appContext); // } // // String versionName = "?"; // try { // versionName = appContext.getPackageManager().getPackageInfo(appContext.getPackageName(), 0).versionName; // } catch (final NameNotFoundException e) { // e.printStackTrace(); // } // // GoogleAnalyticsTracker.getInstance().setProductVersion(appContext.getPackageName(), versionName); // // // I have no idea... // GoogleAnalyticsTracker.getInstance().setCustomVar(1, Integer.toString(VERSION.SDK_INT), // Build.MODEL); // GoogleAnalyticsTracker.getInstance().setCustomVar(2, versionName, // Build.MODEL + "-" + Integer.toString(VERSION.SDK_INT)); // // sessionCount++; // } // // public void onStopSession() { // sessionCount--; // if(sessionCount < 1) // { // sessionCount = 0; // //don't dispatch data to network until we stop // GoogleAnalyticsTracker.getInstance().dispatch(); // GoogleAnalyticsTracker.getInstance().stopSession(); // } // } // // public static void trackEvent(final String label, final int value) { // new AsyncTask<Void, Void, Void>() { // @Override // protected Void doInBackground(Void... params) { // try { // GoogleAnalyticsTracker.getInstance().trackEvent( // Integer.toString(VERSION.SDK_INT), Build.MODEL, label, value); // } catch (final Exception ex) { // Log.d(TAG, "Exception when attempting to track event.", ex); // } // return null; // } // }.execute(); // } // // public static void trackPageView(final String pageUrl) { // new AsyncTask<Void, Void, Void>() { // @Override // protected Void doInBackground(Void... params) { // try { // GoogleAnalyticsTracker.getInstance().trackPageView(pageUrl); // } catch (final Exception ex) { // Log.d(TAG, "Exception while attempting to track page view.", ex); // } // return null; // } // }.execute(); // } // } // // Path: src/com/androsz/electricsleepbeta/util/GoogleAnalyticsTrackerHelper.java // public interface GoogleAnalyticsTrackerHelper { // public void trackEvent(final String label, final int value); // public void trackPageView(final String pageUrl); // } // Path: src/com/androsz/electricsleepbeta/app/LayoutFragment.java import com.androsz.electricsleepbeta.util.GoogleAnalyticsSessionHelper; import com.androsz.electricsleepbeta.util.GoogleAnalyticsTrackerHelper; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; package com.androsz.electricsleepbeta.app; public abstract class LayoutFragment extends Fragment implements GoogleAnalyticsTrackerHelper { public void trackEvent(final String label, final int value) {
GoogleAnalyticsSessionHelper.trackEvent(label, value);
jondwillis/ElectricSleep
src/com/androsz/electricsleepbeta/alarmclock/AlarmKlaxon.java
// Path: src/com/androsz/electricsleepbeta/util/WakeLockManager.java // public class WakeLockManager { // private static Map<String, PowerManager.WakeLock> locks = new ConcurrentHashMap<String, PowerManager.WakeLock>(); // // private static final String TAG = WakeLockManager.class.getSimpleName(); // // public static void acquire(Context context, String id, int flags) { // acquire(context, id, flags, 0); // } // // public static void acquire(Context context, String id, int flags, int releaseAfterMs) { // final PowerManager mgr = (PowerManager) context.getApplicationContext().getSystemService( // Context.POWER_SERVICE); // // // create the new wakelock and put it into the map // final WakeLock newWakeLock = mgr.newWakeLock(flags, id.toString()); // // // if this wakelock doesn't already exist, continue // locks.put(id, newWakeLock); // // only one at a time? TODO // newWakeLock.setReferenceCounted(false); // // if (releaseAfterMs == 0) { // newWakeLock.acquire(); // } else { // newWakeLock.acquire(releaseAfterMs); // } // } // // public static void release(String id) { // final WakeLock wakeLock = locks.get(id); // // if there is was a wakelock, release it. (it has to be held) // try { // if (wakeLock != null) { // wakeLock.release(); // } // } catch (Exception ex) { // // android's wakelocks are buggy? // Log.d(TAG, "Exception while attempting to release wake lock.", ex); // } finally { // locks.remove(id); // } // } // }
import android.app.Service; import android.content.Context; import android.content.Intent; import android.content.res.AssetFileDescriptor; import android.content.res.Resources; import android.media.AudioManager; import android.media.MediaPlayer; import android.media.MediaPlayer.OnErrorListener; import android.media.RingtoneManager; import android.net.Uri; import android.os.Handler; import android.os.IBinder; import android.os.Message; import android.os.PowerManager; import android.os.Vibrator; import android.telephony.PhoneStateListener; import android.telephony.TelephonyManager; import com.androsz.electricsleepbeta.R; import com.androsz.electricsleepbeta.util.WakeLockManager;
/* * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.androsz.electricsleepbeta.alarmclock; /** * Manages alarms and vibe. Runs as a service so that it can continue to play if * another activity overrides the AlarmAlert dialog. */ public class AlarmKlaxon extends Service { /** Play alarm up to 10 minutes before silencing */ private static final int ALARM_TIMEOUT_SECONDS = 10 * 60; // Volume suggested by media team for in-call alarms. private static final float IN_CALL_VOLUME = 0.125f; // Internal messages private static final int KILLER = 1000; private static final long[] sVibratePattern = new long[] { 500, 500 }; private Alarm mCurrentAlarm; private final Handler mHandler = new Handler() { @Override public void handleMessage(final Message msg) { switch (msg.what) { case KILLER: if (Log.LOGV) { Log.v("*********** Alarm killer triggered ***********"); } sendKillBroadcast((Alarm) msg.obj); stopSelf(); break; } } }; private int mInitialCallState; private MediaPlayer mMediaPlayer; private final PhoneStateListener mPhoneStateListener = new PhoneStateListener() { @Override public void onCallStateChanged(final int state, final String ignored) { // The user might already be in a call when the alarm fires. When // we register onCallStateChanged, we get the initial in-call state // which kills the alarm. Check against the initial call state so // we don't kill the alarm during a call. if (state != TelephonyManager.CALL_STATE_IDLE && state != mInitialCallState) { sendKillBroadcast(mCurrentAlarm); stopSelf(); } } }; private boolean mPlaying = false; private long mStartTime; private TelephonyManager mTelephonyManager; private Vibrator mVibrator; private void disableKiller() { mHandler.removeMessages(KILLER); } /** * Kills alarm audio after ALARM_TIMEOUT_SECONDS, so the alarm won't run all * day. * * This just cancels the audio, but leaves the notification popped, so the * user will know that the alarm tripped. */ private void enableKiller(final Alarm alarm) { mHandler.sendMessageDelayed(mHandler.obtainMessage(KILLER, alarm), 1000 * ALARM_TIMEOUT_SECONDS); } @Override public IBinder onBind(final Intent intent) { return null; } @Override public void onCreate() { mVibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE); // Listen for incoming calls to kill the alarm. mTelephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); mTelephonyManager.listen(mPhoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
// Path: src/com/androsz/electricsleepbeta/util/WakeLockManager.java // public class WakeLockManager { // private static Map<String, PowerManager.WakeLock> locks = new ConcurrentHashMap<String, PowerManager.WakeLock>(); // // private static final String TAG = WakeLockManager.class.getSimpleName(); // // public static void acquire(Context context, String id, int flags) { // acquire(context, id, flags, 0); // } // // public static void acquire(Context context, String id, int flags, int releaseAfterMs) { // final PowerManager mgr = (PowerManager) context.getApplicationContext().getSystemService( // Context.POWER_SERVICE); // // // create the new wakelock and put it into the map // final WakeLock newWakeLock = mgr.newWakeLock(flags, id.toString()); // // // if this wakelock doesn't already exist, continue // locks.put(id, newWakeLock); // // only one at a time? TODO // newWakeLock.setReferenceCounted(false); // // if (releaseAfterMs == 0) { // newWakeLock.acquire(); // } else { // newWakeLock.acquire(releaseAfterMs); // } // } // // public static void release(String id) { // final WakeLock wakeLock = locks.get(id); // // if there is was a wakelock, release it. (it has to be held) // try { // if (wakeLock != null) { // wakeLock.release(); // } // } catch (Exception ex) { // // android's wakelocks are buggy? // Log.d(TAG, "Exception while attempting to release wake lock.", ex); // } finally { // locks.remove(id); // } // } // } // Path: src/com/androsz/electricsleepbeta/alarmclock/AlarmKlaxon.java import android.app.Service; import android.content.Context; import android.content.Intent; import android.content.res.AssetFileDescriptor; import android.content.res.Resources; import android.media.AudioManager; import android.media.MediaPlayer; import android.media.MediaPlayer.OnErrorListener; import android.media.RingtoneManager; import android.net.Uri; import android.os.Handler; import android.os.IBinder; import android.os.Message; import android.os.PowerManager; import android.os.Vibrator; import android.telephony.PhoneStateListener; import android.telephony.TelephonyManager; import com.androsz.electricsleepbeta.R; import com.androsz.electricsleepbeta.util.WakeLockManager; /* * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.androsz.electricsleepbeta.alarmclock; /** * Manages alarms and vibe. Runs as a service so that it can continue to play if * another activity overrides the AlarmAlert dialog. */ public class AlarmKlaxon extends Service { /** Play alarm up to 10 minutes before silencing */ private static final int ALARM_TIMEOUT_SECONDS = 10 * 60; // Volume suggested by media team for in-call alarms. private static final float IN_CALL_VOLUME = 0.125f; // Internal messages private static final int KILLER = 1000; private static final long[] sVibratePattern = new long[] { 500, 500 }; private Alarm mCurrentAlarm; private final Handler mHandler = new Handler() { @Override public void handleMessage(final Message msg) { switch (msg.what) { case KILLER: if (Log.LOGV) { Log.v("*********** Alarm killer triggered ***********"); } sendKillBroadcast((Alarm) msg.obj); stopSelf(); break; } } }; private int mInitialCallState; private MediaPlayer mMediaPlayer; private final PhoneStateListener mPhoneStateListener = new PhoneStateListener() { @Override public void onCallStateChanged(final int state, final String ignored) { // The user might already be in a call when the alarm fires. When // we register onCallStateChanged, we get the initial in-call state // which kills the alarm. Check against the initial call state so // we don't kill the alarm during a call. if (state != TelephonyManager.CALL_STATE_IDLE && state != mInitialCallState) { sendKillBroadcast(mCurrentAlarm); stopSelf(); } } }; private boolean mPlaying = false; private long mStartTime; private TelephonyManager mTelephonyManager; private Vibrator mVibrator; private void disableKiller() { mHandler.removeMessages(KILLER); } /** * Kills alarm audio after ALARM_TIMEOUT_SECONDS, so the alarm won't run all * day. * * This just cancels the audio, but leaves the notification popped, so the * user will know that the alarm tripped. */ private void enableKiller(final Alarm alarm) { mHandler.sendMessageDelayed(mHandler.obtainMessage(KILLER, alarm), 1000 * ALARM_TIMEOUT_SECONDS); } @Override public IBinder onBind(final Intent intent) { return null; } @Override public void onCreate() { mVibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE); // Listen for incoming calls to kill the alarm. mTelephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); mTelephonyManager.listen(mPhoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
WakeLockManager.release("alarmReceiver");
jondwillis/ElectricSleep
src/com/androsz/electricsleepbeta/alarmclock/AlarmReceiver.java
// Path: src/com/androsz/electricsleepbeta/util/WakeLockManager.java // public class WakeLockManager { // private static Map<String, PowerManager.WakeLock> locks = new ConcurrentHashMap<String, PowerManager.WakeLock>(); // // private static final String TAG = WakeLockManager.class.getSimpleName(); // // public static void acquire(Context context, String id, int flags) { // acquire(context, id, flags, 0); // } // // public static void acquire(Context context, String id, int flags, int releaseAfterMs) { // final PowerManager mgr = (PowerManager) context.getApplicationContext().getSystemService( // Context.POWER_SERVICE); // // // create the new wakelock and put it into the map // final WakeLock newWakeLock = mgr.newWakeLock(flags, id.toString()); // // // if this wakelock doesn't already exist, continue // locks.put(id, newWakeLock); // // only one at a time? TODO // newWakeLock.setReferenceCounted(false); // // if (releaseAfterMs == 0) { // newWakeLock.acquire(); // } else { // newWakeLock.acquire(releaseAfterMs); // } // } // // public static void release(String id) { // final WakeLock wakeLock = locks.get(id); // // if there is was a wakelock, release it. (it has to be held) // try { // if (wakeLock != null) { // wakeLock.release(); // } // } catch (Exception ex) { // // android's wakelocks are buggy? // Log.d(TAG, "Exception while attempting to release wake lock.", ex); // } finally { // locks.remove(id); // } // } // }
import com.androsz.electricsleepbeta.util.WakeLockManager; import java.text.SimpleDateFormat; import java.util.Date; import android.app.KeyguardManager; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Parcel; import android.os.PowerManager; import com.androsz.electricsleepbeta.R;
// To avoid this, do the marshalling ourselves. final byte[] data = intent.getByteArrayExtra(Alarms.ALARM_RAW_DATA); if (data != null) { final Parcel in = Parcel.obtain(); in.unmarshall(data, 0, data.length); in.setDataPosition(0); alarm = Alarm.CREATOR.createFromParcel(in); } if (alarm == null) { Log.v("AlarmReceiver failed to parse the alarm from the intent"); return; } // Intentionally verbose: always log the alarm time to provide useful // information in bug reports. final long now = System.currentTimeMillis(); final SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss.SSS aaa"); Log.v("AlarmReceiver.onReceive() id " + alarm.id + " setFor " + format.format(new Date(alarm.time))); if (now > alarm.time + STALE_WINDOW * 1000) { if (Log.LOGV) { Log.v("AlarmReceiver ignoring stale alarm"); } return; } // Maintain a cpu wake lock until the AlarmAlert and AlarmKlaxon can // pick it up.
// Path: src/com/androsz/electricsleepbeta/util/WakeLockManager.java // public class WakeLockManager { // private static Map<String, PowerManager.WakeLock> locks = new ConcurrentHashMap<String, PowerManager.WakeLock>(); // // private static final String TAG = WakeLockManager.class.getSimpleName(); // // public static void acquire(Context context, String id, int flags) { // acquire(context, id, flags, 0); // } // // public static void acquire(Context context, String id, int flags, int releaseAfterMs) { // final PowerManager mgr = (PowerManager) context.getApplicationContext().getSystemService( // Context.POWER_SERVICE); // // // create the new wakelock and put it into the map // final WakeLock newWakeLock = mgr.newWakeLock(flags, id.toString()); // // // if this wakelock doesn't already exist, continue // locks.put(id, newWakeLock); // // only one at a time? TODO // newWakeLock.setReferenceCounted(false); // // if (releaseAfterMs == 0) { // newWakeLock.acquire(); // } else { // newWakeLock.acquire(releaseAfterMs); // } // } // // public static void release(String id) { // final WakeLock wakeLock = locks.get(id); // // if there is was a wakelock, release it. (it has to be held) // try { // if (wakeLock != null) { // wakeLock.release(); // } // } catch (Exception ex) { // // android's wakelocks are buggy? // Log.d(TAG, "Exception while attempting to release wake lock.", ex); // } finally { // locks.remove(id); // } // } // } // Path: src/com/androsz/electricsleepbeta/alarmclock/AlarmReceiver.java import com.androsz.electricsleepbeta.util.WakeLockManager; import java.text.SimpleDateFormat; import java.util.Date; import android.app.KeyguardManager; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Parcel; import android.os.PowerManager; import com.androsz.electricsleepbeta.R; // To avoid this, do the marshalling ourselves. final byte[] data = intent.getByteArrayExtra(Alarms.ALARM_RAW_DATA); if (data != null) { final Parcel in = Parcel.obtain(); in.unmarshall(data, 0, data.length); in.setDataPosition(0); alarm = Alarm.CREATOR.createFromParcel(in); } if (alarm == null) { Log.v("AlarmReceiver failed to parse the alarm from the intent"); return; } // Intentionally verbose: always log the alarm time to provide useful // information in bug reports. final long now = System.currentTimeMillis(); final SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss.SSS aaa"); Log.v("AlarmReceiver.onReceive() id " + alarm.id + " setFor " + format.format(new Date(alarm.time))); if (now > alarm.time + STALE_WINDOW * 1000) { if (Log.LOGV) { Log.v("AlarmReceiver ignoring stale alarm"); } return; } // Maintain a cpu wake lock until the AlarmAlert and AlarmKlaxon can // pick it up.
WakeLockManager.acquire(context, "alarmReceiver", PowerManager.PARTIAL_WAKE_LOCK
jondwillis/ElectricSleep
src/com/androsz/electricsleepbeta/db/ElectricSleepDatabase.java
// Path: src/com/androsz/electricsleepbeta/util/PointD.java // public class PointD implements Serializable { // private static final long serialVersionUID = -7526147553632397385L; // public static int BYTE_LENGTH = 16; // // public static PointD fromByteArray(final byte[] data) { // final byte[] temp = new byte[8]; // double x; // double y; // System.arraycopy(data, 0, temp, 0, 8); // x = toDouble(temp); // System.arraycopy(data, 8, temp, 0, 8); // y = toDouble(temp); // return new PointD(x, y); // } // // private static byte[] toByte(final double data) { // return toByte(Double.doubleToRawLongBits(data)); // } // // private static byte[] toByte(final long data) { // return new byte[] { (byte) (data >> 56 & 0xff), (byte) (data >> 48 & 0xff), // (byte) (data >> 40 & 0xff), (byte) (data >> 32 & 0xff), (byte) (data >> 24 & 0xff), // (byte) (data >> 16 & 0xff), (byte) (data >> 8 & 0xff), (byte) (data >> 0 & 0xff), }; // } // // public static byte[] toByteArray(final PointD point) { // final byte[] bytes = new byte[16]; // System.arraycopy(toByte(point.x), 0, bytes, 0, 8); // System.arraycopy(toByte(point.y), 0, bytes, 8, 8); // return bytes; // } // // private static double toDouble(final byte[] data) { // if (data == null || data.length != 8) { // return 0x0; // } // return Double.longBitsToDouble(toLong(data)); // } // // private static long toLong(final byte[] data) { // if (data == null || data.length != 8) { // return 0x0; // } // return (long) (0xff & data[0]) << 56 | (long) (0xff & data[1]) << 48 // | (long) (0xff & data[2]) << 40 | (long) (0xff & data[3]) << 32 // | (long) (0xff & data[4]) << 24 | (long) (0xff & data[5]) << 16 // | (long) (0xff & data[6]) << 8 | (long) (0xff & data[7]) << 0; // } // // public double x; // // public double y; // // public PointD(final double x, final double y) { // this.x = x; // this.y = y; // } // // public static List<org.achartengine.model.PointD> convertToNew(List<PointD> oldList) { // ArrayList<org.achartengine.model.PointD> newList = new ArrayList<org.achartengine.model.PointD>(oldList.size()); // for(PointD oldPoint : oldList) // { // newList.add(new org.achartengine.model.PointD(oldPoint.x, oldPoint.y)); // } // return newList; // } // }
import com.androsz.electricsleepbeta.util.PointD; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.util.List; import java.util.TimeZone;
SleepSession.DURATION + " INTEGER," + SleepSession.CALIBRATION_LEVEL + " REAL," + SleepSession.MIN + " REAL," + SleepSession.NOTE + " TEXT" + ")"); final String DURATION = "KEY_SLEEP_DATA_DURATION"; final String ALARM = "sleep_data_alarm"; final String MIN = "sleep_data_min"; final String NOTE = "KEY_SLEEP_DATA_NOTE"; final String RATING = "sleep_data_rating"; final String SPIKES = "KEY_SLEEP_DATA_SPIKES"; final String DATA = "sleep_data"; final String FELL_ASLEEP_TIMESTAMP = "KEY_SLEEP_DATA_TIME_FELL_ASLEEP"; // copy over existing data Cursor cursor = db.query( "FTSsleephistory", new String[] { DATA, SPIKES, RATING, NOTE, MIN, DURATION, ALARM, FELL_ASLEEP_TIMESTAMP }, null, null, null, null, null); if (cursor.moveToFirst()) { do { ContentValues values = new ContentValues(8); // populate the start and end timestamps byte[] bytes = cursor.getBlob(0); try { ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bytes));
// Path: src/com/androsz/electricsleepbeta/util/PointD.java // public class PointD implements Serializable { // private static final long serialVersionUID = -7526147553632397385L; // public static int BYTE_LENGTH = 16; // // public static PointD fromByteArray(final byte[] data) { // final byte[] temp = new byte[8]; // double x; // double y; // System.arraycopy(data, 0, temp, 0, 8); // x = toDouble(temp); // System.arraycopy(data, 8, temp, 0, 8); // y = toDouble(temp); // return new PointD(x, y); // } // // private static byte[] toByte(final double data) { // return toByte(Double.doubleToRawLongBits(data)); // } // // private static byte[] toByte(final long data) { // return new byte[] { (byte) (data >> 56 & 0xff), (byte) (data >> 48 & 0xff), // (byte) (data >> 40 & 0xff), (byte) (data >> 32 & 0xff), (byte) (data >> 24 & 0xff), // (byte) (data >> 16 & 0xff), (byte) (data >> 8 & 0xff), (byte) (data >> 0 & 0xff), }; // } // // public static byte[] toByteArray(final PointD point) { // final byte[] bytes = new byte[16]; // System.arraycopy(toByte(point.x), 0, bytes, 0, 8); // System.arraycopy(toByte(point.y), 0, bytes, 8, 8); // return bytes; // } // // private static double toDouble(final byte[] data) { // if (data == null || data.length != 8) { // return 0x0; // } // return Double.longBitsToDouble(toLong(data)); // } // // private static long toLong(final byte[] data) { // if (data == null || data.length != 8) { // return 0x0; // } // return (long) (0xff & data[0]) << 56 | (long) (0xff & data[1]) << 48 // | (long) (0xff & data[2]) << 40 | (long) (0xff & data[3]) << 32 // | (long) (0xff & data[4]) << 24 | (long) (0xff & data[5]) << 16 // | (long) (0xff & data[6]) << 8 | (long) (0xff & data[7]) << 0; // } // // public double x; // // public double y; // // public PointD(final double x, final double y) { // this.x = x; // this.y = y; // } // // public static List<org.achartengine.model.PointD> convertToNew(List<PointD> oldList) { // ArrayList<org.achartengine.model.PointD> newList = new ArrayList<org.achartengine.model.PointD>(oldList.size()); // for(PointD oldPoint : oldList) // { // newList.add(new org.achartengine.model.PointD(oldPoint.x, oldPoint.y)); // } // return newList; // } // } // Path: src/com/androsz/electricsleepbeta/db/ElectricSleepDatabase.java import com.androsz.electricsleepbeta.util.PointD; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.util.List; import java.util.TimeZone; SleepSession.DURATION + " INTEGER," + SleepSession.CALIBRATION_LEVEL + " REAL," + SleepSession.MIN + " REAL," + SleepSession.NOTE + " TEXT" + ")"); final String DURATION = "KEY_SLEEP_DATA_DURATION"; final String ALARM = "sleep_data_alarm"; final String MIN = "sleep_data_min"; final String NOTE = "KEY_SLEEP_DATA_NOTE"; final String RATING = "sleep_data_rating"; final String SPIKES = "KEY_SLEEP_DATA_SPIKES"; final String DATA = "sleep_data"; final String FELL_ASLEEP_TIMESTAMP = "KEY_SLEEP_DATA_TIME_FELL_ASLEEP"; // copy over existing data Cursor cursor = db.query( "FTSsleephistory", new String[] { DATA, SPIKES, RATING, NOTE, MIN, DURATION, ALARM, FELL_ASLEEP_TIMESTAMP }, null, null, null, null, null); if (cursor.moveToFirst()) { do { ContentValues values = new ContentValues(8); // populate the start and end timestamps byte[] bytes = cursor.getBlob(0); try { ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bytes));
List<PointD> data = (List<PointD>) ois.readObject();
jondwillis/ElectricSleep
src/com/androsz/electricsleepbeta/db/ElectricSleepProvider.java
// Path: src/com/google/android/apps/iosched/util/SelectionBuilder.java // public class SelectionBuilder { // private static final String TAG = "SelectionBuilder"; // private static final boolean LOGV = false; // // private String mTable = null; // private Map<String, String> mProjectionMap = Maps.newHashMap(); // private StringBuilder mSelection = new StringBuilder(); // private ArrayList<String> mSelectionArgs = Lists.newArrayList(); // // /** // * Reset any internal state, allowing this builder to be recycled. // */ // public SelectionBuilder reset() { // mTable = null; // mSelection.setLength(0); // mSelectionArgs.clear(); // return this; // } // // /** // * Append the given selection clause to the internal state. Each clause is // * surrounded with parenthesis and combined using {@code AND}. // */ // public SelectionBuilder where(String selection, String... selectionArgs) { // if (TextUtils.isEmpty(selection)) { // if (selectionArgs != null && selectionArgs.length > 0) { // throw new IllegalArgumentException( // "Valid selection required when including arguments="); // } // // // Shortcut when clause is empty // return this; // } // // if (mSelection.length() > 0) { // mSelection.append(" AND "); // } // // mSelection.append("(").append(selection).append(")"); // if (selectionArgs != null) { // for (String arg : selectionArgs) { // mSelectionArgs.add(arg); // } // } // // return this; // } // // public SelectionBuilder table(String table) { // mTable = table; // return this; // } // // private void assertTable() { // if (mTable == null) { // throw new IllegalStateException("Table not specified"); // } // } // // public SelectionBuilder mapToTable(String column, String table) { // mProjectionMap.put(column, table + "." + column); // return this; // } // // public SelectionBuilder map(String fromColumn, String toClause) { // mProjectionMap.put(fromColumn, toClause + " AS " + fromColumn); // return this; // } // // /** // * Return selection string for current internal state. // * // * @see #getSelectionArgs() // */ // public String getSelection() { // return mSelection.toString(); // } // // /** // * Return selection arguments for current internal state. // * // * @see #getSelection() // */ // public String[] getSelectionArgs() { // return mSelectionArgs.toArray(new String[mSelectionArgs.size()]); // } // // private void mapColumns(String[] columns) { // for (int i = 0; i < columns.length; i++) { // final String target = mProjectionMap.get(columns[i]); // if (target != null) { // columns[i] = target; // } // } // } // // @Override // public String toString() { // return "SelectionBuilder[table=" + mTable + ", selection=" + getSelection() // + ", selectionArgs=" + Arrays.toString(getSelectionArgs()) + "]"; // } // // /** // * Execute query using the current internal state as {@code WHERE} clause. // */ // public Cursor query(SQLiteDatabase db, String[] columns, String orderBy) { // return query(db, columns, null, null, orderBy, null); // } // // /** // * Execute query using the current internal state as {@code WHERE} clause. // */ // public Cursor query(SQLiteDatabase db, String[] columns, String groupBy, // String having, String orderBy, String limit) { // assertTable(); // if (columns != null) { // mapColumns(columns); // } // if (LOGV) { // Log.v(TAG, "query(columns=" + Arrays.toString(columns) + ") " + this); // } // return db.query(mTable, columns, getSelection(), getSelectionArgs(), groupBy, having, // orderBy, limit); // } // // /** // * Execute update using the current internal state as {@code WHERE} clause. // */ // public int update(SQLiteDatabase db, ContentValues values) { // assertTable(); // if (LOGV) { // Log.v(TAG, "update() " + this); // } // return db.update(mTable, values, getSelection(), getSelectionArgs()); // } // // /** // * Execute delete using the current internal state as {@code WHERE} clause. // */ // public int delete(SQLiteDatabase db) { // assertTable(); // if (LOGV) { // Log.v(TAG, "delete() " + this); // } // return db.delete(mTable, getSelection(), getSelectionArgs()); // } // }
import com.google.android.apps.iosched.util.SelectionBuilder; import android.content.ContentProvider; import android.content.ContentUris; import android.content.ContentValues; import android.content.UriMatcher; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.net.Uri; import java.util.TimeZone;
/* @(#)ElectricSleepProvider.java * *======================================================================== * Copyright 2011 by Zeo Inc. All Rights Reserved *======================================================================== * * Date: $Date$ * Author: Jon Willis * Author: Brandon Edens <brandon.edens@myzeo.com> * Version: $Revision$ */ package com.androsz.electricsleepbeta.db; /** * Provider for electric sleep data. * * @author Jon Willis * @author Brandon Edens * @version $Revision$ */ public class ElectricSleepProvider extends ContentProvider { public static final String CONTENT_AUTHORITY = "com.androsz.electricsleepbeta.db.electric_sleep_provider"; public static final Uri BASE_CONTENT_URI = Uri.parse("content://" + CONTENT_AUTHORITY); public interface TimestampColumns { String CREATED_ON = "created_on"; String UPDATED_ON = "updated_on"; } private static final int SLEEP_SESSIONS = 100; private static final int SLEEP_SESSIONS_ID = 101; private static final UriMatcher URI_MATCHER = buildUriMatcher(); private ElectricSleepDatabase mOpenHelper; @Override public int delete(Uri uri, String selection, String[] selectionArgs) { final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
// Path: src/com/google/android/apps/iosched/util/SelectionBuilder.java // public class SelectionBuilder { // private static final String TAG = "SelectionBuilder"; // private static final boolean LOGV = false; // // private String mTable = null; // private Map<String, String> mProjectionMap = Maps.newHashMap(); // private StringBuilder mSelection = new StringBuilder(); // private ArrayList<String> mSelectionArgs = Lists.newArrayList(); // // /** // * Reset any internal state, allowing this builder to be recycled. // */ // public SelectionBuilder reset() { // mTable = null; // mSelection.setLength(0); // mSelectionArgs.clear(); // return this; // } // // /** // * Append the given selection clause to the internal state. Each clause is // * surrounded with parenthesis and combined using {@code AND}. // */ // public SelectionBuilder where(String selection, String... selectionArgs) { // if (TextUtils.isEmpty(selection)) { // if (selectionArgs != null && selectionArgs.length > 0) { // throw new IllegalArgumentException( // "Valid selection required when including arguments="); // } // // // Shortcut when clause is empty // return this; // } // // if (mSelection.length() > 0) { // mSelection.append(" AND "); // } // // mSelection.append("(").append(selection).append(")"); // if (selectionArgs != null) { // for (String arg : selectionArgs) { // mSelectionArgs.add(arg); // } // } // // return this; // } // // public SelectionBuilder table(String table) { // mTable = table; // return this; // } // // private void assertTable() { // if (mTable == null) { // throw new IllegalStateException("Table not specified"); // } // } // // public SelectionBuilder mapToTable(String column, String table) { // mProjectionMap.put(column, table + "." + column); // return this; // } // // public SelectionBuilder map(String fromColumn, String toClause) { // mProjectionMap.put(fromColumn, toClause + " AS " + fromColumn); // return this; // } // // /** // * Return selection string for current internal state. // * // * @see #getSelectionArgs() // */ // public String getSelection() { // return mSelection.toString(); // } // // /** // * Return selection arguments for current internal state. // * // * @see #getSelection() // */ // public String[] getSelectionArgs() { // return mSelectionArgs.toArray(new String[mSelectionArgs.size()]); // } // // private void mapColumns(String[] columns) { // for (int i = 0; i < columns.length; i++) { // final String target = mProjectionMap.get(columns[i]); // if (target != null) { // columns[i] = target; // } // } // } // // @Override // public String toString() { // return "SelectionBuilder[table=" + mTable + ", selection=" + getSelection() // + ", selectionArgs=" + Arrays.toString(getSelectionArgs()) + "]"; // } // // /** // * Execute query using the current internal state as {@code WHERE} clause. // */ // public Cursor query(SQLiteDatabase db, String[] columns, String orderBy) { // return query(db, columns, null, null, orderBy, null); // } // // /** // * Execute query using the current internal state as {@code WHERE} clause. // */ // public Cursor query(SQLiteDatabase db, String[] columns, String groupBy, // String having, String orderBy, String limit) { // assertTable(); // if (columns != null) { // mapColumns(columns); // } // if (LOGV) { // Log.v(TAG, "query(columns=" + Arrays.toString(columns) + ") " + this); // } // return db.query(mTable, columns, getSelection(), getSelectionArgs(), groupBy, having, // orderBy, limit); // } // // /** // * Execute update using the current internal state as {@code WHERE} clause. // */ // public int update(SQLiteDatabase db, ContentValues values) { // assertTable(); // if (LOGV) { // Log.v(TAG, "update() " + this); // } // return db.update(mTable, values, getSelection(), getSelectionArgs()); // } // // /** // * Execute delete using the current internal state as {@code WHERE} clause. // */ // public int delete(SQLiteDatabase db) { // assertTable(); // if (LOGV) { // Log.v(TAG, "delete() " + this); // } // return db.delete(mTable, getSelection(), getSelectionArgs()); // } // } // Path: src/com/androsz/electricsleepbeta/db/ElectricSleepProvider.java import com.google.android.apps.iosched.util.SelectionBuilder; import android.content.ContentProvider; import android.content.ContentUris; import android.content.ContentValues; import android.content.UriMatcher; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.net.Uri; import java.util.TimeZone; /* @(#)ElectricSleepProvider.java * *======================================================================== * Copyright 2011 by Zeo Inc. All Rights Reserved *======================================================================== * * Date: $Date$ * Author: Jon Willis * Author: Brandon Edens <brandon.edens@myzeo.com> * Version: $Revision$ */ package com.androsz.electricsleepbeta.db; /** * Provider for electric sleep data. * * @author Jon Willis * @author Brandon Edens * @version $Revision$ */ public class ElectricSleepProvider extends ContentProvider { public static final String CONTENT_AUTHORITY = "com.androsz.electricsleepbeta.db.electric_sleep_provider"; public static final Uri BASE_CONTENT_URI = Uri.parse("content://" + CONTENT_AUTHORITY); public interface TimestampColumns { String CREATED_ON = "created_on"; String UPDATED_ON = "updated_on"; } private static final int SLEEP_SESSIONS = 100; private static final int SLEEP_SESSIONS_ID = 101; private static final UriMatcher URI_MATCHER = buildUriMatcher(); private ElectricSleepDatabase mOpenHelper; @Override public int delete(Uri uri, String selection, String[] selectionArgs) { final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
final SelectionBuilder builder = buildSimpleSelection(uri, "");
opaluchlukasz/junit2spock
src/main/java/com/github/opaluchlukasz/junit2spock/core/model/method/CodeBasedSpockBlocksStrategy.java
// Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/junit/AssertEqualsFeature.java // public static final String ASSERT_ARRAY_EQUALS = "assertArrayEquals"; // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/junit/AssertEqualsFeature.java // public static final String ASSERT_EQUALS = "assertEquals"; // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/junit/AssertFalseFeature.java // public static final String ASSERT_FALSE = "assertFalse"; // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/junit/AssertNotNullFeature.java // public static final String ASSERT_NOT_NULL = "assertNotNull"; // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/junit/AssertNullFeature.java // public static final String ASSERT_NULL = "assertNull"; // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/junit/AssertTrueFeature.java // public static final String ASSERT_TRUE = "assertTrue"; // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/mockito/GivenWillReturnFeature.java // public static final String WILL_RETURN = "willReturn"; // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/mockito/GivenWillThrowFeature.java // public static final String WILL_THROW = "willThrow"; // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/mockito/MockitoVerifyFeature.java // public static final String VERIFY = "verify"; // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/mockito/MockitoVerifyNoMoreInteractionsFeature.java // public static final String VERIFY_NO_MORE_INTERACTIONS = "verifyNoMoreInteractions"; // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/mockito/WhenThenReturnFeature.java // public static final String THEN_RETURN = "thenReturn"; // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/mockito/WhenThenThrowFeature.java // public static final String THEN_THROW = "thenThrow"; // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/node/SpockBlockNode.java // public static SpockBlockNode expect() { // return new SpockBlockNode("expect"); // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/node/SpockBlockNode.java // public static SpockBlockNode given() { // return new SpockBlockNode("given"); // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/node/SpockBlockNode.java // public static SpockBlockNode then() { // return new SpockBlockNode("then"); // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/node/SpockBlockNode.java // public static SpockBlockNode when() { // return new SpockBlockNode("when"); // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/util/AstNodeFinder.java // public static Optional<MethodInvocation> methodInvocation(Object bodyElement, String... methodNames) { // return stream(methodNames) // .map(methodName -> methodInvocation(bodyElement, methodName)) // .filter(Optional::isPresent) // .map(Optional::get) // .findFirst(); // }
import org.eclipse.jdt.core.dom.Expression; import org.eclipse.jdt.core.dom.ExpressionStatement; import org.eclipse.jdt.core.dom.MethodInvocation; import java.util.List; import static com.github.opaluchlukasz.junit2spock.core.feature.junit.AssertEqualsFeature.ASSERT_ARRAY_EQUALS; import static com.github.opaluchlukasz.junit2spock.core.feature.junit.AssertEqualsFeature.ASSERT_EQUALS; import static com.github.opaluchlukasz.junit2spock.core.feature.junit.AssertFalseFeature.ASSERT_FALSE; import static com.github.opaluchlukasz.junit2spock.core.feature.junit.AssertNotNullFeature.ASSERT_NOT_NULL; import static com.github.opaluchlukasz.junit2spock.core.feature.junit.AssertNullFeature.ASSERT_NULL; import static com.github.opaluchlukasz.junit2spock.core.feature.junit.AssertTrueFeature.ASSERT_TRUE; import static com.github.opaluchlukasz.junit2spock.core.feature.mockito.GivenWillReturnFeature.WILL_RETURN; import static com.github.opaluchlukasz.junit2spock.core.feature.mockito.GivenWillThrowFeature.WILL_THROW; import static com.github.opaluchlukasz.junit2spock.core.feature.mockito.MockitoVerifyFeature.VERIFY; import static com.github.opaluchlukasz.junit2spock.core.feature.mockito.MockitoVerifyNoMoreInteractionsFeature.VERIFY_NO_MORE_INTERACTIONS; import static com.github.opaluchlukasz.junit2spock.core.feature.mockito.WhenThenReturnFeature.THEN_RETURN; import static com.github.opaluchlukasz.junit2spock.core.feature.mockito.WhenThenThrowFeature.THEN_THROW; import static com.github.opaluchlukasz.junit2spock.core.node.SpockBlockNode.expect; import static com.github.opaluchlukasz.junit2spock.core.node.SpockBlockNode.given; import static com.github.opaluchlukasz.junit2spock.core.node.SpockBlockNode.then; import static com.github.opaluchlukasz.junit2spock.core.node.SpockBlockNode.when; import static com.github.opaluchlukasz.junit2spock.core.util.AstNodeFinder.methodInvocation; import static org.spockframework.util.Identifiers.THROWN;
package com.github.opaluchlukasz.junit2spock.core.model.method; public class CodeBasedSpockBlocksStrategy implements SpockBlockApplier { private static final String ASSERT_THAT = "assertThat";
// Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/junit/AssertEqualsFeature.java // public static final String ASSERT_ARRAY_EQUALS = "assertArrayEquals"; // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/junit/AssertEqualsFeature.java // public static final String ASSERT_EQUALS = "assertEquals"; // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/junit/AssertFalseFeature.java // public static final String ASSERT_FALSE = "assertFalse"; // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/junit/AssertNotNullFeature.java // public static final String ASSERT_NOT_NULL = "assertNotNull"; // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/junit/AssertNullFeature.java // public static final String ASSERT_NULL = "assertNull"; // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/junit/AssertTrueFeature.java // public static final String ASSERT_TRUE = "assertTrue"; // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/mockito/GivenWillReturnFeature.java // public static final String WILL_RETURN = "willReturn"; // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/mockito/GivenWillThrowFeature.java // public static final String WILL_THROW = "willThrow"; // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/mockito/MockitoVerifyFeature.java // public static final String VERIFY = "verify"; // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/mockito/MockitoVerifyNoMoreInteractionsFeature.java // public static final String VERIFY_NO_MORE_INTERACTIONS = "verifyNoMoreInteractions"; // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/mockito/WhenThenReturnFeature.java // public static final String THEN_RETURN = "thenReturn"; // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/mockito/WhenThenThrowFeature.java // public static final String THEN_THROW = "thenThrow"; // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/node/SpockBlockNode.java // public static SpockBlockNode expect() { // return new SpockBlockNode("expect"); // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/node/SpockBlockNode.java // public static SpockBlockNode given() { // return new SpockBlockNode("given"); // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/node/SpockBlockNode.java // public static SpockBlockNode then() { // return new SpockBlockNode("then"); // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/node/SpockBlockNode.java // public static SpockBlockNode when() { // return new SpockBlockNode("when"); // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/util/AstNodeFinder.java // public static Optional<MethodInvocation> methodInvocation(Object bodyElement, String... methodNames) { // return stream(methodNames) // .map(methodName -> methodInvocation(bodyElement, methodName)) // .filter(Optional::isPresent) // .map(Optional::get) // .findFirst(); // } // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/model/method/CodeBasedSpockBlocksStrategy.java import org.eclipse.jdt.core.dom.Expression; import org.eclipse.jdt.core.dom.ExpressionStatement; import org.eclipse.jdt.core.dom.MethodInvocation; import java.util.List; import static com.github.opaluchlukasz.junit2spock.core.feature.junit.AssertEqualsFeature.ASSERT_ARRAY_EQUALS; import static com.github.opaluchlukasz.junit2spock.core.feature.junit.AssertEqualsFeature.ASSERT_EQUALS; import static com.github.opaluchlukasz.junit2spock.core.feature.junit.AssertFalseFeature.ASSERT_FALSE; import static com.github.opaluchlukasz.junit2spock.core.feature.junit.AssertNotNullFeature.ASSERT_NOT_NULL; import static com.github.opaluchlukasz.junit2spock.core.feature.junit.AssertNullFeature.ASSERT_NULL; import static com.github.opaluchlukasz.junit2spock.core.feature.junit.AssertTrueFeature.ASSERT_TRUE; import static com.github.opaluchlukasz.junit2spock.core.feature.mockito.GivenWillReturnFeature.WILL_RETURN; import static com.github.opaluchlukasz.junit2spock.core.feature.mockito.GivenWillThrowFeature.WILL_THROW; import static com.github.opaluchlukasz.junit2spock.core.feature.mockito.MockitoVerifyFeature.VERIFY; import static com.github.opaluchlukasz.junit2spock.core.feature.mockito.MockitoVerifyNoMoreInteractionsFeature.VERIFY_NO_MORE_INTERACTIONS; import static com.github.opaluchlukasz.junit2spock.core.feature.mockito.WhenThenReturnFeature.THEN_RETURN; import static com.github.opaluchlukasz.junit2spock.core.feature.mockito.WhenThenThrowFeature.THEN_THROW; import static com.github.opaluchlukasz.junit2spock.core.node.SpockBlockNode.expect; import static com.github.opaluchlukasz.junit2spock.core.node.SpockBlockNode.given; import static com.github.opaluchlukasz.junit2spock.core.node.SpockBlockNode.then; import static com.github.opaluchlukasz.junit2spock.core.node.SpockBlockNode.when; import static com.github.opaluchlukasz.junit2spock.core.util.AstNodeFinder.methodInvocation; import static org.spockframework.util.Identifiers.THROWN; package com.github.opaluchlukasz.junit2spock.core.model.method; public class CodeBasedSpockBlocksStrategy implements SpockBlockApplier { private static final String ASSERT_THAT = "assertThat";
public static final String[] THEN_BLOCK_START = new String[]{ASSERT_EQUALS, ASSERT_NOT_NULL, ASSERT_ARRAY_EQUALS, ASSERT_TRUE,
opaluchlukasz/junit2spock
src/main/java/com/github/opaluchlukasz/junit2spock/core/model/method/CodeBasedSpockBlocksStrategy.java
// Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/junit/AssertEqualsFeature.java // public static final String ASSERT_ARRAY_EQUALS = "assertArrayEquals"; // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/junit/AssertEqualsFeature.java // public static final String ASSERT_EQUALS = "assertEquals"; // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/junit/AssertFalseFeature.java // public static final String ASSERT_FALSE = "assertFalse"; // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/junit/AssertNotNullFeature.java // public static final String ASSERT_NOT_NULL = "assertNotNull"; // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/junit/AssertNullFeature.java // public static final String ASSERT_NULL = "assertNull"; // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/junit/AssertTrueFeature.java // public static final String ASSERT_TRUE = "assertTrue"; // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/mockito/GivenWillReturnFeature.java // public static final String WILL_RETURN = "willReturn"; // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/mockito/GivenWillThrowFeature.java // public static final String WILL_THROW = "willThrow"; // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/mockito/MockitoVerifyFeature.java // public static final String VERIFY = "verify"; // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/mockito/MockitoVerifyNoMoreInteractionsFeature.java // public static final String VERIFY_NO_MORE_INTERACTIONS = "verifyNoMoreInteractions"; // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/mockito/WhenThenReturnFeature.java // public static final String THEN_RETURN = "thenReturn"; // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/mockito/WhenThenThrowFeature.java // public static final String THEN_THROW = "thenThrow"; // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/node/SpockBlockNode.java // public static SpockBlockNode expect() { // return new SpockBlockNode("expect"); // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/node/SpockBlockNode.java // public static SpockBlockNode given() { // return new SpockBlockNode("given"); // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/node/SpockBlockNode.java // public static SpockBlockNode then() { // return new SpockBlockNode("then"); // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/node/SpockBlockNode.java // public static SpockBlockNode when() { // return new SpockBlockNode("when"); // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/util/AstNodeFinder.java // public static Optional<MethodInvocation> methodInvocation(Object bodyElement, String... methodNames) { // return stream(methodNames) // .map(methodName -> methodInvocation(bodyElement, methodName)) // .filter(Optional::isPresent) // .map(Optional::get) // .findFirst(); // }
import org.eclipse.jdt.core.dom.Expression; import org.eclipse.jdt.core.dom.ExpressionStatement; import org.eclipse.jdt.core.dom.MethodInvocation; import java.util.List; import static com.github.opaluchlukasz.junit2spock.core.feature.junit.AssertEqualsFeature.ASSERT_ARRAY_EQUALS; import static com.github.opaluchlukasz.junit2spock.core.feature.junit.AssertEqualsFeature.ASSERT_EQUALS; import static com.github.opaluchlukasz.junit2spock.core.feature.junit.AssertFalseFeature.ASSERT_FALSE; import static com.github.opaluchlukasz.junit2spock.core.feature.junit.AssertNotNullFeature.ASSERT_NOT_NULL; import static com.github.opaluchlukasz.junit2spock.core.feature.junit.AssertNullFeature.ASSERT_NULL; import static com.github.opaluchlukasz.junit2spock.core.feature.junit.AssertTrueFeature.ASSERT_TRUE; import static com.github.opaluchlukasz.junit2spock.core.feature.mockito.GivenWillReturnFeature.WILL_RETURN; import static com.github.opaluchlukasz.junit2spock.core.feature.mockito.GivenWillThrowFeature.WILL_THROW; import static com.github.opaluchlukasz.junit2spock.core.feature.mockito.MockitoVerifyFeature.VERIFY; import static com.github.opaluchlukasz.junit2spock.core.feature.mockito.MockitoVerifyNoMoreInteractionsFeature.VERIFY_NO_MORE_INTERACTIONS; import static com.github.opaluchlukasz.junit2spock.core.feature.mockito.WhenThenReturnFeature.THEN_RETURN; import static com.github.opaluchlukasz.junit2spock.core.feature.mockito.WhenThenThrowFeature.THEN_THROW; import static com.github.opaluchlukasz.junit2spock.core.node.SpockBlockNode.expect; import static com.github.opaluchlukasz.junit2spock.core.node.SpockBlockNode.given; import static com.github.opaluchlukasz.junit2spock.core.node.SpockBlockNode.then; import static com.github.opaluchlukasz.junit2spock.core.node.SpockBlockNode.when; import static com.github.opaluchlukasz.junit2spock.core.util.AstNodeFinder.methodInvocation; import static org.spockframework.util.Identifiers.THROWN;
package com.github.opaluchlukasz.junit2spock.core.model.method; public class CodeBasedSpockBlocksStrategy implements SpockBlockApplier { private static final String ASSERT_THAT = "assertThat";
// Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/junit/AssertEqualsFeature.java // public static final String ASSERT_ARRAY_EQUALS = "assertArrayEquals"; // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/junit/AssertEqualsFeature.java // public static final String ASSERT_EQUALS = "assertEquals"; // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/junit/AssertFalseFeature.java // public static final String ASSERT_FALSE = "assertFalse"; // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/junit/AssertNotNullFeature.java // public static final String ASSERT_NOT_NULL = "assertNotNull"; // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/junit/AssertNullFeature.java // public static final String ASSERT_NULL = "assertNull"; // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/junit/AssertTrueFeature.java // public static final String ASSERT_TRUE = "assertTrue"; // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/mockito/GivenWillReturnFeature.java // public static final String WILL_RETURN = "willReturn"; // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/mockito/GivenWillThrowFeature.java // public static final String WILL_THROW = "willThrow"; // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/mockito/MockitoVerifyFeature.java // public static final String VERIFY = "verify"; // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/mockito/MockitoVerifyNoMoreInteractionsFeature.java // public static final String VERIFY_NO_MORE_INTERACTIONS = "verifyNoMoreInteractions"; // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/mockito/WhenThenReturnFeature.java // public static final String THEN_RETURN = "thenReturn"; // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/mockito/WhenThenThrowFeature.java // public static final String THEN_THROW = "thenThrow"; // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/node/SpockBlockNode.java // public static SpockBlockNode expect() { // return new SpockBlockNode("expect"); // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/node/SpockBlockNode.java // public static SpockBlockNode given() { // return new SpockBlockNode("given"); // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/node/SpockBlockNode.java // public static SpockBlockNode then() { // return new SpockBlockNode("then"); // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/node/SpockBlockNode.java // public static SpockBlockNode when() { // return new SpockBlockNode("when"); // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/util/AstNodeFinder.java // public static Optional<MethodInvocation> methodInvocation(Object bodyElement, String... methodNames) { // return stream(methodNames) // .map(methodName -> methodInvocation(bodyElement, methodName)) // .filter(Optional::isPresent) // .map(Optional::get) // .findFirst(); // } // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/model/method/CodeBasedSpockBlocksStrategy.java import org.eclipse.jdt.core.dom.Expression; import org.eclipse.jdt.core.dom.ExpressionStatement; import org.eclipse.jdt.core.dom.MethodInvocation; import java.util.List; import static com.github.opaluchlukasz.junit2spock.core.feature.junit.AssertEqualsFeature.ASSERT_ARRAY_EQUALS; import static com.github.opaluchlukasz.junit2spock.core.feature.junit.AssertEqualsFeature.ASSERT_EQUALS; import static com.github.opaluchlukasz.junit2spock.core.feature.junit.AssertFalseFeature.ASSERT_FALSE; import static com.github.opaluchlukasz.junit2spock.core.feature.junit.AssertNotNullFeature.ASSERT_NOT_NULL; import static com.github.opaluchlukasz.junit2spock.core.feature.junit.AssertNullFeature.ASSERT_NULL; import static com.github.opaluchlukasz.junit2spock.core.feature.junit.AssertTrueFeature.ASSERT_TRUE; import static com.github.opaluchlukasz.junit2spock.core.feature.mockito.GivenWillReturnFeature.WILL_RETURN; import static com.github.opaluchlukasz.junit2spock.core.feature.mockito.GivenWillThrowFeature.WILL_THROW; import static com.github.opaluchlukasz.junit2spock.core.feature.mockito.MockitoVerifyFeature.VERIFY; import static com.github.opaluchlukasz.junit2spock.core.feature.mockito.MockitoVerifyNoMoreInteractionsFeature.VERIFY_NO_MORE_INTERACTIONS; import static com.github.opaluchlukasz.junit2spock.core.feature.mockito.WhenThenReturnFeature.THEN_RETURN; import static com.github.opaluchlukasz.junit2spock.core.feature.mockito.WhenThenThrowFeature.THEN_THROW; import static com.github.opaluchlukasz.junit2spock.core.node.SpockBlockNode.expect; import static com.github.opaluchlukasz.junit2spock.core.node.SpockBlockNode.given; import static com.github.opaluchlukasz.junit2spock.core.node.SpockBlockNode.then; import static com.github.opaluchlukasz.junit2spock.core.node.SpockBlockNode.when; import static com.github.opaluchlukasz.junit2spock.core.util.AstNodeFinder.methodInvocation; import static org.spockframework.util.Identifiers.THROWN; package com.github.opaluchlukasz.junit2spock.core.model.method; public class CodeBasedSpockBlocksStrategy implements SpockBlockApplier { private static final String ASSERT_THAT = "assertThat";
public static final String[] THEN_BLOCK_START = new String[]{ASSERT_EQUALS, ASSERT_NOT_NULL, ASSERT_ARRAY_EQUALS, ASSERT_TRUE,
opaluchlukasz/junit2spock
src/main/java/com/github/opaluchlukasz/junit2spock/core/model/method/CodeBasedSpockBlocksStrategy.java
// Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/junit/AssertEqualsFeature.java // public static final String ASSERT_ARRAY_EQUALS = "assertArrayEquals"; // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/junit/AssertEqualsFeature.java // public static final String ASSERT_EQUALS = "assertEquals"; // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/junit/AssertFalseFeature.java // public static final String ASSERT_FALSE = "assertFalse"; // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/junit/AssertNotNullFeature.java // public static final String ASSERT_NOT_NULL = "assertNotNull"; // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/junit/AssertNullFeature.java // public static final String ASSERT_NULL = "assertNull"; // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/junit/AssertTrueFeature.java // public static final String ASSERT_TRUE = "assertTrue"; // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/mockito/GivenWillReturnFeature.java // public static final String WILL_RETURN = "willReturn"; // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/mockito/GivenWillThrowFeature.java // public static final String WILL_THROW = "willThrow"; // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/mockito/MockitoVerifyFeature.java // public static final String VERIFY = "verify"; // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/mockito/MockitoVerifyNoMoreInteractionsFeature.java // public static final String VERIFY_NO_MORE_INTERACTIONS = "verifyNoMoreInteractions"; // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/mockito/WhenThenReturnFeature.java // public static final String THEN_RETURN = "thenReturn"; // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/mockito/WhenThenThrowFeature.java // public static final String THEN_THROW = "thenThrow"; // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/node/SpockBlockNode.java // public static SpockBlockNode expect() { // return new SpockBlockNode("expect"); // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/node/SpockBlockNode.java // public static SpockBlockNode given() { // return new SpockBlockNode("given"); // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/node/SpockBlockNode.java // public static SpockBlockNode then() { // return new SpockBlockNode("then"); // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/node/SpockBlockNode.java // public static SpockBlockNode when() { // return new SpockBlockNode("when"); // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/util/AstNodeFinder.java // public static Optional<MethodInvocation> methodInvocation(Object bodyElement, String... methodNames) { // return stream(methodNames) // .map(methodName -> methodInvocation(bodyElement, methodName)) // .filter(Optional::isPresent) // .map(Optional::get) // .findFirst(); // }
import org.eclipse.jdt.core.dom.Expression; import org.eclipse.jdt.core.dom.ExpressionStatement; import org.eclipse.jdt.core.dom.MethodInvocation; import java.util.List; import static com.github.opaluchlukasz.junit2spock.core.feature.junit.AssertEqualsFeature.ASSERT_ARRAY_EQUALS; import static com.github.opaluchlukasz.junit2spock.core.feature.junit.AssertEqualsFeature.ASSERT_EQUALS; import static com.github.opaluchlukasz.junit2spock.core.feature.junit.AssertFalseFeature.ASSERT_FALSE; import static com.github.opaluchlukasz.junit2spock.core.feature.junit.AssertNotNullFeature.ASSERT_NOT_NULL; import static com.github.opaluchlukasz.junit2spock.core.feature.junit.AssertNullFeature.ASSERT_NULL; import static com.github.opaluchlukasz.junit2spock.core.feature.junit.AssertTrueFeature.ASSERT_TRUE; import static com.github.opaluchlukasz.junit2spock.core.feature.mockito.GivenWillReturnFeature.WILL_RETURN; import static com.github.opaluchlukasz.junit2spock.core.feature.mockito.GivenWillThrowFeature.WILL_THROW; import static com.github.opaluchlukasz.junit2spock.core.feature.mockito.MockitoVerifyFeature.VERIFY; import static com.github.opaluchlukasz.junit2spock.core.feature.mockito.MockitoVerifyNoMoreInteractionsFeature.VERIFY_NO_MORE_INTERACTIONS; import static com.github.opaluchlukasz.junit2spock.core.feature.mockito.WhenThenReturnFeature.THEN_RETURN; import static com.github.opaluchlukasz.junit2spock.core.feature.mockito.WhenThenThrowFeature.THEN_THROW; import static com.github.opaluchlukasz.junit2spock.core.node.SpockBlockNode.expect; import static com.github.opaluchlukasz.junit2spock.core.node.SpockBlockNode.given; import static com.github.opaluchlukasz.junit2spock.core.node.SpockBlockNode.then; import static com.github.opaluchlukasz.junit2spock.core.node.SpockBlockNode.when; import static com.github.opaluchlukasz.junit2spock.core.util.AstNodeFinder.methodInvocation; import static org.spockframework.util.Identifiers.THROWN;
package com.github.opaluchlukasz.junit2spock.core.model.method; public class CodeBasedSpockBlocksStrategy implements SpockBlockApplier { private static final String ASSERT_THAT = "assertThat";
// Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/junit/AssertEqualsFeature.java // public static final String ASSERT_ARRAY_EQUALS = "assertArrayEquals"; // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/junit/AssertEqualsFeature.java // public static final String ASSERT_EQUALS = "assertEquals"; // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/junit/AssertFalseFeature.java // public static final String ASSERT_FALSE = "assertFalse"; // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/junit/AssertNotNullFeature.java // public static final String ASSERT_NOT_NULL = "assertNotNull"; // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/junit/AssertNullFeature.java // public static final String ASSERT_NULL = "assertNull"; // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/junit/AssertTrueFeature.java // public static final String ASSERT_TRUE = "assertTrue"; // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/mockito/GivenWillReturnFeature.java // public static final String WILL_RETURN = "willReturn"; // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/mockito/GivenWillThrowFeature.java // public static final String WILL_THROW = "willThrow"; // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/mockito/MockitoVerifyFeature.java // public static final String VERIFY = "verify"; // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/mockito/MockitoVerifyNoMoreInteractionsFeature.java // public static final String VERIFY_NO_MORE_INTERACTIONS = "verifyNoMoreInteractions"; // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/mockito/WhenThenReturnFeature.java // public static final String THEN_RETURN = "thenReturn"; // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/mockito/WhenThenThrowFeature.java // public static final String THEN_THROW = "thenThrow"; // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/node/SpockBlockNode.java // public static SpockBlockNode expect() { // return new SpockBlockNode("expect"); // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/node/SpockBlockNode.java // public static SpockBlockNode given() { // return new SpockBlockNode("given"); // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/node/SpockBlockNode.java // public static SpockBlockNode then() { // return new SpockBlockNode("then"); // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/node/SpockBlockNode.java // public static SpockBlockNode when() { // return new SpockBlockNode("when"); // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/util/AstNodeFinder.java // public static Optional<MethodInvocation> methodInvocation(Object bodyElement, String... methodNames) { // return stream(methodNames) // .map(methodName -> methodInvocation(bodyElement, methodName)) // .filter(Optional::isPresent) // .map(Optional::get) // .findFirst(); // } // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/model/method/CodeBasedSpockBlocksStrategy.java import org.eclipse.jdt.core.dom.Expression; import org.eclipse.jdt.core.dom.ExpressionStatement; import org.eclipse.jdt.core.dom.MethodInvocation; import java.util.List; import static com.github.opaluchlukasz.junit2spock.core.feature.junit.AssertEqualsFeature.ASSERT_ARRAY_EQUALS; import static com.github.opaluchlukasz.junit2spock.core.feature.junit.AssertEqualsFeature.ASSERT_EQUALS; import static com.github.opaluchlukasz.junit2spock.core.feature.junit.AssertFalseFeature.ASSERT_FALSE; import static com.github.opaluchlukasz.junit2spock.core.feature.junit.AssertNotNullFeature.ASSERT_NOT_NULL; import static com.github.opaluchlukasz.junit2spock.core.feature.junit.AssertNullFeature.ASSERT_NULL; import static com.github.opaluchlukasz.junit2spock.core.feature.junit.AssertTrueFeature.ASSERT_TRUE; import static com.github.opaluchlukasz.junit2spock.core.feature.mockito.GivenWillReturnFeature.WILL_RETURN; import static com.github.opaluchlukasz.junit2spock.core.feature.mockito.GivenWillThrowFeature.WILL_THROW; import static com.github.opaluchlukasz.junit2spock.core.feature.mockito.MockitoVerifyFeature.VERIFY; import static com.github.opaluchlukasz.junit2spock.core.feature.mockito.MockitoVerifyNoMoreInteractionsFeature.VERIFY_NO_MORE_INTERACTIONS; import static com.github.opaluchlukasz.junit2spock.core.feature.mockito.WhenThenReturnFeature.THEN_RETURN; import static com.github.opaluchlukasz.junit2spock.core.feature.mockito.WhenThenThrowFeature.THEN_THROW; import static com.github.opaluchlukasz.junit2spock.core.node.SpockBlockNode.expect; import static com.github.opaluchlukasz.junit2spock.core.node.SpockBlockNode.given; import static com.github.opaluchlukasz.junit2spock.core.node.SpockBlockNode.then; import static com.github.opaluchlukasz.junit2spock.core.node.SpockBlockNode.when; import static com.github.opaluchlukasz.junit2spock.core.util.AstNodeFinder.methodInvocation; import static org.spockframework.util.Identifiers.THROWN; package com.github.opaluchlukasz.junit2spock.core.model.method; public class CodeBasedSpockBlocksStrategy implements SpockBlockApplier { private static final String ASSERT_THAT = "assertThat";
public static final String[] THEN_BLOCK_START = new String[]{ASSERT_EQUALS, ASSERT_NOT_NULL, ASSERT_ARRAY_EQUALS, ASSERT_TRUE,
opaluchlukasz/junit2spock
src/main/java/com/github/opaluchlukasz/junit2spock/core/model/method/CodeBasedSpockBlocksStrategy.java
// Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/junit/AssertEqualsFeature.java // public static final String ASSERT_ARRAY_EQUALS = "assertArrayEquals"; // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/junit/AssertEqualsFeature.java // public static final String ASSERT_EQUALS = "assertEquals"; // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/junit/AssertFalseFeature.java // public static final String ASSERT_FALSE = "assertFalse"; // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/junit/AssertNotNullFeature.java // public static final String ASSERT_NOT_NULL = "assertNotNull"; // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/junit/AssertNullFeature.java // public static final String ASSERT_NULL = "assertNull"; // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/junit/AssertTrueFeature.java // public static final String ASSERT_TRUE = "assertTrue"; // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/mockito/GivenWillReturnFeature.java // public static final String WILL_RETURN = "willReturn"; // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/mockito/GivenWillThrowFeature.java // public static final String WILL_THROW = "willThrow"; // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/mockito/MockitoVerifyFeature.java // public static final String VERIFY = "verify"; // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/mockito/MockitoVerifyNoMoreInteractionsFeature.java // public static final String VERIFY_NO_MORE_INTERACTIONS = "verifyNoMoreInteractions"; // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/mockito/WhenThenReturnFeature.java // public static final String THEN_RETURN = "thenReturn"; // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/mockito/WhenThenThrowFeature.java // public static final String THEN_THROW = "thenThrow"; // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/node/SpockBlockNode.java // public static SpockBlockNode expect() { // return new SpockBlockNode("expect"); // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/node/SpockBlockNode.java // public static SpockBlockNode given() { // return new SpockBlockNode("given"); // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/node/SpockBlockNode.java // public static SpockBlockNode then() { // return new SpockBlockNode("then"); // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/node/SpockBlockNode.java // public static SpockBlockNode when() { // return new SpockBlockNode("when"); // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/util/AstNodeFinder.java // public static Optional<MethodInvocation> methodInvocation(Object bodyElement, String... methodNames) { // return stream(methodNames) // .map(methodName -> methodInvocation(bodyElement, methodName)) // .filter(Optional::isPresent) // .map(Optional::get) // .findFirst(); // }
import org.eclipse.jdt.core.dom.Expression; import org.eclipse.jdt.core.dom.ExpressionStatement; import org.eclipse.jdt.core.dom.MethodInvocation; import java.util.List; import static com.github.opaluchlukasz.junit2spock.core.feature.junit.AssertEqualsFeature.ASSERT_ARRAY_EQUALS; import static com.github.opaluchlukasz.junit2spock.core.feature.junit.AssertEqualsFeature.ASSERT_EQUALS; import static com.github.opaluchlukasz.junit2spock.core.feature.junit.AssertFalseFeature.ASSERT_FALSE; import static com.github.opaluchlukasz.junit2spock.core.feature.junit.AssertNotNullFeature.ASSERT_NOT_NULL; import static com.github.opaluchlukasz.junit2spock.core.feature.junit.AssertNullFeature.ASSERT_NULL; import static com.github.opaluchlukasz.junit2spock.core.feature.junit.AssertTrueFeature.ASSERT_TRUE; import static com.github.opaluchlukasz.junit2spock.core.feature.mockito.GivenWillReturnFeature.WILL_RETURN; import static com.github.opaluchlukasz.junit2spock.core.feature.mockito.GivenWillThrowFeature.WILL_THROW; import static com.github.opaluchlukasz.junit2spock.core.feature.mockito.MockitoVerifyFeature.VERIFY; import static com.github.opaluchlukasz.junit2spock.core.feature.mockito.MockitoVerifyNoMoreInteractionsFeature.VERIFY_NO_MORE_INTERACTIONS; import static com.github.opaluchlukasz.junit2spock.core.feature.mockito.WhenThenReturnFeature.THEN_RETURN; import static com.github.opaluchlukasz.junit2spock.core.feature.mockito.WhenThenThrowFeature.THEN_THROW; import static com.github.opaluchlukasz.junit2spock.core.node.SpockBlockNode.expect; import static com.github.opaluchlukasz.junit2spock.core.node.SpockBlockNode.given; import static com.github.opaluchlukasz.junit2spock.core.node.SpockBlockNode.then; import static com.github.opaluchlukasz.junit2spock.core.node.SpockBlockNode.when; import static com.github.opaluchlukasz.junit2spock.core.util.AstNodeFinder.methodInvocation; import static org.spockframework.util.Identifiers.THROWN;
package com.github.opaluchlukasz.junit2spock.core.model.method; public class CodeBasedSpockBlocksStrategy implements SpockBlockApplier { private static final String ASSERT_THAT = "assertThat";
// Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/junit/AssertEqualsFeature.java // public static final String ASSERT_ARRAY_EQUALS = "assertArrayEquals"; // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/junit/AssertEqualsFeature.java // public static final String ASSERT_EQUALS = "assertEquals"; // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/junit/AssertFalseFeature.java // public static final String ASSERT_FALSE = "assertFalse"; // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/junit/AssertNotNullFeature.java // public static final String ASSERT_NOT_NULL = "assertNotNull"; // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/junit/AssertNullFeature.java // public static final String ASSERT_NULL = "assertNull"; // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/junit/AssertTrueFeature.java // public static final String ASSERT_TRUE = "assertTrue"; // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/mockito/GivenWillReturnFeature.java // public static final String WILL_RETURN = "willReturn"; // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/mockito/GivenWillThrowFeature.java // public static final String WILL_THROW = "willThrow"; // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/mockito/MockitoVerifyFeature.java // public static final String VERIFY = "verify"; // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/mockito/MockitoVerifyNoMoreInteractionsFeature.java // public static final String VERIFY_NO_MORE_INTERACTIONS = "verifyNoMoreInteractions"; // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/mockito/WhenThenReturnFeature.java // public static final String THEN_RETURN = "thenReturn"; // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/mockito/WhenThenThrowFeature.java // public static final String THEN_THROW = "thenThrow"; // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/node/SpockBlockNode.java // public static SpockBlockNode expect() { // return new SpockBlockNode("expect"); // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/node/SpockBlockNode.java // public static SpockBlockNode given() { // return new SpockBlockNode("given"); // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/node/SpockBlockNode.java // public static SpockBlockNode then() { // return new SpockBlockNode("then"); // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/node/SpockBlockNode.java // public static SpockBlockNode when() { // return new SpockBlockNode("when"); // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/util/AstNodeFinder.java // public static Optional<MethodInvocation> methodInvocation(Object bodyElement, String... methodNames) { // return stream(methodNames) // .map(methodName -> methodInvocation(bodyElement, methodName)) // .filter(Optional::isPresent) // .map(Optional::get) // .findFirst(); // } // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/model/method/CodeBasedSpockBlocksStrategy.java import org.eclipse.jdt.core.dom.Expression; import org.eclipse.jdt.core.dom.ExpressionStatement; import org.eclipse.jdt.core.dom.MethodInvocation; import java.util.List; import static com.github.opaluchlukasz.junit2spock.core.feature.junit.AssertEqualsFeature.ASSERT_ARRAY_EQUALS; import static com.github.opaluchlukasz.junit2spock.core.feature.junit.AssertEqualsFeature.ASSERT_EQUALS; import static com.github.opaluchlukasz.junit2spock.core.feature.junit.AssertFalseFeature.ASSERT_FALSE; import static com.github.opaluchlukasz.junit2spock.core.feature.junit.AssertNotNullFeature.ASSERT_NOT_NULL; import static com.github.opaluchlukasz.junit2spock.core.feature.junit.AssertNullFeature.ASSERT_NULL; import static com.github.opaluchlukasz.junit2spock.core.feature.junit.AssertTrueFeature.ASSERT_TRUE; import static com.github.opaluchlukasz.junit2spock.core.feature.mockito.GivenWillReturnFeature.WILL_RETURN; import static com.github.opaluchlukasz.junit2spock.core.feature.mockito.GivenWillThrowFeature.WILL_THROW; import static com.github.opaluchlukasz.junit2spock.core.feature.mockito.MockitoVerifyFeature.VERIFY; import static com.github.opaluchlukasz.junit2spock.core.feature.mockito.MockitoVerifyNoMoreInteractionsFeature.VERIFY_NO_MORE_INTERACTIONS; import static com.github.opaluchlukasz.junit2spock.core.feature.mockito.WhenThenReturnFeature.THEN_RETURN; import static com.github.opaluchlukasz.junit2spock.core.feature.mockito.WhenThenThrowFeature.THEN_THROW; import static com.github.opaluchlukasz.junit2spock.core.node.SpockBlockNode.expect; import static com.github.opaluchlukasz.junit2spock.core.node.SpockBlockNode.given; import static com.github.opaluchlukasz.junit2spock.core.node.SpockBlockNode.then; import static com.github.opaluchlukasz.junit2spock.core.node.SpockBlockNode.when; import static com.github.opaluchlukasz.junit2spock.core.util.AstNodeFinder.methodInvocation; import static org.spockframework.util.Identifiers.THROWN; package com.github.opaluchlukasz.junit2spock.core.model.method; public class CodeBasedSpockBlocksStrategy implements SpockBlockApplier { private static final String ASSERT_THAT = "assertThat";
public static final String[] THEN_BLOCK_START = new String[]{ASSERT_EQUALS, ASSERT_NOT_NULL, ASSERT_ARRAY_EQUALS, ASSERT_TRUE,
opaluchlukasz/junit2spock
src/main/java/com/github/opaluchlukasz/junit2spock/core/model/method/MethodDeclarationHelper.java
// Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/model/ModifierHelper.java // public final class ModifierHelper { // // private ModifierHelper() { // //NOOP // } // // public static Optional<Annotation> annotatedWith(List<ASTNode> modifiers, String annotationName) { // Optional<?> optionalAnnotation = modifiers.stream() // .filter(modifier -> modifier instanceof Annotation) // .filter(modifier -> ((Annotation) modifier).getTypeName().getFullyQualifiedName().equals(annotationName)).findFirst(); // return optionalAnnotation.map(annotation -> (Annotation) annotation); // } // }
import com.github.opaluchlukasz.junit2spock.core.model.ModifierHelper; import org.eclipse.jdt.core.dom.Annotation; import org.eclipse.jdt.core.dom.MethodDeclaration; import org.eclipse.jdt.core.dom.Modifier; import java.util.Optional;
package com.github.opaluchlukasz.junit2spock.core.model.method; public final class MethodDeclarationHelper { private MethodDeclarationHelper() { //NOOP } public static boolean isPrivate(MethodDeclaration methodDeclaration) { return Modifier.isPrivate(methodDeclaration.getModifiers()); } public static boolean isTestMethod(MethodDeclaration methodDeclaration) { return annotatedWith(methodDeclaration, "Test").isPresent(); } static Optional<Annotation> annotatedWith(MethodDeclaration methodDeclaration, String annotationName) {
// Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/model/ModifierHelper.java // public final class ModifierHelper { // // private ModifierHelper() { // //NOOP // } // // public static Optional<Annotation> annotatedWith(List<ASTNode> modifiers, String annotationName) { // Optional<?> optionalAnnotation = modifiers.stream() // .filter(modifier -> modifier instanceof Annotation) // .filter(modifier -> ((Annotation) modifier).getTypeName().getFullyQualifiedName().equals(annotationName)).findFirst(); // return optionalAnnotation.map(annotation -> (Annotation) annotation); // } // } // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/model/method/MethodDeclarationHelper.java import com.github.opaluchlukasz.junit2spock.core.model.ModifierHelper; import org.eclipse.jdt.core.dom.Annotation; import org.eclipse.jdt.core.dom.MethodDeclaration; import org.eclipse.jdt.core.dom.Modifier; import java.util.Optional; package com.github.opaluchlukasz.junit2spock.core.model.method; public final class MethodDeclarationHelper { private MethodDeclarationHelper() { //NOOP } public static boolean isPrivate(MethodDeclaration methodDeclaration) { return Modifier.isPrivate(methodDeclaration.getModifiers()); } public static boolean isTestMethod(MethodDeclaration methodDeclaration) { return annotatedWith(methodDeclaration, "Test").isPresent(); } static Optional<Annotation> annotatedWith(MethodDeclaration methodDeclaration, String annotationName) {
return ModifierHelper.annotatedWith(methodDeclaration.modifiers(), annotationName);
opaluchlukasz/junit2spock
src/main/java/com/github/opaluchlukasz/junit2spock/core/model/InterfaceModel.java
// Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/groovism/Groovism.java // public abstract class Groovism implements UnaryOperator<String> { // // private final Optional<Groovism> next; // // Groovism(Optional<Groovism> next) { // this.next = next; // } // // @Override // public String apply(String line) { // String groovierLine = applyGroovism(line); // return next.map(next -> next.apply(groovierLine)).orElse(groovierLine); // } // // protected abstract String applyGroovism(String line); // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/model/method/MethodModel.java // public abstract class MethodModel { // // static final String DEF_MODIFIER = "def "; // // private final ASTNodeFactory astNodeFactory; // private final MethodDeclaration methodDeclaration; // private final Groovism groovism; // private final List<Object> body = new LinkedList<>(); // // MethodModel(ASTNodeFactory astNodeFactory, MethodDeclaration methodDeclaration) { // this.astNodeFactory = astNodeFactory; // this.methodDeclaration = methodDeclaration; // groovism = provide(); // if (methodDeclaration.getBody() != null && methodDeclaration.getBody().statements() != null) { // methodDeclaration.getBody().statements().forEach(statement -> body.add(wrap(statement, 1, methodType()))); // } // } // // public String asGroovyMethod(int baseIndentationInTabs) { // StringBuilder methodBuilder = methodDeclarationBuilder(baseIndentationInTabs); // methodBuilder.append(" {"); // methodBuilder.append(SEPARATOR); // // methodBuilder.append(body().stream() // .map(node -> nodeAsString(baseIndentationInTabs, node)) // .map(groovism) // .collect(joining(SEPARATOR, "", methodSuffix()))); // // indent(methodBuilder, baseIndentationInTabs).append("}"); // methodBuilder.append(SEPARATOR).append(SEPARATOR); // // return methodBuilder.toString(); // } // // private String nodeAsString(int baseIndentationInTabs, Object node) { // if (node instanceof IfStatementWrapper) { // return node.toString(); // } // return indentation(baseIndentationInTabs + 1) + node.toString(); // } // // public String methodDeclaration(int baseIndentationInTabs) { // return methodDeclarationBuilder(baseIndentationInTabs).toString(); // } // // private StringBuilder methodDeclarationBuilder(int baseIndentationInTabs) { // StringBuilder methodBuilder = new StringBuilder(); // // indent(methodBuilder, baseIndentationInTabs); // methodBuilder.append(groovism.apply(methodModifier())); // // returnedType().ifPresent(type -> methodBuilder.append(type).append(" ")); // // methodBuilder.append(getMethodName()); // methodBuilder.append(methodDeclaration.parameters().stream() // .map(Object::toString) // .collect(joining(", ", "(", ")"))); // return methodBuilder; // } // // protected abstract String methodSuffix(); // // protected abstract String getMethodName(); // // protected abstract Applicable methodType(); // // protected List<Object> body() { // return body; // } // // protected MethodDeclaration methodDeclaration() { // return methodDeclaration; // } // // protected ASTNodeFactory astNodeFactory() { // return astNodeFactory; // } // // private Optional<String> returnedType() { // return Optional.ofNullable(methodDeclaration.getReturnType2()) // .filter(type -> !methodDeclaration.isConstructor()) // .filter(type -> !methodModifier().equals(DEF_MODIFIER)) // .map(Object::toString); // } // // protected abstract String methodModifier(); // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/groovism/GroovismChainProvider.java // public static Groovism provide() { // return new NoSemicolon(new NoClassKeyword(new RegularString(new NoPublicKeyword()))); // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/util/StringUtil.java // public static final String SEPARATOR = System.getProperty("line.separator"); // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/util/StringUtil.java // public static StringBuilder indent(StringBuilder stringBuilder, int indentationInTabs) { // IntStream.rangeClosed(1, indentationInTabs).forEach(__ -> stringBuilder.append("\t")); // return stringBuilder; // }
import com.github.opaluchlukasz.junit2spock.core.groovism.Groovism; import com.github.opaluchlukasz.junit2spock.core.model.method.MethodModel; import org.eclipse.jdt.core.dom.ASTNode; import org.eclipse.jdt.core.dom.FieldDeclaration; import org.eclipse.jdt.core.dom.ImportDeclaration; import org.eclipse.jdt.core.dom.PackageDeclaration; import org.eclipse.jdt.core.dom.Type; import org.spockframework.util.Immutable; import java.util.LinkedList; import java.util.List; import java.util.Optional; import static com.github.opaluchlukasz.junit2spock.core.SupportedTestFeature.imports; import static com.github.opaluchlukasz.junit2spock.core.groovism.GroovismChainProvider.provide; import static com.github.opaluchlukasz.junit2spock.core.util.StringUtil.SEPARATOR; import static com.github.opaluchlukasz.junit2spock.core.util.StringUtil.indent; import static java.util.Collections.unmodifiableList; import static java.util.stream.Collectors.joining;
package com.github.opaluchlukasz.junit2spock.core.model; @Immutable public class InterfaceModel extends TypeModel { private final String typeName; private final PackageDeclaration packageDeclaration; private final List<FieldDeclaration> fields;
// Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/groovism/Groovism.java // public abstract class Groovism implements UnaryOperator<String> { // // private final Optional<Groovism> next; // // Groovism(Optional<Groovism> next) { // this.next = next; // } // // @Override // public String apply(String line) { // String groovierLine = applyGroovism(line); // return next.map(next -> next.apply(groovierLine)).orElse(groovierLine); // } // // protected abstract String applyGroovism(String line); // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/model/method/MethodModel.java // public abstract class MethodModel { // // static final String DEF_MODIFIER = "def "; // // private final ASTNodeFactory astNodeFactory; // private final MethodDeclaration methodDeclaration; // private final Groovism groovism; // private final List<Object> body = new LinkedList<>(); // // MethodModel(ASTNodeFactory astNodeFactory, MethodDeclaration methodDeclaration) { // this.astNodeFactory = astNodeFactory; // this.methodDeclaration = methodDeclaration; // groovism = provide(); // if (methodDeclaration.getBody() != null && methodDeclaration.getBody().statements() != null) { // methodDeclaration.getBody().statements().forEach(statement -> body.add(wrap(statement, 1, methodType()))); // } // } // // public String asGroovyMethod(int baseIndentationInTabs) { // StringBuilder methodBuilder = methodDeclarationBuilder(baseIndentationInTabs); // methodBuilder.append(" {"); // methodBuilder.append(SEPARATOR); // // methodBuilder.append(body().stream() // .map(node -> nodeAsString(baseIndentationInTabs, node)) // .map(groovism) // .collect(joining(SEPARATOR, "", methodSuffix()))); // // indent(methodBuilder, baseIndentationInTabs).append("}"); // methodBuilder.append(SEPARATOR).append(SEPARATOR); // // return methodBuilder.toString(); // } // // private String nodeAsString(int baseIndentationInTabs, Object node) { // if (node instanceof IfStatementWrapper) { // return node.toString(); // } // return indentation(baseIndentationInTabs + 1) + node.toString(); // } // // public String methodDeclaration(int baseIndentationInTabs) { // return methodDeclarationBuilder(baseIndentationInTabs).toString(); // } // // private StringBuilder methodDeclarationBuilder(int baseIndentationInTabs) { // StringBuilder methodBuilder = new StringBuilder(); // // indent(methodBuilder, baseIndentationInTabs); // methodBuilder.append(groovism.apply(methodModifier())); // // returnedType().ifPresent(type -> methodBuilder.append(type).append(" ")); // // methodBuilder.append(getMethodName()); // methodBuilder.append(methodDeclaration.parameters().stream() // .map(Object::toString) // .collect(joining(", ", "(", ")"))); // return methodBuilder; // } // // protected abstract String methodSuffix(); // // protected abstract String getMethodName(); // // protected abstract Applicable methodType(); // // protected List<Object> body() { // return body; // } // // protected MethodDeclaration methodDeclaration() { // return methodDeclaration; // } // // protected ASTNodeFactory astNodeFactory() { // return astNodeFactory; // } // // private Optional<String> returnedType() { // return Optional.ofNullable(methodDeclaration.getReturnType2()) // .filter(type -> !methodDeclaration.isConstructor()) // .filter(type -> !methodModifier().equals(DEF_MODIFIER)) // .map(Object::toString); // } // // protected abstract String methodModifier(); // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/groovism/GroovismChainProvider.java // public static Groovism provide() { // return new NoSemicolon(new NoClassKeyword(new RegularString(new NoPublicKeyword()))); // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/util/StringUtil.java // public static final String SEPARATOR = System.getProperty("line.separator"); // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/util/StringUtil.java // public static StringBuilder indent(StringBuilder stringBuilder, int indentationInTabs) { // IntStream.rangeClosed(1, indentationInTabs).forEach(__ -> stringBuilder.append("\t")); // return stringBuilder; // } // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/model/InterfaceModel.java import com.github.opaluchlukasz.junit2spock.core.groovism.Groovism; import com.github.opaluchlukasz.junit2spock.core.model.method.MethodModel; import org.eclipse.jdt.core.dom.ASTNode; import org.eclipse.jdt.core.dom.FieldDeclaration; import org.eclipse.jdt.core.dom.ImportDeclaration; import org.eclipse.jdt.core.dom.PackageDeclaration; import org.eclipse.jdt.core.dom.Type; import org.spockframework.util.Immutable; import java.util.LinkedList; import java.util.List; import java.util.Optional; import static com.github.opaluchlukasz.junit2spock.core.SupportedTestFeature.imports; import static com.github.opaluchlukasz.junit2spock.core.groovism.GroovismChainProvider.provide; import static com.github.opaluchlukasz.junit2spock.core.util.StringUtil.SEPARATOR; import static com.github.opaluchlukasz.junit2spock.core.util.StringUtil.indent; import static java.util.Collections.unmodifiableList; import static java.util.stream.Collectors.joining; package com.github.opaluchlukasz.junit2spock.core.model; @Immutable public class InterfaceModel extends TypeModel { private final String typeName; private final PackageDeclaration packageDeclaration; private final List<FieldDeclaration> fields;
private final List<MethodModel> methods;
opaluchlukasz/junit2spock
src/main/java/com/github/opaluchlukasz/junit2spock/core/model/InterfaceModel.java
// Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/groovism/Groovism.java // public abstract class Groovism implements UnaryOperator<String> { // // private final Optional<Groovism> next; // // Groovism(Optional<Groovism> next) { // this.next = next; // } // // @Override // public String apply(String line) { // String groovierLine = applyGroovism(line); // return next.map(next -> next.apply(groovierLine)).orElse(groovierLine); // } // // protected abstract String applyGroovism(String line); // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/model/method/MethodModel.java // public abstract class MethodModel { // // static final String DEF_MODIFIER = "def "; // // private final ASTNodeFactory astNodeFactory; // private final MethodDeclaration methodDeclaration; // private final Groovism groovism; // private final List<Object> body = new LinkedList<>(); // // MethodModel(ASTNodeFactory astNodeFactory, MethodDeclaration methodDeclaration) { // this.astNodeFactory = astNodeFactory; // this.methodDeclaration = methodDeclaration; // groovism = provide(); // if (methodDeclaration.getBody() != null && methodDeclaration.getBody().statements() != null) { // methodDeclaration.getBody().statements().forEach(statement -> body.add(wrap(statement, 1, methodType()))); // } // } // // public String asGroovyMethod(int baseIndentationInTabs) { // StringBuilder methodBuilder = methodDeclarationBuilder(baseIndentationInTabs); // methodBuilder.append(" {"); // methodBuilder.append(SEPARATOR); // // methodBuilder.append(body().stream() // .map(node -> nodeAsString(baseIndentationInTabs, node)) // .map(groovism) // .collect(joining(SEPARATOR, "", methodSuffix()))); // // indent(methodBuilder, baseIndentationInTabs).append("}"); // methodBuilder.append(SEPARATOR).append(SEPARATOR); // // return methodBuilder.toString(); // } // // private String nodeAsString(int baseIndentationInTabs, Object node) { // if (node instanceof IfStatementWrapper) { // return node.toString(); // } // return indentation(baseIndentationInTabs + 1) + node.toString(); // } // // public String methodDeclaration(int baseIndentationInTabs) { // return methodDeclarationBuilder(baseIndentationInTabs).toString(); // } // // private StringBuilder methodDeclarationBuilder(int baseIndentationInTabs) { // StringBuilder methodBuilder = new StringBuilder(); // // indent(methodBuilder, baseIndentationInTabs); // methodBuilder.append(groovism.apply(methodModifier())); // // returnedType().ifPresent(type -> methodBuilder.append(type).append(" ")); // // methodBuilder.append(getMethodName()); // methodBuilder.append(methodDeclaration.parameters().stream() // .map(Object::toString) // .collect(joining(", ", "(", ")"))); // return methodBuilder; // } // // protected abstract String methodSuffix(); // // protected abstract String getMethodName(); // // protected abstract Applicable methodType(); // // protected List<Object> body() { // return body; // } // // protected MethodDeclaration methodDeclaration() { // return methodDeclaration; // } // // protected ASTNodeFactory astNodeFactory() { // return astNodeFactory; // } // // private Optional<String> returnedType() { // return Optional.ofNullable(methodDeclaration.getReturnType2()) // .filter(type -> !methodDeclaration.isConstructor()) // .filter(type -> !methodModifier().equals(DEF_MODIFIER)) // .map(Object::toString); // } // // protected abstract String methodModifier(); // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/groovism/GroovismChainProvider.java // public static Groovism provide() { // return new NoSemicolon(new NoClassKeyword(new RegularString(new NoPublicKeyword()))); // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/util/StringUtil.java // public static final String SEPARATOR = System.getProperty("line.separator"); // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/util/StringUtil.java // public static StringBuilder indent(StringBuilder stringBuilder, int indentationInTabs) { // IntStream.rangeClosed(1, indentationInTabs).forEach(__ -> stringBuilder.append("\t")); // return stringBuilder; // }
import com.github.opaluchlukasz.junit2spock.core.groovism.Groovism; import com.github.opaluchlukasz.junit2spock.core.model.method.MethodModel; import org.eclipse.jdt.core.dom.ASTNode; import org.eclipse.jdt.core.dom.FieldDeclaration; import org.eclipse.jdt.core.dom.ImportDeclaration; import org.eclipse.jdt.core.dom.PackageDeclaration; import org.eclipse.jdt.core.dom.Type; import org.spockframework.util.Immutable; import java.util.LinkedList; import java.util.List; import java.util.Optional; import static com.github.opaluchlukasz.junit2spock.core.SupportedTestFeature.imports; import static com.github.opaluchlukasz.junit2spock.core.groovism.GroovismChainProvider.provide; import static com.github.opaluchlukasz.junit2spock.core.util.StringUtil.SEPARATOR; import static com.github.opaluchlukasz.junit2spock.core.util.StringUtil.indent; import static java.util.Collections.unmodifiableList; import static java.util.stream.Collectors.joining;
package com.github.opaluchlukasz.junit2spock.core.model; @Immutable public class InterfaceModel extends TypeModel { private final String typeName; private final PackageDeclaration packageDeclaration; private final List<FieldDeclaration> fields; private final List<MethodModel> methods; private final List<ImportDeclaration> imports; private final Optional<String> superClassType; private final List<ASTNode> modifiers;
// Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/groovism/Groovism.java // public abstract class Groovism implements UnaryOperator<String> { // // private final Optional<Groovism> next; // // Groovism(Optional<Groovism> next) { // this.next = next; // } // // @Override // public String apply(String line) { // String groovierLine = applyGroovism(line); // return next.map(next -> next.apply(groovierLine)).orElse(groovierLine); // } // // protected abstract String applyGroovism(String line); // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/model/method/MethodModel.java // public abstract class MethodModel { // // static final String DEF_MODIFIER = "def "; // // private final ASTNodeFactory astNodeFactory; // private final MethodDeclaration methodDeclaration; // private final Groovism groovism; // private final List<Object> body = new LinkedList<>(); // // MethodModel(ASTNodeFactory astNodeFactory, MethodDeclaration methodDeclaration) { // this.astNodeFactory = astNodeFactory; // this.methodDeclaration = methodDeclaration; // groovism = provide(); // if (methodDeclaration.getBody() != null && methodDeclaration.getBody().statements() != null) { // methodDeclaration.getBody().statements().forEach(statement -> body.add(wrap(statement, 1, methodType()))); // } // } // // public String asGroovyMethod(int baseIndentationInTabs) { // StringBuilder methodBuilder = methodDeclarationBuilder(baseIndentationInTabs); // methodBuilder.append(" {"); // methodBuilder.append(SEPARATOR); // // methodBuilder.append(body().stream() // .map(node -> nodeAsString(baseIndentationInTabs, node)) // .map(groovism) // .collect(joining(SEPARATOR, "", methodSuffix()))); // // indent(methodBuilder, baseIndentationInTabs).append("}"); // methodBuilder.append(SEPARATOR).append(SEPARATOR); // // return methodBuilder.toString(); // } // // private String nodeAsString(int baseIndentationInTabs, Object node) { // if (node instanceof IfStatementWrapper) { // return node.toString(); // } // return indentation(baseIndentationInTabs + 1) + node.toString(); // } // // public String methodDeclaration(int baseIndentationInTabs) { // return methodDeclarationBuilder(baseIndentationInTabs).toString(); // } // // private StringBuilder methodDeclarationBuilder(int baseIndentationInTabs) { // StringBuilder methodBuilder = new StringBuilder(); // // indent(methodBuilder, baseIndentationInTabs); // methodBuilder.append(groovism.apply(methodModifier())); // // returnedType().ifPresent(type -> methodBuilder.append(type).append(" ")); // // methodBuilder.append(getMethodName()); // methodBuilder.append(methodDeclaration.parameters().stream() // .map(Object::toString) // .collect(joining(", ", "(", ")"))); // return methodBuilder; // } // // protected abstract String methodSuffix(); // // protected abstract String getMethodName(); // // protected abstract Applicable methodType(); // // protected List<Object> body() { // return body; // } // // protected MethodDeclaration methodDeclaration() { // return methodDeclaration; // } // // protected ASTNodeFactory astNodeFactory() { // return astNodeFactory; // } // // private Optional<String> returnedType() { // return Optional.ofNullable(methodDeclaration.getReturnType2()) // .filter(type -> !methodDeclaration.isConstructor()) // .filter(type -> !methodModifier().equals(DEF_MODIFIER)) // .map(Object::toString); // } // // protected abstract String methodModifier(); // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/groovism/GroovismChainProvider.java // public static Groovism provide() { // return new NoSemicolon(new NoClassKeyword(new RegularString(new NoPublicKeyword()))); // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/util/StringUtil.java // public static final String SEPARATOR = System.getProperty("line.separator"); // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/util/StringUtil.java // public static StringBuilder indent(StringBuilder stringBuilder, int indentationInTabs) { // IntStream.rangeClosed(1, indentationInTabs).forEach(__ -> stringBuilder.append("\t")); // return stringBuilder; // } // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/model/InterfaceModel.java import com.github.opaluchlukasz.junit2spock.core.groovism.Groovism; import com.github.opaluchlukasz.junit2spock.core.model.method.MethodModel; import org.eclipse.jdt.core.dom.ASTNode; import org.eclipse.jdt.core.dom.FieldDeclaration; import org.eclipse.jdt.core.dom.ImportDeclaration; import org.eclipse.jdt.core.dom.PackageDeclaration; import org.eclipse.jdt.core.dom.Type; import org.spockframework.util.Immutable; import java.util.LinkedList; import java.util.List; import java.util.Optional; import static com.github.opaluchlukasz.junit2spock.core.SupportedTestFeature.imports; import static com.github.opaluchlukasz.junit2spock.core.groovism.GroovismChainProvider.provide; import static com.github.opaluchlukasz.junit2spock.core.util.StringUtil.SEPARATOR; import static com.github.opaluchlukasz.junit2spock.core.util.StringUtil.indent; import static java.util.Collections.unmodifiableList; import static java.util.stream.Collectors.joining; package com.github.opaluchlukasz.junit2spock.core.model; @Immutable public class InterfaceModel extends TypeModel { private final String typeName; private final PackageDeclaration packageDeclaration; private final List<FieldDeclaration> fields; private final List<MethodModel> methods; private final List<ImportDeclaration> imports; private final Optional<String> superClassType; private final List<ASTNode> modifiers;
private final Groovism groovism;
opaluchlukasz/junit2spock
src/main/java/com/github/opaluchlukasz/junit2spock/core/node/wrapper/TryStatementWrapper.java
// Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/Applicable.java // public enum Applicable { // TEST_METHOD, FIXTURE_METHOD, REGULAR_METHOD, FIELD_FEATURE; // // @Component // static class ApplicableInjector { // @Autowired private FeatureProvider featureProvider; // // @PostConstruct // public void init() { // stream(Applicable.values()).forEach(applicable -> applicable.featureProvider = featureProvider); // } // } // // private FeatureProvider featureProvider; // // public void applyFeaturesToStatements(List<Object> statements) { // List<Feature> features = features(); // for (int i = 0; i < statements.size(); i++) { // Object bodyNode = statements.get(i); // statements.remove(i); // for (Feature testMethodFeature : features) { // bodyNode = testMethodFeature.apply(bodyNode); // } // statements.add(i, bodyNode); // } // } // // public List<Feature> features() { // return featureProvider.features(this); // } // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/util/StringUtil.java // public static final String SEPARATOR = System.getProperty("line.separator"); // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/util/StringUtil.java // public static String indentation(int indentationInTabs) { // return IntStream.rangeClosed(1, indentationInTabs).mapToObj(__ -> "\t").reduce("", (a, b) -> a + b); // }
import com.github.opaluchlukasz.junit2spock.core.Applicable; import org.eclipse.jdt.core.dom.Block; import org.eclipse.jdt.core.dom.CatchClause; import org.eclipse.jdt.core.dom.SingleVariableDeclaration; import org.eclipse.jdt.core.dom.TryStatement; import java.util.LinkedList; import java.util.List; import java.util.Optional; import static com.github.opaluchlukasz.junit2spock.core.util.StringUtil.SEPARATOR; import static com.github.opaluchlukasz.junit2spock.core.util.StringUtil.indentation; import static java.util.Optional.ofNullable; import static java.util.stream.Collectors.toCollection;
package com.github.opaluchlukasz.junit2spock.core.node.wrapper; public class TryStatementWrapper extends BaseWrapper { private final LinkedList body = new LinkedList(); private final Optional<List<Object>> finallyBody; private final LinkedList<CatchClauseWrapper> catchClauses;
// Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/Applicable.java // public enum Applicable { // TEST_METHOD, FIXTURE_METHOD, REGULAR_METHOD, FIELD_FEATURE; // // @Component // static class ApplicableInjector { // @Autowired private FeatureProvider featureProvider; // // @PostConstruct // public void init() { // stream(Applicable.values()).forEach(applicable -> applicable.featureProvider = featureProvider); // } // } // // private FeatureProvider featureProvider; // // public void applyFeaturesToStatements(List<Object> statements) { // List<Feature> features = features(); // for (int i = 0; i < statements.size(); i++) { // Object bodyNode = statements.get(i); // statements.remove(i); // for (Feature testMethodFeature : features) { // bodyNode = testMethodFeature.apply(bodyNode); // } // statements.add(i, bodyNode); // } // } // // public List<Feature> features() { // return featureProvider.features(this); // } // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/util/StringUtil.java // public static final String SEPARATOR = System.getProperty("line.separator"); // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/util/StringUtil.java // public static String indentation(int indentationInTabs) { // return IntStream.rangeClosed(1, indentationInTabs).mapToObj(__ -> "\t").reduce("", (a, b) -> a + b); // } // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/node/wrapper/TryStatementWrapper.java import com.github.opaluchlukasz.junit2spock.core.Applicable; import org.eclipse.jdt.core.dom.Block; import org.eclipse.jdt.core.dom.CatchClause; import org.eclipse.jdt.core.dom.SingleVariableDeclaration; import org.eclipse.jdt.core.dom.TryStatement; import java.util.LinkedList; import java.util.List; import java.util.Optional; import static com.github.opaluchlukasz.junit2spock.core.util.StringUtil.SEPARATOR; import static com.github.opaluchlukasz.junit2spock.core.util.StringUtil.indentation; import static java.util.Optional.ofNullable; import static java.util.stream.Collectors.toCollection; package com.github.opaluchlukasz.junit2spock.core.node.wrapper; public class TryStatementWrapper extends BaseWrapper { private final LinkedList body = new LinkedList(); private final Optional<List<Object>> finallyBody; private final LinkedList<CatchClauseWrapper> catchClauses;
TryStatementWrapper(TryStatement statement, int indentationLevel, Applicable applicable) {
opaluchlukasz/junit2spock
src/main/java/com/github/opaluchlukasz/junit2spock/core/node/wrapper/TryStatementWrapper.java
// Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/Applicable.java // public enum Applicable { // TEST_METHOD, FIXTURE_METHOD, REGULAR_METHOD, FIELD_FEATURE; // // @Component // static class ApplicableInjector { // @Autowired private FeatureProvider featureProvider; // // @PostConstruct // public void init() { // stream(Applicable.values()).forEach(applicable -> applicable.featureProvider = featureProvider); // } // } // // private FeatureProvider featureProvider; // // public void applyFeaturesToStatements(List<Object> statements) { // List<Feature> features = features(); // for (int i = 0; i < statements.size(); i++) { // Object bodyNode = statements.get(i); // statements.remove(i); // for (Feature testMethodFeature : features) { // bodyNode = testMethodFeature.apply(bodyNode); // } // statements.add(i, bodyNode); // } // } // // public List<Feature> features() { // return featureProvider.features(this); // } // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/util/StringUtil.java // public static final String SEPARATOR = System.getProperty("line.separator"); // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/util/StringUtil.java // public static String indentation(int indentationInTabs) { // return IntStream.rangeClosed(1, indentationInTabs).mapToObj(__ -> "\t").reduce("", (a, b) -> a + b); // }
import com.github.opaluchlukasz.junit2spock.core.Applicable; import org.eclipse.jdt.core.dom.Block; import org.eclipse.jdt.core.dom.CatchClause; import org.eclipse.jdt.core.dom.SingleVariableDeclaration; import org.eclipse.jdt.core.dom.TryStatement; import java.util.LinkedList; import java.util.List; import java.util.Optional; import static com.github.opaluchlukasz.junit2spock.core.util.StringUtil.SEPARATOR; import static com.github.opaluchlukasz.junit2spock.core.util.StringUtil.indentation; import static java.util.Optional.ofNullable; import static java.util.stream.Collectors.toCollection;
package com.github.opaluchlukasz.junit2spock.core.node.wrapper; public class TryStatementWrapper extends BaseWrapper { private final LinkedList body = new LinkedList(); private final Optional<List<Object>> finallyBody; private final LinkedList<CatchClauseWrapper> catchClauses; TryStatementWrapper(TryStatement statement, int indentationLevel, Applicable applicable) { super(indentationLevel, applicable); body.addAll(statement.resources()); ofNullable(statement.getBody()).ifPresent(block -> body.addAll(block.statements())); this.catchClauses = (LinkedList<CatchClauseWrapper>) statement.catchClauses().stream() .map(catchClause -> new CatchClauseWrapper((CatchClause) catchClause, indentationLevel, applicable)) .collect(toCollection(LinkedList::new)); finallyBody = ofNullable(statement.getFinally()) .map(Block::statements); applicable.applyFeaturesToStatements(body); finallyBody.ifPresent(applicable::applyFeaturesToStatements); } @Override public String toString() { StringBuilder stringBuilder = new StringBuilder();
// Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/Applicable.java // public enum Applicable { // TEST_METHOD, FIXTURE_METHOD, REGULAR_METHOD, FIELD_FEATURE; // // @Component // static class ApplicableInjector { // @Autowired private FeatureProvider featureProvider; // // @PostConstruct // public void init() { // stream(Applicable.values()).forEach(applicable -> applicable.featureProvider = featureProvider); // } // } // // private FeatureProvider featureProvider; // // public void applyFeaturesToStatements(List<Object> statements) { // List<Feature> features = features(); // for (int i = 0; i < statements.size(); i++) { // Object bodyNode = statements.get(i); // statements.remove(i); // for (Feature testMethodFeature : features) { // bodyNode = testMethodFeature.apply(bodyNode); // } // statements.add(i, bodyNode); // } // } // // public List<Feature> features() { // return featureProvider.features(this); // } // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/util/StringUtil.java // public static final String SEPARATOR = System.getProperty("line.separator"); // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/util/StringUtil.java // public static String indentation(int indentationInTabs) { // return IntStream.rangeClosed(1, indentationInTabs).mapToObj(__ -> "\t").reduce("", (a, b) -> a + b); // } // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/node/wrapper/TryStatementWrapper.java import com.github.opaluchlukasz.junit2spock.core.Applicable; import org.eclipse.jdt.core.dom.Block; import org.eclipse.jdt.core.dom.CatchClause; import org.eclipse.jdt.core.dom.SingleVariableDeclaration; import org.eclipse.jdt.core.dom.TryStatement; import java.util.LinkedList; import java.util.List; import java.util.Optional; import static com.github.opaluchlukasz.junit2spock.core.util.StringUtil.SEPARATOR; import static com.github.opaluchlukasz.junit2spock.core.util.StringUtil.indentation; import static java.util.Optional.ofNullable; import static java.util.stream.Collectors.toCollection; package com.github.opaluchlukasz.junit2spock.core.node.wrapper; public class TryStatementWrapper extends BaseWrapper { private final LinkedList body = new LinkedList(); private final Optional<List<Object>> finallyBody; private final LinkedList<CatchClauseWrapper> catchClauses; TryStatementWrapper(TryStatement statement, int indentationLevel, Applicable applicable) { super(indentationLevel, applicable); body.addAll(statement.resources()); ofNullable(statement.getBody()).ifPresent(block -> body.addAll(block.statements())); this.catchClauses = (LinkedList<CatchClauseWrapper>) statement.catchClauses().stream() .map(catchClause -> new CatchClauseWrapper((CatchClause) catchClause, indentationLevel, applicable)) .collect(toCollection(LinkedList::new)); finallyBody = ofNullable(statement.getFinally()) .map(Block::statements); applicable.applyFeaturesToStatements(body); finallyBody.ifPresent(applicable::applyFeaturesToStatements); } @Override public String toString() { StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("try {").append(SEPARATOR);
opaluchlukasz/junit2spock
src/main/java/com/github/opaluchlukasz/junit2spock/core/node/wrapper/TryStatementWrapper.java
// Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/Applicable.java // public enum Applicable { // TEST_METHOD, FIXTURE_METHOD, REGULAR_METHOD, FIELD_FEATURE; // // @Component // static class ApplicableInjector { // @Autowired private FeatureProvider featureProvider; // // @PostConstruct // public void init() { // stream(Applicable.values()).forEach(applicable -> applicable.featureProvider = featureProvider); // } // } // // private FeatureProvider featureProvider; // // public void applyFeaturesToStatements(List<Object> statements) { // List<Feature> features = features(); // for (int i = 0; i < statements.size(); i++) { // Object bodyNode = statements.get(i); // statements.remove(i); // for (Feature testMethodFeature : features) { // bodyNode = testMethodFeature.apply(bodyNode); // } // statements.add(i, bodyNode); // } // } // // public List<Feature> features() { // return featureProvider.features(this); // } // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/util/StringUtil.java // public static final String SEPARATOR = System.getProperty("line.separator"); // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/util/StringUtil.java // public static String indentation(int indentationInTabs) { // return IntStream.rangeClosed(1, indentationInTabs).mapToObj(__ -> "\t").reduce("", (a, b) -> a + b); // }
import com.github.opaluchlukasz.junit2spock.core.Applicable; import org.eclipse.jdt.core.dom.Block; import org.eclipse.jdt.core.dom.CatchClause; import org.eclipse.jdt.core.dom.SingleVariableDeclaration; import org.eclipse.jdt.core.dom.TryStatement; import java.util.LinkedList; import java.util.List; import java.util.Optional; import static com.github.opaluchlukasz.junit2spock.core.util.StringUtil.SEPARATOR; import static com.github.opaluchlukasz.junit2spock.core.util.StringUtil.indentation; import static java.util.Optional.ofNullable; import static java.util.stream.Collectors.toCollection;
package com.github.opaluchlukasz.junit2spock.core.node.wrapper; public class TryStatementWrapper extends BaseWrapper { private final LinkedList body = new LinkedList(); private final Optional<List<Object>> finallyBody; private final LinkedList<CatchClauseWrapper> catchClauses; TryStatementWrapper(TryStatement statement, int indentationLevel, Applicable applicable) { super(indentationLevel, applicable); body.addAll(statement.resources()); ofNullable(statement.getBody()).ifPresent(block -> body.addAll(block.statements())); this.catchClauses = (LinkedList<CatchClauseWrapper>) statement.catchClauses().stream() .map(catchClause -> new CatchClauseWrapper((CatchClause) catchClause, indentationLevel, applicable)) .collect(toCollection(LinkedList::new)); finallyBody = ofNullable(statement.getFinally()) .map(Block::statements); applicable.applyFeaturesToStatements(body); finallyBody.ifPresent(applicable::applyFeaturesToStatements); } @Override public String toString() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("try {").append(SEPARATOR); body.forEach(printStatement(stringBuilder));
// Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/Applicable.java // public enum Applicable { // TEST_METHOD, FIXTURE_METHOD, REGULAR_METHOD, FIELD_FEATURE; // // @Component // static class ApplicableInjector { // @Autowired private FeatureProvider featureProvider; // // @PostConstruct // public void init() { // stream(Applicable.values()).forEach(applicable -> applicable.featureProvider = featureProvider); // } // } // // private FeatureProvider featureProvider; // // public void applyFeaturesToStatements(List<Object> statements) { // List<Feature> features = features(); // for (int i = 0; i < statements.size(); i++) { // Object bodyNode = statements.get(i); // statements.remove(i); // for (Feature testMethodFeature : features) { // bodyNode = testMethodFeature.apply(bodyNode); // } // statements.add(i, bodyNode); // } // } // // public List<Feature> features() { // return featureProvider.features(this); // } // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/util/StringUtil.java // public static final String SEPARATOR = System.getProperty("line.separator"); // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/util/StringUtil.java // public static String indentation(int indentationInTabs) { // return IntStream.rangeClosed(1, indentationInTabs).mapToObj(__ -> "\t").reduce("", (a, b) -> a + b); // } // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/node/wrapper/TryStatementWrapper.java import com.github.opaluchlukasz.junit2spock.core.Applicable; import org.eclipse.jdt.core.dom.Block; import org.eclipse.jdt.core.dom.CatchClause; import org.eclipse.jdt.core.dom.SingleVariableDeclaration; import org.eclipse.jdt.core.dom.TryStatement; import java.util.LinkedList; import java.util.List; import java.util.Optional; import static com.github.opaluchlukasz.junit2spock.core.util.StringUtil.SEPARATOR; import static com.github.opaluchlukasz.junit2spock.core.util.StringUtil.indentation; import static java.util.Optional.ofNullable; import static java.util.stream.Collectors.toCollection; package com.github.opaluchlukasz.junit2spock.core.node.wrapper; public class TryStatementWrapper extends BaseWrapper { private final LinkedList body = new LinkedList(); private final Optional<List<Object>> finallyBody; private final LinkedList<CatchClauseWrapper> catchClauses; TryStatementWrapper(TryStatement statement, int indentationLevel, Applicable applicable) { super(indentationLevel, applicable); body.addAll(statement.resources()); ofNullable(statement.getBody()).ifPresent(block -> body.addAll(block.statements())); this.catchClauses = (LinkedList<CatchClauseWrapper>) statement.catchClauses().stream() .map(catchClause -> new CatchClauseWrapper((CatchClause) catchClause, indentationLevel, applicable)) .collect(toCollection(LinkedList::new)); finallyBody = ofNullable(statement.getFinally()) .map(Block::statements); applicable.applyFeaturesToStatements(body); finallyBody.ifPresent(applicable::applyFeaturesToStatements); } @Override public String toString() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("try {").append(SEPARATOR); body.forEach(printStatement(stringBuilder));
stringBuilder.append(indentation(indentationLevel() + 1)).append("}");
opaluchlukasz/junit2spock
src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/FeatureProvider.java
// Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/Applicable.java // public enum Applicable { // TEST_METHOD, FIXTURE_METHOD, REGULAR_METHOD, FIELD_FEATURE; // // @Component // static class ApplicableInjector { // @Autowired private FeatureProvider featureProvider; // // @PostConstruct // public void init() { // stream(Applicable.values()).forEach(applicable -> applicable.featureProvider = featureProvider); // } // } // // private FeatureProvider featureProvider; // // public void applyFeaturesToStatements(List<Object> statements) { // List<Feature> features = features(); // for (int i = 0; i < statements.size(); i++) { // Object bodyNode = statements.get(i); // statements.remove(i); // for (Feature testMethodFeature : features) { // bodyNode = testMethodFeature.apply(bodyNode); // } // statements.add(i, bodyNode); // } // } // // public List<Feature> features() { // return featureProvider.features(this); // } // }
import com.github.opaluchlukasz.junit2spock.core.Applicable; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.List; import static com.github.opaluchlukasz.junit2spock.core.SupportedTestFeature.featuresTypes; import static java.util.stream.Collectors.toList;
package com.github.opaluchlukasz.junit2spock.core.feature; @Component public class FeatureProvider { private final FeatureFactory featureFactory; @Autowired public FeatureProvider(FeatureFactory featureFactory) { this.featureFactory = featureFactory; }
// Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/Applicable.java // public enum Applicable { // TEST_METHOD, FIXTURE_METHOD, REGULAR_METHOD, FIELD_FEATURE; // // @Component // static class ApplicableInjector { // @Autowired private FeatureProvider featureProvider; // // @PostConstruct // public void init() { // stream(Applicable.values()).forEach(applicable -> applicable.featureProvider = featureProvider); // } // } // // private FeatureProvider featureProvider; // // public void applyFeaturesToStatements(List<Object> statements) { // List<Feature> features = features(); // for (int i = 0; i < statements.size(); i++) { // Object bodyNode = statements.get(i); // statements.remove(i); // for (Feature testMethodFeature : features) { // bodyNode = testMethodFeature.apply(bodyNode); // } // statements.add(i, bodyNode); // } // } // // public List<Feature> features() { // return featureProvider.features(this); // } // } // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/FeatureProvider.java import com.github.opaluchlukasz.junit2spock.core.Applicable; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.List; import static com.github.opaluchlukasz.junit2spock.core.SupportedTestFeature.featuresTypes; import static java.util.stream.Collectors.toList; package com.github.opaluchlukasz.junit2spock.core.feature; @Component public class FeatureProvider { private final FeatureFactory featureFactory; @Autowired public FeatureProvider(FeatureFactory featureFactory) { this.featureFactory = featureFactory; }
public List<Feature> features(Applicable applicable) {
opaluchlukasz/junit2spock
src/main/java/com/github/opaluchlukasz/junit2spock/App.java
// Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/Spocker.java // @Component // public class Spocker { // // private final AstProxy astProxy; // private final Supplier<TypeVisitor> testClassVisitorSupplier; // // @Autowired // public Spocker(AstProxy astProxy, Supplier<TypeVisitor> testClassVisitorSupplier) { // this.astProxy = astProxy; // this.testClassVisitorSupplier = testClassVisitorSupplier; // } // // public TypeModel toGroovyTypeModel(String source) { // source = source.replaceAll("//(?i)\\s*" + quote("given") + SEPARATOR, "givenBlockStart();"); // source = source.replaceAll("//(?i)\\s*" + quote("when") + SEPARATOR, "whenBlockStart();"); // source = source.replaceAll("//(?i)\\s*" + quote("then") + SEPARATOR, "thenBlockStart();"); // // ASTParser parser = ASTParser.newParser(JLS8); // parser.setSource(source.toCharArray()); // parser.setKind(K_COMPILATION_UNIT); // parser.setCompilerOptions(compilerOptions()); // // CompilationUnit cu = (CompilationUnit) parser.createAST(null); // astProxy.setTarget(cu.getAST()); // // TypeVisitor visitor = testClassVisitorSupplier.get(); // cu.accept(visitor); // return visitor.typeModel(); // } // // private Map<String, String> compilerOptions() { // Map<String, String> compilerOptions = getOptions(); // compilerOptions.put(COMPILER_COMPLIANCE, VERSION_1_8); // compilerOptions.put(COMPILER_CODEGEN_TARGET_PLATFORM, VERSION_1_8); // compilerOptions.put(COMPILER_SOURCE, VERSION_1_8); // return compilerOptions; // } // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/model/TypeModel.java // public abstract class TypeModel { // public abstract String asGroovyClass(int typeIndent); // public abstract String typeName(); // abstract Optional<String> packageDeclaration(); // // public String outputFilePath() { // StringBuilder path = new StringBuilder(); // packageDeclaration() // .ifPresent(declaration -> path.append(declaration.replace(quoteReplacement("."), separator)) // .append(separator)); // path.append(typeName()).append(".groovy"); // return path.toString(); // } // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/util/StringUtil.java // public static final String SEPARATOR = System.getProperty("line.separator");
import com.github.opaluchlukasz.junit2spock.core.Spocker; import com.github.opaluchlukasz.junit2spock.core.model.TypeModel; import org.apache.commons.io.FileUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import java.io.File; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; import java.util.Optional; import static com.github.opaluchlukasz.junit2spock.core.util.StringUtil.SEPARATOR; import static java.lang.Integer.MAX_VALUE; import static java.lang.String.format; import static java.nio.charset.StandardCharsets.UTF_8; import static java.nio.file.Files.find; import static java.nio.file.Files.readAllLines; import static java.util.stream.Collectors.joining; import static java.util.stream.Collectors.toList;
package com.github.opaluchlukasz.junit2spock; public final class App { private static final Logger LOG = LoggerFactory.getLogger(App.class); private App() { //NOOP } public static void main(String... args) throws IOException { AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(); applicationContext.scan(App.class.getPackage().getName()); applicationContext.refresh();
// Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/Spocker.java // @Component // public class Spocker { // // private final AstProxy astProxy; // private final Supplier<TypeVisitor> testClassVisitorSupplier; // // @Autowired // public Spocker(AstProxy astProxy, Supplier<TypeVisitor> testClassVisitorSupplier) { // this.astProxy = astProxy; // this.testClassVisitorSupplier = testClassVisitorSupplier; // } // // public TypeModel toGroovyTypeModel(String source) { // source = source.replaceAll("//(?i)\\s*" + quote("given") + SEPARATOR, "givenBlockStart();"); // source = source.replaceAll("//(?i)\\s*" + quote("when") + SEPARATOR, "whenBlockStart();"); // source = source.replaceAll("//(?i)\\s*" + quote("then") + SEPARATOR, "thenBlockStart();"); // // ASTParser parser = ASTParser.newParser(JLS8); // parser.setSource(source.toCharArray()); // parser.setKind(K_COMPILATION_UNIT); // parser.setCompilerOptions(compilerOptions()); // // CompilationUnit cu = (CompilationUnit) parser.createAST(null); // astProxy.setTarget(cu.getAST()); // // TypeVisitor visitor = testClassVisitorSupplier.get(); // cu.accept(visitor); // return visitor.typeModel(); // } // // private Map<String, String> compilerOptions() { // Map<String, String> compilerOptions = getOptions(); // compilerOptions.put(COMPILER_COMPLIANCE, VERSION_1_8); // compilerOptions.put(COMPILER_CODEGEN_TARGET_PLATFORM, VERSION_1_8); // compilerOptions.put(COMPILER_SOURCE, VERSION_1_8); // return compilerOptions; // } // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/model/TypeModel.java // public abstract class TypeModel { // public abstract String asGroovyClass(int typeIndent); // public abstract String typeName(); // abstract Optional<String> packageDeclaration(); // // public String outputFilePath() { // StringBuilder path = new StringBuilder(); // packageDeclaration() // .ifPresent(declaration -> path.append(declaration.replace(quoteReplacement("."), separator)) // .append(separator)); // path.append(typeName()).append(".groovy"); // return path.toString(); // } // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/util/StringUtil.java // public static final String SEPARATOR = System.getProperty("line.separator"); // Path: src/main/java/com/github/opaluchlukasz/junit2spock/App.java import com.github.opaluchlukasz.junit2spock.core.Spocker; import com.github.opaluchlukasz.junit2spock.core.model.TypeModel; import org.apache.commons.io.FileUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import java.io.File; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; import java.util.Optional; import static com.github.opaluchlukasz.junit2spock.core.util.StringUtil.SEPARATOR; import static java.lang.Integer.MAX_VALUE; import static java.lang.String.format; import static java.nio.charset.StandardCharsets.UTF_8; import static java.nio.file.Files.find; import static java.nio.file.Files.readAllLines; import static java.util.stream.Collectors.joining; import static java.util.stream.Collectors.toList; package com.github.opaluchlukasz.junit2spock; public final class App { private static final Logger LOG = LoggerFactory.getLogger(App.class); private App() { //NOOP } public static void main(String... args) throws IOException { AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(); applicationContext.scan(App.class.getPackage().getName()); applicationContext.refresh();
Spocker spocker = applicationContext.getBean(Spocker.class);
opaluchlukasz/junit2spock
src/main/java/com/github/opaluchlukasz/junit2spock/App.java
// Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/Spocker.java // @Component // public class Spocker { // // private final AstProxy astProxy; // private final Supplier<TypeVisitor> testClassVisitorSupplier; // // @Autowired // public Spocker(AstProxy astProxy, Supplier<TypeVisitor> testClassVisitorSupplier) { // this.astProxy = astProxy; // this.testClassVisitorSupplier = testClassVisitorSupplier; // } // // public TypeModel toGroovyTypeModel(String source) { // source = source.replaceAll("//(?i)\\s*" + quote("given") + SEPARATOR, "givenBlockStart();"); // source = source.replaceAll("//(?i)\\s*" + quote("when") + SEPARATOR, "whenBlockStart();"); // source = source.replaceAll("//(?i)\\s*" + quote("then") + SEPARATOR, "thenBlockStart();"); // // ASTParser parser = ASTParser.newParser(JLS8); // parser.setSource(source.toCharArray()); // parser.setKind(K_COMPILATION_UNIT); // parser.setCompilerOptions(compilerOptions()); // // CompilationUnit cu = (CompilationUnit) parser.createAST(null); // astProxy.setTarget(cu.getAST()); // // TypeVisitor visitor = testClassVisitorSupplier.get(); // cu.accept(visitor); // return visitor.typeModel(); // } // // private Map<String, String> compilerOptions() { // Map<String, String> compilerOptions = getOptions(); // compilerOptions.put(COMPILER_COMPLIANCE, VERSION_1_8); // compilerOptions.put(COMPILER_CODEGEN_TARGET_PLATFORM, VERSION_1_8); // compilerOptions.put(COMPILER_SOURCE, VERSION_1_8); // return compilerOptions; // } // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/model/TypeModel.java // public abstract class TypeModel { // public abstract String asGroovyClass(int typeIndent); // public abstract String typeName(); // abstract Optional<String> packageDeclaration(); // // public String outputFilePath() { // StringBuilder path = new StringBuilder(); // packageDeclaration() // .ifPresent(declaration -> path.append(declaration.replace(quoteReplacement("."), separator)) // .append(separator)); // path.append(typeName()).append(".groovy"); // return path.toString(); // } // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/util/StringUtil.java // public static final String SEPARATOR = System.getProperty("line.separator");
import com.github.opaluchlukasz.junit2spock.core.Spocker; import com.github.opaluchlukasz.junit2spock.core.model.TypeModel; import org.apache.commons.io.FileUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import java.io.File; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; import java.util.Optional; import static com.github.opaluchlukasz.junit2spock.core.util.StringUtil.SEPARATOR; import static java.lang.Integer.MAX_VALUE; import static java.lang.String.format; import static java.nio.charset.StandardCharsets.UTF_8; import static java.nio.file.Files.find; import static java.nio.file.Files.readAllLines; import static java.util.stream.Collectors.joining; import static java.util.stream.Collectors.toList;
package com.github.opaluchlukasz.junit2spock; public final class App { private static final Logger LOG = LoggerFactory.getLogger(App.class); private App() { //NOOP } public static void main(String... args) throws IOException { AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(); applicationContext.scan(App.class.getPackage().getName()); applicationContext.refresh(); Spocker spocker = applicationContext.getBean(Spocker.class); if (args.length != 2) { throw new IllegalArgumentException("Source and output directory should be passed as arguments"); } List<Path> paths = find(Paths.get(args[0]), MAX_VALUE, (filePath, fileAttr) -> fileAttr.isRegularFile() && filePath.getFileName().toString().matches(".*\\.java")) .collect(toList()); paths.stream().map(App::parse) .filter(Optional::isPresent) .map(Optional::get) .map(spocker::toGroovyTypeModel) .forEach(typeModel -> save(typeModel, args[1])); }
// Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/Spocker.java // @Component // public class Spocker { // // private final AstProxy astProxy; // private final Supplier<TypeVisitor> testClassVisitorSupplier; // // @Autowired // public Spocker(AstProxy astProxy, Supplier<TypeVisitor> testClassVisitorSupplier) { // this.astProxy = astProxy; // this.testClassVisitorSupplier = testClassVisitorSupplier; // } // // public TypeModel toGroovyTypeModel(String source) { // source = source.replaceAll("//(?i)\\s*" + quote("given") + SEPARATOR, "givenBlockStart();"); // source = source.replaceAll("//(?i)\\s*" + quote("when") + SEPARATOR, "whenBlockStart();"); // source = source.replaceAll("//(?i)\\s*" + quote("then") + SEPARATOR, "thenBlockStart();"); // // ASTParser parser = ASTParser.newParser(JLS8); // parser.setSource(source.toCharArray()); // parser.setKind(K_COMPILATION_UNIT); // parser.setCompilerOptions(compilerOptions()); // // CompilationUnit cu = (CompilationUnit) parser.createAST(null); // astProxy.setTarget(cu.getAST()); // // TypeVisitor visitor = testClassVisitorSupplier.get(); // cu.accept(visitor); // return visitor.typeModel(); // } // // private Map<String, String> compilerOptions() { // Map<String, String> compilerOptions = getOptions(); // compilerOptions.put(COMPILER_COMPLIANCE, VERSION_1_8); // compilerOptions.put(COMPILER_CODEGEN_TARGET_PLATFORM, VERSION_1_8); // compilerOptions.put(COMPILER_SOURCE, VERSION_1_8); // return compilerOptions; // } // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/model/TypeModel.java // public abstract class TypeModel { // public abstract String asGroovyClass(int typeIndent); // public abstract String typeName(); // abstract Optional<String> packageDeclaration(); // // public String outputFilePath() { // StringBuilder path = new StringBuilder(); // packageDeclaration() // .ifPresent(declaration -> path.append(declaration.replace(quoteReplacement("."), separator)) // .append(separator)); // path.append(typeName()).append(".groovy"); // return path.toString(); // } // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/util/StringUtil.java // public static final String SEPARATOR = System.getProperty("line.separator"); // Path: src/main/java/com/github/opaluchlukasz/junit2spock/App.java import com.github.opaluchlukasz.junit2spock.core.Spocker; import com.github.opaluchlukasz.junit2spock.core.model.TypeModel; import org.apache.commons.io.FileUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import java.io.File; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; import java.util.Optional; import static com.github.opaluchlukasz.junit2spock.core.util.StringUtil.SEPARATOR; import static java.lang.Integer.MAX_VALUE; import static java.lang.String.format; import static java.nio.charset.StandardCharsets.UTF_8; import static java.nio.file.Files.find; import static java.nio.file.Files.readAllLines; import static java.util.stream.Collectors.joining; import static java.util.stream.Collectors.toList; package com.github.opaluchlukasz.junit2spock; public final class App { private static final Logger LOG = LoggerFactory.getLogger(App.class); private App() { //NOOP } public static void main(String... args) throws IOException { AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(); applicationContext.scan(App.class.getPackage().getName()); applicationContext.refresh(); Spocker spocker = applicationContext.getBean(Spocker.class); if (args.length != 2) { throw new IllegalArgumentException("Source and output directory should be passed as arguments"); } List<Path> paths = find(Paths.get(args[0]), MAX_VALUE, (filePath, fileAttr) -> fileAttr.isRegularFile() && filePath.getFileName().toString().matches(".*\\.java")) .collect(toList()); paths.stream().map(App::parse) .filter(Optional::isPresent) .map(Optional::get) .map(spocker::toGroovyTypeModel) .forEach(typeModel -> save(typeModel, args[1])); }
private static void save(TypeModel typeModel, String outputPath) {
opaluchlukasz/junit2spock
src/main/java/com/github/opaluchlukasz/junit2spock/App.java
// Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/Spocker.java // @Component // public class Spocker { // // private final AstProxy astProxy; // private final Supplier<TypeVisitor> testClassVisitorSupplier; // // @Autowired // public Spocker(AstProxy astProxy, Supplier<TypeVisitor> testClassVisitorSupplier) { // this.astProxy = astProxy; // this.testClassVisitorSupplier = testClassVisitorSupplier; // } // // public TypeModel toGroovyTypeModel(String source) { // source = source.replaceAll("//(?i)\\s*" + quote("given") + SEPARATOR, "givenBlockStart();"); // source = source.replaceAll("//(?i)\\s*" + quote("when") + SEPARATOR, "whenBlockStart();"); // source = source.replaceAll("//(?i)\\s*" + quote("then") + SEPARATOR, "thenBlockStart();"); // // ASTParser parser = ASTParser.newParser(JLS8); // parser.setSource(source.toCharArray()); // parser.setKind(K_COMPILATION_UNIT); // parser.setCompilerOptions(compilerOptions()); // // CompilationUnit cu = (CompilationUnit) parser.createAST(null); // astProxy.setTarget(cu.getAST()); // // TypeVisitor visitor = testClassVisitorSupplier.get(); // cu.accept(visitor); // return visitor.typeModel(); // } // // private Map<String, String> compilerOptions() { // Map<String, String> compilerOptions = getOptions(); // compilerOptions.put(COMPILER_COMPLIANCE, VERSION_1_8); // compilerOptions.put(COMPILER_CODEGEN_TARGET_PLATFORM, VERSION_1_8); // compilerOptions.put(COMPILER_SOURCE, VERSION_1_8); // return compilerOptions; // } // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/model/TypeModel.java // public abstract class TypeModel { // public abstract String asGroovyClass(int typeIndent); // public abstract String typeName(); // abstract Optional<String> packageDeclaration(); // // public String outputFilePath() { // StringBuilder path = new StringBuilder(); // packageDeclaration() // .ifPresent(declaration -> path.append(declaration.replace(quoteReplacement("."), separator)) // .append(separator)); // path.append(typeName()).append(".groovy"); // return path.toString(); // } // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/util/StringUtil.java // public static final String SEPARATOR = System.getProperty("line.separator");
import com.github.opaluchlukasz.junit2spock.core.Spocker; import com.github.opaluchlukasz.junit2spock.core.model.TypeModel; import org.apache.commons.io.FileUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import java.io.File; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; import java.util.Optional; import static com.github.opaluchlukasz.junit2spock.core.util.StringUtil.SEPARATOR; import static java.lang.Integer.MAX_VALUE; import static java.lang.String.format; import static java.nio.charset.StandardCharsets.UTF_8; import static java.nio.file.Files.find; import static java.nio.file.Files.readAllLines; import static java.util.stream.Collectors.joining; import static java.util.stream.Collectors.toList;
applicationContext.refresh(); Spocker spocker = applicationContext.getBean(Spocker.class); if (args.length != 2) { throw new IllegalArgumentException("Source and output directory should be passed as arguments"); } List<Path> paths = find(Paths.get(args[0]), MAX_VALUE, (filePath, fileAttr) -> fileAttr.isRegularFile() && filePath.getFileName().toString().matches(".*\\.java")) .collect(toList()); paths.stream().map(App::parse) .filter(Optional::isPresent) .map(Optional::get) .map(spocker::toGroovyTypeModel) .forEach(typeModel -> save(typeModel, args[1])); } private static void save(TypeModel typeModel, String outputPath) { try { File outputFile = new File(format("%s/%s", outputPath, typeModel.outputFilePath())); outputFile.getParentFile().mkdirs(); outputFile.createNewFile(); FileUtils.writeStringToFile(outputFile, typeModel.asGroovyClass(0), UTF_8); } catch (IOException ex) { LOG.error(format("Unable to save output file: %s", typeModel.outputFilePath()), ex); } } private static Optional<String> parse(Path path) { try {
// Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/Spocker.java // @Component // public class Spocker { // // private final AstProxy astProxy; // private final Supplier<TypeVisitor> testClassVisitorSupplier; // // @Autowired // public Spocker(AstProxy astProxy, Supplier<TypeVisitor> testClassVisitorSupplier) { // this.astProxy = astProxy; // this.testClassVisitorSupplier = testClassVisitorSupplier; // } // // public TypeModel toGroovyTypeModel(String source) { // source = source.replaceAll("//(?i)\\s*" + quote("given") + SEPARATOR, "givenBlockStart();"); // source = source.replaceAll("//(?i)\\s*" + quote("when") + SEPARATOR, "whenBlockStart();"); // source = source.replaceAll("//(?i)\\s*" + quote("then") + SEPARATOR, "thenBlockStart();"); // // ASTParser parser = ASTParser.newParser(JLS8); // parser.setSource(source.toCharArray()); // parser.setKind(K_COMPILATION_UNIT); // parser.setCompilerOptions(compilerOptions()); // // CompilationUnit cu = (CompilationUnit) parser.createAST(null); // astProxy.setTarget(cu.getAST()); // // TypeVisitor visitor = testClassVisitorSupplier.get(); // cu.accept(visitor); // return visitor.typeModel(); // } // // private Map<String, String> compilerOptions() { // Map<String, String> compilerOptions = getOptions(); // compilerOptions.put(COMPILER_COMPLIANCE, VERSION_1_8); // compilerOptions.put(COMPILER_CODEGEN_TARGET_PLATFORM, VERSION_1_8); // compilerOptions.put(COMPILER_SOURCE, VERSION_1_8); // return compilerOptions; // } // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/model/TypeModel.java // public abstract class TypeModel { // public abstract String asGroovyClass(int typeIndent); // public abstract String typeName(); // abstract Optional<String> packageDeclaration(); // // public String outputFilePath() { // StringBuilder path = new StringBuilder(); // packageDeclaration() // .ifPresent(declaration -> path.append(declaration.replace(quoteReplacement("."), separator)) // .append(separator)); // path.append(typeName()).append(".groovy"); // return path.toString(); // } // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/util/StringUtil.java // public static final String SEPARATOR = System.getProperty("line.separator"); // Path: src/main/java/com/github/opaluchlukasz/junit2spock/App.java import com.github.opaluchlukasz.junit2spock.core.Spocker; import com.github.opaluchlukasz.junit2spock.core.model.TypeModel; import org.apache.commons.io.FileUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import java.io.File; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; import java.util.Optional; import static com.github.opaluchlukasz.junit2spock.core.util.StringUtil.SEPARATOR; import static java.lang.Integer.MAX_VALUE; import static java.lang.String.format; import static java.nio.charset.StandardCharsets.UTF_8; import static java.nio.file.Files.find; import static java.nio.file.Files.readAllLines; import static java.util.stream.Collectors.joining; import static java.util.stream.Collectors.toList; applicationContext.refresh(); Spocker spocker = applicationContext.getBean(Spocker.class); if (args.length != 2) { throw new IllegalArgumentException("Source and output directory should be passed as arguments"); } List<Path> paths = find(Paths.get(args[0]), MAX_VALUE, (filePath, fileAttr) -> fileAttr.isRegularFile() && filePath.getFileName().toString().matches(".*\\.java")) .collect(toList()); paths.stream().map(App::parse) .filter(Optional::isPresent) .map(Optional::get) .map(spocker::toGroovyTypeModel) .forEach(typeModel -> save(typeModel, args[1])); } private static void save(TypeModel typeModel, String outputPath) { try { File outputFile = new File(format("%s/%s", outputPath, typeModel.outputFilePath())); outputFile.getParentFile().mkdirs(); outputFile.createNewFile(); FileUtils.writeStringToFile(outputFile, typeModel.asGroovyClass(0), UTF_8); } catch (IOException ex) { LOG.error(format("Unable to save output file: %s", typeModel.outputFilePath()), ex); } } private static Optional<String> parse(Path path) { try {
return Optional.of(readAllLines(path, UTF_8).stream().collect(joining(SEPARATOR)));
opaluchlukasz/junit2spock
src/main/java/com/github/opaluchlukasz/junit2spock/core/node/wrapper/WrapperDecorator.java
// Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/Applicable.java // public enum Applicable { // TEST_METHOD, FIXTURE_METHOD, REGULAR_METHOD, FIELD_FEATURE; // // @Component // static class ApplicableInjector { // @Autowired private FeatureProvider featureProvider; // // @PostConstruct // public void init() { // stream(Applicable.values()).forEach(applicable -> applicable.featureProvider = featureProvider); // } // } // // private FeatureProvider featureProvider; // // public void applyFeaturesToStatements(List<Object> statements) { // List<Feature> features = features(); // for (int i = 0; i < statements.size(); i++) { // Object bodyNode = statements.get(i); // statements.remove(i); // for (Feature testMethodFeature : features) { // bodyNode = testMethodFeature.apply(bodyNode); // } // statements.add(i, bodyNode); // } // } // // public List<Feature> features() { // return featureProvider.features(this); // } // }
import com.github.opaluchlukasz.junit2spock.core.Applicable; import org.eclipse.jdt.core.dom.IfStatement; import org.eclipse.jdt.core.dom.TryStatement; import static io.vavr.Predicates.instanceOf; import static io.vavr.API.$; import static io.vavr.API.Case; import static io.vavr.API.Match;
package com.github.opaluchlukasz.junit2spock.core.node.wrapper; public final class WrapperDecorator { private WrapperDecorator() { // NOOP }
// Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/Applicable.java // public enum Applicable { // TEST_METHOD, FIXTURE_METHOD, REGULAR_METHOD, FIELD_FEATURE; // // @Component // static class ApplicableInjector { // @Autowired private FeatureProvider featureProvider; // // @PostConstruct // public void init() { // stream(Applicable.values()).forEach(applicable -> applicable.featureProvider = featureProvider); // } // } // // private FeatureProvider featureProvider; // // public void applyFeaturesToStatements(List<Object> statements) { // List<Feature> features = features(); // for (int i = 0; i < statements.size(); i++) { // Object bodyNode = statements.get(i); // statements.remove(i); // for (Feature testMethodFeature : features) { // bodyNode = testMethodFeature.apply(bodyNode); // } // statements.add(i, bodyNode); // } // } // // public List<Feature> features() { // return featureProvider.features(this); // } // } // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/node/wrapper/WrapperDecorator.java import com.github.opaluchlukasz.junit2spock.core.Applicable; import org.eclipse.jdt.core.dom.IfStatement; import org.eclipse.jdt.core.dom.TryStatement; import static io.vavr.Predicates.instanceOf; import static io.vavr.API.$; import static io.vavr.API.Case; import static io.vavr.API.Match; package com.github.opaluchlukasz.junit2spock.core.node.wrapper; public final class WrapperDecorator { private WrapperDecorator() { // NOOP }
public static Object wrap(Object statement, int indentation, Applicable applicable) {
opaluchlukasz/junit2spock
src/main/java/com/github/opaluchlukasz/junit2spock/core/Applicable.java
// Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/Feature.java // public abstract class Feature<T> { // protected abstract Optional<T> applicable(Object object); // protected abstract Object apply(Object object, T applicable); // // public final Object apply(Object astNode) { // return applicable(astNode) // .map(t -> apply(astNode, t)) // .orElse(astNode); // } // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/FeatureProvider.java // @Component // public class FeatureProvider { // // private final FeatureFactory featureFactory; // // @Autowired // public FeatureProvider(FeatureFactory featureFactory) { // this.featureFactory = featureFactory; // } // // public List<Feature> features(Applicable applicable) { // return featuresTypes(applicable).stream() // .map(featureFactory::provide) // .collect(toList()); // } // }
import com.github.opaluchlukasz.junit2spock.core.feature.Feature; import com.github.opaluchlukasz.junit2spock.core.feature.FeatureProvider; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; import java.util.List; import static java.util.Arrays.stream;
package com.github.opaluchlukasz.junit2spock.core; public enum Applicable { TEST_METHOD, FIXTURE_METHOD, REGULAR_METHOD, FIELD_FEATURE; @Component static class ApplicableInjector {
// Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/Feature.java // public abstract class Feature<T> { // protected abstract Optional<T> applicable(Object object); // protected abstract Object apply(Object object, T applicable); // // public final Object apply(Object astNode) { // return applicable(astNode) // .map(t -> apply(astNode, t)) // .orElse(astNode); // } // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/FeatureProvider.java // @Component // public class FeatureProvider { // // private final FeatureFactory featureFactory; // // @Autowired // public FeatureProvider(FeatureFactory featureFactory) { // this.featureFactory = featureFactory; // } // // public List<Feature> features(Applicable applicable) { // return featuresTypes(applicable).stream() // .map(featureFactory::provide) // .collect(toList()); // } // } // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/Applicable.java import com.github.opaluchlukasz.junit2spock.core.feature.Feature; import com.github.opaluchlukasz.junit2spock.core.feature.FeatureProvider; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; import java.util.List; import static java.util.Arrays.stream; package com.github.opaluchlukasz.junit2spock.core; public enum Applicable { TEST_METHOD, FIXTURE_METHOD, REGULAR_METHOD, FIELD_FEATURE; @Component static class ApplicableInjector {
@Autowired private FeatureProvider featureProvider;
opaluchlukasz/junit2spock
src/main/java/com/github/opaluchlukasz/junit2spock/core/Applicable.java
// Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/Feature.java // public abstract class Feature<T> { // protected abstract Optional<T> applicable(Object object); // protected abstract Object apply(Object object, T applicable); // // public final Object apply(Object astNode) { // return applicable(astNode) // .map(t -> apply(astNode, t)) // .orElse(astNode); // } // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/FeatureProvider.java // @Component // public class FeatureProvider { // // private final FeatureFactory featureFactory; // // @Autowired // public FeatureProvider(FeatureFactory featureFactory) { // this.featureFactory = featureFactory; // } // // public List<Feature> features(Applicable applicable) { // return featuresTypes(applicable).stream() // .map(featureFactory::provide) // .collect(toList()); // } // }
import com.github.opaluchlukasz.junit2spock.core.feature.Feature; import com.github.opaluchlukasz.junit2spock.core.feature.FeatureProvider; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; import java.util.List; import static java.util.Arrays.stream;
package com.github.opaluchlukasz.junit2spock.core; public enum Applicable { TEST_METHOD, FIXTURE_METHOD, REGULAR_METHOD, FIELD_FEATURE; @Component static class ApplicableInjector { @Autowired private FeatureProvider featureProvider; @PostConstruct public void init() { stream(Applicable.values()).forEach(applicable -> applicable.featureProvider = featureProvider); } } private FeatureProvider featureProvider; public void applyFeaturesToStatements(List<Object> statements) {
// Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/Feature.java // public abstract class Feature<T> { // protected abstract Optional<T> applicable(Object object); // protected abstract Object apply(Object object, T applicable); // // public final Object apply(Object astNode) { // return applicable(astNode) // .map(t -> apply(astNode, t)) // .orElse(astNode); // } // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/feature/FeatureProvider.java // @Component // public class FeatureProvider { // // private final FeatureFactory featureFactory; // // @Autowired // public FeatureProvider(FeatureFactory featureFactory) { // this.featureFactory = featureFactory; // } // // public List<Feature> features(Applicable applicable) { // return featuresTypes(applicable).stream() // .map(featureFactory::provide) // .collect(toList()); // } // } // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/Applicable.java import com.github.opaluchlukasz.junit2spock.core.feature.Feature; import com.github.opaluchlukasz.junit2spock.core.feature.FeatureProvider; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; import java.util.List; import static java.util.Arrays.stream; package com.github.opaluchlukasz.junit2spock.core; public enum Applicable { TEST_METHOD, FIXTURE_METHOD, REGULAR_METHOD, FIELD_FEATURE; @Component static class ApplicableInjector { @Autowired private FeatureProvider featureProvider; @PostConstruct public void init() { stream(Applicable.values()).forEach(applicable -> applicable.featureProvider = featureProvider); } } private FeatureProvider featureProvider; public void applyFeaturesToStatements(List<Object> statements) {
List<Feature> features = features();
opaluchlukasz/junit2spock
src/main/java/com/github/opaluchlukasz/junit2spock/core/model/method/CommentBasedSpockBlocksStrategy.java
// Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/node/SpockBlockNode.java // public final class SpockBlockNode { // // private final String block; // // private SpockBlockNode(String block) { // this.block = block; // } // // public static SpockBlockNode given() { // return new SpockBlockNode("given"); // } // // public static SpockBlockNode when() { // return new SpockBlockNode("when"); // } // // public static SpockBlockNode then() { // return new SpockBlockNode("then"); // } // // public static SpockBlockNode expect() { // return new SpockBlockNode("expect"); // } // // @Override // public String toString() { // return format("%s:", block); // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // SpockBlockNode that = (SpockBlockNode) o; // return Objects.equals(block, that.block); // } // // @Override // public int hashCode() { // return Objects.hash(block); // } // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/node/SpockBlockNode.java // public static SpockBlockNode given() { // return new SpockBlockNode("given"); // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/node/SpockBlockNode.java // public static SpockBlockNode then() { // return new SpockBlockNode("then"); // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/node/SpockBlockNode.java // public static SpockBlockNode when() { // return new SpockBlockNode("when"); // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/util/AstNodeFinder.java // public static Optional<MethodInvocation> methodInvocation(Object bodyElement, String... methodNames) { // return stream(methodNames) // .map(methodName -> methodInvocation(bodyElement, methodName)) // .filter(Optional::isPresent) // .map(Optional::get) // .findFirst(); // }
import com.github.opaluchlukasz.junit2spock.core.node.SpockBlockNode; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import static com.github.opaluchlukasz.junit2spock.core.node.SpockBlockNode.given; import static com.github.opaluchlukasz.junit2spock.core.node.SpockBlockNode.then; import static com.github.opaluchlukasz.junit2spock.core.node.SpockBlockNode.when; import static com.github.opaluchlukasz.junit2spock.core.util.AstNodeFinder.methodInvocation; import static java.lang.String.format; import static java.util.Collections.reverseOrder;
package com.github.opaluchlukasz.junit2spock.core.model.method; public class CommentBasedSpockBlocksStrategy implements SpockBlockApplier { private static final Logger LOG = LoggerFactory.getLogger(CommentBasedSpockBlocksStrategy.class); static final String GIVEN_BLOCK_START_MARKER_METHOD = "givenBlockStart"; static final String WHEN_BLOCK_START_MARKER_METHOD = "whenBlockStart"; static final String THEN_BLOCK_START_MARKER_METHOD = "thenBlockStart"; private final List<Object> body; private final String methodName; public CommentBasedSpockBlocksStrategy(List<Object> body, String methodName) { this.body = body; this.methodName = methodName; } @Override public boolean apply() { List<Integer> givenIndexes = markerMethod(GIVEN_BLOCK_START_MARKER_METHOD); List<Integer> whenIndexes = markerMethod(WHEN_BLOCK_START_MARKER_METHOD); List<Integer> thenIndexes = markerMethod(THEN_BLOCK_START_MARKER_METHOD);
// Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/node/SpockBlockNode.java // public final class SpockBlockNode { // // private final String block; // // private SpockBlockNode(String block) { // this.block = block; // } // // public static SpockBlockNode given() { // return new SpockBlockNode("given"); // } // // public static SpockBlockNode when() { // return new SpockBlockNode("when"); // } // // public static SpockBlockNode then() { // return new SpockBlockNode("then"); // } // // public static SpockBlockNode expect() { // return new SpockBlockNode("expect"); // } // // @Override // public String toString() { // return format("%s:", block); // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // SpockBlockNode that = (SpockBlockNode) o; // return Objects.equals(block, that.block); // } // // @Override // public int hashCode() { // return Objects.hash(block); // } // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/node/SpockBlockNode.java // public static SpockBlockNode given() { // return new SpockBlockNode("given"); // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/node/SpockBlockNode.java // public static SpockBlockNode then() { // return new SpockBlockNode("then"); // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/node/SpockBlockNode.java // public static SpockBlockNode when() { // return new SpockBlockNode("when"); // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/util/AstNodeFinder.java // public static Optional<MethodInvocation> methodInvocation(Object bodyElement, String... methodNames) { // return stream(methodNames) // .map(methodName -> methodInvocation(bodyElement, methodName)) // .filter(Optional::isPresent) // .map(Optional::get) // .findFirst(); // } // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/model/method/CommentBasedSpockBlocksStrategy.java import com.github.opaluchlukasz.junit2spock.core.node.SpockBlockNode; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import static com.github.opaluchlukasz.junit2spock.core.node.SpockBlockNode.given; import static com.github.opaluchlukasz.junit2spock.core.node.SpockBlockNode.then; import static com.github.opaluchlukasz.junit2spock.core.node.SpockBlockNode.when; import static com.github.opaluchlukasz.junit2spock.core.util.AstNodeFinder.methodInvocation; import static java.lang.String.format; import static java.util.Collections.reverseOrder; package com.github.opaluchlukasz.junit2spock.core.model.method; public class CommentBasedSpockBlocksStrategy implements SpockBlockApplier { private static final Logger LOG = LoggerFactory.getLogger(CommentBasedSpockBlocksStrategy.class); static final String GIVEN_BLOCK_START_MARKER_METHOD = "givenBlockStart"; static final String WHEN_BLOCK_START_MARKER_METHOD = "whenBlockStart"; static final String THEN_BLOCK_START_MARKER_METHOD = "thenBlockStart"; private final List<Object> body; private final String methodName; public CommentBasedSpockBlocksStrategy(List<Object> body, String methodName) { this.body = body; this.methodName = methodName; } @Override public boolean apply() { List<Integer> givenIndexes = markerMethod(GIVEN_BLOCK_START_MARKER_METHOD); List<Integer> whenIndexes = markerMethod(WHEN_BLOCK_START_MARKER_METHOD); List<Integer> thenIndexes = markerMethod(THEN_BLOCK_START_MARKER_METHOD);
Map<Integer, SpockBlockNode> blocksToBeAdded = new HashMap<>();
opaluchlukasz/junit2spock
src/main/java/com/github/opaluchlukasz/junit2spock/core/model/method/CommentBasedSpockBlocksStrategy.java
// Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/node/SpockBlockNode.java // public final class SpockBlockNode { // // private final String block; // // private SpockBlockNode(String block) { // this.block = block; // } // // public static SpockBlockNode given() { // return new SpockBlockNode("given"); // } // // public static SpockBlockNode when() { // return new SpockBlockNode("when"); // } // // public static SpockBlockNode then() { // return new SpockBlockNode("then"); // } // // public static SpockBlockNode expect() { // return new SpockBlockNode("expect"); // } // // @Override // public String toString() { // return format("%s:", block); // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // SpockBlockNode that = (SpockBlockNode) o; // return Objects.equals(block, that.block); // } // // @Override // public int hashCode() { // return Objects.hash(block); // } // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/node/SpockBlockNode.java // public static SpockBlockNode given() { // return new SpockBlockNode("given"); // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/node/SpockBlockNode.java // public static SpockBlockNode then() { // return new SpockBlockNode("then"); // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/node/SpockBlockNode.java // public static SpockBlockNode when() { // return new SpockBlockNode("when"); // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/util/AstNodeFinder.java // public static Optional<MethodInvocation> methodInvocation(Object bodyElement, String... methodNames) { // return stream(methodNames) // .map(methodName -> methodInvocation(bodyElement, methodName)) // .filter(Optional::isPresent) // .map(Optional::get) // .findFirst(); // }
import com.github.opaluchlukasz.junit2spock.core.node.SpockBlockNode; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import static com.github.opaluchlukasz.junit2spock.core.node.SpockBlockNode.given; import static com.github.opaluchlukasz.junit2spock.core.node.SpockBlockNode.then; import static com.github.opaluchlukasz.junit2spock.core.node.SpockBlockNode.when; import static com.github.opaluchlukasz.junit2spock.core.util.AstNodeFinder.methodInvocation; import static java.lang.String.format; import static java.util.Collections.reverseOrder;
package com.github.opaluchlukasz.junit2spock.core.model.method; public class CommentBasedSpockBlocksStrategy implements SpockBlockApplier { private static final Logger LOG = LoggerFactory.getLogger(CommentBasedSpockBlocksStrategy.class); static final String GIVEN_BLOCK_START_MARKER_METHOD = "givenBlockStart"; static final String WHEN_BLOCK_START_MARKER_METHOD = "whenBlockStart"; static final String THEN_BLOCK_START_MARKER_METHOD = "thenBlockStart"; private final List<Object> body; private final String methodName; public CommentBasedSpockBlocksStrategy(List<Object> body, String methodName) { this.body = body; this.methodName = methodName; } @Override public boolean apply() { List<Integer> givenIndexes = markerMethod(GIVEN_BLOCK_START_MARKER_METHOD); List<Integer> whenIndexes = markerMethod(WHEN_BLOCK_START_MARKER_METHOD); List<Integer> thenIndexes = markerMethod(THEN_BLOCK_START_MARKER_METHOD); Map<Integer, SpockBlockNode> blocksToBeAdded = new HashMap<>(); if (givenIndexes.size() > 0) {
// Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/node/SpockBlockNode.java // public final class SpockBlockNode { // // private final String block; // // private SpockBlockNode(String block) { // this.block = block; // } // // public static SpockBlockNode given() { // return new SpockBlockNode("given"); // } // // public static SpockBlockNode when() { // return new SpockBlockNode("when"); // } // // public static SpockBlockNode then() { // return new SpockBlockNode("then"); // } // // public static SpockBlockNode expect() { // return new SpockBlockNode("expect"); // } // // @Override // public String toString() { // return format("%s:", block); // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // SpockBlockNode that = (SpockBlockNode) o; // return Objects.equals(block, that.block); // } // // @Override // public int hashCode() { // return Objects.hash(block); // } // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/node/SpockBlockNode.java // public static SpockBlockNode given() { // return new SpockBlockNode("given"); // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/node/SpockBlockNode.java // public static SpockBlockNode then() { // return new SpockBlockNode("then"); // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/node/SpockBlockNode.java // public static SpockBlockNode when() { // return new SpockBlockNode("when"); // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/util/AstNodeFinder.java // public static Optional<MethodInvocation> methodInvocation(Object bodyElement, String... methodNames) { // return stream(methodNames) // .map(methodName -> methodInvocation(bodyElement, methodName)) // .filter(Optional::isPresent) // .map(Optional::get) // .findFirst(); // } // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/model/method/CommentBasedSpockBlocksStrategy.java import com.github.opaluchlukasz.junit2spock.core.node.SpockBlockNode; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import static com.github.opaluchlukasz.junit2spock.core.node.SpockBlockNode.given; import static com.github.opaluchlukasz.junit2spock.core.node.SpockBlockNode.then; import static com.github.opaluchlukasz.junit2spock.core.node.SpockBlockNode.when; import static com.github.opaluchlukasz.junit2spock.core.util.AstNodeFinder.methodInvocation; import static java.lang.String.format; import static java.util.Collections.reverseOrder; package com.github.opaluchlukasz.junit2spock.core.model.method; public class CommentBasedSpockBlocksStrategy implements SpockBlockApplier { private static final Logger LOG = LoggerFactory.getLogger(CommentBasedSpockBlocksStrategy.class); static final String GIVEN_BLOCK_START_MARKER_METHOD = "givenBlockStart"; static final String WHEN_BLOCK_START_MARKER_METHOD = "whenBlockStart"; static final String THEN_BLOCK_START_MARKER_METHOD = "thenBlockStart"; private final List<Object> body; private final String methodName; public CommentBasedSpockBlocksStrategy(List<Object> body, String methodName) { this.body = body; this.methodName = methodName; } @Override public boolean apply() { List<Integer> givenIndexes = markerMethod(GIVEN_BLOCK_START_MARKER_METHOD); List<Integer> whenIndexes = markerMethod(WHEN_BLOCK_START_MARKER_METHOD); List<Integer> thenIndexes = markerMethod(THEN_BLOCK_START_MARKER_METHOD); Map<Integer, SpockBlockNode> blocksToBeAdded = new HashMap<>(); if (givenIndexes.size() > 0) {
blocksToBeAdded.put(givenIndexes.get(0), given());
opaluchlukasz/junit2spock
src/main/java/com/github/opaluchlukasz/junit2spock/core/model/method/CommentBasedSpockBlocksStrategy.java
// Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/node/SpockBlockNode.java // public final class SpockBlockNode { // // private final String block; // // private SpockBlockNode(String block) { // this.block = block; // } // // public static SpockBlockNode given() { // return new SpockBlockNode("given"); // } // // public static SpockBlockNode when() { // return new SpockBlockNode("when"); // } // // public static SpockBlockNode then() { // return new SpockBlockNode("then"); // } // // public static SpockBlockNode expect() { // return new SpockBlockNode("expect"); // } // // @Override // public String toString() { // return format("%s:", block); // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // SpockBlockNode that = (SpockBlockNode) o; // return Objects.equals(block, that.block); // } // // @Override // public int hashCode() { // return Objects.hash(block); // } // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/node/SpockBlockNode.java // public static SpockBlockNode given() { // return new SpockBlockNode("given"); // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/node/SpockBlockNode.java // public static SpockBlockNode then() { // return new SpockBlockNode("then"); // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/node/SpockBlockNode.java // public static SpockBlockNode when() { // return new SpockBlockNode("when"); // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/util/AstNodeFinder.java // public static Optional<MethodInvocation> methodInvocation(Object bodyElement, String... methodNames) { // return stream(methodNames) // .map(methodName -> methodInvocation(bodyElement, methodName)) // .filter(Optional::isPresent) // .map(Optional::get) // .findFirst(); // }
import com.github.opaluchlukasz.junit2spock.core.node.SpockBlockNode; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import static com.github.opaluchlukasz.junit2spock.core.node.SpockBlockNode.given; import static com.github.opaluchlukasz.junit2spock.core.node.SpockBlockNode.then; import static com.github.opaluchlukasz.junit2spock.core.node.SpockBlockNode.when; import static com.github.opaluchlukasz.junit2spock.core.util.AstNodeFinder.methodInvocation; import static java.lang.String.format; import static java.util.Collections.reverseOrder;
package com.github.opaluchlukasz.junit2spock.core.model.method; public class CommentBasedSpockBlocksStrategy implements SpockBlockApplier { private static final Logger LOG = LoggerFactory.getLogger(CommentBasedSpockBlocksStrategy.class); static final String GIVEN_BLOCK_START_MARKER_METHOD = "givenBlockStart"; static final String WHEN_BLOCK_START_MARKER_METHOD = "whenBlockStart"; static final String THEN_BLOCK_START_MARKER_METHOD = "thenBlockStart"; private final List<Object> body; private final String methodName; public CommentBasedSpockBlocksStrategy(List<Object> body, String methodName) { this.body = body; this.methodName = methodName; } @Override public boolean apply() { List<Integer> givenIndexes = markerMethod(GIVEN_BLOCK_START_MARKER_METHOD); List<Integer> whenIndexes = markerMethod(WHEN_BLOCK_START_MARKER_METHOD); List<Integer> thenIndexes = markerMethod(THEN_BLOCK_START_MARKER_METHOD); Map<Integer, SpockBlockNode> blocksToBeAdded = new HashMap<>(); if (givenIndexes.size() > 0) { blocksToBeAdded.put(givenIndexes.get(0), given()); } if (whenIndexes.size() != thenIndexes.size()) { LOG.warn(format("Numbers of when/then blocks do not match for test method: %s", methodName)); }
// Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/node/SpockBlockNode.java // public final class SpockBlockNode { // // private final String block; // // private SpockBlockNode(String block) { // this.block = block; // } // // public static SpockBlockNode given() { // return new SpockBlockNode("given"); // } // // public static SpockBlockNode when() { // return new SpockBlockNode("when"); // } // // public static SpockBlockNode then() { // return new SpockBlockNode("then"); // } // // public static SpockBlockNode expect() { // return new SpockBlockNode("expect"); // } // // @Override // public String toString() { // return format("%s:", block); // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // SpockBlockNode that = (SpockBlockNode) o; // return Objects.equals(block, that.block); // } // // @Override // public int hashCode() { // return Objects.hash(block); // } // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/node/SpockBlockNode.java // public static SpockBlockNode given() { // return new SpockBlockNode("given"); // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/node/SpockBlockNode.java // public static SpockBlockNode then() { // return new SpockBlockNode("then"); // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/node/SpockBlockNode.java // public static SpockBlockNode when() { // return new SpockBlockNode("when"); // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/util/AstNodeFinder.java // public static Optional<MethodInvocation> methodInvocation(Object bodyElement, String... methodNames) { // return stream(methodNames) // .map(methodName -> methodInvocation(bodyElement, methodName)) // .filter(Optional::isPresent) // .map(Optional::get) // .findFirst(); // } // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/model/method/CommentBasedSpockBlocksStrategy.java import com.github.opaluchlukasz.junit2spock.core.node.SpockBlockNode; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import static com.github.opaluchlukasz.junit2spock.core.node.SpockBlockNode.given; import static com.github.opaluchlukasz.junit2spock.core.node.SpockBlockNode.then; import static com.github.opaluchlukasz.junit2spock.core.node.SpockBlockNode.when; import static com.github.opaluchlukasz.junit2spock.core.util.AstNodeFinder.methodInvocation; import static java.lang.String.format; import static java.util.Collections.reverseOrder; package com.github.opaluchlukasz.junit2spock.core.model.method; public class CommentBasedSpockBlocksStrategy implements SpockBlockApplier { private static final Logger LOG = LoggerFactory.getLogger(CommentBasedSpockBlocksStrategy.class); static final String GIVEN_BLOCK_START_MARKER_METHOD = "givenBlockStart"; static final String WHEN_BLOCK_START_MARKER_METHOD = "whenBlockStart"; static final String THEN_BLOCK_START_MARKER_METHOD = "thenBlockStart"; private final List<Object> body; private final String methodName; public CommentBasedSpockBlocksStrategy(List<Object> body, String methodName) { this.body = body; this.methodName = methodName; } @Override public boolean apply() { List<Integer> givenIndexes = markerMethod(GIVEN_BLOCK_START_MARKER_METHOD); List<Integer> whenIndexes = markerMethod(WHEN_BLOCK_START_MARKER_METHOD); List<Integer> thenIndexes = markerMethod(THEN_BLOCK_START_MARKER_METHOD); Map<Integer, SpockBlockNode> blocksToBeAdded = new HashMap<>(); if (givenIndexes.size() > 0) { blocksToBeAdded.put(givenIndexes.get(0), given()); } if (whenIndexes.size() != thenIndexes.size()) { LOG.warn(format("Numbers of when/then blocks do not match for test method: %s", methodName)); }
whenIndexes.forEach(index -> blocksToBeAdded.put(index, when()));
opaluchlukasz/junit2spock
src/main/java/com/github/opaluchlukasz/junit2spock/core/model/method/CommentBasedSpockBlocksStrategy.java
// Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/node/SpockBlockNode.java // public final class SpockBlockNode { // // private final String block; // // private SpockBlockNode(String block) { // this.block = block; // } // // public static SpockBlockNode given() { // return new SpockBlockNode("given"); // } // // public static SpockBlockNode when() { // return new SpockBlockNode("when"); // } // // public static SpockBlockNode then() { // return new SpockBlockNode("then"); // } // // public static SpockBlockNode expect() { // return new SpockBlockNode("expect"); // } // // @Override // public String toString() { // return format("%s:", block); // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // SpockBlockNode that = (SpockBlockNode) o; // return Objects.equals(block, that.block); // } // // @Override // public int hashCode() { // return Objects.hash(block); // } // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/node/SpockBlockNode.java // public static SpockBlockNode given() { // return new SpockBlockNode("given"); // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/node/SpockBlockNode.java // public static SpockBlockNode then() { // return new SpockBlockNode("then"); // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/node/SpockBlockNode.java // public static SpockBlockNode when() { // return new SpockBlockNode("when"); // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/util/AstNodeFinder.java // public static Optional<MethodInvocation> methodInvocation(Object bodyElement, String... methodNames) { // return stream(methodNames) // .map(methodName -> methodInvocation(bodyElement, methodName)) // .filter(Optional::isPresent) // .map(Optional::get) // .findFirst(); // }
import com.github.opaluchlukasz.junit2spock.core.node.SpockBlockNode; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import static com.github.opaluchlukasz.junit2spock.core.node.SpockBlockNode.given; import static com.github.opaluchlukasz.junit2spock.core.node.SpockBlockNode.then; import static com.github.opaluchlukasz.junit2spock.core.node.SpockBlockNode.when; import static com.github.opaluchlukasz.junit2spock.core.util.AstNodeFinder.methodInvocation; import static java.lang.String.format; import static java.util.Collections.reverseOrder;
package com.github.opaluchlukasz.junit2spock.core.model.method; public class CommentBasedSpockBlocksStrategy implements SpockBlockApplier { private static final Logger LOG = LoggerFactory.getLogger(CommentBasedSpockBlocksStrategy.class); static final String GIVEN_BLOCK_START_MARKER_METHOD = "givenBlockStart"; static final String WHEN_BLOCK_START_MARKER_METHOD = "whenBlockStart"; static final String THEN_BLOCK_START_MARKER_METHOD = "thenBlockStart"; private final List<Object> body; private final String methodName; public CommentBasedSpockBlocksStrategy(List<Object> body, String methodName) { this.body = body; this.methodName = methodName; } @Override public boolean apply() { List<Integer> givenIndexes = markerMethod(GIVEN_BLOCK_START_MARKER_METHOD); List<Integer> whenIndexes = markerMethod(WHEN_BLOCK_START_MARKER_METHOD); List<Integer> thenIndexes = markerMethod(THEN_BLOCK_START_MARKER_METHOD); Map<Integer, SpockBlockNode> blocksToBeAdded = new HashMap<>(); if (givenIndexes.size() > 0) { blocksToBeAdded.put(givenIndexes.get(0), given()); } if (whenIndexes.size() != thenIndexes.size()) { LOG.warn(format("Numbers of when/then blocks do not match for test method: %s", methodName)); } whenIndexes.forEach(index -> blocksToBeAdded.put(index, when()));
// Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/node/SpockBlockNode.java // public final class SpockBlockNode { // // private final String block; // // private SpockBlockNode(String block) { // this.block = block; // } // // public static SpockBlockNode given() { // return new SpockBlockNode("given"); // } // // public static SpockBlockNode when() { // return new SpockBlockNode("when"); // } // // public static SpockBlockNode then() { // return new SpockBlockNode("then"); // } // // public static SpockBlockNode expect() { // return new SpockBlockNode("expect"); // } // // @Override // public String toString() { // return format("%s:", block); // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // SpockBlockNode that = (SpockBlockNode) o; // return Objects.equals(block, that.block); // } // // @Override // public int hashCode() { // return Objects.hash(block); // } // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/node/SpockBlockNode.java // public static SpockBlockNode given() { // return new SpockBlockNode("given"); // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/node/SpockBlockNode.java // public static SpockBlockNode then() { // return new SpockBlockNode("then"); // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/node/SpockBlockNode.java // public static SpockBlockNode when() { // return new SpockBlockNode("when"); // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/util/AstNodeFinder.java // public static Optional<MethodInvocation> methodInvocation(Object bodyElement, String... methodNames) { // return stream(methodNames) // .map(methodName -> methodInvocation(bodyElement, methodName)) // .filter(Optional::isPresent) // .map(Optional::get) // .findFirst(); // } // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/model/method/CommentBasedSpockBlocksStrategy.java import com.github.opaluchlukasz.junit2spock.core.node.SpockBlockNode; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import static com.github.opaluchlukasz.junit2spock.core.node.SpockBlockNode.given; import static com.github.opaluchlukasz.junit2spock.core.node.SpockBlockNode.then; import static com.github.opaluchlukasz.junit2spock.core.node.SpockBlockNode.when; import static com.github.opaluchlukasz.junit2spock.core.util.AstNodeFinder.methodInvocation; import static java.lang.String.format; import static java.util.Collections.reverseOrder; package com.github.opaluchlukasz.junit2spock.core.model.method; public class CommentBasedSpockBlocksStrategy implements SpockBlockApplier { private static final Logger LOG = LoggerFactory.getLogger(CommentBasedSpockBlocksStrategy.class); static final String GIVEN_BLOCK_START_MARKER_METHOD = "givenBlockStart"; static final String WHEN_BLOCK_START_MARKER_METHOD = "whenBlockStart"; static final String THEN_BLOCK_START_MARKER_METHOD = "thenBlockStart"; private final List<Object> body; private final String methodName; public CommentBasedSpockBlocksStrategy(List<Object> body, String methodName) { this.body = body; this.methodName = methodName; } @Override public boolean apply() { List<Integer> givenIndexes = markerMethod(GIVEN_BLOCK_START_MARKER_METHOD); List<Integer> whenIndexes = markerMethod(WHEN_BLOCK_START_MARKER_METHOD); List<Integer> thenIndexes = markerMethod(THEN_BLOCK_START_MARKER_METHOD); Map<Integer, SpockBlockNode> blocksToBeAdded = new HashMap<>(); if (givenIndexes.size() > 0) { blocksToBeAdded.put(givenIndexes.get(0), given()); } if (whenIndexes.size() != thenIndexes.size()) { LOG.warn(format("Numbers of when/then blocks do not match for test method: %s", methodName)); } whenIndexes.forEach(index -> blocksToBeAdded.put(index, when()));
thenIndexes.forEach(index -> blocksToBeAdded.put(index, then()));
opaluchlukasz/junit2spock
src/main/java/com/github/opaluchlukasz/junit2spock/core/model/method/CommentBasedSpockBlocksStrategy.java
// Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/node/SpockBlockNode.java // public final class SpockBlockNode { // // private final String block; // // private SpockBlockNode(String block) { // this.block = block; // } // // public static SpockBlockNode given() { // return new SpockBlockNode("given"); // } // // public static SpockBlockNode when() { // return new SpockBlockNode("when"); // } // // public static SpockBlockNode then() { // return new SpockBlockNode("then"); // } // // public static SpockBlockNode expect() { // return new SpockBlockNode("expect"); // } // // @Override // public String toString() { // return format("%s:", block); // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // SpockBlockNode that = (SpockBlockNode) o; // return Objects.equals(block, that.block); // } // // @Override // public int hashCode() { // return Objects.hash(block); // } // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/node/SpockBlockNode.java // public static SpockBlockNode given() { // return new SpockBlockNode("given"); // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/node/SpockBlockNode.java // public static SpockBlockNode then() { // return new SpockBlockNode("then"); // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/node/SpockBlockNode.java // public static SpockBlockNode when() { // return new SpockBlockNode("when"); // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/util/AstNodeFinder.java // public static Optional<MethodInvocation> methodInvocation(Object bodyElement, String... methodNames) { // return stream(methodNames) // .map(methodName -> methodInvocation(bodyElement, methodName)) // .filter(Optional::isPresent) // .map(Optional::get) // .findFirst(); // }
import com.github.opaluchlukasz.junit2spock.core.node.SpockBlockNode; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import static com.github.opaluchlukasz.junit2spock.core.node.SpockBlockNode.given; import static com.github.opaluchlukasz.junit2spock.core.node.SpockBlockNode.then; import static com.github.opaluchlukasz.junit2spock.core.node.SpockBlockNode.when; import static com.github.opaluchlukasz.junit2spock.core.util.AstNodeFinder.methodInvocation; import static java.lang.String.format; import static java.util.Collections.reverseOrder;
package com.github.opaluchlukasz.junit2spock.core.model.method; public class CommentBasedSpockBlocksStrategy implements SpockBlockApplier { private static final Logger LOG = LoggerFactory.getLogger(CommentBasedSpockBlocksStrategy.class); static final String GIVEN_BLOCK_START_MARKER_METHOD = "givenBlockStart"; static final String WHEN_BLOCK_START_MARKER_METHOD = "whenBlockStart"; static final String THEN_BLOCK_START_MARKER_METHOD = "thenBlockStart"; private final List<Object> body; private final String methodName; public CommentBasedSpockBlocksStrategy(List<Object> body, String methodName) { this.body = body; this.methodName = methodName; } @Override public boolean apply() { List<Integer> givenIndexes = markerMethod(GIVEN_BLOCK_START_MARKER_METHOD); List<Integer> whenIndexes = markerMethod(WHEN_BLOCK_START_MARKER_METHOD); List<Integer> thenIndexes = markerMethod(THEN_BLOCK_START_MARKER_METHOD); Map<Integer, SpockBlockNode> blocksToBeAdded = new HashMap<>(); if (givenIndexes.size() > 0) { blocksToBeAdded.put(givenIndexes.get(0), given()); } if (whenIndexes.size() != thenIndexes.size()) { LOG.warn(format("Numbers of when/then blocks do not match for test method: %s", methodName)); } whenIndexes.forEach(index -> blocksToBeAdded.put(index, when())); thenIndexes.forEach(index -> blocksToBeAdded.put(index, then())); blocksToBeAdded.keySet().stream().sorted(reverseOrder()).forEach(key -> body.add(key, blocksToBeAdded.get(key)));
// Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/node/SpockBlockNode.java // public final class SpockBlockNode { // // private final String block; // // private SpockBlockNode(String block) { // this.block = block; // } // // public static SpockBlockNode given() { // return new SpockBlockNode("given"); // } // // public static SpockBlockNode when() { // return new SpockBlockNode("when"); // } // // public static SpockBlockNode then() { // return new SpockBlockNode("then"); // } // // public static SpockBlockNode expect() { // return new SpockBlockNode("expect"); // } // // @Override // public String toString() { // return format("%s:", block); // } // // @Override // public boolean equals(Object o) { // if (this == o) { // return true; // } // if (o == null || getClass() != o.getClass()) { // return false; // } // SpockBlockNode that = (SpockBlockNode) o; // return Objects.equals(block, that.block); // } // // @Override // public int hashCode() { // return Objects.hash(block); // } // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/node/SpockBlockNode.java // public static SpockBlockNode given() { // return new SpockBlockNode("given"); // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/node/SpockBlockNode.java // public static SpockBlockNode then() { // return new SpockBlockNode("then"); // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/node/SpockBlockNode.java // public static SpockBlockNode when() { // return new SpockBlockNode("when"); // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/util/AstNodeFinder.java // public static Optional<MethodInvocation> methodInvocation(Object bodyElement, String... methodNames) { // return stream(methodNames) // .map(methodName -> methodInvocation(bodyElement, methodName)) // .filter(Optional::isPresent) // .map(Optional::get) // .findFirst(); // } // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/model/method/CommentBasedSpockBlocksStrategy.java import com.github.opaluchlukasz.junit2spock.core.node.SpockBlockNode; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import static com.github.opaluchlukasz.junit2spock.core.node.SpockBlockNode.given; import static com.github.opaluchlukasz.junit2spock.core.node.SpockBlockNode.then; import static com.github.opaluchlukasz.junit2spock.core.node.SpockBlockNode.when; import static com.github.opaluchlukasz.junit2spock.core.util.AstNodeFinder.methodInvocation; import static java.lang.String.format; import static java.util.Collections.reverseOrder; package com.github.opaluchlukasz.junit2spock.core.model.method; public class CommentBasedSpockBlocksStrategy implements SpockBlockApplier { private static final Logger LOG = LoggerFactory.getLogger(CommentBasedSpockBlocksStrategy.class); static final String GIVEN_BLOCK_START_MARKER_METHOD = "givenBlockStart"; static final String WHEN_BLOCK_START_MARKER_METHOD = "whenBlockStart"; static final String THEN_BLOCK_START_MARKER_METHOD = "thenBlockStart"; private final List<Object> body; private final String methodName; public CommentBasedSpockBlocksStrategy(List<Object> body, String methodName) { this.body = body; this.methodName = methodName; } @Override public boolean apply() { List<Integer> givenIndexes = markerMethod(GIVEN_BLOCK_START_MARKER_METHOD); List<Integer> whenIndexes = markerMethod(WHEN_BLOCK_START_MARKER_METHOD); List<Integer> thenIndexes = markerMethod(THEN_BLOCK_START_MARKER_METHOD); Map<Integer, SpockBlockNode> blocksToBeAdded = new HashMap<>(); if (givenIndexes.size() > 0) { blocksToBeAdded.put(givenIndexes.get(0), given()); } if (whenIndexes.size() != thenIndexes.size()) { LOG.warn(format("Numbers of when/then blocks do not match for test method: %s", methodName)); } whenIndexes.forEach(index -> blocksToBeAdded.put(index, when())); thenIndexes.forEach(index -> blocksToBeAdded.put(index, then())); blocksToBeAdded.keySet().stream().sorted(reverseOrder()).forEach(key -> body.add(key, blocksToBeAdded.get(key)));
body.removeIf(node -> methodInvocation(node, new String[]{GIVEN_BLOCK_START_MARKER_METHOD,
opaluchlukasz/junit2spock
src/main/java/com/github/opaluchlukasz/junit2spock/core/node/wrapper/IfStatementWrapper.java
// Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/Applicable.java // public enum Applicable { // TEST_METHOD, FIXTURE_METHOD, REGULAR_METHOD, FIELD_FEATURE; // // @Component // static class ApplicableInjector { // @Autowired private FeatureProvider featureProvider; // // @PostConstruct // public void init() { // stream(Applicable.values()).forEach(applicable -> applicable.featureProvider = featureProvider); // } // } // // private FeatureProvider featureProvider; // // public void applyFeaturesToStatements(List<Object> statements) { // List<Feature> features = features(); // for (int i = 0; i < statements.size(); i++) { // Object bodyNode = statements.get(i); // statements.remove(i); // for (Feature testMethodFeature : features) { // bodyNode = testMethodFeature.apply(bodyNode); // } // statements.add(i, bodyNode); // } // } // // public List<Feature> features() { // return featureProvider.features(this); // } // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/node/wrapper/WrapperDecorator.java // public static Object wrap(Object statement, int indentation, Applicable applicable) { // return Match(statement).of( // Case($(instanceOf(IfStatement.class)), stmt -> new IfStatementWrapper(stmt, indentation, applicable)), // Case($(instanceOf(TryStatement.class)), stmt -> new TryStatementWrapper(stmt, indentation, applicable)), // Case($(), statement) // ); // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/util/StringUtil.java // public static final String SEPARATOR = System.getProperty("line.separator"); // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/util/StringUtil.java // public static String indentation(int indentationInTabs) { // return IntStream.rangeClosed(1, indentationInTabs).mapToObj(__ -> "\t").reduce("", (a, b) -> a + b); // }
import com.github.opaluchlukasz.junit2spock.core.Applicable; import org.eclipse.jdt.core.dom.Block; import org.eclipse.jdt.core.dom.Expression; import org.eclipse.jdt.core.dom.IfStatement; import org.eclipse.jdt.core.dom.Statement; import java.util.LinkedList; import static com.github.opaluchlukasz.junit2spock.core.node.wrapper.WrapperDecorator.wrap; import static com.github.opaluchlukasz.junit2spock.core.util.StringUtil.SEPARATOR; import static com.github.opaluchlukasz.junit2spock.core.util.StringUtil.indentation; import static java.util.regex.Pattern.quote;
package com.github.opaluchlukasz.junit2spock.core.node.wrapper; public class IfStatementWrapper extends BaseWrapper { private final Expression expression; private final LinkedList thenBlock; private final LinkedList elseBlock;
// Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/Applicable.java // public enum Applicable { // TEST_METHOD, FIXTURE_METHOD, REGULAR_METHOD, FIELD_FEATURE; // // @Component // static class ApplicableInjector { // @Autowired private FeatureProvider featureProvider; // // @PostConstruct // public void init() { // stream(Applicable.values()).forEach(applicable -> applicable.featureProvider = featureProvider); // } // } // // private FeatureProvider featureProvider; // // public void applyFeaturesToStatements(List<Object> statements) { // List<Feature> features = features(); // for (int i = 0; i < statements.size(); i++) { // Object bodyNode = statements.get(i); // statements.remove(i); // for (Feature testMethodFeature : features) { // bodyNode = testMethodFeature.apply(bodyNode); // } // statements.add(i, bodyNode); // } // } // // public List<Feature> features() { // return featureProvider.features(this); // } // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/node/wrapper/WrapperDecorator.java // public static Object wrap(Object statement, int indentation, Applicable applicable) { // return Match(statement).of( // Case($(instanceOf(IfStatement.class)), stmt -> new IfStatementWrapper(stmt, indentation, applicable)), // Case($(instanceOf(TryStatement.class)), stmt -> new TryStatementWrapper(stmt, indentation, applicable)), // Case($(), statement) // ); // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/util/StringUtil.java // public static final String SEPARATOR = System.getProperty("line.separator"); // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/util/StringUtil.java // public static String indentation(int indentationInTabs) { // return IntStream.rangeClosed(1, indentationInTabs).mapToObj(__ -> "\t").reduce("", (a, b) -> a + b); // } // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/node/wrapper/IfStatementWrapper.java import com.github.opaluchlukasz.junit2spock.core.Applicable; import org.eclipse.jdt.core.dom.Block; import org.eclipse.jdt.core.dom.Expression; import org.eclipse.jdt.core.dom.IfStatement; import org.eclipse.jdt.core.dom.Statement; import java.util.LinkedList; import static com.github.opaluchlukasz.junit2spock.core.node.wrapper.WrapperDecorator.wrap; import static com.github.opaluchlukasz.junit2spock.core.util.StringUtil.SEPARATOR; import static com.github.opaluchlukasz.junit2spock.core.util.StringUtil.indentation; import static java.util.regex.Pattern.quote; package com.github.opaluchlukasz.junit2spock.core.node.wrapper; public class IfStatementWrapper extends BaseWrapper { private final Expression expression; private final LinkedList thenBlock; private final LinkedList elseBlock;
public IfStatementWrapper(IfStatement statement, int indentationLevel, Applicable applicable) {
opaluchlukasz/junit2spock
src/main/java/com/github/opaluchlukasz/junit2spock/core/node/wrapper/IfStatementWrapper.java
// Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/Applicable.java // public enum Applicable { // TEST_METHOD, FIXTURE_METHOD, REGULAR_METHOD, FIELD_FEATURE; // // @Component // static class ApplicableInjector { // @Autowired private FeatureProvider featureProvider; // // @PostConstruct // public void init() { // stream(Applicable.values()).forEach(applicable -> applicable.featureProvider = featureProvider); // } // } // // private FeatureProvider featureProvider; // // public void applyFeaturesToStatements(List<Object> statements) { // List<Feature> features = features(); // for (int i = 0; i < statements.size(); i++) { // Object bodyNode = statements.get(i); // statements.remove(i); // for (Feature testMethodFeature : features) { // bodyNode = testMethodFeature.apply(bodyNode); // } // statements.add(i, bodyNode); // } // } // // public List<Feature> features() { // return featureProvider.features(this); // } // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/node/wrapper/WrapperDecorator.java // public static Object wrap(Object statement, int indentation, Applicable applicable) { // return Match(statement).of( // Case($(instanceOf(IfStatement.class)), stmt -> new IfStatementWrapper(stmt, indentation, applicable)), // Case($(instanceOf(TryStatement.class)), stmt -> new TryStatementWrapper(stmt, indentation, applicable)), // Case($(), statement) // ); // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/util/StringUtil.java // public static final String SEPARATOR = System.getProperty("line.separator"); // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/util/StringUtil.java // public static String indentation(int indentationInTabs) { // return IntStream.rangeClosed(1, indentationInTabs).mapToObj(__ -> "\t").reduce("", (a, b) -> a + b); // }
import com.github.opaluchlukasz.junit2spock.core.Applicable; import org.eclipse.jdt.core.dom.Block; import org.eclipse.jdt.core.dom.Expression; import org.eclipse.jdt.core.dom.IfStatement; import org.eclipse.jdt.core.dom.Statement; import java.util.LinkedList; import static com.github.opaluchlukasz.junit2spock.core.node.wrapper.WrapperDecorator.wrap; import static com.github.opaluchlukasz.junit2spock.core.util.StringUtil.SEPARATOR; import static com.github.opaluchlukasz.junit2spock.core.util.StringUtil.indentation; import static java.util.regex.Pattern.quote;
package com.github.opaluchlukasz.junit2spock.core.node.wrapper; public class IfStatementWrapper extends BaseWrapper { private final Expression expression; private final LinkedList thenBlock; private final LinkedList elseBlock; public IfStatementWrapper(IfStatement statement, int indentationLevel, Applicable applicable) { super(indentationLevel, applicable); this.expression = statement.getExpression(); this.thenBlock = new LinkedList<>(); this.elseBlock = new LinkedList<>(); statementsFrom(statement.getThenStatement(), thenBlock); statementsFrom(statement.getElseStatement(), elseBlock); applicable.applyFeaturesToStatements(thenBlock); applicable.applyFeaturesToStatements(elseBlock); } private void statementsFrom(Statement statement, LinkedList extracted) { if (statement instanceof Block) {
// Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/Applicable.java // public enum Applicable { // TEST_METHOD, FIXTURE_METHOD, REGULAR_METHOD, FIELD_FEATURE; // // @Component // static class ApplicableInjector { // @Autowired private FeatureProvider featureProvider; // // @PostConstruct // public void init() { // stream(Applicable.values()).forEach(applicable -> applicable.featureProvider = featureProvider); // } // } // // private FeatureProvider featureProvider; // // public void applyFeaturesToStatements(List<Object> statements) { // List<Feature> features = features(); // for (int i = 0; i < statements.size(); i++) { // Object bodyNode = statements.get(i); // statements.remove(i); // for (Feature testMethodFeature : features) { // bodyNode = testMethodFeature.apply(bodyNode); // } // statements.add(i, bodyNode); // } // } // // public List<Feature> features() { // return featureProvider.features(this); // } // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/node/wrapper/WrapperDecorator.java // public static Object wrap(Object statement, int indentation, Applicable applicable) { // return Match(statement).of( // Case($(instanceOf(IfStatement.class)), stmt -> new IfStatementWrapper(stmt, indentation, applicable)), // Case($(instanceOf(TryStatement.class)), stmt -> new TryStatementWrapper(stmt, indentation, applicable)), // Case($(), statement) // ); // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/util/StringUtil.java // public static final String SEPARATOR = System.getProperty("line.separator"); // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/util/StringUtil.java // public static String indentation(int indentationInTabs) { // return IntStream.rangeClosed(1, indentationInTabs).mapToObj(__ -> "\t").reduce("", (a, b) -> a + b); // } // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/node/wrapper/IfStatementWrapper.java import com.github.opaluchlukasz.junit2spock.core.Applicable; import org.eclipse.jdt.core.dom.Block; import org.eclipse.jdt.core.dom.Expression; import org.eclipse.jdt.core.dom.IfStatement; import org.eclipse.jdt.core.dom.Statement; import java.util.LinkedList; import static com.github.opaluchlukasz.junit2spock.core.node.wrapper.WrapperDecorator.wrap; import static com.github.opaluchlukasz.junit2spock.core.util.StringUtil.SEPARATOR; import static com.github.opaluchlukasz.junit2spock.core.util.StringUtil.indentation; import static java.util.regex.Pattern.quote; package com.github.opaluchlukasz.junit2spock.core.node.wrapper; public class IfStatementWrapper extends BaseWrapper { private final Expression expression; private final LinkedList thenBlock; private final LinkedList elseBlock; public IfStatementWrapper(IfStatement statement, int indentationLevel, Applicable applicable) { super(indentationLevel, applicable); this.expression = statement.getExpression(); this.thenBlock = new LinkedList<>(); this.elseBlock = new LinkedList<>(); statementsFrom(statement.getThenStatement(), thenBlock); statementsFrom(statement.getElseStatement(), elseBlock); applicable.applyFeaturesToStatements(thenBlock); applicable.applyFeaturesToStatements(elseBlock); } private void statementsFrom(Statement statement, LinkedList extracted) { if (statement instanceof Block) {
((Block) statement).statements().forEach(stmt -> extracted.add(wrap(stmt, indentationLevel() + 1, applicable())));
opaluchlukasz/junit2spock
src/main/java/com/github/opaluchlukasz/junit2spock/core/node/wrapper/IfStatementWrapper.java
// Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/Applicable.java // public enum Applicable { // TEST_METHOD, FIXTURE_METHOD, REGULAR_METHOD, FIELD_FEATURE; // // @Component // static class ApplicableInjector { // @Autowired private FeatureProvider featureProvider; // // @PostConstruct // public void init() { // stream(Applicable.values()).forEach(applicable -> applicable.featureProvider = featureProvider); // } // } // // private FeatureProvider featureProvider; // // public void applyFeaturesToStatements(List<Object> statements) { // List<Feature> features = features(); // for (int i = 0; i < statements.size(); i++) { // Object bodyNode = statements.get(i); // statements.remove(i); // for (Feature testMethodFeature : features) { // bodyNode = testMethodFeature.apply(bodyNode); // } // statements.add(i, bodyNode); // } // } // // public List<Feature> features() { // return featureProvider.features(this); // } // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/node/wrapper/WrapperDecorator.java // public static Object wrap(Object statement, int indentation, Applicable applicable) { // return Match(statement).of( // Case($(instanceOf(IfStatement.class)), stmt -> new IfStatementWrapper(stmt, indentation, applicable)), // Case($(instanceOf(TryStatement.class)), stmt -> new TryStatementWrapper(stmt, indentation, applicable)), // Case($(), statement) // ); // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/util/StringUtil.java // public static final String SEPARATOR = System.getProperty("line.separator"); // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/util/StringUtil.java // public static String indentation(int indentationInTabs) { // return IntStream.rangeClosed(1, indentationInTabs).mapToObj(__ -> "\t").reduce("", (a, b) -> a + b); // }
import com.github.opaluchlukasz.junit2spock.core.Applicable; import org.eclipse.jdt.core.dom.Block; import org.eclipse.jdt.core.dom.Expression; import org.eclipse.jdt.core.dom.IfStatement; import org.eclipse.jdt.core.dom.Statement; import java.util.LinkedList; import static com.github.opaluchlukasz.junit2spock.core.node.wrapper.WrapperDecorator.wrap; import static com.github.opaluchlukasz.junit2spock.core.util.StringUtil.SEPARATOR; import static com.github.opaluchlukasz.junit2spock.core.util.StringUtil.indentation; import static java.util.regex.Pattern.quote;
package com.github.opaluchlukasz.junit2spock.core.node.wrapper; public class IfStatementWrapper extends BaseWrapper { private final Expression expression; private final LinkedList thenBlock; private final LinkedList elseBlock; public IfStatementWrapper(IfStatement statement, int indentationLevel, Applicable applicable) { super(indentationLevel, applicable); this.expression = statement.getExpression(); this.thenBlock = new LinkedList<>(); this.elseBlock = new LinkedList<>(); statementsFrom(statement.getThenStatement(), thenBlock); statementsFrom(statement.getElseStatement(), elseBlock); applicable.applyFeaturesToStatements(thenBlock); applicable.applyFeaturesToStatements(elseBlock); } private void statementsFrom(Statement statement, LinkedList extracted) { if (statement instanceof Block) { ((Block) statement).statements().forEach(stmt -> extracted.add(wrap(stmt, indentationLevel() + 1, applicable()))); } else if (statement != null) { extracted.add(wrap(statement, indentationLevel(), applicable())); } } @Override public String toString() { StringBuilder stringBuilder = new StringBuilder();
// Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/Applicable.java // public enum Applicable { // TEST_METHOD, FIXTURE_METHOD, REGULAR_METHOD, FIELD_FEATURE; // // @Component // static class ApplicableInjector { // @Autowired private FeatureProvider featureProvider; // // @PostConstruct // public void init() { // stream(Applicable.values()).forEach(applicable -> applicable.featureProvider = featureProvider); // } // } // // private FeatureProvider featureProvider; // // public void applyFeaturesToStatements(List<Object> statements) { // List<Feature> features = features(); // for (int i = 0; i < statements.size(); i++) { // Object bodyNode = statements.get(i); // statements.remove(i); // for (Feature testMethodFeature : features) { // bodyNode = testMethodFeature.apply(bodyNode); // } // statements.add(i, bodyNode); // } // } // // public List<Feature> features() { // return featureProvider.features(this); // } // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/node/wrapper/WrapperDecorator.java // public static Object wrap(Object statement, int indentation, Applicable applicable) { // return Match(statement).of( // Case($(instanceOf(IfStatement.class)), stmt -> new IfStatementWrapper(stmt, indentation, applicable)), // Case($(instanceOf(TryStatement.class)), stmt -> new TryStatementWrapper(stmt, indentation, applicable)), // Case($(), statement) // ); // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/util/StringUtil.java // public static final String SEPARATOR = System.getProperty("line.separator"); // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/util/StringUtil.java // public static String indentation(int indentationInTabs) { // return IntStream.rangeClosed(1, indentationInTabs).mapToObj(__ -> "\t").reduce("", (a, b) -> a + b); // } // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/node/wrapper/IfStatementWrapper.java import com.github.opaluchlukasz.junit2spock.core.Applicable; import org.eclipse.jdt.core.dom.Block; import org.eclipse.jdt.core.dom.Expression; import org.eclipse.jdt.core.dom.IfStatement; import org.eclipse.jdt.core.dom.Statement; import java.util.LinkedList; import static com.github.opaluchlukasz.junit2spock.core.node.wrapper.WrapperDecorator.wrap; import static com.github.opaluchlukasz.junit2spock.core.util.StringUtil.SEPARATOR; import static com.github.opaluchlukasz.junit2spock.core.util.StringUtil.indentation; import static java.util.regex.Pattern.quote; package com.github.opaluchlukasz.junit2spock.core.node.wrapper; public class IfStatementWrapper extends BaseWrapper { private final Expression expression; private final LinkedList thenBlock; private final LinkedList elseBlock; public IfStatementWrapper(IfStatement statement, int indentationLevel, Applicable applicable) { super(indentationLevel, applicable); this.expression = statement.getExpression(); this.thenBlock = new LinkedList<>(); this.elseBlock = new LinkedList<>(); statementsFrom(statement.getThenStatement(), thenBlock); statementsFrom(statement.getElseStatement(), elseBlock); applicable.applyFeaturesToStatements(thenBlock); applicable.applyFeaturesToStatements(elseBlock); } private void statementsFrom(Statement statement, LinkedList extracted) { if (statement instanceof Block) { ((Block) statement).statements().forEach(stmt -> extracted.add(wrap(stmt, indentationLevel() + 1, applicable()))); } else if (statement != null) { extracted.add(wrap(statement, indentationLevel(), applicable())); } } @Override public String toString() { StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(indentation(indentationLevel() + 1)).append("if (").append(expression.toString()).append(") {").append(SEPARATOR);
opaluchlukasz/junit2spock
src/main/java/com/github/opaluchlukasz/junit2spock/core/node/wrapper/IfStatementWrapper.java
// Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/Applicable.java // public enum Applicable { // TEST_METHOD, FIXTURE_METHOD, REGULAR_METHOD, FIELD_FEATURE; // // @Component // static class ApplicableInjector { // @Autowired private FeatureProvider featureProvider; // // @PostConstruct // public void init() { // stream(Applicable.values()).forEach(applicable -> applicable.featureProvider = featureProvider); // } // } // // private FeatureProvider featureProvider; // // public void applyFeaturesToStatements(List<Object> statements) { // List<Feature> features = features(); // for (int i = 0; i < statements.size(); i++) { // Object bodyNode = statements.get(i); // statements.remove(i); // for (Feature testMethodFeature : features) { // bodyNode = testMethodFeature.apply(bodyNode); // } // statements.add(i, bodyNode); // } // } // // public List<Feature> features() { // return featureProvider.features(this); // } // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/node/wrapper/WrapperDecorator.java // public static Object wrap(Object statement, int indentation, Applicable applicable) { // return Match(statement).of( // Case($(instanceOf(IfStatement.class)), stmt -> new IfStatementWrapper(stmt, indentation, applicable)), // Case($(instanceOf(TryStatement.class)), stmt -> new TryStatementWrapper(stmt, indentation, applicable)), // Case($(), statement) // ); // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/util/StringUtil.java // public static final String SEPARATOR = System.getProperty("line.separator"); // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/util/StringUtil.java // public static String indentation(int indentationInTabs) { // return IntStream.rangeClosed(1, indentationInTabs).mapToObj(__ -> "\t").reduce("", (a, b) -> a + b); // }
import com.github.opaluchlukasz.junit2spock.core.Applicable; import org.eclipse.jdt.core.dom.Block; import org.eclipse.jdt.core.dom.Expression; import org.eclipse.jdt.core.dom.IfStatement; import org.eclipse.jdt.core.dom.Statement; import java.util.LinkedList; import static com.github.opaluchlukasz.junit2spock.core.node.wrapper.WrapperDecorator.wrap; import static com.github.opaluchlukasz.junit2spock.core.util.StringUtil.SEPARATOR; import static com.github.opaluchlukasz.junit2spock.core.util.StringUtil.indentation; import static java.util.regex.Pattern.quote;
package com.github.opaluchlukasz.junit2spock.core.node.wrapper; public class IfStatementWrapper extends BaseWrapper { private final Expression expression; private final LinkedList thenBlock; private final LinkedList elseBlock; public IfStatementWrapper(IfStatement statement, int indentationLevel, Applicable applicable) { super(indentationLevel, applicable); this.expression = statement.getExpression(); this.thenBlock = new LinkedList<>(); this.elseBlock = new LinkedList<>(); statementsFrom(statement.getThenStatement(), thenBlock); statementsFrom(statement.getElseStatement(), elseBlock); applicable.applyFeaturesToStatements(thenBlock); applicable.applyFeaturesToStatements(elseBlock); } private void statementsFrom(Statement statement, LinkedList extracted) { if (statement instanceof Block) { ((Block) statement).statements().forEach(stmt -> extracted.add(wrap(stmt, indentationLevel() + 1, applicable()))); } else if (statement != null) { extracted.add(wrap(statement, indentationLevel(), applicable())); } } @Override public String toString() { StringBuilder stringBuilder = new StringBuilder();
// Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/Applicable.java // public enum Applicable { // TEST_METHOD, FIXTURE_METHOD, REGULAR_METHOD, FIELD_FEATURE; // // @Component // static class ApplicableInjector { // @Autowired private FeatureProvider featureProvider; // // @PostConstruct // public void init() { // stream(Applicable.values()).forEach(applicable -> applicable.featureProvider = featureProvider); // } // } // // private FeatureProvider featureProvider; // // public void applyFeaturesToStatements(List<Object> statements) { // List<Feature> features = features(); // for (int i = 0; i < statements.size(); i++) { // Object bodyNode = statements.get(i); // statements.remove(i); // for (Feature testMethodFeature : features) { // bodyNode = testMethodFeature.apply(bodyNode); // } // statements.add(i, bodyNode); // } // } // // public List<Feature> features() { // return featureProvider.features(this); // } // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/node/wrapper/WrapperDecorator.java // public static Object wrap(Object statement, int indentation, Applicable applicable) { // return Match(statement).of( // Case($(instanceOf(IfStatement.class)), stmt -> new IfStatementWrapper(stmt, indentation, applicable)), // Case($(instanceOf(TryStatement.class)), stmt -> new TryStatementWrapper(stmt, indentation, applicable)), // Case($(), statement) // ); // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/util/StringUtil.java // public static final String SEPARATOR = System.getProperty("line.separator"); // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/util/StringUtil.java // public static String indentation(int indentationInTabs) { // return IntStream.rangeClosed(1, indentationInTabs).mapToObj(__ -> "\t").reduce("", (a, b) -> a + b); // } // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/node/wrapper/IfStatementWrapper.java import com.github.opaluchlukasz.junit2spock.core.Applicable; import org.eclipse.jdt.core.dom.Block; import org.eclipse.jdt.core.dom.Expression; import org.eclipse.jdt.core.dom.IfStatement; import org.eclipse.jdt.core.dom.Statement; import java.util.LinkedList; import static com.github.opaluchlukasz.junit2spock.core.node.wrapper.WrapperDecorator.wrap; import static com.github.opaluchlukasz.junit2spock.core.util.StringUtil.SEPARATOR; import static com.github.opaluchlukasz.junit2spock.core.util.StringUtil.indentation; import static java.util.regex.Pattern.quote; package com.github.opaluchlukasz.junit2spock.core.node.wrapper; public class IfStatementWrapper extends BaseWrapper { private final Expression expression; private final LinkedList thenBlock; private final LinkedList elseBlock; public IfStatementWrapper(IfStatement statement, int indentationLevel, Applicable applicable) { super(indentationLevel, applicable); this.expression = statement.getExpression(); this.thenBlock = new LinkedList<>(); this.elseBlock = new LinkedList<>(); statementsFrom(statement.getThenStatement(), thenBlock); statementsFrom(statement.getElseStatement(), elseBlock); applicable.applyFeaturesToStatements(thenBlock); applicable.applyFeaturesToStatements(elseBlock); } private void statementsFrom(Statement statement, LinkedList extracted) { if (statement instanceof Block) { ((Block) statement).statements().forEach(stmt -> extracted.add(wrap(stmt, indentationLevel() + 1, applicable()))); } else if (statement != null) { extracted.add(wrap(statement, indentationLevel(), applicable())); } } @Override public String toString() { StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(indentation(indentationLevel() + 1)).append("if (").append(expression.toString()).append(") {").append(SEPARATOR);
opaluchlukasz/junit2spock
src/main/java/com/github/opaluchlukasz/junit2spock/core/Spocker.java
// Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/model/TypeModel.java // public abstract class TypeModel { // public abstract String asGroovyClass(int typeIndent); // public abstract String typeName(); // abstract Optional<String> packageDeclaration(); // // public String outputFilePath() { // StringBuilder path = new StringBuilder(); // packageDeclaration() // .ifPresent(declaration -> path.append(declaration.replace(quoteReplacement("."), separator)) // .append(separator)); // path.append(typeName()).append(".groovy"); // return path.toString(); // } // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/visitor/TypeVisitor.java // public class TypeVisitor extends ASTVisitor { // // private final ASTNodeFactory astNodeFactory; // private final MethodModelFactory methodModelFactory; // private final Stack<TypeModelBuilder> typeModelBuilders; // // TypeVisitor(MethodModelFactory methodModelFactory, ASTNodeFactory astNodeFactory) { // this.methodModelFactory = methodModelFactory; // this.astNodeFactory = astNodeFactory; // typeModelBuilders = new Stack<>(); // typeModelBuilders.push(new TypeModelBuilder(astNodeFactory)); // } // // @Override // public boolean visit(TypeDeclaration node) { // if (currentTypeModelBuilder().typeName() != null) { // typeModelBuilders.push(new TypeModelBuilder(astNodeFactory)); // } // currentTypeModelBuilder().withTypeName(node.getName()) // .withModifiers(node.modifiers()) // .withSuperType(node.getSuperclassType()) // .withIsInterface(node.isInterface()); // return true; // } // // @Override // public void endVisit(TypeDeclaration node) { // if (typeModelBuilders.size() > 1) { // TypeModel typeModel = typeModelBuilders.pop().build(); // currentTypeModelBuilder().withInnerType(typeModel); // } // } // // @Override // public boolean visit(ImportDeclaration node) { // currentTypeModelBuilder().withImport(node); // return false; // } // // @Override // public boolean visit(PackageDeclaration node) { // currentTypeModelBuilder().withPackageDeclaration(node); // return false; // } // // @Override // public boolean visit(FieldDeclaration node) { // currentTypeModelBuilder().withField(node); // return false; // } // // @Override // public boolean visit(MethodDeclaration methodDeclaration) { // currentTypeModelBuilder().withMethod(methodModelFactory.get(methodDeclaration)); // return false; // } // // public TypeModel typeModel() { // return currentTypeModelBuilder().build(); // } // // private TypeModelBuilder currentTypeModelBuilder() { // return typeModelBuilders.peek(); // } // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/util/StringUtil.java // public static final String SEPARATOR = System.getProperty("line.separator");
import com.github.opaluchlukasz.junit2spock.core.model.TypeModel; import com.github.opaluchlukasz.junit2spock.core.visitor.TypeVisitor; import org.eclipse.jdt.core.dom.ASTParser; import org.eclipse.jdt.core.dom.CompilationUnit; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.Map; import java.util.function.Supplier; import static com.github.opaluchlukasz.junit2spock.core.util.StringUtil.SEPARATOR; import static java.util.regex.Pattern.quote; import static org.eclipse.jdt.core.JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM; import static org.eclipse.jdt.core.JavaCore.COMPILER_COMPLIANCE; import static org.eclipse.jdt.core.JavaCore.COMPILER_SOURCE; import static org.eclipse.jdt.core.JavaCore.VERSION_1_8; import static org.eclipse.jdt.core.JavaCore.getOptions; import static org.eclipse.jdt.core.dom.AST.JLS8; import static org.eclipse.jdt.core.dom.ASTParser.K_COMPILATION_UNIT;
package com.github.opaluchlukasz.junit2spock.core; @Component public class Spocker { private final AstProxy astProxy;
// Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/model/TypeModel.java // public abstract class TypeModel { // public abstract String asGroovyClass(int typeIndent); // public abstract String typeName(); // abstract Optional<String> packageDeclaration(); // // public String outputFilePath() { // StringBuilder path = new StringBuilder(); // packageDeclaration() // .ifPresent(declaration -> path.append(declaration.replace(quoteReplacement("."), separator)) // .append(separator)); // path.append(typeName()).append(".groovy"); // return path.toString(); // } // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/visitor/TypeVisitor.java // public class TypeVisitor extends ASTVisitor { // // private final ASTNodeFactory astNodeFactory; // private final MethodModelFactory methodModelFactory; // private final Stack<TypeModelBuilder> typeModelBuilders; // // TypeVisitor(MethodModelFactory methodModelFactory, ASTNodeFactory astNodeFactory) { // this.methodModelFactory = methodModelFactory; // this.astNodeFactory = astNodeFactory; // typeModelBuilders = new Stack<>(); // typeModelBuilders.push(new TypeModelBuilder(astNodeFactory)); // } // // @Override // public boolean visit(TypeDeclaration node) { // if (currentTypeModelBuilder().typeName() != null) { // typeModelBuilders.push(new TypeModelBuilder(astNodeFactory)); // } // currentTypeModelBuilder().withTypeName(node.getName()) // .withModifiers(node.modifiers()) // .withSuperType(node.getSuperclassType()) // .withIsInterface(node.isInterface()); // return true; // } // // @Override // public void endVisit(TypeDeclaration node) { // if (typeModelBuilders.size() > 1) { // TypeModel typeModel = typeModelBuilders.pop().build(); // currentTypeModelBuilder().withInnerType(typeModel); // } // } // // @Override // public boolean visit(ImportDeclaration node) { // currentTypeModelBuilder().withImport(node); // return false; // } // // @Override // public boolean visit(PackageDeclaration node) { // currentTypeModelBuilder().withPackageDeclaration(node); // return false; // } // // @Override // public boolean visit(FieldDeclaration node) { // currentTypeModelBuilder().withField(node); // return false; // } // // @Override // public boolean visit(MethodDeclaration methodDeclaration) { // currentTypeModelBuilder().withMethod(methodModelFactory.get(methodDeclaration)); // return false; // } // // public TypeModel typeModel() { // return currentTypeModelBuilder().build(); // } // // private TypeModelBuilder currentTypeModelBuilder() { // return typeModelBuilders.peek(); // } // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/util/StringUtil.java // public static final String SEPARATOR = System.getProperty("line.separator"); // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/Spocker.java import com.github.opaluchlukasz.junit2spock.core.model.TypeModel; import com.github.opaluchlukasz.junit2spock.core.visitor.TypeVisitor; import org.eclipse.jdt.core.dom.ASTParser; import org.eclipse.jdt.core.dom.CompilationUnit; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.Map; import java.util.function.Supplier; import static com.github.opaluchlukasz.junit2spock.core.util.StringUtil.SEPARATOR; import static java.util.regex.Pattern.quote; import static org.eclipse.jdt.core.JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM; import static org.eclipse.jdt.core.JavaCore.COMPILER_COMPLIANCE; import static org.eclipse.jdt.core.JavaCore.COMPILER_SOURCE; import static org.eclipse.jdt.core.JavaCore.VERSION_1_8; import static org.eclipse.jdt.core.JavaCore.getOptions; import static org.eclipse.jdt.core.dom.AST.JLS8; import static org.eclipse.jdt.core.dom.ASTParser.K_COMPILATION_UNIT; package com.github.opaluchlukasz.junit2spock.core; @Component public class Spocker { private final AstProxy astProxy;
private final Supplier<TypeVisitor> testClassVisitorSupplier;
opaluchlukasz/junit2spock
src/main/java/com/github/opaluchlukasz/junit2spock/core/Spocker.java
// Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/model/TypeModel.java // public abstract class TypeModel { // public abstract String asGroovyClass(int typeIndent); // public abstract String typeName(); // abstract Optional<String> packageDeclaration(); // // public String outputFilePath() { // StringBuilder path = new StringBuilder(); // packageDeclaration() // .ifPresent(declaration -> path.append(declaration.replace(quoteReplacement("."), separator)) // .append(separator)); // path.append(typeName()).append(".groovy"); // return path.toString(); // } // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/visitor/TypeVisitor.java // public class TypeVisitor extends ASTVisitor { // // private final ASTNodeFactory astNodeFactory; // private final MethodModelFactory methodModelFactory; // private final Stack<TypeModelBuilder> typeModelBuilders; // // TypeVisitor(MethodModelFactory methodModelFactory, ASTNodeFactory astNodeFactory) { // this.methodModelFactory = methodModelFactory; // this.astNodeFactory = astNodeFactory; // typeModelBuilders = new Stack<>(); // typeModelBuilders.push(new TypeModelBuilder(astNodeFactory)); // } // // @Override // public boolean visit(TypeDeclaration node) { // if (currentTypeModelBuilder().typeName() != null) { // typeModelBuilders.push(new TypeModelBuilder(astNodeFactory)); // } // currentTypeModelBuilder().withTypeName(node.getName()) // .withModifiers(node.modifiers()) // .withSuperType(node.getSuperclassType()) // .withIsInterface(node.isInterface()); // return true; // } // // @Override // public void endVisit(TypeDeclaration node) { // if (typeModelBuilders.size() > 1) { // TypeModel typeModel = typeModelBuilders.pop().build(); // currentTypeModelBuilder().withInnerType(typeModel); // } // } // // @Override // public boolean visit(ImportDeclaration node) { // currentTypeModelBuilder().withImport(node); // return false; // } // // @Override // public boolean visit(PackageDeclaration node) { // currentTypeModelBuilder().withPackageDeclaration(node); // return false; // } // // @Override // public boolean visit(FieldDeclaration node) { // currentTypeModelBuilder().withField(node); // return false; // } // // @Override // public boolean visit(MethodDeclaration methodDeclaration) { // currentTypeModelBuilder().withMethod(methodModelFactory.get(methodDeclaration)); // return false; // } // // public TypeModel typeModel() { // return currentTypeModelBuilder().build(); // } // // private TypeModelBuilder currentTypeModelBuilder() { // return typeModelBuilders.peek(); // } // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/util/StringUtil.java // public static final String SEPARATOR = System.getProperty("line.separator");
import com.github.opaluchlukasz.junit2spock.core.model.TypeModel; import com.github.opaluchlukasz.junit2spock.core.visitor.TypeVisitor; import org.eclipse.jdt.core.dom.ASTParser; import org.eclipse.jdt.core.dom.CompilationUnit; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.Map; import java.util.function.Supplier; import static com.github.opaluchlukasz.junit2spock.core.util.StringUtil.SEPARATOR; import static java.util.regex.Pattern.quote; import static org.eclipse.jdt.core.JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM; import static org.eclipse.jdt.core.JavaCore.COMPILER_COMPLIANCE; import static org.eclipse.jdt.core.JavaCore.COMPILER_SOURCE; import static org.eclipse.jdt.core.JavaCore.VERSION_1_8; import static org.eclipse.jdt.core.JavaCore.getOptions; import static org.eclipse.jdt.core.dom.AST.JLS8; import static org.eclipse.jdt.core.dom.ASTParser.K_COMPILATION_UNIT;
package com.github.opaluchlukasz.junit2spock.core; @Component public class Spocker { private final AstProxy astProxy; private final Supplier<TypeVisitor> testClassVisitorSupplier; @Autowired public Spocker(AstProxy astProxy, Supplier<TypeVisitor> testClassVisitorSupplier) { this.astProxy = astProxy; this.testClassVisitorSupplier = testClassVisitorSupplier; }
// Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/model/TypeModel.java // public abstract class TypeModel { // public abstract String asGroovyClass(int typeIndent); // public abstract String typeName(); // abstract Optional<String> packageDeclaration(); // // public String outputFilePath() { // StringBuilder path = new StringBuilder(); // packageDeclaration() // .ifPresent(declaration -> path.append(declaration.replace(quoteReplacement("."), separator)) // .append(separator)); // path.append(typeName()).append(".groovy"); // return path.toString(); // } // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/visitor/TypeVisitor.java // public class TypeVisitor extends ASTVisitor { // // private final ASTNodeFactory astNodeFactory; // private final MethodModelFactory methodModelFactory; // private final Stack<TypeModelBuilder> typeModelBuilders; // // TypeVisitor(MethodModelFactory methodModelFactory, ASTNodeFactory astNodeFactory) { // this.methodModelFactory = methodModelFactory; // this.astNodeFactory = astNodeFactory; // typeModelBuilders = new Stack<>(); // typeModelBuilders.push(new TypeModelBuilder(astNodeFactory)); // } // // @Override // public boolean visit(TypeDeclaration node) { // if (currentTypeModelBuilder().typeName() != null) { // typeModelBuilders.push(new TypeModelBuilder(astNodeFactory)); // } // currentTypeModelBuilder().withTypeName(node.getName()) // .withModifiers(node.modifiers()) // .withSuperType(node.getSuperclassType()) // .withIsInterface(node.isInterface()); // return true; // } // // @Override // public void endVisit(TypeDeclaration node) { // if (typeModelBuilders.size() > 1) { // TypeModel typeModel = typeModelBuilders.pop().build(); // currentTypeModelBuilder().withInnerType(typeModel); // } // } // // @Override // public boolean visit(ImportDeclaration node) { // currentTypeModelBuilder().withImport(node); // return false; // } // // @Override // public boolean visit(PackageDeclaration node) { // currentTypeModelBuilder().withPackageDeclaration(node); // return false; // } // // @Override // public boolean visit(FieldDeclaration node) { // currentTypeModelBuilder().withField(node); // return false; // } // // @Override // public boolean visit(MethodDeclaration methodDeclaration) { // currentTypeModelBuilder().withMethod(methodModelFactory.get(methodDeclaration)); // return false; // } // // public TypeModel typeModel() { // return currentTypeModelBuilder().build(); // } // // private TypeModelBuilder currentTypeModelBuilder() { // return typeModelBuilders.peek(); // } // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/util/StringUtil.java // public static final String SEPARATOR = System.getProperty("line.separator"); // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/Spocker.java import com.github.opaluchlukasz.junit2spock.core.model.TypeModel; import com.github.opaluchlukasz.junit2spock.core.visitor.TypeVisitor; import org.eclipse.jdt.core.dom.ASTParser; import org.eclipse.jdt.core.dom.CompilationUnit; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.Map; import java.util.function.Supplier; import static com.github.opaluchlukasz.junit2spock.core.util.StringUtil.SEPARATOR; import static java.util.regex.Pattern.quote; import static org.eclipse.jdt.core.JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM; import static org.eclipse.jdt.core.JavaCore.COMPILER_COMPLIANCE; import static org.eclipse.jdt.core.JavaCore.COMPILER_SOURCE; import static org.eclipse.jdt.core.JavaCore.VERSION_1_8; import static org.eclipse.jdt.core.JavaCore.getOptions; import static org.eclipse.jdt.core.dom.AST.JLS8; import static org.eclipse.jdt.core.dom.ASTParser.K_COMPILATION_UNIT; package com.github.opaluchlukasz.junit2spock.core; @Component public class Spocker { private final AstProxy astProxy; private final Supplier<TypeVisitor> testClassVisitorSupplier; @Autowired public Spocker(AstProxy astProxy, Supplier<TypeVisitor> testClassVisitorSupplier) { this.astProxy = astProxy; this.testClassVisitorSupplier = testClassVisitorSupplier; }
public TypeModel toGroovyTypeModel(String source) {
opaluchlukasz/junit2spock
src/main/java/com/github/opaluchlukasz/junit2spock/core/Spocker.java
// Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/model/TypeModel.java // public abstract class TypeModel { // public abstract String asGroovyClass(int typeIndent); // public abstract String typeName(); // abstract Optional<String> packageDeclaration(); // // public String outputFilePath() { // StringBuilder path = new StringBuilder(); // packageDeclaration() // .ifPresent(declaration -> path.append(declaration.replace(quoteReplacement("."), separator)) // .append(separator)); // path.append(typeName()).append(".groovy"); // return path.toString(); // } // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/visitor/TypeVisitor.java // public class TypeVisitor extends ASTVisitor { // // private final ASTNodeFactory astNodeFactory; // private final MethodModelFactory methodModelFactory; // private final Stack<TypeModelBuilder> typeModelBuilders; // // TypeVisitor(MethodModelFactory methodModelFactory, ASTNodeFactory astNodeFactory) { // this.methodModelFactory = methodModelFactory; // this.astNodeFactory = astNodeFactory; // typeModelBuilders = new Stack<>(); // typeModelBuilders.push(new TypeModelBuilder(astNodeFactory)); // } // // @Override // public boolean visit(TypeDeclaration node) { // if (currentTypeModelBuilder().typeName() != null) { // typeModelBuilders.push(new TypeModelBuilder(astNodeFactory)); // } // currentTypeModelBuilder().withTypeName(node.getName()) // .withModifiers(node.modifiers()) // .withSuperType(node.getSuperclassType()) // .withIsInterface(node.isInterface()); // return true; // } // // @Override // public void endVisit(TypeDeclaration node) { // if (typeModelBuilders.size() > 1) { // TypeModel typeModel = typeModelBuilders.pop().build(); // currentTypeModelBuilder().withInnerType(typeModel); // } // } // // @Override // public boolean visit(ImportDeclaration node) { // currentTypeModelBuilder().withImport(node); // return false; // } // // @Override // public boolean visit(PackageDeclaration node) { // currentTypeModelBuilder().withPackageDeclaration(node); // return false; // } // // @Override // public boolean visit(FieldDeclaration node) { // currentTypeModelBuilder().withField(node); // return false; // } // // @Override // public boolean visit(MethodDeclaration methodDeclaration) { // currentTypeModelBuilder().withMethod(methodModelFactory.get(methodDeclaration)); // return false; // } // // public TypeModel typeModel() { // return currentTypeModelBuilder().build(); // } // // private TypeModelBuilder currentTypeModelBuilder() { // return typeModelBuilders.peek(); // } // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/util/StringUtil.java // public static final String SEPARATOR = System.getProperty("line.separator");
import com.github.opaluchlukasz.junit2spock.core.model.TypeModel; import com.github.opaluchlukasz.junit2spock.core.visitor.TypeVisitor; import org.eclipse.jdt.core.dom.ASTParser; import org.eclipse.jdt.core.dom.CompilationUnit; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.Map; import java.util.function.Supplier; import static com.github.opaluchlukasz.junit2spock.core.util.StringUtil.SEPARATOR; import static java.util.regex.Pattern.quote; import static org.eclipse.jdt.core.JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM; import static org.eclipse.jdt.core.JavaCore.COMPILER_COMPLIANCE; import static org.eclipse.jdt.core.JavaCore.COMPILER_SOURCE; import static org.eclipse.jdt.core.JavaCore.VERSION_1_8; import static org.eclipse.jdt.core.JavaCore.getOptions; import static org.eclipse.jdt.core.dom.AST.JLS8; import static org.eclipse.jdt.core.dom.ASTParser.K_COMPILATION_UNIT;
package com.github.opaluchlukasz.junit2spock.core; @Component public class Spocker { private final AstProxy astProxy; private final Supplier<TypeVisitor> testClassVisitorSupplier; @Autowired public Spocker(AstProxy astProxy, Supplier<TypeVisitor> testClassVisitorSupplier) { this.astProxy = astProxy; this.testClassVisitorSupplier = testClassVisitorSupplier; } public TypeModel toGroovyTypeModel(String source) {
// Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/model/TypeModel.java // public abstract class TypeModel { // public abstract String asGroovyClass(int typeIndent); // public abstract String typeName(); // abstract Optional<String> packageDeclaration(); // // public String outputFilePath() { // StringBuilder path = new StringBuilder(); // packageDeclaration() // .ifPresent(declaration -> path.append(declaration.replace(quoteReplacement("."), separator)) // .append(separator)); // path.append(typeName()).append(".groovy"); // return path.toString(); // } // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/visitor/TypeVisitor.java // public class TypeVisitor extends ASTVisitor { // // private final ASTNodeFactory astNodeFactory; // private final MethodModelFactory methodModelFactory; // private final Stack<TypeModelBuilder> typeModelBuilders; // // TypeVisitor(MethodModelFactory methodModelFactory, ASTNodeFactory astNodeFactory) { // this.methodModelFactory = methodModelFactory; // this.astNodeFactory = astNodeFactory; // typeModelBuilders = new Stack<>(); // typeModelBuilders.push(new TypeModelBuilder(astNodeFactory)); // } // // @Override // public boolean visit(TypeDeclaration node) { // if (currentTypeModelBuilder().typeName() != null) { // typeModelBuilders.push(new TypeModelBuilder(astNodeFactory)); // } // currentTypeModelBuilder().withTypeName(node.getName()) // .withModifiers(node.modifiers()) // .withSuperType(node.getSuperclassType()) // .withIsInterface(node.isInterface()); // return true; // } // // @Override // public void endVisit(TypeDeclaration node) { // if (typeModelBuilders.size() > 1) { // TypeModel typeModel = typeModelBuilders.pop().build(); // currentTypeModelBuilder().withInnerType(typeModel); // } // } // // @Override // public boolean visit(ImportDeclaration node) { // currentTypeModelBuilder().withImport(node); // return false; // } // // @Override // public boolean visit(PackageDeclaration node) { // currentTypeModelBuilder().withPackageDeclaration(node); // return false; // } // // @Override // public boolean visit(FieldDeclaration node) { // currentTypeModelBuilder().withField(node); // return false; // } // // @Override // public boolean visit(MethodDeclaration methodDeclaration) { // currentTypeModelBuilder().withMethod(methodModelFactory.get(methodDeclaration)); // return false; // } // // public TypeModel typeModel() { // return currentTypeModelBuilder().build(); // } // // private TypeModelBuilder currentTypeModelBuilder() { // return typeModelBuilders.peek(); // } // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/util/StringUtil.java // public static final String SEPARATOR = System.getProperty("line.separator"); // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/Spocker.java import com.github.opaluchlukasz.junit2spock.core.model.TypeModel; import com.github.opaluchlukasz.junit2spock.core.visitor.TypeVisitor; import org.eclipse.jdt.core.dom.ASTParser; import org.eclipse.jdt.core.dom.CompilationUnit; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.Map; import java.util.function.Supplier; import static com.github.opaluchlukasz.junit2spock.core.util.StringUtil.SEPARATOR; import static java.util.regex.Pattern.quote; import static org.eclipse.jdt.core.JavaCore.COMPILER_CODEGEN_TARGET_PLATFORM; import static org.eclipse.jdt.core.JavaCore.COMPILER_COMPLIANCE; import static org.eclipse.jdt.core.JavaCore.COMPILER_SOURCE; import static org.eclipse.jdt.core.JavaCore.VERSION_1_8; import static org.eclipse.jdt.core.JavaCore.getOptions; import static org.eclipse.jdt.core.dom.AST.JLS8; import static org.eclipse.jdt.core.dom.ASTParser.K_COMPILATION_UNIT; package com.github.opaluchlukasz.junit2spock.core; @Component public class Spocker { private final AstProxy astProxy; private final Supplier<TypeVisitor> testClassVisitorSupplier; @Autowired public Spocker(AstProxy astProxy, Supplier<TypeVisitor> testClassVisitorSupplier) { this.astProxy = astProxy; this.testClassVisitorSupplier = testClassVisitorSupplier; } public TypeModel toGroovyTypeModel(String source) {
source = source.replaceAll("//(?i)\\s*" + quote("given") + SEPARATOR, "givenBlockStart();");
opaluchlukasz/junit2spock
src/main/java/com/github/opaluchlukasz/junit2spock/core/node/wrapper/BaseWrapper.java
// Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/Applicable.java // public enum Applicable { // TEST_METHOD, FIXTURE_METHOD, REGULAR_METHOD, FIELD_FEATURE; // // @Component // static class ApplicableInjector { // @Autowired private FeatureProvider featureProvider; // // @PostConstruct // public void init() { // stream(Applicable.values()).forEach(applicable -> applicable.featureProvider = featureProvider); // } // } // // private FeatureProvider featureProvider; // // public void applyFeaturesToStatements(List<Object> statements) { // List<Feature> features = features(); // for (int i = 0; i < statements.size(); i++) { // Object bodyNode = statements.get(i); // statements.remove(i); // for (Feature testMethodFeature : features) { // bodyNode = testMethodFeature.apply(bodyNode); // } // statements.add(i, bodyNode); // } // } // // public List<Feature> features() { // return featureProvider.features(this); // } // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/groovism/Groovism.java // public abstract class Groovism implements UnaryOperator<String> { // // private final Optional<Groovism> next; // // Groovism(Optional<Groovism> next) { // this.next = next; // } // // @Override // public String apply(String line) { // String groovierLine = applyGroovism(line); // return next.map(next -> next.apply(groovierLine)).orElse(groovierLine); // } // // protected abstract String applyGroovism(String line); // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/groovism/GroovismChainProvider.java // public static Groovism provide() { // return new NoSemicolon(new NoClassKeyword(new RegularString(new NoPublicKeyword()))); // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/util/StringUtil.java // public static final String SEPARATOR = System.getProperty("line.separator"); // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/util/StringUtil.java // public static String indentation(int indentationInTabs) { // return IntStream.rangeClosed(1, indentationInTabs).mapToObj(__ -> "\t").reduce("", (a, b) -> a + b); // }
import com.github.opaluchlukasz.junit2spock.core.Applicable; import com.github.opaluchlukasz.junit2spock.core.groovism.Groovism; import java.util.function.Consumer; import static com.github.opaluchlukasz.junit2spock.core.groovism.GroovismChainProvider.provide; import static com.github.opaluchlukasz.junit2spock.core.util.StringUtil.SEPARATOR; import static com.github.opaluchlukasz.junit2spock.core.util.StringUtil.indentation;
package com.github.opaluchlukasz.junit2spock.core.node.wrapper; public class BaseWrapper { private final int indentationLevel;
// Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/Applicable.java // public enum Applicable { // TEST_METHOD, FIXTURE_METHOD, REGULAR_METHOD, FIELD_FEATURE; // // @Component // static class ApplicableInjector { // @Autowired private FeatureProvider featureProvider; // // @PostConstruct // public void init() { // stream(Applicable.values()).forEach(applicable -> applicable.featureProvider = featureProvider); // } // } // // private FeatureProvider featureProvider; // // public void applyFeaturesToStatements(List<Object> statements) { // List<Feature> features = features(); // for (int i = 0; i < statements.size(); i++) { // Object bodyNode = statements.get(i); // statements.remove(i); // for (Feature testMethodFeature : features) { // bodyNode = testMethodFeature.apply(bodyNode); // } // statements.add(i, bodyNode); // } // } // // public List<Feature> features() { // return featureProvider.features(this); // } // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/groovism/Groovism.java // public abstract class Groovism implements UnaryOperator<String> { // // private final Optional<Groovism> next; // // Groovism(Optional<Groovism> next) { // this.next = next; // } // // @Override // public String apply(String line) { // String groovierLine = applyGroovism(line); // return next.map(next -> next.apply(groovierLine)).orElse(groovierLine); // } // // protected abstract String applyGroovism(String line); // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/groovism/GroovismChainProvider.java // public static Groovism provide() { // return new NoSemicolon(new NoClassKeyword(new RegularString(new NoPublicKeyword()))); // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/util/StringUtil.java // public static final String SEPARATOR = System.getProperty("line.separator"); // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/util/StringUtil.java // public static String indentation(int indentationInTabs) { // return IntStream.rangeClosed(1, indentationInTabs).mapToObj(__ -> "\t").reduce("", (a, b) -> a + b); // } // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/node/wrapper/BaseWrapper.java import com.github.opaluchlukasz.junit2spock.core.Applicable; import com.github.opaluchlukasz.junit2spock.core.groovism.Groovism; import java.util.function.Consumer; import static com.github.opaluchlukasz.junit2spock.core.groovism.GroovismChainProvider.provide; import static com.github.opaluchlukasz.junit2spock.core.util.StringUtil.SEPARATOR; import static com.github.opaluchlukasz.junit2spock.core.util.StringUtil.indentation; package com.github.opaluchlukasz.junit2spock.core.node.wrapper; public class BaseWrapper { private final int indentationLevel;
private final Applicable applicable;
opaluchlukasz/junit2spock
src/main/java/com/github/opaluchlukasz/junit2spock/core/node/wrapper/BaseWrapper.java
// Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/Applicable.java // public enum Applicable { // TEST_METHOD, FIXTURE_METHOD, REGULAR_METHOD, FIELD_FEATURE; // // @Component // static class ApplicableInjector { // @Autowired private FeatureProvider featureProvider; // // @PostConstruct // public void init() { // stream(Applicable.values()).forEach(applicable -> applicable.featureProvider = featureProvider); // } // } // // private FeatureProvider featureProvider; // // public void applyFeaturesToStatements(List<Object> statements) { // List<Feature> features = features(); // for (int i = 0; i < statements.size(); i++) { // Object bodyNode = statements.get(i); // statements.remove(i); // for (Feature testMethodFeature : features) { // bodyNode = testMethodFeature.apply(bodyNode); // } // statements.add(i, bodyNode); // } // } // // public List<Feature> features() { // return featureProvider.features(this); // } // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/groovism/Groovism.java // public abstract class Groovism implements UnaryOperator<String> { // // private final Optional<Groovism> next; // // Groovism(Optional<Groovism> next) { // this.next = next; // } // // @Override // public String apply(String line) { // String groovierLine = applyGroovism(line); // return next.map(next -> next.apply(groovierLine)).orElse(groovierLine); // } // // protected abstract String applyGroovism(String line); // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/groovism/GroovismChainProvider.java // public static Groovism provide() { // return new NoSemicolon(new NoClassKeyword(new RegularString(new NoPublicKeyword()))); // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/util/StringUtil.java // public static final String SEPARATOR = System.getProperty("line.separator"); // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/util/StringUtil.java // public static String indentation(int indentationInTabs) { // return IntStream.rangeClosed(1, indentationInTabs).mapToObj(__ -> "\t").reduce("", (a, b) -> a + b); // }
import com.github.opaluchlukasz.junit2spock.core.Applicable; import com.github.opaluchlukasz.junit2spock.core.groovism.Groovism; import java.util.function.Consumer; import static com.github.opaluchlukasz.junit2spock.core.groovism.GroovismChainProvider.provide; import static com.github.opaluchlukasz.junit2spock.core.util.StringUtil.SEPARATOR; import static com.github.opaluchlukasz.junit2spock.core.util.StringUtil.indentation;
package com.github.opaluchlukasz.junit2spock.core.node.wrapper; public class BaseWrapper { private final int indentationLevel; private final Applicable applicable;
// Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/Applicable.java // public enum Applicable { // TEST_METHOD, FIXTURE_METHOD, REGULAR_METHOD, FIELD_FEATURE; // // @Component // static class ApplicableInjector { // @Autowired private FeatureProvider featureProvider; // // @PostConstruct // public void init() { // stream(Applicable.values()).forEach(applicable -> applicable.featureProvider = featureProvider); // } // } // // private FeatureProvider featureProvider; // // public void applyFeaturesToStatements(List<Object> statements) { // List<Feature> features = features(); // for (int i = 0; i < statements.size(); i++) { // Object bodyNode = statements.get(i); // statements.remove(i); // for (Feature testMethodFeature : features) { // bodyNode = testMethodFeature.apply(bodyNode); // } // statements.add(i, bodyNode); // } // } // // public List<Feature> features() { // return featureProvider.features(this); // } // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/groovism/Groovism.java // public abstract class Groovism implements UnaryOperator<String> { // // private final Optional<Groovism> next; // // Groovism(Optional<Groovism> next) { // this.next = next; // } // // @Override // public String apply(String line) { // String groovierLine = applyGroovism(line); // return next.map(next -> next.apply(groovierLine)).orElse(groovierLine); // } // // protected abstract String applyGroovism(String line); // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/groovism/GroovismChainProvider.java // public static Groovism provide() { // return new NoSemicolon(new NoClassKeyword(new RegularString(new NoPublicKeyword()))); // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/util/StringUtil.java // public static final String SEPARATOR = System.getProperty("line.separator"); // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/util/StringUtil.java // public static String indentation(int indentationInTabs) { // return IntStream.rangeClosed(1, indentationInTabs).mapToObj(__ -> "\t").reduce("", (a, b) -> a + b); // } // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/node/wrapper/BaseWrapper.java import com.github.opaluchlukasz.junit2spock.core.Applicable; import com.github.opaluchlukasz.junit2spock.core.groovism.Groovism; import java.util.function.Consumer; import static com.github.opaluchlukasz.junit2spock.core.groovism.GroovismChainProvider.provide; import static com.github.opaluchlukasz.junit2spock.core.util.StringUtil.SEPARATOR; import static com.github.opaluchlukasz.junit2spock.core.util.StringUtil.indentation; package com.github.opaluchlukasz.junit2spock.core.node.wrapper; public class BaseWrapper { private final int indentationLevel; private final Applicable applicable;
private final Groovism groovism;
opaluchlukasz/junit2spock
src/main/java/com/github/opaluchlukasz/junit2spock/core/node/wrapper/BaseWrapper.java
// Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/Applicable.java // public enum Applicable { // TEST_METHOD, FIXTURE_METHOD, REGULAR_METHOD, FIELD_FEATURE; // // @Component // static class ApplicableInjector { // @Autowired private FeatureProvider featureProvider; // // @PostConstruct // public void init() { // stream(Applicable.values()).forEach(applicable -> applicable.featureProvider = featureProvider); // } // } // // private FeatureProvider featureProvider; // // public void applyFeaturesToStatements(List<Object> statements) { // List<Feature> features = features(); // for (int i = 0; i < statements.size(); i++) { // Object bodyNode = statements.get(i); // statements.remove(i); // for (Feature testMethodFeature : features) { // bodyNode = testMethodFeature.apply(bodyNode); // } // statements.add(i, bodyNode); // } // } // // public List<Feature> features() { // return featureProvider.features(this); // } // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/groovism/Groovism.java // public abstract class Groovism implements UnaryOperator<String> { // // private final Optional<Groovism> next; // // Groovism(Optional<Groovism> next) { // this.next = next; // } // // @Override // public String apply(String line) { // String groovierLine = applyGroovism(line); // return next.map(next -> next.apply(groovierLine)).orElse(groovierLine); // } // // protected abstract String applyGroovism(String line); // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/groovism/GroovismChainProvider.java // public static Groovism provide() { // return new NoSemicolon(new NoClassKeyword(new RegularString(new NoPublicKeyword()))); // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/util/StringUtil.java // public static final String SEPARATOR = System.getProperty("line.separator"); // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/util/StringUtil.java // public static String indentation(int indentationInTabs) { // return IntStream.rangeClosed(1, indentationInTabs).mapToObj(__ -> "\t").reduce("", (a, b) -> a + b); // }
import com.github.opaluchlukasz.junit2spock.core.Applicable; import com.github.opaluchlukasz.junit2spock.core.groovism.Groovism; import java.util.function.Consumer; import static com.github.opaluchlukasz.junit2spock.core.groovism.GroovismChainProvider.provide; import static com.github.opaluchlukasz.junit2spock.core.util.StringUtil.SEPARATOR; import static com.github.opaluchlukasz.junit2spock.core.util.StringUtil.indentation;
package com.github.opaluchlukasz.junit2spock.core.node.wrapper; public class BaseWrapper { private final int indentationLevel; private final Applicable applicable; private final Groovism groovism; BaseWrapper(int indentationLevel, Applicable applicable) { this.indentationLevel = indentationLevel; this.applicable = applicable;
// Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/Applicable.java // public enum Applicable { // TEST_METHOD, FIXTURE_METHOD, REGULAR_METHOD, FIELD_FEATURE; // // @Component // static class ApplicableInjector { // @Autowired private FeatureProvider featureProvider; // // @PostConstruct // public void init() { // stream(Applicable.values()).forEach(applicable -> applicable.featureProvider = featureProvider); // } // } // // private FeatureProvider featureProvider; // // public void applyFeaturesToStatements(List<Object> statements) { // List<Feature> features = features(); // for (int i = 0; i < statements.size(); i++) { // Object bodyNode = statements.get(i); // statements.remove(i); // for (Feature testMethodFeature : features) { // bodyNode = testMethodFeature.apply(bodyNode); // } // statements.add(i, bodyNode); // } // } // // public List<Feature> features() { // return featureProvider.features(this); // } // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/groovism/Groovism.java // public abstract class Groovism implements UnaryOperator<String> { // // private final Optional<Groovism> next; // // Groovism(Optional<Groovism> next) { // this.next = next; // } // // @Override // public String apply(String line) { // String groovierLine = applyGroovism(line); // return next.map(next -> next.apply(groovierLine)).orElse(groovierLine); // } // // protected abstract String applyGroovism(String line); // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/groovism/GroovismChainProvider.java // public static Groovism provide() { // return new NoSemicolon(new NoClassKeyword(new RegularString(new NoPublicKeyword()))); // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/util/StringUtil.java // public static final String SEPARATOR = System.getProperty("line.separator"); // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/util/StringUtil.java // public static String indentation(int indentationInTabs) { // return IntStream.rangeClosed(1, indentationInTabs).mapToObj(__ -> "\t").reduce("", (a, b) -> a + b); // } // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/node/wrapper/BaseWrapper.java import com.github.opaluchlukasz.junit2spock.core.Applicable; import com.github.opaluchlukasz.junit2spock.core.groovism.Groovism; import java.util.function.Consumer; import static com.github.opaluchlukasz.junit2spock.core.groovism.GroovismChainProvider.provide; import static com.github.opaluchlukasz.junit2spock.core.util.StringUtil.SEPARATOR; import static com.github.opaluchlukasz.junit2spock.core.util.StringUtil.indentation; package com.github.opaluchlukasz.junit2spock.core.node.wrapper; public class BaseWrapper { private final int indentationLevel; private final Applicable applicable; private final Groovism groovism; BaseWrapper(int indentationLevel, Applicable applicable) { this.indentationLevel = indentationLevel; this.applicable = applicable;
this.groovism = provide();
opaluchlukasz/junit2spock
src/main/java/com/github/opaluchlukasz/junit2spock/core/node/wrapper/BaseWrapper.java
// Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/Applicable.java // public enum Applicable { // TEST_METHOD, FIXTURE_METHOD, REGULAR_METHOD, FIELD_FEATURE; // // @Component // static class ApplicableInjector { // @Autowired private FeatureProvider featureProvider; // // @PostConstruct // public void init() { // stream(Applicable.values()).forEach(applicable -> applicable.featureProvider = featureProvider); // } // } // // private FeatureProvider featureProvider; // // public void applyFeaturesToStatements(List<Object> statements) { // List<Feature> features = features(); // for (int i = 0; i < statements.size(); i++) { // Object bodyNode = statements.get(i); // statements.remove(i); // for (Feature testMethodFeature : features) { // bodyNode = testMethodFeature.apply(bodyNode); // } // statements.add(i, bodyNode); // } // } // // public List<Feature> features() { // return featureProvider.features(this); // } // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/groovism/Groovism.java // public abstract class Groovism implements UnaryOperator<String> { // // private final Optional<Groovism> next; // // Groovism(Optional<Groovism> next) { // this.next = next; // } // // @Override // public String apply(String line) { // String groovierLine = applyGroovism(line); // return next.map(next -> next.apply(groovierLine)).orElse(groovierLine); // } // // protected abstract String applyGroovism(String line); // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/groovism/GroovismChainProvider.java // public static Groovism provide() { // return new NoSemicolon(new NoClassKeyword(new RegularString(new NoPublicKeyword()))); // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/util/StringUtil.java // public static final String SEPARATOR = System.getProperty("line.separator"); // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/util/StringUtil.java // public static String indentation(int indentationInTabs) { // return IntStream.rangeClosed(1, indentationInTabs).mapToObj(__ -> "\t").reduce("", (a, b) -> a + b); // }
import com.github.opaluchlukasz.junit2spock.core.Applicable; import com.github.opaluchlukasz.junit2spock.core.groovism.Groovism; import java.util.function.Consumer; import static com.github.opaluchlukasz.junit2spock.core.groovism.GroovismChainProvider.provide; import static com.github.opaluchlukasz.junit2spock.core.util.StringUtil.SEPARATOR; import static com.github.opaluchlukasz.junit2spock.core.util.StringUtil.indentation;
package com.github.opaluchlukasz.junit2spock.core.node.wrapper; public class BaseWrapper { private final int indentationLevel; private final Applicable applicable; private final Groovism groovism; BaseWrapper(int indentationLevel, Applicable applicable) { this.indentationLevel = indentationLevel; this.applicable = applicable; this.groovism = provide(); } int indentationLevel() { return indentationLevel; } protected Applicable applicable() { return applicable; } Consumer printStatement(StringBuilder builder) { return stmt -> { if (stmt instanceof BaseWrapper) { builder.append(stmt.toString()); } else {
// Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/Applicable.java // public enum Applicable { // TEST_METHOD, FIXTURE_METHOD, REGULAR_METHOD, FIELD_FEATURE; // // @Component // static class ApplicableInjector { // @Autowired private FeatureProvider featureProvider; // // @PostConstruct // public void init() { // stream(Applicable.values()).forEach(applicable -> applicable.featureProvider = featureProvider); // } // } // // private FeatureProvider featureProvider; // // public void applyFeaturesToStatements(List<Object> statements) { // List<Feature> features = features(); // for (int i = 0; i < statements.size(); i++) { // Object bodyNode = statements.get(i); // statements.remove(i); // for (Feature testMethodFeature : features) { // bodyNode = testMethodFeature.apply(bodyNode); // } // statements.add(i, bodyNode); // } // } // // public List<Feature> features() { // return featureProvider.features(this); // } // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/groovism/Groovism.java // public abstract class Groovism implements UnaryOperator<String> { // // private final Optional<Groovism> next; // // Groovism(Optional<Groovism> next) { // this.next = next; // } // // @Override // public String apply(String line) { // String groovierLine = applyGroovism(line); // return next.map(next -> next.apply(groovierLine)).orElse(groovierLine); // } // // protected abstract String applyGroovism(String line); // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/groovism/GroovismChainProvider.java // public static Groovism provide() { // return new NoSemicolon(new NoClassKeyword(new RegularString(new NoPublicKeyword()))); // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/util/StringUtil.java // public static final String SEPARATOR = System.getProperty("line.separator"); // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/util/StringUtil.java // public static String indentation(int indentationInTabs) { // return IntStream.rangeClosed(1, indentationInTabs).mapToObj(__ -> "\t").reduce("", (a, b) -> a + b); // } // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/node/wrapper/BaseWrapper.java import com.github.opaluchlukasz.junit2spock.core.Applicable; import com.github.opaluchlukasz.junit2spock.core.groovism.Groovism; import java.util.function.Consumer; import static com.github.opaluchlukasz.junit2spock.core.groovism.GroovismChainProvider.provide; import static com.github.opaluchlukasz.junit2spock.core.util.StringUtil.SEPARATOR; import static com.github.opaluchlukasz.junit2spock.core.util.StringUtil.indentation; package com.github.opaluchlukasz.junit2spock.core.node.wrapper; public class BaseWrapper { private final int indentationLevel; private final Applicable applicable; private final Groovism groovism; BaseWrapper(int indentationLevel, Applicable applicable) { this.indentationLevel = indentationLevel; this.applicable = applicable; this.groovism = provide(); } int indentationLevel() { return indentationLevel; } protected Applicable applicable() { return applicable; } Consumer printStatement(StringBuilder builder) { return stmt -> { if (stmt instanceof BaseWrapper) { builder.append(stmt.toString()); } else {
builder.append(indentation(indentationLevel + 2)).append(groovism.apply(stmt.toString()));
opaluchlukasz/junit2spock
src/main/java/com/github/opaluchlukasz/junit2spock/core/node/wrapper/BaseWrapper.java
// Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/Applicable.java // public enum Applicable { // TEST_METHOD, FIXTURE_METHOD, REGULAR_METHOD, FIELD_FEATURE; // // @Component // static class ApplicableInjector { // @Autowired private FeatureProvider featureProvider; // // @PostConstruct // public void init() { // stream(Applicable.values()).forEach(applicable -> applicable.featureProvider = featureProvider); // } // } // // private FeatureProvider featureProvider; // // public void applyFeaturesToStatements(List<Object> statements) { // List<Feature> features = features(); // for (int i = 0; i < statements.size(); i++) { // Object bodyNode = statements.get(i); // statements.remove(i); // for (Feature testMethodFeature : features) { // bodyNode = testMethodFeature.apply(bodyNode); // } // statements.add(i, bodyNode); // } // } // // public List<Feature> features() { // return featureProvider.features(this); // } // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/groovism/Groovism.java // public abstract class Groovism implements UnaryOperator<String> { // // private final Optional<Groovism> next; // // Groovism(Optional<Groovism> next) { // this.next = next; // } // // @Override // public String apply(String line) { // String groovierLine = applyGroovism(line); // return next.map(next -> next.apply(groovierLine)).orElse(groovierLine); // } // // protected abstract String applyGroovism(String line); // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/groovism/GroovismChainProvider.java // public static Groovism provide() { // return new NoSemicolon(new NoClassKeyword(new RegularString(new NoPublicKeyword()))); // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/util/StringUtil.java // public static final String SEPARATOR = System.getProperty("line.separator"); // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/util/StringUtil.java // public static String indentation(int indentationInTabs) { // return IntStream.rangeClosed(1, indentationInTabs).mapToObj(__ -> "\t").reduce("", (a, b) -> a + b); // }
import com.github.opaluchlukasz.junit2spock.core.Applicable; import com.github.opaluchlukasz.junit2spock.core.groovism.Groovism; import java.util.function.Consumer; import static com.github.opaluchlukasz.junit2spock.core.groovism.GroovismChainProvider.provide; import static com.github.opaluchlukasz.junit2spock.core.util.StringUtil.SEPARATOR; import static com.github.opaluchlukasz.junit2spock.core.util.StringUtil.indentation;
package com.github.opaluchlukasz.junit2spock.core.node.wrapper; public class BaseWrapper { private final int indentationLevel; private final Applicable applicable; private final Groovism groovism; BaseWrapper(int indentationLevel, Applicable applicable) { this.indentationLevel = indentationLevel; this.applicable = applicable; this.groovism = provide(); } int indentationLevel() { return indentationLevel; } protected Applicable applicable() { return applicable; } Consumer printStatement(StringBuilder builder) { return stmt -> { if (stmt instanceof BaseWrapper) { builder.append(stmt.toString()); } else { builder.append(indentation(indentationLevel + 2)).append(groovism.apply(stmt.toString())); if (!stmt.toString().endsWith("\n")) {
// Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/Applicable.java // public enum Applicable { // TEST_METHOD, FIXTURE_METHOD, REGULAR_METHOD, FIELD_FEATURE; // // @Component // static class ApplicableInjector { // @Autowired private FeatureProvider featureProvider; // // @PostConstruct // public void init() { // stream(Applicable.values()).forEach(applicable -> applicable.featureProvider = featureProvider); // } // } // // private FeatureProvider featureProvider; // // public void applyFeaturesToStatements(List<Object> statements) { // List<Feature> features = features(); // for (int i = 0; i < statements.size(); i++) { // Object bodyNode = statements.get(i); // statements.remove(i); // for (Feature testMethodFeature : features) { // bodyNode = testMethodFeature.apply(bodyNode); // } // statements.add(i, bodyNode); // } // } // // public List<Feature> features() { // return featureProvider.features(this); // } // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/groovism/Groovism.java // public abstract class Groovism implements UnaryOperator<String> { // // private final Optional<Groovism> next; // // Groovism(Optional<Groovism> next) { // this.next = next; // } // // @Override // public String apply(String line) { // String groovierLine = applyGroovism(line); // return next.map(next -> next.apply(groovierLine)).orElse(groovierLine); // } // // protected abstract String applyGroovism(String line); // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/groovism/GroovismChainProvider.java // public static Groovism provide() { // return new NoSemicolon(new NoClassKeyword(new RegularString(new NoPublicKeyword()))); // } // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/util/StringUtil.java // public static final String SEPARATOR = System.getProperty("line.separator"); // // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/util/StringUtil.java // public static String indentation(int indentationInTabs) { // return IntStream.rangeClosed(1, indentationInTabs).mapToObj(__ -> "\t").reduce("", (a, b) -> a + b); // } // Path: src/main/java/com/github/opaluchlukasz/junit2spock/core/node/wrapper/BaseWrapper.java import com.github.opaluchlukasz.junit2spock.core.Applicable; import com.github.opaluchlukasz.junit2spock.core.groovism.Groovism; import java.util.function.Consumer; import static com.github.opaluchlukasz.junit2spock.core.groovism.GroovismChainProvider.provide; import static com.github.opaluchlukasz.junit2spock.core.util.StringUtil.SEPARATOR; import static com.github.opaluchlukasz.junit2spock.core.util.StringUtil.indentation; package com.github.opaluchlukasz.junit2spock.core.node.wrapper; public class BaseWrapper { private final int indentationLevel; private final Applicable applicable; private final Groovism groovism; BaseWrapper(int indentationLevel, Applicable applicable) { this.indentationLevel = indentationLevel; this.applicable = applicable; this.groovism = provide(); } int indentationLevel() { return indentationLevel; } protected Applicable applicable() { return applicable; } Consumer printStatement(StringBuilder builder) { return stmt -> { if (stmt instanceof BaseWrapper) { builder.append(stmt.toString()); } else { builder.append(indentation(indentationLevel + 2)).append(groovism.apply(stmt.toString())); if (!stmt.toString().endsWith("\n")) {
builder.append(SEPARATOR);
bitsoex/bitso-java
src/main/java/com/bitso/websockets/BitsoWebSocket.java
// Path: src/main/java/com/bitso/exceptions/BitsoWebSocketException.java // public class BitsoWebSocketException extends RuntimeException{ // private static final long serialVersionUID = 1L; // // public BitsoWebSocketException(String message) { // super(message); // } // }
import java.net.URI; import java.net.URISyntaxException; import java.util.Observable; import javax.net.ssl.SSLException; import com.bitso.exceptions.BitsoWebSocketException; import io.netty.bootstrap.Bootstrap; import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelPipeline; import io.netty.channel.ChannelPromise; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.handler.codec.http.DefaultHttpHeaders; import io.netty.handler.codec.http.FullHttpResponse; import io.netty.handler.codec.http.HttpClientCodec; import io.netty.handler.codec.http.HttpObjectAggregator; import io.netty.handler.codec.http.websocketx.CloseWebSocketFrame; import io.netty.handler.codec.http.websocketx.TextWebSocketFrame; import io.netty.handler.codec.http.websocketx.WebSocketClientHandshaker; import io.netty.handler.codec.http.websocketx.WebSocketClientHandshakerFactory; import io.netty.handler.codec.http.websocketx.WebSocketFrame; import io.netty.handler.codec.http.websocketx.WebSocketVersion; import io.netty.handler.ssl.SslContext; import io.netty.handler.ssl.SslContextBuilder; import io.netty.handler.ssl.util.InsecureTrustManagerFactory; import io.netty.util.CharsetUtil;
bootstrap.group(mGroup) .channel(NioSocketChannel.class) .handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel socketChannel){ ChannelPipeline channelPipeline = socketChannel.pipeline(); channelPipeline.addLast(mSslContext.newHandler( socketChannel.alloc(), mUri.getHost(), PORT)); channelPipeline.addLast(new HttpClientCodec(), new HttpObjectAggregator(8192), handler); } }); mChannel = bootstrap.connect(mUri.getHost(), PORT).sync().channel(); handler.handshakeFuture().sync(); setConnected(Boolean.TRUE); } public void subscribeBitsoChannel(String channel){ if(mConnected){ String frameMessage = "{ \"action\": \"subscribe\", \"book\": \"btc_mxn\", \"type\": \"" + channel + "\" }"; mChannel.writeAndFlush(new TextWebSocketFrame(frameMessage)); }else{ String message = "Subscription to any channel is not possible while web socket is not connected";
// Path: src/main/java/com/bitso/exceptions/BitsoWebSocketException.java // public class BitsoWebSocketException extends RuntimeException{ // private static final long serialVersionUID = 1L; // // public BitsoWebSocketException(String message) { // super(message); // } // } // Path: src/main/java/com/bitso/websockets/BitsoWebSocket.java import java.net.URI; import java.net.URISyntaxException; import java.util.Observable; import javax.net.ssl.SSLException; import com.bitso.exceptions.BitsoWebSocketException; import io.netty.bootstrap.Bootstrap; import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelPipeline; import io.netty.channel.ChannelPromise; import io.netty.channel.EventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.handler.codec.http.DefaultHttpHeaders; import io.netty.handler.codec.http.FullHttpResponse; import io.netty.handler.codec.http.HttpClientCodec; import io.netty.handler.codec.http.HttpObjectAggregator; import io.netty.handler.codec.http.websocketx.CloseWebSocketFrame; import io.netty.handler.codec.http.websocketx.TextWebSocketFrame; import io.netty.handler.codec.http.websocketx.WebSocketClientHandshaker; import io.netty.handler.codec.http.websocketx.WebSocketClientHandshakerFactory; import io.netty.handler.codec.http.websocketx.WebSocketFrame; import io.netty.handler.codec.http.websocketx.WebSocketVersion; import io.netty.handler.ssl.SslContext; import io.netty.handler.ssl.SslContextBuilder; import io.netty.handler.ssl.util.InsecureTrustManagerFactory; import io.netty.util.CharsetUtil; bootstrap.group(mGroup) .channel(NioSocketChannel.class) .handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel socketChannel){ ChannelPipeline channelPipeline = socketChannel.pipeline(); channelPipeline.addLast(mSslContext.newHandler( socketChannel.alloc(), mUri.getHost(), PORT)); channelPipeline.addLast(new HttpClientCodec(), new HttpObjectAggregator(8192), handler); } }); mChannel = bootstrap.connect(mUri.getHost(), PORT).sync().channel(); handler.handshakeFuture().sync(); setConnected(Boolean.TRUE); } public void subscribeBitsoChannel(String channel){ if(mConnected){ String frameMessage = "{ \"action\": \"subscribe\", \"book\": \"btc_mxn\", \"type\": \"" + channel + "\" }"; mChannel.writeAndFlush(new TextWebSocketFrame(frameMessage)); }else{ String message = "Subscription to any channel is not possible while web socket is not connected";
throw new BitsoWebSocketException(message);
soarcn/COCO-Accessory
adapter/src/main/java/com/cocosw/adapter/recyclerview/SectionSingleTypeAdapter.java
// Path: adapter/src/main/java/com/cocosw/adapter/SectionFinder.java // public class SectionFinder implements SectionIndexer { // // private final Set<Object> sections = new LinkedHashSet<Object>(); // // private final SparseIntArray sectionPositions = new SparseIntArray(); // // private final SparseIntArray itemSections = new SparseIntArray(); // // private int index = 0; // // /** // * Clear all sections // * // * @return this finder // */ // public SectionFinder clear() { // sections.clear(); // sectionPositions.clear(); // itemSections.clear(); // index = 0; // return this; // } // // /** // * Get section for item // * <p/> // * The default behavior is to use the first character from the item's // * {@link #toString()} method // * // * @param item // * @return section // */ // protected Object getSection(final Object item) { // final String string = item.toString(); // if (!TextUtils.isEmpty(string)) // return Character.toUpperCase(string.charAt(0)); // else // return '?'; // } // // private void addSection(Object section) { // int count = sections.size(); // if (sections.add(section)) // sectionPositions.put(count, index); // } // // private void addItem(Object item) { // itemSections.put(index, sections.size()); // index++; // } // // /** // * Index items by section returned from {@link #getSection(Object)} // * // * @param items // * @return this finder // */ // public SectionFinder index(Object... items) { // for (Object item : items) { // addSection(getSection(item)); // addItem(item); // } // return this; // } // // /** // * Add items to given section // * // * @param section // * @param items // * @return this finder // */ // public SectionFinder add(final Object section, final Object... items) { // addSection(section); // for (Object item : items) // addItem(item); // return this; // } // // public int getPositionForSection(final int section) { // return sectionPositions.get(section); // } // // public int getSectionForPosition(final int position) { // return itemSections.get(position); // } // // public Object[] getSections() { // return sections.toArray(); // } // }
import android.app.Activity; import android.content.Context; import android.view.LayoutInflater; import android.widget.SectionIndexer; import com.cocosw.adapter.SectionFinder;
/* * Copyright 2012 Kevin Sawicki <kevinsawicki@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.cocosw.adapter.recyclerview; /** * @param <V> */ public abstract class SectionSingleTypeAdapter<V> extends SingleTypeAdapter<V> implements SectionIndexer {
// Path: adapter/src/main/java/com/cocosw/adapter/SectionFinder.java // public class SectionFinder implements SectionIndexer { // // private final Set<Object> sections = new LinkedHashSet<Object>(); // // private final SparseIntArray sectionPositions = new SparseIntArray(); // // private final SparseIntArray itemSections = new SparseIntArray(); // // private int index = 0; // // /** // * Clear all sections // * // * @return this finder // */ // public SectionFinder clear() { // sections.clear(); // sectionPositions.clear(); // itemSections.clear(); // index = 0; // return this; // } // // /** // * Get section for item // * <p/> // * The default behavior is to use the first character from the item's // * {@link #toString()} method // * // * @param item // * @return section // */ // protected Object getSection(final Object item) { // final String string = item.toString(); // if (!TextUtils.isEmpty(string)) // return Character.toUpperCase(string.charAt(0)); // else // return '?'; // } // // private void addSection(Object section) { // int count = sections.size(); // if (sections.add(section)) // sectionPositions.put(count, index); // } // // private void addItem(Object item) { // itemSections.put(index, sections.size()); // index++; // } // // /** // * Index items by section returned from {@link #getSection(Object)} // * // * @param items // * @return this finder // */ // public SectionFinder index(Object... items) { // for (Object item : items) { // addSection(getSection(item)); // addItem(item); // } // return this; // } // // /** // * Add items to given section // * // * @param section // * @param items // * @return this finder // */ // public SectionFinder add(final Object section, final Object... items) { // addSection(section); // for (Object item : items) // addItem(item); // return this; // } // // public int getPositionForSection(final int section) { // return sectionPositions.get(section); // } // // public int getSectionForPosition(final int position) { // return itemSections.get(position); // } // // public Object[] getSections() { // return sections.toArray(); // } // } // Path: adapter/src/main/java/com/cocosw/adapter/recyclerview/SectionSingleTypeAdapter.java import android.app.Activity; import android.content.Context; import android.view.LayoutInflater; import android.widget.SectionIndexer; import com.cocosw.adapter.SectionFinder; /* * Copyright 2012 Kevin Sawicki <kevinsawicki@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.cocosw.adapter.recyclerview; /** * @param <V> */ public abstract class SectionSingleTypeAdapter<V> extends SingleTypeAdapter<V> implements SectionIndexer {
private final SectionFinder sections = new SectionFinder();
soarcn/COCO-Accessory
adapter/src/main/java/com/cocosw/adapter/recyclerview/SectionMultiTypeAdapter.java
// Path: adapter/src/main/java/com/cocosw/adapter/SectionFinder.java // public class SectionFinder implements SectionIndexer { // // private final Set<Object> sections = new LinkedHashSet<Object>(); // // private final SparseIntArray sectionPositions = new SparseIntArray(); // // private final SparseIntArray itemSections = new SparseIntArray(); // // private int index = 0; // // /** // * Clear all sections // * // * @return this finder // */ // public SectionFinder clear() { // sections.clear(); // sectionPositions.clear(); // itemSections.clear(); // index = 0; // return this; // } // // /** // * Get section for item // * <p/> // * The default behavior is to use the first character from the item's // * {@link #toString()} method // * // * @param item // * @return section // */ // protected Object getSection(final Object item) { // final String string = item.toString(); // if (!TextUtils.isEmpty(string)) // return Character.toUpperCase(string.charAt(0)); // else // return '?'; // } // // private void addSection(Object section) { // int count = sections.size(); // if (sections.add(section)) // sectionPositions.put(count, index); // } // // private void addItem(Object item) { // itemSections.put(index, sections.size()); // index++; // } // // /** // * Index items by section returned from {@link #getSection(Object)} // * // * @param items // * @return this finder // */ // public SectionFinder index(Object... items) { // for (Object item : items) { // addSection(getSection(item)); // addItem(item); // } // return this; // } // // /** // * Add items to given section // * // * @param section // * @param items // * @return this finder // */ // public SectionFinder add(final Object section, final Object... items) { // addSection(section); // for (Object item : items) // addItem(item); // return this; // } // // public int getPositionForSection(final int section) { // return sectionPositions.get(section); // } // // public int getSectionForPosition(final int position) { // return itemSections.get(position); // } // // public Object[] getSections() { // return sections.toArray(); // } // }
import android.app.Activity; import android.content.Context; import android.view.LayoutInflater; import android.widget.SectionIndexer; import com.cocosw.adapter.SectionFinder;
/* * Copyright 2012 Kevin Sawicki <kevinsawicki@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.cocosw.adapter.recyclerview; /** * Type adapter with section indexing according to English alphabet */ public abstract class SectionMultiTypeAdapter<V> extends MultiTypeAdapter<V> implements SectionIndexer {
// Path: adapter/src/main/java/com/cocosw/adapter/SectionFinder.java // public class SectionFinder implements SectionIndexer { // // private final Set<Object> sections = new LinkedHashSet<Object>(); // // private final SparseIntArray sectionPositions = new SparseIntArray(); // // private final SparseIntArray itemSections = new SparseIntArray(); // // private int index = 0; // // /** // * Clear all sections // * // * @return this finder // */ // public SectionFinder clear() { // sections.clear(); // sectionPositions.clear(); // itemSections.clear(); // index = 0; // return this; // } // // /** // * Get section for item // * <p/> // * The default behavior is to use the first character from the item's // * {@link #toString()} method // * // * @param item // * @return section // */ // protected Object getSection(final Object item) { // final String string = item.toString(); // if (!TextUtils.isEmpty(string)) // return Character.toUpperCase(string.charAt(0)); // else // return '?'; // } // // private void addSection(Object section) { // int count = sections.size(); // if (sections.add(section)) // sectionPositions.put(count, index); // } // // private void addItem(Object item) { // itemSections.put(index, sections.size()); // index++; // } // // /** // * Index items by section returned from {@link #getSection(Object)} // * // * @param items // * @return this finder // */ // public SectionFinder index(Object... items) { // for (Object item : items) { // addSection(getSection(item)); // addItem(item); // } // return this; // } // // /** // * Add items to given section // * // * @param section // * @param items // * @return this finder // */ // public SectionFinder add(final Object section, final Object... items) { // addSection(section); // for (Object item : items) // addItem(item); // return this; // } // // public int getPositionForSection(final int section) { // return sectionPositions.get(section); // } // // public int getSectionForPosition(final int position) { // return itemSections.get(position); // } // // public Object[] getSections() { // return sections.toArray(); // } // } // Path: adapter/src/main/java/com/cocosw/adapter/recyclerview/SectionMultiTypeAdapter.java import android.app.Activity; import android.content.Context; import android.view.LayoutInflater; import android.widget.SectionIndexer; import com.cocosw.adapter.SectionFinder; /* * Copyright 2012 Kevin Sawicki <kevinsawicki@gmail.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.cocosw.adapter.recyclerview; /** * Type adapter with section indexing according to English alphabet */ public abstract class SectionMultiTypeAdapter<V> extends MultiTypeAdapter<V> implements SectionIndexer {
private final SectionFinder sections = new SectionFinder();
soarcn/COCO-Accessory
utils/src/main/java/com/cocosw/accessory/utils/PackageUtils.java
// Path: utils/src/main/java/com/cocosw/accessory/utils/ShellUtils.java // public static class CommandResult { // // /** // * result of command * // */ // public int result; // /** // * success message of command result * // */ // public String successMsg; // /** // * error message of command result * // */ // public String errorMsg; // // public CommandResult(int result) { // this.result = result; // } // // public CommandResult(int result, String successMsg, String errorMsg) { // this.result = result; // this.successMsg = successMsg; // this.errorMsg = errorMsg; // } // }
import android.app.ActivityManager; import android.content.Context; import android.content.Intent; import android.content.pm.ApplicationInfo; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.provider.Settings; import android.text.TextUtils; import android.util.Log; import java.io.File; import java.util.List; import static com.cocosw.accessory.utils.ShellUtils.CommandResult;
* install package silent by root * <ul> * <strong>Attentions:</strong> * <li>Don't call this on the ui thread, it may costs some times.</li> * <li>You should add <strong>android.permission.INSTALL_PACKAGES</strong> in manifest, so no need to request root * permission, if you are system app.</li> * </ul> * * @param context * @param filePath file path of package * @param pmParams pm install params * @return {@link PackageUtils#INSTALL_SUCCEEDED} means install success, other means failed. details see * {@link PackageUtils}.INSTALL_FAILED_*. same to {@link PackageManager}.INSTALL_* */ public static int installSilent(Context context, String filePath, String pmParams) { if (filePath == null || filePath.length() == 0) { return INSTALL_FAILED_INVALID_URI; } File file = new File(filePath); if (file == null || file.length() <= 0 || !file.exists() || !file.isFile()) { return INSTALL_FAILED_INVALID_URI; } /** * if context is system app, don't need root permission, but should add <uses-permission * android:name="android.permission.INSTALL_PACKAGES" /> in mainfest **/ StringBuilder command = new StringBuilder().append("LD_LIBRARY_PATH=/vendor/lib:/system/lib pm install ") .append(pmParams == null ? "" : pmParams).append(" ").append(filePath.replace(" ", "\\ "));
// Path: utils/src/main/java/com/cocosw/accessory/utils/ShellUtils.java // public static class CommandResult { // // /** // * result of command * // */ // public int result; // /** // * success message of command result * // */ // public String successMsg; // /** // * error message of command result * // */ // public String errorMsg; // // public CommandResult(int result) { // this.result = result; // } // // public CommandResult(int result, String successMsg, String errorMsg) { // this.result = result; // this.successMsg = successMsg; // this.errorMsg = errorMsg; // } // } // Path: utils/src/main/java/com/cocosw/accessory/utils/PackageUtils.java import android.app.ActivityManager; import android.content.Context; import android.content.Intent; import android.content.pm.ApplicationInfo; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.provider.Settings; import android.text.TextUtils; import android.util.Log; import java.io.File; import java.util.List; import static com.cocosw.accessory.utils.ShellUtils.CommandResult; * install package silent by root * <ul> * <strong>Attentions:</strong> * <li>Don't call this on the ui thread, it may costs some times.</li> * <li>You should add <strong>android.permission.INSTALL_PACKAGES</strong> in manifest, so no need to request root * permission, if you are system app.</li> * </ul> * * @param context * @param filePath file path of package * @param pmParams pm install params * @return {@link PackageUtils#INSTALL_SUCCEEDED} means install success, other means failed. details see * {@link PackageUtils}.INSTALL_FAILED_*. same to {@link PackageManager}.INSTALL_* */ public static int installSilent(Context context, String filePath, String pmParams) { if (filePath == null || filePath.length() == 0) { return INSTALL_FAILED_INVALID_URI; } File file = new File(filePath); if (file == null || file.length() <= 0 || !file.exists() || !file.isFile()) { return INSTALL_FAILED_INVALID_URI; } /** * if context is system app, don't need root permission, but should add <uses-permission * android:name="android.permission.INSTALL_PACKAGES" /> in mainfest **/ StringBuilder command = new StringBuilder().append("LD_LIBRARY_PATH=/vendor/lib:/system/lib pm install ") .append(pmParams == null ? "" : pmParams).append(" ").append(filePath.replace(" ", "\\ "));
CommandResult commandResult = ShellUtils.execCommand(command.toString(), !isSystemApplication(context), true);
janotav/ali-idea-plugin
ali-plugin-main/src/test/java/com/hp/alm/ali/idea/IntellijTest.java
// Path: ali-plugin-main/src/main/java/com/hp/alm/ali/idea/services/MetadataService.java // public class MetadataService extends AbstractCachingService<String, Metadata, AbstractCachingService.Callback<Metadata>> { // // private Project project; // private MetadataSimpleService metadataService; // private RestService restService; // // public MetadataService(Project project, MetadataSimpleService metadataService, RestService restService) { // super(project); // this.project = project; // this.metadataService = metadataService; // this.restService = restService; // } // // public Metadata getEntityMetadata(String entityName) { // return getValue(entityName); // } // // public void loadEntityMetadataAsync(String entityName, MetadataCallback callback) { // getValueAsync(entityName, Proxy.create(callback)); // } // // @Override // protected Metadata doGetValue(String entityName) { // LinkedList<String> list = new LinkedList<String>(); // list.add(entityName); // list.addAll(restService.getServerStrategy().getCompoundEntityTypes(entityName)); // // Metadata result = new Metadata(project, entityName, false); // // for(String entityType: list) { // make the requests run in parallel if necessary // metadataService.getEntityMetadataAsync(entityType, null); // } // for(String entityType: list) { // collect the results // Metadata metadata = metadataService.getEntityMetadata(entityType); // result.add(metadata); // } // // restService.getServerStrategy().fixMetadata(result); // // return result; // } // // public Metadata getCachedEntityMetadata(String entityType) { // return getCachedValue(entityType); // } // // public Exception getCachedFailure(String entityType) { // return super.getCachedFailure(entityType); // } // // public static class Proxy implements Callback<Metadata>, FailureCallback { // // private MetadataCallback callback; // // public static Proxy create(MetadataCallback callback) { // if(callback instanceof DispatchMetadataCallback) { // return new DispatchProxy(callback); // } else { // return new Proxy(callback); // } // } // // private Proxy(MetadataCallback callback) { // this.callback = callback; // } // // @Override // public void loaded(Metadata data) { // if(callback != null) { // callback.metadataLoaded(data); // } // } // // @Override // public void failed() { // if(callback != null) { // callback.metadataFailed(); // } // } // } // // public static class DispatchProxy extends Proxy implements DispatchCallback<Metadata> { // // private DispatchProxy(MetadataCallback callback) { // super(callback); // } // } // // public static interface MetadataCallback { // // void metadataLoaded(Metadata metadata); // // void metadataFailed(); // // } // // public static interface DispatchMetadataCallback extends MetadataCallback { // // // callback to be executed in the context of the dispatching thread // // } // }
import com.hp.alm.ali.Handler; import com.hp.alm.ali.Isolated; import com.hp.alm.ali.ServerVersion; import com.hp.alm.ali.idea.entity.EntityListener; import com.hp.alm.ali.idea.rest.RestException; import com.hp.alm.ali.idea.rest.ServerType; import com.hp.alm.ali.idea.services.EntityService; import com.hp.alm.ali.idea.services.ErrorService; import com.hp.alm.ali.idea.services.MetadataService; import com.hp.alm.ali.idea.services.MetadataSimpleService; import com.hp.alm.ali.idea.services.TestMessages; import com.hp.alm.ali.idea.util.ApplicationUtil; import com.hp.alm.ali.idea.util.DetailUtil; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.ui.TestDialog; import com.intellij.testFramework.fixtures.IdeaProjectTestFixture; import org.junit.After; import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.rules.TestWatcher; import org.junit.runner.Description; import java.util.LinkedList; import java.util.List;
/* * Copyright 2013 Hewlett-Packard Development Company, L.P * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hp.alm.ali.idea; /** * To override the default Intellij logging configuration you need to: * * <pre> * $ cd IDEA_HOME * $ copy bin/log.xml test-log.xml * </pre> * * and edit test-log.xml to your liking. */ public abstract class IntellijTest { protected Handler handler; protected IdeaProjectTestFixture fixture; protected ServerVersion version; protected ErrorService errorService; protected EntityService entityService; private List<EntityListener> entityListeners; public IntellijTest(ServerVersion version) { this.version = version; } @Rule public TestName name = new TestName(); @Rule public TestFailure failure = new TestFailure(); protected TestMessages testMessages; protected TestApplication testApplication; @Before public void reset() throws Exception { if(isIsolated()) { fixture = FixtureFactory.createFixture(version); handler = FixtureFactory.createHandler(version, fixture); } else { fixture = FixtureFactory.ensureFixture(version); handler = FixtureFactory.ensureHandler(version, fixture); handler.clear(); } errorService = getComponent(ErrorService.class); entityService = getComponent(EntityService.class); entityListeners = new LinkedList<EntityListener>();
// Path: ali-plugin-main/src/main/java/com/hp/alm/ali/idea/services/MetadataService.java // public class MetadataService extends AbstractCachingService<String, Metadata, AbstractCachingService.Callback<Metadata>> { // // private Project project; // private MetadataSimpleService metadataService; // private RestService restService; // // public MetadataService(Project project, MetadataSimpleService metadataService, RestService restService) { // super(project); // this.project = project; // this.metadataService = metadataService; // this.restService = restService; // } // // public Metadata getEntityMetadata(String entityName) { // return getValue(entityName); // } // // public void loadEntityMetadataAsync(String entityName, MetadataCallback callback) { // getValueAsync(entityName, Proxy.create(callback)); // } // // @Override // protected Metadata doGetValue(String entityName) { // LinkedList<String> list = new LinkedList<String>(); // list.add(entityName); // list.addAll(restService.getServerStrategy().getCompoundEntityTypes(entityName)); // // Metadata result = new Metadata(project, entityName, false); // // for(String entityType: list) { // make the requests run in parallel if necessary // metadataService.getEntityMetadataAsync(entityType, null); // } // for(String entityType: list) { // collect the results // Metadata metadata = metadataService.getEntityMetadata(entityType); // result.add(metadata); // } // // restService.getServerStrategy().fixMetadata(result); // // return result; // } // // public Metadata getCachedEntityMetadata(String entityType) { // return getCachedValue(entityType); // } // // public Exception getCachedFailure(String entityType) { // return super.getCachedFailure(entityType); // } // // public static class Proxy implements Callback<Metadata>, FailureCallback { // // private MetadataCallback callback; // // public static Proxy create(MetadataCallback callback) { // if(callback instanceof DispatchMetadataCallback) { // return new DispatchProxy(callback); // } else { // return new Proxy(callback); // } // } // // private Proxy(MetadataCallback callback) { // this.callback = callback; // } // // @Override // public void loaded(Metadata data) { // if(callback != null) { // callback.metadataLoaded(data); // } // } // // @Override // public void failed() { // if(callback != null) { // callback.metadataFailed(); // } // } // } // // public static class DispatchProxy extends Proxy implements DispatchCallback<Metadata> { // // private DispatchProxy(MetadataCallback callback) { // super(callback); // } // } // // public static interface MetadataCallback { // // void metadataLoaded(Metadata metadata); // // void metadataFailed(); // // } // // public static interface DispatchMetadataCallback extends MetadataCallback { // // // callback to be executed in the context of the dispatching thread // // } // } // Path: ali-plugin-main/src/test/java/com/hp/alm/ali/idea/IntellijTest.java import com.hp.alm.ali.Handler; import com.hp.alm.ali.Isolated; import com.hp.alm.ali.ServerVersion; import com.hp.alm.ali.idea.entity.EntityListener; import com.hp.alm.ali.idea.rest.RestException; import com.hp.alm.ali.idea.rest.ServerType; import com.hp.alm.ali.idea.services.EntityService; import com.hp.alm.ali.idea.services.ErrorService; import com.hp.alm.ali.idea.services.MetadataService; import com.hp.alm.ali.idea.services.MetadataSimpleService; import com.hp.alm.ali.idea.services.TestMessages; import com.hp.alm.ali.idea.util.ApplicationUtil; import com.hp.alm.ali.idea.util.DetailUtil; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.ui.TestDialog; import com.intellij.testFramework.fixtures.IdeaProjectTestFixture; import org.junit.After; import org.junit.AfterClass; import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.rules.TestWatcher; import org.junit.runner.Description; import java.util.LinkedList; import java.util.List; /* * Copyright 2013 Hewlett-Packard Development Company, L.P * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hp.alm.ali.idea; /** * To override the default Intellij logging configuration you need to: * * <pre> * $ cd IDEA_HOME * $ copy bin/log.xml test-log.xml * </pre> * * and edit test-log.xml to your liking. */ public abstract class IntellijTest { protected Handler handler; protected IdeaProjectTestFixture fixture; protected ServerVersion version; protected ErrorService errorService; protected EntityService entityService; private List<EntityListener> entityListeners; public IntellijTest(ServerVersion version) { this.version = version; } @Rule public TestName name = new TestName(); @Rule public TestFailure failure = new TestFailure(); protected TestMessages testMessages; protected TestApplication testApplication; @Before public void reset() throws Exception { if(isIsolated()) { fixture = FixtureFactory.createFixture(version); handler = FixtureFactory.createHandler(version, fixture); } else { fixture = FixtureFactory.ensureFixture(version); handler = FixtureFactory.ensureHandler(version, fixture); handler.clear(); } errorService = getComponent(ErrorService.class); entityService = getComponent(EntityService.class); entityListeners = new LinkedList<EntityListener>();
getComponent(MetadataService.class).connectedTo(ServerType.NONE);
janotav/ali-idea-plugin
ali-plugin-main/src/main/java/com/hp/alm/ali/idea/services/ProjectUserService.java
// Path: ali-plugin-main/src/main/java/com/hp/alm/ali/idea/model/User.java // public class User { // // private String username; // private String fullName; // // public User(String username, String fullName) { // this.username = username; // this.fullName = fullName; // } // // public String getUsername() { // return username; // } // // public String getFullName() { // return fullName; // } // }
import com.hp.alm.ali.idea.model.User; import com.hp.alm.ali.idea.model.parser.UserList; import com.hp.alm.ali.idea.rest.RestService; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Transform; import java.io.InputStream;
/* * Copyright 2013 Hewlett-Packard Development Company, L.P * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hp.alm.ali.idea.services; public class ProjectUserService extends AbstractCachingService<Integer, UserList, AbstractCachingService.Callback<UserList>> { private RestService restService; public ProjectUserService(Project project) { super(project); restService = project.getComponent(RestService.class); } public void loadUsersAsync(Callback<UserList> callback) { getValueAsync(1, callback); }
// Path: ali-plugin-main/src/main/java/com/hp/alm/ali/idea/model/User.java // public class User { // // private String username; // private String fullName; // // public User(String username, String fullName) { // this.username = username; // this.fullName = fullName; // } // // public String getUsername() { // return username; // } // // public String getFullName() { // return fullName; // } // } // Path: ali-plugin-main/src/main/java/com/hp/alm/ali/idea/services/ProjectUserService.java import com.hp.alm.ali.idea.model.User; import com.hp.alm.ali.idea.model.parser.UserList; import com.hp.alm.ali.idea.rest.RestService; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Transform; import java.io.InputStream; /* * Copyright 2013 Hewlett-Packard Development Company, L.P * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hp.alm.ali.idea.services; public class ProjectUserService extends AbstractCachingService<Integer, UserList, AbstractCachingService.Callback<UserList>> { private RestService restService; public ProjectUserService(Project project) { super(project); restService = project.getComponent(RestService.class); } public void loadUsersAsync(Callback<UserList> callback) { getValueAsync(1, callback); }
public User tryGetUser(String username) {
janotav/ali-idea-plugin
ali-plugin-main/src/main/java/com/hp/alm/ali/idea/model/type/UserType.java
// Path: ali-plugin-main/src/main/java/com/hp/alm/ali/idea/model/User.java // public class User { // // private String username; // private String fullName; // // public User(String username, String fullName) { // this.username = username; // this.fullName = fullName; // } // // public String getUsername() { // return username; // } // // public String getFullName() { // return fullName; // } // } // // Path: ali-plugin-main/src/main/java/com/hp/alm/ali/idea/services/ProjectUserService.java // public class ProjectUserService extends AbstractCachingService<Integer, UserList, AbstractCachingService.Callback<UserList>> { // private RestService restService; // // public ProjectUserService(Project project) { // super(project); // // restService = project.getComponent(RestService.class); // } // // public void loadUsersAsync(Callback<UserList> callback) { // getValueAsync(1, callback); // } // // public User tryGetUser(String username) { // UserList users = getCachedValue(1); // if(users != null) { // User user = users.getUser(username); // if(user == null) { // // avoid infinite loop if users loaded but username not found // return new User(username, username); // } // return user; // } else { // return null; // } // } // // public void loadUserAsync(final String username, final Callback<User> callback) { // loadUsersAsync(translate(callback, new Transform<UserList, User>() { // @Override // public User transform(UserList users) { // User user = users.getUser(username); // if(user == null) { // return new User(username, username); // } else { // return user; // } // } // })); // } // // public UserList getUserList() { // return getValue(1); // } // // public User getUser(String username) { // for(User user: getUserList()) { // if(user.getUsername().equals(username)) { // return user; // } // } // return null; // } // // public String getUserFullName(String username) { // User user = getUser(username); // if(user != null) { // return user.getFullName(); // } else { // return null; // } // } // // @Override // protected UserList doGetValue(Integer key) { // InputStream is = restService.getForStream("customization/users"); // return UserList.create(is); // } // }
import java.util.List; import com.hp.alm.ali.idea.filter.MultipleItemsChooserFactory; import com.hp.alm.ali.idea.model.ItemsProvider; import com.hp.alm.ali.idea.model.User; import com.hp.alm.ali.idea.translate.filter.MultipleItemsTranslatedResolver; import com.hp.alm.ali.idea.translate.Translator; import com.hp.alm.ali.idea.translate.ValueCallback; import com.hp.alm.ali.idea.services.AbstractCachingService; import com.hp.alm.ali.idea.services.ProjectUserService; import com.hp.alm.ali.idea.filter.FilterFactory; import com.hp.alm.ali.idea.translate.filter.FilterResolver; import com.hp.alm.ali.idea.ui.ComboItem; import com.intellij.openapi.project.Project; import java.util.ArrayList;
/* * Copyright 2013 Hewlett-Packard Development Company, L.P * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hp.alm.ali.idea.model.type; public class UserType implements Type, Translator, FilterResolver { private Project project;
// Path: ali-plugin-main/src/main/java/com/hp/alm/ali/idea/model/User.java // public class User { // // private String username; // private String fullName; // // public User(String username, String fullName) { // this.username = username; // this.fullName = fullName; // } // // public String getUsername() { // return username; // } // // public String getFullName() { // return fullName; // } // } // // Path: ali-plugin-main/src/main/java/com/hp/alm/ali/idea/services/ProjectUserService.java // public class ProjectUserService extends AbstractCachingService<Integer, UserList, AbstractCachingService.Callback<UserList>> { // private RestService restService; // // public ProjectUserService(Project project) { // super(project); // // restService = project.getComponent(RestService.class); // } // // public void loadUsersAsync(Callback<UserList> callback) { // getValueAsync(1, callback); // } // // public User tryGetUser(String username) { // UserList users = getCachedValue(1); // if(users != null) { // User user = users.getUser(username); // if(user == null) { // // avoid infinite loop if users loaded but username not found // return new User(username, username); // } // return user; // } else { // return null; // } // } // // public void loadUserAsync(final String username, final Callback<User> callback) { // loadUsersAsync(translate(callback, new Transform<UserList, User>() { // @Override // public User transform(UserList users) { // User user = users.getUser(username); // if(user == null) { // return new User(username, username); // } else { // return user; // } // } // })); // } // // public UserList getUserList() { // return getValue(1); // } // // public User getUser(String username) { // for(User user: getUserList()) { // if(user.getUsername().equals(username)) { // return user; // } // } // return null; // } // // public String getUserFullName(String username) { // User user = getUser(username); // if(user != null) { // return user.getFullName(); // } else { // return null; // } // } // // @Override // protected UserList doGetValue(Integer key) { // InputStream is = restService.getForStream("customization/users"); // return UserList.create(is); // } // } // Path: ali-plugin-main/src/main/java/com/hp/alm/ali/idea/model/type/UserType.java import java.util.List; import com.hp.alm.ali.idea.filter.MultipleItemsChooserFactory; import com.hp.alm.ali.idea.model.ItemsProvider; import com.hp.alm.ali.idea.model.User; import com.hp.alm.ali.idea.translate.filter.MultipleItemsTranslatedResolver; import com.hp.alm.ali.idea.translate.Translator; import com.hp.alm.ali.idea.translate.ValueCallback; import com.hp.alm.ali.idea.services.AbstractCachingService; import com.hp.alm.ali.idea.services.ProjectUserService; import com.hp.alm.ali.idea.filter.FilterFactory; import com.hp.alm.ali.idea.translate.filter.FilterResolver; import com.hp.alm.ali.idea.ui.ComboItem; import com.intellij.openapi.project.Project; import java.util.ArrayList; /* * Copyright 2013 Hewlett-Packard Development Company, L.P * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hp.alm.ali.idea.model.type; public class UserType implements Type, Translator, FilterResolver { private Project project;
private ProjectUserService projectUserService;
janotav/ali-idea-plugin
ali-plugin-main/src/main/java/com/hp/alm/ali/idea/model/type/UserType.java
// Path: ali-plugin-main/src/main/java/com/hp/alm/ali/idea/model/User.java // public class User { // // private String username; // private String fullName; // // public User(String username, String fullName) { // this.username = username; // this.fullName = fullName; // } // // public String getUsername() { // return username; // } // // public String getFullName() { // return fullName; // } // } // // Path: ali-plugin-main/src/main/java/com/hp/alm/ali/idea/services/ProjectUserService.java // public class ProjectUserService extends AbstractCachingService<Integer, UserList, AbstractCachingService.Callback<UserList>> { // private RestService restService; // // public ProjectUserService(Project project) { // super(project); // // restService = project.getComponent(RestService.class); // } // // public void loadUsersAsync(Callback<UserList> callback) { // getValueAsync(1, callback); // } // // public User tryGetUser(String username) { // UserList users = getCachedValue(1); // if(users != null) { // User user = users.getUser(username); // if(user == null) { // // avoid infinite loop if users loaded but username not found // return new User(username, username); // } // return user; // } else { // return null; // } // } // // public void loadUserAsync(final String username, final Callback<User> callback) { // loadUsersAsync(translate(callback, new Transform<UserList, User>() { // @Override // public User transform(UserList users) { // User user = users.getUser(username); // if(user == null) { // return new User(username, username); // } else { // return user; // } // } // })); // } // // public UserList getUserList() { // return getValue(1); // } // // public User getUser(String username) { // for(User user: getUserList()) { // if(user.getUsername().equals(username)) { // return user; // } // } // return null; // } // // public String getUserFullName(String username) { // User user = getUser(username); // if(user != null) { // return user.getFullName(); // } else { // return null; // } // } // // @Override // protected UserList doGetValue(Integer key) { // InputStream is = restService.getForStream("customization/users"); // return UserList.create(is); // } // }
import java.util.List; import com.hp.alm.ali.idea.filter.MultipleItemsChooserFactory; import com.hp.alm.ali.idea.model.ItemsProvider; import com.hp.alm.ali.idea.model.User; import com.hp.alm.ali.idea.translate.filter.MultipleItemsTranslatedResolver; import com.hp.alm.ali.idea.translate.Translator; import com.hp.alm.ali.idea.translate.ValueCallback; import com.hp.alm.ali.idea.services.AbstractCachingService; import com.hp.alm.ali.idea.services.ProjectUserService; import com.hp.alm.ali.idea.filter.FilterFactory; import com.hp.alm.ali.idea.translate.filter.FilterResolver; import com.hp.alm.ali.idea.ui.ComboItem; import com.intellij.openapi.project.Project; import java.util.ArrayList;
/* * Copyright 2013 Hewlett-Packard Development Company, L.P * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hp.alm.ali.idea.model.type; public class UserType implements Type, Translator, FilterResolver { private Project project; private ProjectUserService projectUserService; public UserType(Project project, ProjectUserService projectUserService) { this.project = project; this.projectUserService = projectUserService; } @Override public FilterFactory getFilterFactory(final boolean multiple) {
// Path: ali-plugin-main/src/main/java/com/hp/alm/ali/idea/model/User.java // public class User { // // private String username; // private String fullName; // // public User(String username, String fullName) { // this.username = username; // this.fullName = fullName; // } // // public String getUsername() { // return username; // } // // public String getFullName() { // return fullName; // } // } // // Path: ali-plugin-main/src/main/java/com/hp/alm/ali/idea/services/ProjectUserService.java // public class ProjectUserService extends AbstractCachingService<Integer, UserList, AbstractCachingService.Callback<UserList>> { // private RestService restService; // // public ProjectUserService(Project project) { // super(project); // // restService = project.getComponent(RestService.class); // } // // public void loadUsersAsync(Callback<UserList> callback) { // getValueAsync(1, callback); // } // // public User tryGetUser(String username) { // UserList users = getCachedValue(1); // if(users != null) { // User user = users.getUser(username); // if(user == null) { // // avoid infinite loop if users loaded but username not found // return new User(username, username); // } // return user; // } else { // return null; // } // } // // public void loadUserAsync(final String username, final Callback<User> callback) { // loadUsersAsync(translate(callback, new Transform<UserList, User>() { // @Override // public User transform(UserList users) { // User user = users.getUser(username); // if(user == null) { // return new User(username, username); // } else { // return user; // } // } // })); // } // // public UserList getUserList() { // return getValue(1); // } // // public User getUser(String username) { // for(User user: getUserList()) { // if(user.getUsername().equals(username)) { // return user; // } // } // return null; // } // // public String getUserFullName(String username) { // User user = getUser(username); // if(user != null) { // return user.getFullName(); // } else { // return null; // } // } // // @Override // protected UserList doGetValue(Integer key) { // InputStream is = restService.getForStream("customization/users"); // return UserList.create(is); // } // } // Path: ali-plugin-main/src/main/java/com/hp/alm/ali/idea/model/type/UserType.java import java.util.List; import com.hp.alm.ali.idea.filter.MultipleItemsChooserFactory; import com.hp.alm.ali.idea.model.ItemsProvider; import com.hp.alm.ali.idea.model.User; import com.hp.alm.ali.idea.translate.filter.MultipleItemsTranslatedResolver; import com.hp.alm.ali.idea.translate.Translator; import com.hp.alm.ali.idea.translate.ValueCallback; import com.hp.alm.ali.idea.services.AbstractCachingService; import com.hp.alm.ali.idea.services.ProjectUserService; import com.hp.alm.ali.idea.filter.FilterFactory; import com.hp.alm.ali.idea.translate.filter.FilterResolver; import com.hp.alm.ali.idea.ui.ComboItem; import com.intellij.openapi.project.Project; import java.util.ArrayList; /* * Copyright 2013 Hewlett-Packard Development Company, L.P * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hp.alm.ali.idea.model.type; public class UserType implements Type, Translator, FilterResolver { private Project project; private ProjectUserService projectUserService; public UserType(Project project, ProjectUserService projectUserService) { this.project = project; this.projectUserService = projectUserService; } @Override public FilterFactory getFilterFactory(final boolean multiple) {
return new MultipleItemsChooserFactory(project, "User", multiple, new ItemsProvider.Loader<ComboItem>() {
saoj/mentabean
src/main/java/org/mentabean/util/DefaultProxy.java
// Path: src/main/java/org/mentabean/BeanException.java // public class BeanException extends RuntimeException { // // private static final long serialVersionUID = -6402197033079197979L; // // protected final Throwable rootCause; // // public BeanException() { // super(); // this.rootCause = null; // } // // public BeanException(Throwable e) { // super(getMsg(e), e); // Throwable root = getRootCause(e); // this.setStackTrace(root.getStackTrace()); // // this.rootCause = root == this ? null : root; // } // // public BeanException(String msg) { // super(msg); // // this.rootCause = null; // } // // public BeanException(String msg, Throwable e) { // // super(msg, e); // Throwable root = getRootCause(e); // this.setStackTrace(root.getStackTrace()); // // this.rootCause = root == this ? null : root; // } // // private static String getMsg(Throwable t) { // // Throwable root = getRootCause(t); // // String msg = root.getMessage(); // // if (msg == null || msg.length() == 0) { // // msg = t.getMessage(); // // if (msg == null || msg.length() == 0) { // return root.getClass().getName(); // } // } // // return msg; // } // // private static Throwable getRootCause(Throwable t) { // // Throwable root = t.getCause(); // // if (root == null) { // return t; // } // // while (root.getCause() != null) { // // root = root.getCause(); // } // // return root; // // } // // @Override // public Throwable getCause() { // // return rootCause; // } // }
import java.lang.reflect.Method; import javassist.util.proxy.MethodFilter; import javassist.util.proxy.MethodHandler; import javassist.util.proxy.ProxyFactory; import org.mentabean.BeanException;
package org.mentabean.util; public class DefaultProxy extends PropertiesProxy { public DefaultProxy(String chainProp) { super(chainProp); } public DefaultProxy() { super(null); } @SuppressWarnings("unchecked") @Override protected <E> E createInternal(final Class<E> klass) { try { ProxyFactory factory = new ProxyFactory(); factory.setSuperclass(klass); factory.setFilter(new MethodFilter() { @Override public boolean isHandled(Method m) { return getPropName(m) != null; } }); MethodHandler handler = new MethodHandler() { @Override public Object invoke(Object self, Method thisMethod, Method proceed, Object[] args) throws Throwable { return DefaultProxy.this.invoke(self, thisMethod, args); } }; return (E) factory.create(new Class[0], new Object[0], handler); } catch(Exception e) {
// Path: src/main/java/org/mentabean/BeanException.java // public class BeanException extends RuntimeException { // // private static final long serialVersionUID = -6402197033079197979L; // // protected final Throwable rootCause; // // public BeanException() { // super(); // this.rootCause = null; // } // // public BeanException(Throwable e) { // super(getMsg(e), e); // Throwable root = getRootCause(e); // this.setStackTrace(root.getStackTrace()); // // this.rootCause = root == this ? null : root; // } // // public BeanException(String msg) { // super(msg); // // this.rootCause = null; // } // // public BeanException(String msg, Throwable e) { // // super(msg, e); // Throwable root = getRootCause(e); // this.setStackTrace(root.getStackTrace()); // // this.rootCause = root == this ? null : root; // } // // private static String getMsg(Throwable t) { // // Throwable root = getRootCause(t); // // String msg = root.getMessage(); // // if (msg == null || msg.length() == 0) { // // msg = t.getMessage(); // // if (msg == null || msg.length() == 0) { // return root.getClass().getName(); // } // } // // return msg; // } // // private static Throwable getRootCause(Throwable t) { // // Throwable root = t.getCause(); // // if (root == null) { // return t; // } // // while (root.getCause() != null) { // // root = root.getCause(); // } // // return root; // // } // // @Override // public Throwable getCause() { // // return rootCause; // } // } // Path: src/main/java/org/mentabean/util/DefaultProxy.java import java.lang.reflect.Method; import javassist.util.proxy.MethodFilter; import javassist.util.proxy.MethodHandler; import javassist.util.proxy.ProxyFactory; import org.mentabean.BeanException; package org.mentabean.util; public class DefaultProxy extends PropertiesProxy { public DefaultProxy(String chainProp) { super(chainProp); } public DefaultProxy() { super(null); } @SuppressWarnings("unchecked") @Override protected <E> E createInternal(final Class<E> klass) { try { ProxyFactory factory = new ProxyFactory(); factory.setSuperclass(klass); factory.setFilter(new MethodFilter() { @Override public boolean isHandled(Method m) { return getPropName(m) != null; } }); MethodHandler handler = new MethodHandler() { @Override public Object invoke(Object self, Method thisMethod, Method proceed, Object[] args) throws Throwable { return DefaultProxy.this.invoke(self, thisMethod, args); } }; return (E) factory.create(new Class[0], new Object[0], handler); } catch(Exception e) {
throw new BeanException(e);
saoj/mentabean
src/main/java/org/mentabean/sql/functions/Nullif.java
// Path: src/main/java/org/mentabean/sql/Function.java // public interface Function extends HasParams { // // } // // Path: src/main/java/org/mentabean/sql/Parametrizable.java // public abstract class Parametrizable implements HasParams { // // protected List<Param> params = new ArrayList<Param>(); // // public abstract String name(); // // @Override // public Param[] getParams() { // return params.toArray(new Param[0]); // } // // protected Parametrizable addParam(Param param) { // params.add(param); // return this; // } // // @Override // public String build() { // // StringBuilder sb = new StringBuilder(name()); // // sb.append(" ("); // // for (Param param : getParams()) { // sb.append(param.paramInQuery()).append(','); // } // // sb.setCharAt(sb.length()-1, ')'); // // return sb.toString(); // } // // } // // Path: src/main/java/org/mentabean/sql/param/Param.java // public interface Param { // // /** // * Represents the parameters in query. In other words, this method returns a String // * with the expression exactly as will be shown in SQL before its execution. // * @return String // */ // public String paramInQuery(); // // /** // * The parameter's values // * @return Object[] // */ // public Object[] values(); // // } // // Path: src/main/java/org/mentabean/sql/param/ParamValue.java // public class ParamValue implements Param { // // private Object value; // // public ParamValue(Object value) { // this.value = value; // } // // @Override // public String paramInQuery() { // return "?"; // } // // @Override // public Object[] values() { // return new Object[] {value}; // } // // }
import org.mentabean.sql.Function; import org.mentabean.sql.Parametrizable; import org.mentabean.sql.param.Param; import org.mentabean.sql.param.ParamValue;
package org.mentabean.sql.functions; public class Nullif extends Parametrizable implements Function { private Param p1, p2; public Nullif(Param p1, Param p2) { this.p1 = p1; this.p2 = p2; } public Nullif(Object p1, Object p2) {
// Path: src/main/java/org/mentabean/sql/Function.java // public interface Function extends HasParams { // // } // // Path: src/main/java/org/mentabean/sql/Parametrizable.java // public abstract class Parametrizable implements HasParams { // // protected List<Param> params = new ArrayList<Param>(); // // public abstract String name(); // // @Override // public Param[] getParams() { // return params.toArray(new Param[0]); // } // // protected Parametrizable addParam(Param param) { // params.add(param); // return this; // } // // @Override // public String build() { // // StringBuilder sb = new StringBuilder(name()); // // sb.append(" ("); // // for (Param param : getParams()) { // sb.append(param.paramInQuery()).append(','); // } // // sb.setCharAt(sb.length()-1, ')'); // // return sb.toString(); // } // // } // // Path: src/main/java/org/mentabean/sql/param/Param.java // public interface Param { // // /** // * Represents the parameters in query. In other words, this method returns a String // * with the expression exactly as will be shown in SQL before its execution. // * @return String // */ // public String paramInQuery(); // // /** // * The parameter's values // * @return Object[] // */ // public Object[] values(); // // } // // Path: src/main/java/org/mentabean/sql/param/ParamValue.java // public class ParamValue implements Param { // // private Object value; // // public ParamValue(Object value) { // this.value = value; // } // // @Override // public String paramInQuery() { // return "?"; // } // // @Override // public Object[] values() { // return new Object[] {value}; // } // // } // Path: src/main/java/org/mentabean/sql/functions/Nullif.java import org.mentabean.sql.Function; import org.mentabean.sql.Parametrizable; import org.mentabean.sql.param.Param; import org.mentabean.sql.param.ParamValue; package org.mentabean.sql.functions; public class Nullif extends Parametrizable implements Function { private Param p1, p2; public Nullif(Param p1, Param p2) { this.p1 = p1; this.p2 = p2; } public Nullif(Object p1, Object p2) {
this.p1 = new ParamValue(p1);
saoj/mentabean
src/main/java/org/mentabean/util/SQLBuilder.java
// Path: src/main/java/org/mentabean/sql/TableAlias.java // public class TableAlias<E> { // // private final Class<? extends E> beanClass; // private final String prefix; // private final BeanSession session; // private final BeanConfig config; // private final E proxy; // // public TableAlias(BeanSession session, BeanConfig config, Class<? extends E> beanClass) { // this(session, config, beanClass, null); // } // // public TableAlias(BeanSession session, BeanConfig config, Class<? extends E> beanClass, String prefix) { // this.beanClass = beanClass; // this.prefix = prefix; // this.session = session; // this.config = config; // this.proxy = PropertiesProxy.create(beanClass); // } // // @Override // public String toString() { // return "TableAlias [beanClass=" + beanClass.getSimpleName() + ", prefix=" + prefix + "]"; // } // // /** // * Return the db columns of a select statements. // * // * @return the columns to build a select statement // */ // public String columns(Object... props) { // if (prefix != null) { // return session.buildSelect(beanClass, prefix, props); // } else { // return session.buildSelect(beanClass, props); // } // } // // public String columnsMinus(Object... props) { // if (prefix != null) { // return session.buildSelectMinus(beanClass, prefix, props); // } else { // return session.buildSelectMinus(beanClass, props); // } // } // // /** // * Return the table name. // * // * @return the table name // */ // public String tableName() { // if (prefix != null) { // return config.getTableName() + " " + prefix; // } else { // return config.getTableName(); // } // } // // /** // * Return the db column name for this bean property. // * // * @param prop this is a filler parameter because a proxy call will be performed! // * @return the db column name of this property // */ // public String column(Object prop) { // // String propName = PropertiesProxy.getPropertyName(); // // DBField field = config.getField(propName); // // if (field == null) throw new IllegalStateException("Cannot find field for property \"" + propName + "\" on beanconfig: " + config); // // if (prefix != null) { // return prefix + "." + field.getDbName(); // } else { // return field.getDbName(); // } // } // // public E pxy() { // return proxy; // } // // public E proxy() { // return proxy; // } // // public String prefix() { // return prefix; // } // // public Class<? extends E> beanClass() { // return beanClass; // } // // }
import org.mentabean.sql.TableAlias;
package org.mentabean.util; public class SQLBuilder implements CharSequence { private final StringBuilder sb;
// Path: src/main/java/org/mentabean/sql/TableAlias.java // public class TableAlias<E> { // // private final Class<? extends E> beanClass; // private final String prefix; // private final BeanSession session; // private final BeanConfig config; // private final E proxy; // // public TableAlias(BeanSession session, BeanConfig config, Class<? extends E> beanClass) { // this(session, config, beanClass, null); // } // // public TableAlias(BeanSession session, BeanConfig config, Class<? extends E> beanClass, String prefix) { // this.beanClass = beanClass; // this.prefix = prefix; // this.session = session; // this.config = config; // this.proxy = PropertiesProxy.create(beanClass); // } // // @Override // public String toString() { // return "TableAlias [beanClass=" + beanClass.getSimpleName() + ", prefix=" + prefix + "]"; // } // // /** // * Return the db columns of a select statements. // * // * @return the columns to build a select statement // */ // public String columns(Object... props) { // if (prefix != null) { // return session.buildSelect(beanClass, prefix, props); // } else { // return session.buildSelect(beanClass, props); // } // } // // public String columnsMinus(Object... props) { // if (prefix != null) { // return session.buildSelectMinus(beanClass, prefix, props); // } else { // return session.buildSelectMinus(beanClass, props); // } // } // // /** // * Return the table name. // * // * @return the table name // */ // public String tableName() { // if (prefix != null) { // return config.getTableName() + " " + prefix; // } else { // return config.getTableName(); // } // } // // /** // * Return the db column name for this bean property. // * // * @param prop this is a filler parameter because a proxy call will be performed! // * @return the db column name of this property // */ // public String column(Object prop) { // // String propName = PropertiesProxy.getPropertyName(); // // DBField field = config.getField(propName); // // if (field == null) throw new IllegalStateException("Cannot find field for property \"" + propName + "\" on beanconfig: " + config); // // if (prefix != null) { // return prefix + "." + field.getDbName(); // } else { // return field.getDbName(); // } // } // // public E pxy() { // return proxy; // } // // public E proxy() { // return proxy; // } // // public String prefix() { // return prefix; // } // // public Class<? extends E> beanClass() { // return beanClass; // } // // } // Path: src/main/java/org/mentabean/util/SQLBuilder.java import org.mentabean.sql.TableAlias; package org.mentabean.util; public class SQLBuilder implements CharSequence { private final StringBuilder sb;
private final TableAlias<?>[] aliases;
saoj/mentabean
src/main/java/org/mentabean/sql/conditions/Between.java
// Path: src/main/java/org/mentabean/sql/param/Param.java // public interface Param { // // /** // * Represents the parameters in query. In other words, this method returns a String // * with the expression exactly as will be shown in SQL before its execution. // * @return String // */ // public String paramInQuery(); // // /** // * The parameter's values // * @return Object[] // */ // public Object[] values(); // // }
import org.mentabean.sql.param.Param;
package org.mentabean.sql.conditions; public class Between extends AbstractBetween { private boolean not;
// Path: src/main/java/org/mentabean/sql/param/Param.java // public interface Param { // // /** // * Represents the parameters in query. In other words, this method returns a String // * with the expression exactly as will be shown in SQL before its execution. // * @return String // */ // public String paramInQuery(); // // /** // * The parameter's values // * @return Object[] // */ // public Object[] values(); // // } // Path: src/main/java/org/mentabean/sql/conditions/Between.java import org.mentabean.sql.param.Param; package org.mentabean.sql.conditions; public class Between extends AbstractBetween { private boolean not;
public Between(Param begin, Param end) {
saoj/mentabean
src/main/java/org/mentabean/sql/conditions/SimpleComparison.java
// Path: src/main/java/org/mentabean/sql/Condition.java // public interface Condition extends HasParams { // // } // // Path: src/main/java/org/mentabean/sql/param/Param.java // public interface Param { // // /** // * Represents the parameters in query. In other words, this method returns a String // * with the expression exactly as will be shown in SQL before its execution. // * @return String // */ // public String paramInQuery(); // // /** // * The parameter's values // * @return Object[] // */ // public Object[] values(); // // } // // Path: src/main/java/org/mentabean/sql/param/ParamValue.java // public class ParamValue implements Param { // // private Object value; // // public ParamValue(Object value) { // this.value = value; // } // // @Override // public String paramInQuery() { // return "?"; // } // // @Override // public Object[] values() { // return new Object[] {value}; // } // // }
import org.mentabean.sql.Condition; import org.mentabean.sql.param.Param; import org.mentabean.sql.param.ParamValue;
package org.mentabean.sql.conditions; public abstract class SimpleComparison implements Condition { private Param param; public abstract String comparisonSignal(); public SimpleComparison(Param param) { this.param = param; } public SimpleComparison(Object value) {
// Path: src/main/java/org/mentabean/sql/Condition.java // public interface Condition extends HasParams { // // } // // Path: src/main/java/org/mentabean/sql/param/Param.java // public interface Param { // // /** // * Represents the parameters in query. In other words, this method returns a String // * with the expression exactly as will be shown in SQL before its execution. // * @return String // */ // public String paramInQuery(); // // /** // * The parameter's values // * @return Object[] // */ // public Object[] values(); // // } // // Path: src/main/java/org/mentabean/sql/param/ParamValue.java // public class ParamValue implements Param { // // private Object value; // // public ParamValue(Object value) { // this.value = value; // } // // @Override // public String paramInQuery() { // return "?"; // } // // @Override // public Object[] values() { // return new Object[] {value}; // } // // } // Path: src/main/java/org/mentabean/sql/conditions/SimpleComparison.java import org.mentabean.sql.Condition; import org.mentabean.sql.param.Param; import org.mentabean.sql.param.ParamValue; package org.mentabean.sql.conditions; public abstract class SimpleComparison implements Condition { private Param param; public abstract String comparisonSignal(); public SimpleComparison(Param param) { this.param = param; } public SimpleComparison(Object value) {
this.param = new ParamValue(value);
saoj/mentabean
src/main/java/org/mentabean/sql/functions/Coalesce.java
// Path: src/main/java/org/mentabean/sql/Function.java // public interface Function extends HasParams { // // } // // Path: src/main/java/org/mentabean/sql/Parametrizable.java // public abstract class Parametrizable implements HasParams { // // protected List<Param> params = new ArrayList<Param>(); // // public abstract String name(); // // @Override // public Param[] getParams() { // return params.toArray(new Param[0]); // } // // protected Parametrizable addParam(Param param) { // params.add(param); // return this; // } // // @Override // public String build() { // // StringBuilder sb = new StringBuilder(name()); // // sb.append(" ("); // // for (Param param : getParams()) { // sb.append(param.paramInQuery()).append(','); // } // // sb.setCharAt(sb.length()-1, ')'); // // return sb.toString(); // } // // } // // Path: src/main/java/org/mentabean/sql/param/Param.java // public interface Param { // // /** // * Represents the parameters in query. In other words, this method returns a String // * with the expression exactly as will be shown in SQL before its execution. // * @return String // */ // public String paramInQuery(); // // /** // * The parameter's values // * @return Object[] // */ // public Object[] values(); // // }
import org.mentabean.sql.Function; import org.mentabean.sql.Parametrizable; import org.mentabean.sql.param.Param;
package org.mentabean.sql.functions; public class Coalesce extends Parametrizable implements Function { @Override public String name() { return "COALESCE"; } @Override
// Path: src/main/java/org/mentabean/sql/Function.java // public interface Function extends HasParams { // // } // // Path: src/main/java/org/mentabean/sql/Parametrizable.java // public abstract class Parametrizable implements HasParams { // // protected List<Param> params = new ArrayList<Param>(); // // public abstract String name(); // // @Override // public Param[] getParams() { // return params.toArray(new Param[0]); // } // // protected Parametrizable addParam(Param param) { // params.add(param); // return this; // } // // @Override // public String build() { // // StringBuilder sb = new StringBuilder(name()); // // sb.append(" ("); // // for (Param param : getParams()) { // sb.append(param.paramInQuery()).append(','); // } // // sb.setCharAt(sb.length()-1, ')'); // // return sb.toString(); // } // // } // // Path: src/main/java/org/mentabean/sql/param/Param.java // public interface Param { // // /** // * Represents the parameters in query. In other words, this method returns a String // * with the expression exactly as will be shown in SQL before its execution. // * @return String // */ // public String paramInQuery(); // // /** // * The parameter's values // * @return Object[] // */ // public Object[] values(); // // } // Path: src/main/java/org/mentabean/sql/functions/Coalesce.java import org.mentabean.sql.Function; import org.mentabean.sql.Parametrizable; import org.mentabean.sql.param.Param; package org.mentabean.sql.functions; public class Coalesce extends Parametrizable implements Function { @Override public String name() { return "COALESCE"; } @Override
public Coalesce addParam(Param param) {
saoj/mentabean
src/main/java/org/mentabean/BeanManager.java
// Path: src/main/java/org/mentabean/util/DefaultProxy.java // public class DefaultProxy extends PropertiesProxy { // // public DefaultProxy(String chainProp) { // super(chainProp); // } // // public DefaultProxy() { // super(null); // } // // @SuppressWarnings("unchecked") // @Override // protected <E> E createInternal(final Class<E> klass) { // // try { // // ProxyFactory factory = new ProxyFactory(); // factory.setSuperclass(klass); // // factory.setFilter(new MethodFilter() { // // @Override // public boolean isHandled(Method m) { // return getPropName(m) != null; // } // }); // // MethodHandler handler = new MethodHandler() { // // @Override // public Object invoke(Object self, Method thisMethod, Method proceed, Object[] args) throws Throwable { // // return DefaultProxy.this.invoke(self, thisMethod, args); // } // }; // // return (E) factory.create(new Class[0], new Object[0], handler); // // } catch(Exception e) { // throw new BeanException(e); // } // } // // }
import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.mentabean.util.DefaultProxy; import org.mentabean.util.PropertiesProxy;
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * MentaBean => http://www.mentabean.org * Author: Sergio Oliveira Jr. (sergio.oliveira.jr@gmail.com) */ package org.mentabean; /** * The manager that keeps track of the configuration for all beans. * * @author sergio.oliveira.jr@gmail.com */ public class BeanManager { private final Map<Class<? extends Object>, BeanConfig> beans = new HashMap<Class<? extends Object>, BeanConfig>(); public BeanManager(PropertiesProxy proxy) {
// Path: src/main/java/org/mentabean/util/DefaultProxy.java // public class DefaultProxy extends PropertiesProxy { // // public DefaultProxy(String chainProp) { // super(chainProp); // } // // public DefaultProxy() { // super(null); // } // // @SuppressWarnings("unchecked") // @Override // protected <E> E createInternal(final Class<E> klass) { // // try { // // ProxyFactory factory = new ProxyFactory(); // factory.setSuperclass(klass); // // factory.setFilter(new MethodFilter() { // // @Override // public boolean isHandled(Method m) { // return getPropName(m) != null; // } // }); // // MethodHandler handler = new MethodHandler() { // // @Override // public Object invoke(Object self, Method thisMethod, Method proceed, Object[] args) throws Throwable { // // return DefaultProxy.this.invoke(self, thisMethod, args); // } // }; // // return (E) factory.create(new Class[0], new Object[0], handler); // // } catch(Exception e) { // throw new BeanException(e); // } // } // // } // Path: src/main/java/org/mentabean/BeanManager.java import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.mentabean.util.DefaultProxy; import org.mentabean.util.PropertiesProxy; /* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * MentaBean => http://www.mentabean.org * Author: Sergio Oliveira Jr. (sergio.oliveira.jr@gmail.com) */ package org.mentabean; /** * The manager that keeps track of the configuration for all beans. * * @author sergio.oliveira.jr@gmail.com */ public class BeanManager { private final Map<Class<? extends Object>, BeanConfig> beans = new HashMap<Class<? extends Object>, BeanConfig>(); public BeanManager(PropertiesProxy proxy) {
PropertiesProxy.INSTANCE = proxy == null ? new DefaultProxy() : proxy;
saoj/mentabean
src/main/java/org/mentabean/sql/conditions/In.java
// Path: src/main/java/org/mentabean/sql/Condition.java // public interface Condition extends HasParams { // // } // // Path: src/main/java/org/mentabean/sql/Parametrizable.java // public abstract class Parametrizable implements HasParams { // // protected List<Param> params = new ArrayList<Param>(); // // public abstract String name(); // // @Override // public Param[] getParams() { // return params.toArray(new Param[0]); // } // // protected Parametrizable addParam(Param param) { // params.add(param); // return this; // } // // @Override // public String build() { // // StringBuilder sb = new StringBuilder(name()); // // sb.append(" ("); // // for (Param param : getParams()) { // sb.append(param.paramInQuery()).append(','); // } // // sb.setCharAt(sb.length()-1, ')'); // // return sb.toString(); // } // // } // // Path: src/main/java/org/mentabean/sql/param/Param.java // public interface Param { // // /** // * Represents the parameters in query. In other words, this method returns a String // * with the expression exactly as will be shown in SQL before its execution. // * @return String // */ // public String paramInQuery(); // // /** // * The parameter's values // * @return Object[] // */ // public Object[] values(); // // }
import org.mentabean.sql.Condition; import org.mentabean.sql.Parametrizable; import org.mentabean.sql.param.Param;
package org.mentabean.sql.conditions; public class In extends Parametrizable implements Condition { @Override public String name() { return "IN"; }
// Path: src/main/java/org/mentabean/sql/Condition.java // public interface Condition extends HasParams { // // } // // Path: src/main/java/org/mentabean/sql/Parametrizable.java // public abstract class Parametrizable implements HasParams { // // protected List<Param> params = new ArrayList<Param>(); // // public abstract String name(); // // @Override // public Param[] getParams() { // return params.toArray(new Param[0]); // } // // protected Parametrizable addParam(Param param) { // params.add(param); // return this; // } // // @Override // public String build() { // // StringBuilder sb = new StringBuilder(name()); // // sb.append(" ("); // // for (Param param : getParams()) { // sb.append(param.paramInQuery()).append(','); // } // // sb.setCharAt(sb.length()-1, ')'); // // return sb.toString(); // } // // } // // Path: src/main/java/org/mentabean/sql/param/Param.java // public interface Param { // // /** // * Represents the parameters in query. In other words, this method returns a String // * with the expression exactly as will be shown in SQL before its execution. // * @return String // */ // public String paramInQuery(); // // /** // * The parameter's values // * @return Object[] // */ // public Object[] values(); // // } // Path: src/main/java/org/mentabean/sql/conditions/In.java import org.mentabean.sql.Condition; import org.mentabean.sql.Parametrizable; import org.mentabean.sql.param.Param; package org.mentabean.sql.conditions; public class In extends Parametrizable implements Condition { @Override public String name() { return "IN"; }
public In (Param param) {
saoj/mentabean
src/main/java/org/mentabean/sql/conditions/Equals.java
// Path: src/main/java/org/mentabean/sql/Condition.java // public interface Condition extends HasParams { // // } // // Path: src/main/java/org/mentabean/sql/param/Param.java // public interface Param { // // /** // * Represents the parameters in query. In other words, this method returns a String // * with the expression exactly as will be shown in SQL before its execution. // * @return String // */ // public String paramInQuery(); // // /** // * The parameter's values // * @return Object[] // */ // public Object[] values(); // // } // // Path: src/main/java/org/mentabean/sql/param/ParamValue.java // public class ParamValue implements Param { // // private Object value; // // public ParamValue(Object value) { // this.value = value; // } // // @Override // public String paramInQuery() { // return "?"; // } // // @Override // public Object[] values() { // return new Object[] {value}; // } // // }
import org.mentabean.sql.Condition; import org.mentabean.sql.param.Param; import org.mentabean.sql.param.ParamValue;
package org.mentabean.sql.conditions; public class Equals implements Condition { protected Param param; public Equals(Object value) { if (value != null) {
// Path: src/main/java/org/mentabean/sql/Condition.java // public interface Condition extends HasParams { // // } // // Path: src/main/java/org/mentabean/sql/param/Param.java // public interface Param { // // /** // * Represents the parameters in query. In other words, this method returns a String // * with the expression exactly as will be shown in SQL before its execution. // * @return String // */ // public String paramInQuery(); // // /** // * The parameter's values // * @return Object[] // */ // public Object[] values(); // // } // // Path: src/main/java/org/mentabean/sql/param/ParamValue.java // public class ParamValue implements Param { // // private Object value; // // public ParamValue(Object value) { // this.value = value; // } // // @Override // public String paramInQuery() { // return "?"; // } // // @Override // public Object[] values() { // return new Object[] {value}; // } // // } // Path: src/main/java/org/mentabean/sql/conditions/Equals.java import org.mentabean.sql.Condition; import org.mentabean.sql.param.Param; import org.mentabean.sql.param.ParamValue; package org.mentabean.sql.conditions; public class Equals implements Condition { protected Param param; public Equals(Object value) { if (value != null) {
this.param = new ParamValue(value);
saoj/mentabean
src/test/java/org/mentabean/jdbc/PropertiesProxyTest.java
// Path: src/main/java/org/mentabean/util/DefaultProxy.java // public class DefaultProxy extends PropertiesProxy { // // public DefaultProxy(String chainProp) { // super(chainProp); // } // // public DefaultProxy() { // super(null); // } // // @SuppressWarnings("unchecked") // @Override // protected <E> E createInternal(final Class<E> klass) { // // try { // // ProxyFactory factory = new ProxyFactory(); // factory.setSuperclass(klass); // // factory.setFilter(new MethodFilter() { // // @Override // public boolean isHandled(Method m) { // return getPropName(m) != null; // } // }); // // MethodHandler handler = new MethodHandler() { // // @Override // public Object invoke(Object self, Method thisMethod, Method proceed, Object[] args) throws Throwable { // // return DefaultProxy.this.invoke(self, thisMethod, args); // } // }; // // return (E) factory.create(new Class[0], new Object[0], handler); // // } catch(Exception e) { // throw new BeanException(e); // } // } // // }
import junit.framework.Assert; import org.junit.Before; import org.junit.Test; import org.mentabean.util.DefaultProxy; import org.mentabean.util.PropertiesProxy;
} public static class City { private int id; private String name; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } private static boolean check(String[] array, String s) { for(String x : array) { if (s.equals(x)) return true; } return false; } @Before public void setUp() {
// Path: src/main/java/org/mentabean/util/DefaultProxy.java // public class DefaultProxy extends PropertiesProxy { // // public DefaultProxy(String chainProp) { // super(chainProp); // } // // public DefaultProxy() { // super(null); // } // // @SuppressWarnings("unchecked") // @Override // protected <E> E createInternal(final Class<E> klass) { // // try { // // ProxyFactory factory = new ProxyFactory(); // factory.setSuperclass(klass); // // factory.setFilter(new MethodFilter() { // // @Override // public boolean isHandled(Method m) { // return getPropName(m) != null; // } // }); // // MethodHandler handler = new MethodHandler() { // // @Override // public Object invoke(Object self, Method thisMethod, Method proceed, Object[] args) throws Throwable { // // return DefaultProxy.this.invoke(self, thisMethod, args); // } // }; // // return (E) factory.create(new Class[0], new Object[0], handler); // // } catch(Exception e) { // throw new BeanException(e); // } // } // // } // Path: src/test/java/org/mentabean/jdbc/PropertiesProxyTest.java import junit.framework.Assert; import org.junit.Before; import org.junit.Test; import org.mentabean.util.DefaultProxy; import org.mentabean.util.PropertiesProxy; } public static class City { private int id; private String name; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } private static boolean check(String[] array, String s) { for(String x : array) { if (s.equals(x)) return true; } return false; } @Before public void setUp() {
PropertiesProxy.INSTANCE = new DefaultProxy();
saoj/mentabean
src/main/java/org/mentabean/util/SQLUtils.java
// Path: src/main/java/org/mentabean/BeanException.java // public class BeanException extends RuntimeException { // // private static final long serialVersionUID = -6402197033079197979L; // // protected final Throwable rootCause; // // public BeanException() { // super(); // this.rootCause = null; // } // // public BeanException(Throwable e) { // super(getMsg(e), e); // Throwable root = getRootCause(e); // this.setStackTrace(root.getStackTrace()); // // this.rootCause = root == this ? null : root; // } // // public BeanException(String msg) { // super(msg); // // this.rootCause = null; // } // // public BeanException(String msg, Throwable e) { // // super(msg, e); // Throwable root = getRootCause(e); // this.setStackTrace(root.getStackTrace()); // // this.rootCause = root == this ? null : root; // } // // private static String getMsg(Throwable t) { // // Throwable root = getRootCause(t); // // String msg = root.getMessage(); // // if (msg == null || msg.length() == 0) { // // msg = t.getMessage(); // // if (msg == null || msg.length() == 0) { // return root.getClass().getName(); // } // } // // return msg; // } // // private static Throwable getRootCause(Throwable t) { // // Throwable root = t.getCause(); // // if (root == null) { // return t; // } // // while (root.getCause() != null) { // // root = root.getCause(); // } // // return root; // // } // // @Override // public Throwable getCause() { // // return rootCause; // } // }
import java.io.BufferedReader; import java.io.FileInputStream; import java.io.InputStreamReader; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import org.mentabean.BeanException;
package org.mentabean.util; public class SQLUtils { public static final String UNIQUE_KEY_VIOLATED_STATE = "23505"; public static final String FOREIGN_KEY_VIOLATED_STATE = "23503"; public static void executeScript(Connection conn, String file, String charset) { FileInputStream fis = null; BufferedReader br = null; try { ScriptRunner script = new ScriptRunner(conn); fis = new FileInputStream(file); if (charset != null) { br = new BufferedReader(new InputStreamReader(fis, charset)); } else { br = new BufferedReader(new InputStreamReader(fis)); } script.runScript(br); } catch(Exception e) {
// Path: src/main/java/org/mentabean/BeanException.java // public class BeanException extends RuntimeException { // // private static final long serialVersionUID = -6402197033079197979L; // // protected final Throwable rootCause; // // public BeanException() { // super(); // this.rootCause = null; // } // // public BeanException(Throwable e) { // super(getMsg(e), e); // Throwable root = getRootCause(e); // this.setStackTrace(root.getStackTrace()); // // this.rootCause = root == this ? null : root; // } // // public BeanException(String msg) { // super(msg); // // this.rootCause = null; // } // // public BeanException(String msg, Throwable e) { // // super(msg, e); // Throwable root = getRootCause(e); // this.setStackTrace(root.getStackTrace()); // // this.rootCause = root == this ? null : root; // } // // private static String getMsg(Throwable t) { // // Throwable root = getRootCause(t); // // String msg = root.getMessage(); // // if (msg == null || msg.length() == 0) { // // msg = t.getMessage(); // // if (msg == null || msg.length() == 0) { // return root.getClass().getName(); // } // } // // return msg; // } // // private static Throwable getRootCause(Throwable t) { // // Throwable root = t.getCause(); // // if (root == null) { // return t; // } // // while (root.getCause() != null) { // // root = root.getCause(); // } // // return root; // // } // // @Override // public Throwable getCause() { // // return rootCause; // } // } // Path: src/main/java/org/mentabean/util/SQLUtils.java import java.io.BufferedReader; import java.io.FileInputStream; import java.io.InputStreamReader; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import org.mentabean.BeanException; package org.mentabean.util; public class SQLUtils { public static final String UNIQUE_KEY_VIOLATED_STATE = "23505"; public static final String FOREIGN_KEY_VIOLATED_STATE = "23503"; public static void executeScript(Connection conn, String file, String charset) { FileInputStream fis = null; BufferedReader br = null; try { ScriptRunner script = new ScriptRunner(conn); fis = new FileInputStream(file); if (charset != null) { br = new BufferedReader(new InputStreamReader(fis, charset)); } else { br = new BufferedReader(new InputStreamReader(fis)); } script.runScript(br); } catch(Exception e) {
throw new BeanException(e);
saoj/mentabean
src/main/java/org/mentabean/sql/functions/Substring.java
// Path: src/main/java/org/mentabean/sql/Function.java // public interface Function extends HasParams { // // } // // Path: src/main/java/org/mentabean/sql/Parametrizable.java // public abstract class Parametrizable implements HasParams { // // protected List<Param> params = new ArrayList<Param>(); // // public abstract String name(); // // @Override // public Param[] getParams() { // return params.toArray(new Param[0]); // } // // protected Parametrizable addParam(Param param) { // params.add(param); // return this; // } // // @Override // public String build() { // // StringBuilder sb = new StringBuilder(name()); // // sb.append(" ("); // // for (Param param : getParams()) { // sb.append(param.paramInQuery()).append(','); // } // // sb.setCharAt(sb.length()-1, ')'); // // return sb.toString(); // } // // } // // Path: src/main/java/org/mentabean/sql/param/Param.java // public interface Param { // // /** // * Represents the parameters in query. In other words, this method returns a String // * with the expression exactly as will be shown in SQL before its execution. // * @return String // */ // public String paramInQuery(); // // /** // * The parameter's values // * @return Object[] // */ // public Object[] values(); // // } // // Path: src/main/java/org/mentabean/sql/param/ParamFunction.java // public class ParamFunction implements Param { // // private Function function; // // public ParamFunction(Function function) { // this.function = function; // } // // @Override // public String paramInQuery() { // return function.build(); // } // // @Override // public Object[] values() { // // List<Object> values = new ArrayList<Object>(); // // Param[] params = function.getParams(); // // if (params != null && params.length > 0) { // for (Param p : params) { // if (p.values() != null && p.values().length > 0) { // values.addAll(Arrays.asList(p.values())); // } // } // } // // return values.toArray(); // } // // } // // Path: src/main/java/org/mentabean/sql/param/ParamValue.java // public class ParamValue implements Param { // // private Object value; // // public ParamValue(Object value) { // this.value = value; // } // // @Override // public String paramInQuery() { // return "?"; // } // // @Override // public Object[] values() { // return new Object[] {value}; // } // // }
import org.mentabean.sql.Function; import org.mentabean.sql.Parametrizable; import org.mentabean.sql.param.Param; import org.mentabean.sql.param.ParamFunction; import org.mentabean.sql.param.ParamValue;
package org.mentabean.sql.functions; public class Substring extends Parametrizable implements Function { private Param str, beginIndex, endIndex; public Substring(Param str) { this.str = str; } public Substring endIndex(Param param) { endIndex = param; return this; } public Substring beginIndex(Param param) { beginIndex = param; return this; } @Override public Param[] getParams() { if (beginIndex == null)
// Path: src/main/java/org/mentabean/sql/Function.java // public interface Function extends HasParams { // // } // // Path: src/main/java/org/mentabean/sql/Parametrizable.java // public abstract class Parametrizable implements HasParams { // // protected List<Param> params = new ArrayList<Param>(); // // public abstract String name(); // // @Override // public Param[] getParams() { // return params.toArray(new Param[0]); // } // // protected Parametrizable addParam(Param param) { // params.add(param); // return this; // } // // @Override // public String build() { // // StringBuilder sb = new StringBuilder(name()); // // sb.append(" ("); // // for (Param param : getParams()) { // sb.append(param.paramInQuery()).append(','); // } // // sb.setCharAt(sb.length()-1, ')'); // // return sb.toString(); // } // // } // // Path: src/main/java/org/mentabean/sql/param/Param.java // public interface Param { // // /** // * Represents the parameters in query. In other words, this method returns a String // * with the expression exactly as will be shown in SQL before its execution. // * @return String // */ // public String paramInQuery(); // // /** // * The parameter's values // * @return Object[] // */ // public Object[] values(); // // } // // Path: src/main/java/org/mentabean/sql/param/ParamFunction.java // public class ParamFunction implements Param { // // private Function function; // // public ParamFunction(Function function) { // this.function = function; // } // // @Override // public String paramInQuery() { // return function.build(); // } // // @Override // public Object[] values() { // // List<Object> values = new ArrayList<Object>(); // // Param[] params = function.getParams(); // // if (params != null && params.length > 0) { // for (Param p : params) { // if (p.values() != null && p.values().length > 0) { // values.addAll(Arrays.asList(p.values())); // } // } // } // // return values.toArray(); // } // // } // // Path: src/main/java/org/mentabean/sql/param/ParamValue.java // public class ParamValue implements Param { // // private Object value; // // public ParamValue(Object value) { // this.value = value; // } // // @Override // public String paramInQuery() { // return "?"; // } // // @Override // public Object[] values() { // return new Object[] {value}; // } // // } // Path: src/main/java/org/mentabean/sql/functions/Substring.java import org.mentabean.sql.Function; import org.mentabean.sql.Parametrizable; import org.mentabean.sql.param.Param; import org.mentabean.sql.param.ParamFunction; import org.mentabean.sql.param.ParamValue; package org.mentabean.sql.functions; public class Substring extends Parametrizable implements Function { private Param str, beginIndex, endIndex; public Substring(Param str) { this.str = str; } public Substring endIndex(Param param) { endIndex = param; return this; } public Substring beginIndex(Param param) { beginIndex = param; return this; } @Override public Param[] getParams() { if (beginIndex == null)
beginIndex = new ParamValue(0);
saoj/mentabean
src/main/java/org/mentabean/sql/functions/Substring.java
// Path: src/main/java/org/mentabean/sql/Function.java // public interface Function extends HasParams { // // } // // Path: src/main/java/org/mentabean/sql/Parametrizable.java // public abstract class Parametrizable implements HasParams { // // protected List<Param> params = new ArrayList<Param>(); // // public abstract String name(); // // @Override // public Param[] getParams() { // return params.toArray(new Param[0]); // } // // protected Parametrizable addParam(Param param) { // params.add(param); // return this; // } // // @Override // public String build() { // // StringBuilder sb = new StringBuilder(name()); // // sb.append(" ("); // // for (Param param : getParams()) { // sb.append(param.paramInQuery()).append(','); // } // // sb.setCharAt(sb.length()-1, ')'); // // return sb.toString(); // } // // } // // Path: src/main/java/org/mentabean/sql/param/Param.java // public interface Param { // // /** // * Represents the parameters in query. In other words, this method returns a String // * with the expression exactly as will be shown in SQL before its execution. // * @return String // */ // public String paramInQuery(); // // /** // * The parameter's values // * @return Object[] // */ // public Object[] values(); // // } // // Path: src/main/java/org/mentabean/sql/param/ParamFunction.java // public class ParamFunction implements Param { // // private Function function; // // public ParamFunction(Function function) { // this.function = function; // } // // @Override // public String paramInQuery() { // return function.build(); // } // // @Override // public Object[] values() { // // List<Object> values = new ArrayList<Object>(); // // Param[] params = function.getParams(); // // if (params != null && params.length > 0) { // for (Param p : params) { // if (p.values() != null && p.values().length > 0) { // values.addAll(Arrays.asList(p.values())); // } // } // } // // return values.toArray(); // } // // } // // Path: src/main/java/org/mentabean/sql/param/ParamValue.java // public class ParamValue implements Param { // // private Object value; // // public ParamValue(Object value) { // this.value = value; // } // // @Override // public String paramInQuery() { // return "?"; // } // // @Override // public Object[] values() { // return new Object[] {value}; // } // // }
import org.mentabean.sql.Function; import org.mentabean.sql.Parametrizable; import org.mentabean.sql.param.Param; import org.mentabean.sql.param.ParamFunction; import org.mentabean.sql.param.ParamValue;
package org.mentabean.sql.functions; public class Substring extends Parametrizable implements Function { private Param str, beginIndex, endIndex; public Substring(Param str) { this.str = str; } public Substring endIndex(Param param) { endIndex = param; return this; } public Substring beginIndex(Param param) { beginIndex = param; return this; } @Override public Param[] getParams() { if (beginIndex == null) beginIndex = new ParamValue(0); if (endIndex == null)
// Path: src/main/java/org/mentabean/sql/Function.java // public interface Function extends HasParams { // // } // // Path: src/main/java/org/mentabean/sql/Parametrizable.java // public abstract class Parametrizable implements HasParams { // // protected List<Param> params = new ArrayList<Param>(); // // public abstract String name(); // // @Override // public Param[] getParams() { // return params.toArray(new Param[0]); // } // // protected Parametrizable addParam(Param param) { // params.add(param); // return this; // } // // @Override // public String build() { // // StringBuilder sb = new StringBuilder(name()); // // sb.append(" ("); // // for (Param param : getParams()) { // sb.append(param.paramInQuery()).append(','); // } // // sb.setCharAt(sb.length()-1, ')'); // // return sb.toString(); // } // // } // // Path: src/main/java/org/mentabean/sql/param/Param.java // public interface Param { // // /** // * Represents the parameters in query. In other words, this method returns a String // * with the expression exactly as will be shown in SQL before its execution. // * @return String // */ // public String paramInQuery(); // // /** // * The parameter's values // * @return Object[] // */ // public Object[] values(); // // } // // Path: src/main/java/org/mentabean/sql/param/ParamFunction.java // public class ParamFunction implements Param { // // private Function function; // // public ParamFunction(Function function) { // this.function = function; // } // // @Override // public String paramInQuery() { // return function.build(); // } // // @Override // public Object[] values() { // // List<Object> values = new ArrayList<Object>(); // // Param[] params = function.getParams(); // // if (params != null && params.length > 0) { // for (Param p : params) { // if (p.values() != null && p.values().length > 0) { // values.addAll(Arrays.asList(p.values())); // } // } // } // // return values.toArray(); // } // // } // // Path: src/main/java/org/mentabean/sql/param/ParamValue.java // public class ParamValue implements Param { // // private Object value; // // public ParamValue(Object value) { // this.value = value; // } // // @Override // public String paramInQuery() { // return "?"; // } // // @Override // public Object[] values() { // return new Object[] {value}; // } // // } // Path: src/main/java/org/mentabean/sql/functions/Substring.java import org.mentabean.sql.Function; import org.mentabean.sql.Parametrizable; import org.mentabean.sql.param.Param; import org.mentabean.sql.param.ParamFunction; import org.mentabean.sql.param.ParamValue; package org.mentabean.sql.functions; public class Substring extends Parametrizable implements Function { private Param str, beginIndex, endIndex; public Substring(Param str) { this.str = str; } public Substring endIndex(Param param) { endIndex = param; return this; } public Substring beginIndex(Param param) { beginIndex = param; return this; } @Override public Param[] getParams() { if (beginIndex == null) beginIndex = new ParamValue(0); if (endIndex == null)
endIndex = new ParamFunction(new Length(str));
saoj/mentabean
src/main/java/org/mentabean/util/PropertiesProxy.java
// Path: src/main/java/org/mentabean/BeanException.java // public class BeanException extends RuntimeException { // // private static final long serialVersionUID = -6402197033079197979L; // // protected final Throwable rootCause; // // public BeanException() { // super(); // this.rootCause = null; // } // // public BeanException(Throwable e) { // super(getMsg(e), e); // Throwable root = getRootCause(e); // this.setStackTrace(root.getStackTrace()); // // this.rootCause = root == this ? null : root; // } // // public BeanException(String msg) { // super(msg); // // this.rootCause = null; // } // // public BeanException(String msg, Throwable e) { // // super(msg, e); // Throwable root = getRootCause(e); // this.setStackTrace(root.getStackTrace()); // // this.rootCause = root == this ? null : root; // } // // private static String getMsg(Throwable t) { // // Throwable root = getRootCause(t); // // String msg = root.getMessage(); // // if (msg == null || msg.length() == 0) { // // msg = t.getMessage(); // // if (msg == null || msg.length() == 0) { // return root.getClass().getName(); // } // } // // return msg; // } // // private static Throwable getRootCause(Throwable t) { // // Throwable root = t.getCause(); // // if (root == null) { // return t; // } // // while (root.getCause() != null) { // // root = root.getCause(); // } // // return root; // // } // // @Override // public Throwable getCause() { // // return rootCause; // } // }
import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.math.BigDecimal; import java.sql.Date; import java.sql.Time; import java.sql.Timestamp; import java.util.Collection; import java.util.LinkedList; import java.util.List; import org.mentabean.BeanException;
package org.mentabean.util; public abstract class PropertiesProxy { public static PropertiesProxy INSTANCE; private static final ThreadLocal<List<String>> propertyNames = new ThreadLocal<List<String>>(); private static final ThreadLocal<List<Object>> beanInstances = new ThreadLocal<List<Object>>(); private String chainProp; public PropertiesProxy(String chainProp) { this.chainProp = chainProp; } private PropertiesProxy createInstance(String chainProp) { try { return getClass().getConstructor(String.class).newInstance(chainProp); } catch (Exception e) {
// Path: src/main/java/org/mentabean/BeanException.java // public class BeanException extends RuntimeException { // // private static final long serialVersionUID = -6402197033079197979L; // // protected final Throwable rootCause; // // public BeanException() { // super(); // this.rootCause = null; // } // // public BeanException(Throwable e) { // super(getMsg(e), e); // Throwable root = getRootCause(e); // this.setStackTrace(root.getStackTrace()); // // this.rootCause = root == this ? null : root; // } // // public BeanException(String msg) { // super(msg); // // this.rootCause = null; // } // // public BeanException(String msg, Throwable e) { // // super(msg, e); // Throwable root = getRootCause(e); // this.setStackTrace(root.getStackTrace()); // // this.rootCause = root == this ? null : root; // } // // private static String getMsg(Throwable t) { // // Throwable root = getRootCause(t); // // String msg = root.getMessage(); // // if (msg == null || msg.length() == 0) { // // msg = t.getMessage(); // // if (msg == null || msg.length() == 0) { // return root.getClass().getName(); // } // } // // return msg; // } // // private static Throwable getRootCause(Throwable t) { // // Throwable root = t.getCause(); // // if (root == null) { // return t; // } // // while (root.getCause() != null) { // // root = root.getCause(); // } // // return root; // // } // // @Override // public Throwable getCause() { // // return rootCause; // } // } // Path: src/main/java/org/mentabean/util/PropertiesProxy.java import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.math.BigDecimal; import java.sql.Date; import java.sql.Time; import java.sql.Timestamp; import java.util.Collection; import java.util.LinkedList; import java.util.List; import org.mentabean.BeanException; package org.mentabean.util; public abstract class PropertiesProxy { public static PropertiesProxy INSTANCE; private static final ThreadLocal<List<String>> propertyNames = new ThreadLocal<List<String>>(); private static final ThreadLocal<List<Object>> beanInstances = new ThreadLocal<List<Object>>(); private String chainProp; public PropertiesProxy(String chainProp) { this.chainProp = chainProp; } private PropertiesProxy createInstance(String chainProp) { try { return getClass().getConstructor(String.class).newInstance(chainProp); } catch (Exception e) {
throw new BeanException("Was not able to get PropertiesProxy instance!", e);
saoj/mentabean
src/main/java/org/mentabean/sql/param/ParamField.java
// Path: src/main/java/org/mentabean/jdbc/QueryBuilder.java // public class Alias<T> { // // private BeanConfig config; // private String aliasStr; // private T proxy; // private String[] returns; // private String[] returnMinus; // private Map<Key, Alias> joined = new HashMap<Key, Alias>(); // // private Alias(Class<? extends T> clazz, String aliasStr) { // // this.aliasStr = aliasStr; // this.config = session.getConfigFor(clazz); // // if (this.config == null) // throw new BeanException("BeanConfig not found for "+clazz); // // this.proxy = (T) PropertiesProxy.create(config.getBeanClass()); // // createdAliases.add(this); // } // // /** // * Defines the properties that will return. In other words, <b>only</b> these properties will be populated // * @param returns // */ // public void setReturns(Object... returns){ // // this.returns = AnsiSQLBeanSession.getProperties(returns); // } // // /** // * Defines the properties that will <b>NOT</b> return. In other words, these properties will be not populated // * @param returns // */ // public void setReturnMinus(Object... returns){ // // this.returnMinus = AnsiSQLBeanSession.getProperties(returns); // } // // /** // * Returns the proxy for bean class // * @return The proxy // * @deprecated Use {@link #proxy()} instead // */ // public T pxy(){ // // return proxy; // } // // public T proxy(){ // // return proxy; // } // // /** // * Convert the given property to database column // * @param property - The bean property (can be through proxy) // * @return The database column name // */ // public String toColumn(Object property){ // // return session.propertyToColumn(config.getBeanClass(), property, aliasStr); // } // // /** // * Populates the bean according to ResultSet // * @param rs // * @param bean // */ // public void populateBean(ResultSet rs, T bean){ // // session.populateBeanImpl(rs, bean, aliasStr, returns, returnMinus, false); // } // // public void populateAll(ResultSet rs, T bean) { // // populateBean(rs, bean); // // for (Map.Entry<Key, Alias> m : joined.entrySet()) { // // //only if alias is in SELECT clause // if (selectAliases.contains(m.getValue())) { // // Object value = session.getPropertyBean(bean, m.getKey().property, m.getKey().forceInstance); // // if (value != null) { // m.getValue().populateAll(rs, value); // } // } // // } // } // // @Override // public String toString() { // return "Alias "+aliasStr+" of "+config.getBeanClass(); // } // // /** // * Configures a property name to receive data from alias. When <code>forceIntance</code> is <b>true</b> // * it will force the creation of a new instance for the property, in other words, // * the value will never be <code>null</code> // * @param property - Bean property to populate // * @param forceInstance // * @param alias - Alias // */ // private void put(Object property, boolean forceInstance, Alias<?> alias) { // joined.put(new Key().property(property).forceInstance(forceInstance), alias); // } // // private class Key { // // private String property; // private boolean forceInstance; // // public Key property(Object property) { // this.property = AnsiSQLBeanSession.getProperties(new Object[] {property})[0]; // //this.property = PropertiesProxy.getPropertyName(); // return this; // } // // public Key forceInstance(boolean force) { // this.forceInstance = force; // return this; // } // } // // }
import org.mentabean.jdbc.QueryBuilder.Alias;
package org.mentabean.sql.param; public class ParamField implements Param { private String column;
// Path: src/main/java/org/mentabean/jdbc/QueryBuilder.java // public class Alias<T> { // // private BeanConfig config; // private String aliasStr; // private T proxy; // private String[] returns; // private String[] returnMinus; // private Map<Key, Alias> joined = new HashMap<Key, Alias>(); // // private Alias(Class<? extends T> clazz, String aliasStr) { // // this.aliasStr = aliasStr; // this.config = session.getConfigFor(clazz); // // if (this.config == null) // throw new BeanException("BeanConfig not found for "+clazz); // // this.proxy = (T) PropertiesProxy.create(config.getBeanClass()); // // createdAliases.add(this); // } // // /** // * Defines the properties that will return. In other words, <b>only</b> these properties will be populated // * @param returns // */ // public void setReturns(Object... returns){ // // this.returns = AnsiSQLBeanSession.getProperties(returns); // } // // /** // * Defines the properties that will <b>NOT</b> return. In other words, these properties will be not populated // * @param returns // */ // public void setReturnMinus(Object... returns){ // // this.returnMinus = AnsiSQLBeanSession.getProperties(returns); // } // // /** // * Returns the proxy for bean class // * @return The proxy // * @deprecated Use {@link #proxy()} instead // */ // public T pxy(){ // // return proxy; // } // // public T proxy(){ // // return proxy; // } // // /** // * Convert the given property to database column // * @param property - The bean property (can be through proxy) // * @return The database column name // */ // public String toColumn(Object property){ // // return session.propertyToColumn(config.getBeanClass(), property, aliasStr); // } // // /** // * Populates the bean according to ResultSet // * @param rs // * @param bean // */ // public void populateBean(ResultSet rs, T bean){ // // session.populateBeanImpl(rs, bean, aliasStr, returns, returnMinus, false); // } // // public void populateAll(ResultSet rs, T bean) { // // populateBean(rs, bean); // // for (Map.Entry<Key, Alias> m : joined.entrySet()) { // // //only if alias is in SELECT clause // if (selectAliases.contains(m.getValue())) { // // Object value = session.getPropertyBean(bean, m.getKey().property, m.getKey().forceInstance); // // if (value != null) { // m.getValue().populateAll(rs, value); // } // } // // } // } // // @Override // public String toString() { // return "Alias "+aliasStr+" of "+config.getBeanClass(); // } // // /** // * Configures a property name to receive data from alias. When <code>forceIntance</code> is <b>true</b> // * it will force the creation of a new instance for the property, in other words, // * the value will never be <code>null</code> // * @param property - Bean property to populate // * @param forceInstance // * @param alias - Alias // */ // private void put(Object property, boolean forceInstance, Alias<?> alias) { // joined.put(new Key().property(property).forceInstance(forceInstance), alias); // } // // private class Key { // // private String property; // private boolean forceInstance; // // public Key property(Object property) { // this.property = AnsiSQLBeanSession.getProperties(new Object[] {property})[0]; // //this.property = PropertiesProxy.getPropertyName(); // return this; // } // // public Key forceInstance(boolean force) { // this.forceInstance = force; // return this; // } // } // // } // Path: src/main/java/org/mentabean/sql/param/ParamField.java import org.mentabean.jdbc.QueryBuilder.Alias; package org.mentabean.sql.param; public class ParamField implements Param { private String column;
public ParamField(Alias<?> alias, Object property) {
saoj/mentabean
src/main/java/org/mentabean/sql/conditions/AbstractBetween.java
// Path: src/main/java/org/mentabean/sql/Condition.java // public interface Condition extends HasParams { // // } // // Path: src/main/java/org/mentabean/sql/param/Param.java // public interface Param { // // /** // * Represents the parameters in query. In other words, this method returns a String // * with the expression exactly as will be shown in SQL before its execution. // * @return String // */ // public String paramInQuery(); // // /** // * The parameter's values // * @return Object[] // */ // public Object[] values(); // // } // // Path: src/main/java/org/mentabean/sql/param/ParamValue.java // public class ParamValue implements Param { // // private Object value; // // public ParamValue(Object value) { // this.value = value; // } // // @Override // public String paramInQuery() { // return "?"; // } // // @Override // public Object[] values() { // return new Object[] {value}; // } // // }
import org.mentabean.sql.Condition; import org.mentabean.sql.param.Param; import org.mentabean.sql.param.ParamValue;
package org.mentabean.sql.conditions; public abstract class AbstractBetween implements Condition { protected Param begin, end; public AbstractBetween(Param begin, Param end) { this.begin = begin; this.end = end; } public AbstractBetween(Object beginValue, Object endValue) { if (beginValue != null)
// Path: src/main/java/org/mentabean/sql/Condition.java // public interface Condition extends HasParams { // // } // // Path: src/main/java/org/mentabean/sql/param/Param.java // public interface Param { // // /** // * Represents the parameters in query. In other words, this method returns a String // * with the expression exactly as will be shown in SQL before its execution. // * @return String // */ // public String paramInQuery(); // // /** // * The parameter's values // * @return Object[] // */ // public Object[] values(); // // } // // Path: src/main/java/org/mentabean/sql/param/ParamValue.java // public class ParamValue implements Param { // // private Object value; // // public ParamValue(Object value) { // this.value = value; // } // // @Override // public String paramInQuery() { // return "?"; // } // // @Override // public Object[] values() { // return new Object[] {value}; // } // // } // Path: src/main/java/org/mentabean/sql/conditions/AbstractBetween.java import org.mentabean.sql.Condition; import org.mentabean.sql.param.Param; import org.mentabean.sql.param.ParamValue; package org.mentabean.sql.conditions; public abstract class AbstractBetween implements Condition { protected Param begin, end; public AbstractBetween(Param begin, Param end) { this.begin = begin; this.end = end; } public AbstractBetween(Object beginValue, Object endValue) { if (beginValue != null)
begin = new ParamValue(beginValue);
saoj/mentabean
src/main/java/org/mentabean/AutoBeanConfig.java
// Path: src/main/java/org/mentabean/util/FindProperties.java // public class FindProperties { // // public static Map<String, Class<? extends Object>> all(Class<? extends Object> clazz) { // // Map<String, Class<? extends Object>> all = new HashMap<String, Class<? extends Object>>(); // // for (Method method : clazz.getMethods()) { // String name = method.getName(); // Class<? extends Object> returnType = method.getReturnType(); // if (name.length() > 3 && (name.startsWith("get") || name.startsWith("is")) && !name.equals("getClass") && method.getParameterTypes().length == 0 && returnType != null && !returnType.equals(Void.class)) { // // String propName = name.startsWith("get") ? name.substring(3) : name.substring(2); // propName = propName.substring(0, 1).toLowerCase() + propName.substring(1); // // all.put(propName, returnType); // } // } // return all; // } // }
import java.util.Map; import org.mentabean.util.FindProperties;
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * MentaBean => http://www.mentabean.org * Author: Sergio Oliveira Jr. (sergio.oliveira.jr@gmail.com) */ package org.mentabean; /** * A bean config that uses reflection to try to guess the database column type from the bean properties. * * @author soliveira */ public class AutoBeanConfig extends BeanConfig { public AutoBeanConfig(Class<? extends Object> klass, String tableName) { super(klass, tableName); // now use reflection to configure this guy...
// Path: src/main/java/org/mentabean/util/FindProperties.java // public class FindProperties { // // public static Map<String, Class<? extends Object>> all(Class<? extends Object> clazz) { // // Map<String, Class<? extends Object>> all = new HashMap<String, Class<? extends Object>>(); // // for (Method method : clazz.getMethods()) { // String name = method.getName(); // Class<? extends Object> returnType = method.getReturnType(); // if (name.length() > 3 && (name.startsWith("get") || name.startsWith("is")) && !name.equals("getClass") && method.getParameterTypes().length == 0 && returnType != null && !returnType.equals(Void.class)) { // // String propName = name.startsWith("get") ? name.substring(3) : name.substring(2); // propName = propName.substring(0, 1).toLowerCase() + propName.substring(1); // // all.put(propName, returnType); // } // } // return all; // } // } // Path: src/main/java/org/mentabean/AutoBeanConfig.java import java.util.Map; import org.mentabean.util.FindProperties; /* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * MentaBean => http://www.mentabean.org * Author: Sergio Oliveira Jr. (sergio.oliveira.jr@gmail.com) */ package org.mentabean; /** * A bean config that uses reflection to try to guess the database column type from the bean properties. * * @author soliveira */ public class AutoBeanConfig extends BeanConfig { public AutoBeanConfig(Class<? extends Object> klass, String tableName) { super(klass, tableName); // now use reflection to configure this guy...
Map<String, Class<? extends Object>> props = FindProperties.all(klass);
saoj/mentabean
src/main/java/org/mentabean/util/AndroidProxy.java
// Path: src/main/java/org/mentabean/BeanException.java // public class BeanException extends RuntimeException { // // private static final long serialVersionUID = -6402197033079197979L; // // protected final Throwable rootCause; // // public BeanException() { // super(); // this.rootCause = null; // } // // public BeanException(Throwable e) { // super(getMsg(e), e); // Throwable root = getRootCause(e); // this.setStackTrace(root.getStackTrace()); // // this.rootCause = root == this ? null : root; // } // // public BeanException(String msg) { // super(msg); // // this.rootCause = null; // } // // public BeanException(String msg, Throwable e) { // // super(msg, e); // Throwable root = getRootCause(e); // this.setStackTrace(root.getStackTrace()); // // this.rootCause = root == this ? null : root; // } // // private static String getMsg(Throwable t) { // // Throwable root = getRootCause(t); // // String msg = root.getMessage(); // // if (msg == null || msg.length() == 0) { // // msg = t.getMessage(); // // if (msg == null || msg.length() == 0) { // return root.getClass().getName(); // } // } // // return msg; // } // // private static Throwable getRootCause(Throwable t) { // // Throwable root = t.getCause(); // // if (root == null) { // return t; // } // // while (root.getCause() != null) { // // root = root.getCause(); // } // // return root; // // } // // @Override // public Throwable getCause() { // // return rootCause; // } // }
import java.io.File; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import org.mentabean.BeanException; import com.google.dexmaker.stock.ProxyBuilder;
package org.mentabean.util; public class AndroidProxy extends PropertiesProxy { private static File dexCache; public AndroidProxy(File dexCache) { super(null); AndroidProxy.dexCache = dexCache; } public AndroidProxy(String chainProp) { super(chainProp); } @Override protected <E> E createInternal(Class<E> klass) { try { return ProxyBuilder.forClass(klass) .dexCache(dexCache) .handler(new Handler()) .build(); } catch (Exception e) {
// Path: src/main/java/org/mentabean/BeanException.java // public class BeanException extends RuntimeException { // // private static final long serialVersionUID = -6402197033079197979L; // // protected final Throwable rootCause; // // public BeanException() { // super(); // this.rootCause = null; // } // // public BeanException(Throwable e) { // super(getMsg(e), e); // Throwable root = getRootCause(e); // this.setStackTrace(root.getStackTrace()); // // this.rootCause = root == this ? null : root; // } // // public BeanException(String msg) { // super(msg); // // this.rootCause = null; // } // // public BeanException(String msg, Throwable e) { // // super(msg, e); // Throwable root = getRootCause(e); // this.setStackTrace(root.getStackTrace()); // // this.rootCause = root == this ? null : root; // } // // private static String getMsg(Throwable t) { // // Throwable root = getRootCause(t); // // String msg = root.getMessage(); // // if (msg == null || msg.length() == 0) { // // msg = t.getMessage(); // // if (msg == null || msg.length() == 0) { // return root.getClass().getName(); // } // } // // return msg; // } // // private static Throwable getRootCause(Throwable t) { // // Throwable root = t.getCause(); // // if (root == null) { // return t; // } // // while (root.getCause() != null) { // // root = root.getCause(); // } // // return root; // // } // // @Override // public Throwable getCause() { // // return rootCause; // } // } // Path: src/main/java/org/mentabean/util/AndroidProxy.java import java.io.File; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import org.mentabean.BeanException; import com.google.dexmaker.stock.ProxyBuilder; package org.mentabean.util; public class AndroidProxy extends PropertiesProxy { private static File dexCache; public AndroidProxy(File dexCache) { super(null); AndroidProxy.dexCache = dexCache; } public AndroidProxy(String chainProp) { super(chainProp); } @Override protected <E> E createInternal(Class<E> klass) { try { return ProxyBuilder.forClass(klass) .dexCache(dexCache) .handler(new Handler()) .build(); } catch (Exception e) {
throw new BeanException(e);
saoj/mentabean
src/main/java/org/mentabean/type/BooleanStringType.java
// Path: src/main/java/org/mentabean/BeanException.java // public class BeanException extends RuntimeException { // // private static final long serialVersionUID = -6402197033079197979L; // // protected final Throwable rootCause; // // public BeanException() { // super(); // this.rootCause = null; // } // // public BeanException(Throwable e) { // super(getMsg(e), e); // Throwable root = getRootCause(e); // this.setStackTrace(root.getStackTrace()); // // this.rootCause = root == this ? null : root; // } // // public BeanException(String msg) { // super(msg); // // this.rootCause = null; // } // // public BeanException(String msg, Throwable e) { // // super(msg, e); // Throwable root = getRootCause(e); // this.setStackTrace(root.getStackTrace()); // // this.rootCause = root == this ? null : root; // } // // private static String getMsg(Throwable t) { // // Throwable root = getRootCause(t); // // String msg = root.getMessage(); // // if (msg == null || msg.length() == 0) { // // msg = t.getMessage(); // // if (msg == null || msg.length() == 0) { // return root.getClass().getName(); // } // } // // return msg; // } // // private static Throwable getRootCause(Throwable t) { // // Throwable root = t.getCause(); // // if (root == null) { // return t; // } // // while (root.getCause() != null) { // // root = root.getCause(); // } // // return root; // // } // // @Override // public Throwable getCause() { // // return rootCause; // } // } // // Path: src/main/java/org/mentabean/DBType.java // public interface DBType<E> { // // /** // * Do what you have to do to get and return this database type from a result set. // * // * @param rset // * The result set // * @param index // * The index in the result set // * @return The value from the result set // * @throws SQLException // */ // public E getFromResultSet(ResultSet rset, int index) throws SQLException; // // /** // * Do what you have to do to bind a value to a prepared statement. // * // * @param stmt // * The prepared statement // * @param index // * The index in the prepared statement // * @param value // * The value to be bound to the prepared statement // * @throws SQLException // */ // public void bindToStmt(PreparedStatement stmt, int index, E value) throws SQLException; // // /** // * Do what you have to do to get and return this database type from a result set. // * // * @param rset // * The result set // * @param field // * The name of the field in the result set // * @return The value from the result set // * @throws SQLException // */ // public E getFromResultSet(ResultSet rset, String field) throws SQLException; // // /** // * Return the java type representing this database type. // * // * @return The java type of this database type. // */ // public Class<? extends Object> getTypeClass(); // // /** // * Returns whether this type can be NULL in the database. This is used by the session.createTable() method. // * // * @return true if field can be NULL in the database. // */ // public boolean canBeNull(); // // /** // * Return the best ANSI type for this database type. This is used by the session.createTable() method. // * // * @return the ANSI type for this database type. // */ // public String getAnsiType(); // // }
import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import org.mentabean.BeanException; import org.mentabean.DBType;
} if (s.equals(sFalse)) { return false; } return null; } private static Boolean getBoolValue(final boolean b) { if (b) { return Boolean.TRUE; } return Boolean.FALSE; } @Override public Boolean getFromResultSet(final ResultSet rset, final int index) throws SQLException { final String s = rset.getString(index); if (rset.wasNull() || s == null) { return null; } final Boolean b = getBooleanValue(s); if (b == null) {
// Path: src/main/java/org/mentabean/BeanException.java // public class BeanException extends RuntimeException { // // private static final long serialVersionUID = -6402197033079197979L; // // protected final Throwable rootCause; // // public BeanException() { // super(); // this.rootCause = null; // } // // public BeanException(Throwable e) { // super(getMsg(e), e); // Throwable root = getRootCause(e); // this.setStackTrace(root.getStackTrace()); // // this.rootCause = root == this ? null : root; // } // // public BeanException(String msg) { // super(msg); // // this.rootCause = null; // } // // public BeanException(String msg, Throwable e) { // // super(msg, e); // Throwable root = getRootCause(e); // this.setStackTrace(root.getStackTrace()); // // this.rootCause = root == this ? null : root; // } // // private static String getMsg(Throwable t) { // // Throwable root = getRootCause(t); // // String msg = root.getMessage(); // // if (msg == null || msg.length() == 0) { // // msg = t.getMessage(); // // if (msg == null || msg.length() == 0) { // return root.getClass().getName(); // } // } // // return msg; // } // // private static Throwable getRootCause(Throwable t) { // // Throwable root = t.getCause(); // // if (root == null) { // return t; // } // // while (root.getCause() != null) { // // root = root.getCause(); // } // // return root; // // } // // @Override // public Throwable getCause() { // // return rootCause; // } // } // // Path: src/main/java/org/mentabean/DBType.java // public interface DBType<E> { // // /** // * Do what you have to do to get and return this database type from a result set. // * // * @param rset // * The result set // * @param index // * The index in the result set // * @return The value from the result set // * @throws SQLException // */ // public E getFromResultSet(ResultSet rset, int index) throws SQLException; // // /** // * Do what you have to do to bind a value to a prepared statement. // * // * @param stmt // * The prepared statement // * @param index // * The index in the prepared statement // * @param value // * The value to be bound to the prepared statement // * @throws SQLException // */ // public void bindToStmt(PreparedStatement stmt, int index, E value) throws SQLException; // // /** // * Do what you have to do to get and return this database type from a result set. // * // * @param rset // * The result set // * @param field // * The name of the field in the result set // * @return The value from the result set // * @throws SQLException // */ // public E getFromResultSet(ResultSet rset, String field) throws SQLException; // // /** // * Return the java type representing this database type. // * // * @return The java type of this database type. // */ // public Class<? extends Object> getTypeClass(); // // /** // * Returns whether this type can be NULL in the database. This is used by the session.createTable() method. // * // * @return true if field can be NULL in the database. // */ // public boolean canBeNull(); // // /** // * Return the best ANSI type for this database type. This is used by the session.createTable() method. // * // * @return the ANSI type for this database type. // */ // public String getAnsiType(); // // } // Path: src/main/java/org/mentabean/type/BooleanStringType.java import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import org.mentabean.BeanException; import org.mentabean.DBType; } if (s.equals(sFalse)) { return false; } return null; } private static Boolean getBoolValue(final boolean b) { if (b) { return Boolean.TRUE; } return Boolean.FALSE; } @Override public Boolean getFromResultSet(final ResultSet rset, final int index) throws SQLException { final String s = rset.getString(index); if (rset.wasNull() || s == null) { return null; } final Boolean b = getBooleanValue(s); if (b == null) {
throw new BeanException("Don't know how to convert String to boolean:" + s);
bmoyer/osrsclient
src/rsclient/chat/ChatMainPane.java
// Path: src/logic/IrcManager.java // public class IrcManager { // // NetworkSession networkSession; // ChatMainPane mainIrcPanel; // // public IrcManager() { // //called from gui // //mainIrcPanel = ircPanel; // } // // public void addConnection(String nick, ArrayList<String> chanNames) { // networkSession = new NetworkSession(nick, chanNames, this); // } // // public void startConnections() throws IOException, IrcException { // networkSession.startSession(); // } // // public void messageReceived(String channel, String message, String user) { // mainIrcPanel.addMessageToPanel(user, channel, message); // } // // public void onUserInput(String str) { // String lexed[] = str.split("\\s+"); // if (lexed.length == 2 && lexed[0].equals("/join")) { // if (mainIrcPanel.getMessagePanels().containsKey(lexed[1])) { // mainIrcPanel.clearInputField(); // mainIrcPanel.switchChanPanels(lexed[1]); // } else { // mainIrcPanel.clearInputField(); // joinChannel(lexed[1]); // } // } else { // mainIrcPanel.clearInputField(); // networkSession.sendMessage(mainIrcPanel.getCurrentChannel(), str); // } // // } // // public void onJoinEvent(Object[] users) { // for (Object o : users) { // System.out.println(); // } // } // // public void setIrcPanel(ChatMainPane ircPanel) { // mainIrcPanel = ircPanel; // } // // public void joinChannel(final String chanName) { // // mainIrcPanel.addChanPanel(chanName); // mainIrcPanel.switchChanPanels(chanName); // networkSession.joinChannel(chanName); // // } // }
import java.awt.Color; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import javax.swing.BorderFactory; import javax.swing.DefaultListModel; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.ListModel; import javax.swing.UIManager; import javax.swing.border.Border; import javax.swing.border.EtchedBorder; import javax.swing.text.DefaultCaret; import logic.IrcManager; import net.miginfocom.swing.MigLayout; import org.pircbotx.User;
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package rsclient.chat; /** * * @author ben */ public class ChatMainPane extends JPanel { JTextArea messagewindow; JTextField inputfield; JTextArea userlist; JList chanlist; ListModel curChans; JScrollPane messagescroll, userscroll, chanscroll; private ActionListener inputListener; String currentChannel; Font ircFont; HashMap<String, JTextArea> messagePanels = new HashMap(); HashMap<String, JTextArea> userPanels = new HashMap(); IrcPanel mainPanel;
// Path: src/logic/IrcManager.java // public class IrcManager { // // NetworkSession networkSession; // ChatMainPane mainIrcPanel; // // public IrcManager() { // //called from gui // //mainIrcPanel = ircPanel; // } // // public void addConnection(String nick, ArrayList<String> chanNames) { // networkSession = new NetworkSession(nick, chanNames, this); // } // // public void startConnections() throws IOException, IrcException { // networkSession.startSession(); // } // // public void messageReceived(String channel, String message, String user) { // mainIrcPanel.addMessageToPanel(user, channel, message); // } // // public void onUserInput(String str) { // String lexed[] = str.split("\\s+"); // if (lexed.length == 2 && lexed[0].equals("/join")) { // if (mainIrcPanel.getMessagePanels().containsKey(lexed[1])) { // mainIrcPanel.clearInputField(); // mainIrcPanel.switchChanPanels(lexed[1]); // } else { // mainIrcPanel.clearInputField(); // joinChannel(lexed[1]); // } // } else { // mainIrcPanel.clearInputField(); // networkSession.sendMessage(mainIrcPanel.getCurrentChannel(), str); // } // // } // // public void onJoinEvent(Object[] users) { // for (Object o : users) { // System.out.println(); // } // } // // public void setIrcPanel(ChatMainPane ircPanel) { // mainIrcPanel = ircPanel; // } // // public void joinChannel(final String chanName) { // // mainIrcPanel.addChanPanel(chanName); // mainIrcPanel.switchChanPanels(chanName); // networkSession.joinChannel(chanName); // // } // } // Path: src/rsclient/chat/ChatMainPane.java import java.awt.Color; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import javax.swing.BorderFactory; import javax.swing.DefaultListModel; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.ListModel; import javax.swing.UIManager; import javax.swing.border.Border; import javax.swing.border.EtchedBorder; import javax.swing.text.DefaultCaret; import logic.IrcManager; import net.miginfocom.swing.MigLayout; import org.pircbotx.User; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package rsclient.chat; /** * * @author ben */ public class ChatMainPane extends JPanel { JTextArea messagewindow; JTextField inputfield; JTextArea userlist; JList chanlist; ListModel curChans; JScrollPane messagescroll, userscroll, chanscroll; private ActionListener inputListener; String currentChannel; Font ircFont; HashMap<String, JTextArea> messagePanels = new HashMap(); HashMap<String, JTextArea> userPanels = new HashMap(); IrcPanel mainPanel;
IrcManager manager;
bmoyer/osrsclient
src/rsclient/market/ItemListPanel.java
// Path: src/logic/ZybezItemListing.java // public class ZybezItemListing { // // private String itemName, imageURL, averagePrice, itemID; // private ArrayList<ZybezOffer> offerList = new ArrayList(); // private int numOffers; // private final String apiURL = "http://forums.zybez.net/runescape-2007-prices/api/item/"; // private String listingJsonString; // // public ZybezItemListing(String id) { // // itemID = id; // setItemData(); // setItemOffers(); // } // // private void setItemData() { // // try { // listingJsonString = getJsonString(); // JSONObject o = (JSONObject) JSONValue.parse(listingJsonString); // // itemName = o.get("name").toString(); // imageURL = o.get("image").toString(); // averagePrice = o.get("average").toString(); // // // } catch (IOException ex) { // Logger.getLogger(ZybezItemListing.class.getName()).log(Level.SEVERE, null, ex); // } // // } // // private void setItemOffers(){ // // JSONObject o = (JSONObject) JSONValue.parse(listingJsonString); // String offerString = o.get("offers").toString(); // JSONArray array = (JSONArray) JSONValue.parse(offerString); // // numOffers = array.size(); // for(int i = 0; i < numOffers; i ++){ // JSONObject o2 = (JSONObject) JSONValue.parse(array.get(i).toString()); // // ZybezOffer z = new ZybezOffer(itemID, o2.get("selling").toString(), // o2.get("quantity").toString(), o2.get("price").toString(), itemName, o2.get("rs_name").toString(), o2.get("notes").toString()); // // offerList.add(z); // } // // // } // // //returns Json string for offers for this item // private String getJsonString() throws MalformedURLException, IOException { // URL url = new URL(apiURL + itemID); // URLConnection urlConnection = url.openConnection(); // urlConnection.addRequestProperty("User-Agent", "Mozilla/5.0"); // BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); // //Put JSON data into String message // String message = org.apache.commons.io.IOUtils.toString(in); // return message; // } // // public String getItemID() { // return itemID; // } // // public String getItemName() { // return itemName; // } // // public String getImageURL() { // return imageURL; // } // // public String getAveragePrice() { // return averagePrice; // } // // public ArrayList<ZybezOffer> getOfferList() { // return offerList; // } // // }
import java.awt.Color; import java.util.ArrayList; import javax.swing.BorderFactory; import javax.swing.JPanel; import javax.swing.border.Border; import javax.swing.border.EtchedBorder; import logic.ZybezItemListing; import net.miginfocom.swing.MigLayout;
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package rsclient.market; /** * * @author ben */ public class ItemListPanel extends JPanel implements ItemListingRolloverListener { ItemResultPanel offerPanels[] = new ItemResultPanel[5]; private ItemResultPanel selectedPanel = null; private ItemListingRolloverListener rolloverListener; public boolean itemsFound; private final Border selectedBorder = BorderFactory.createEtchedBorder(Color.white, Color.blue); public ItemListPanel() { setup(); for (int x = 0; x < 5; x++) { offerPanels[x] = new ItemResultPanel(); offerPanels[x].setRolloverListener(this); } int i = 0; for (ItemResultPanel j : offerPanels) { add(j, "height 20%, width 100%, spanx, growx, cell 0 " + i); i++; } }
// Path: src/logic/ZybezItemListing.java // public class ZybezItemListing { // // private String itemName, imageURL, averagePrice, itemID; // private ArrayList<ZybezOffer> offerList = new ArrayList(); // private int numOffers; // private final String apiURL = "http://forums.zybez.net/runescape-2007-prices/api/item/"; // private String listingJsonString; // // public ZybezItemListing(String id) { // // itemID = id; // setItemData(); // setItemOffers(); // } // // private void setItemData() { // // try { // listingJsonString = getJsonString(); // JSONObject o = (JSONObject) JSONValue.parse(listingJsonString); // // itemName = o.get("name").toString(); // imageURL = o.get("image").toString(); // averagePrice = o.get("average").toString(); // // // } catch (IOException ex) { // Logger.getLogger(ZybezItemListing.class.getName()).log(Level.SEVERE, null, ex); // } // // } // // private void setItemOffers(){ // // JSONObject o = (JSONObject) JSONValue.parse(listingJsonString); // String offerString = o.get("offers").toString(); // JSONArray array = (JSONArray) JSONValue.parse(offerString); // // numOffers = array.size(); // for(int i = 0; i < numOffers; i ++){ // JSONObject o2 = (JSONObject) JSONValue.parse(array.get(i).toString()); // // ZybezOffer z = new ZybezOffer(itemID, o2.get("selling").toString(), // o2.get("quantity").toString(), o2.get("price").toString(), itemName, o2.get("rs_name").toString(), o2.get("notes").toString()); // // offerList.add(z); // } // // // } // // //returns Json string for offers for this item // private String getJsonString() throws MalformedURLException, IOException { // URL url = new URL(apiURL + itemID); // URLConnection urlConnection = url.openConnection(); // urlConnection.addRequestProperty("User-Agent", "Mozilla/5.0"); // BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); // //Put JSON data into String message // String message = org.apache.commons.io.IOUtils.toString(in); // return message; // } // // public String getItemID() { // return itemID; // } // // public String getItemName() { // return itemName; // } // // public String getImageURL() { // return imageURL; // } // // public String getAveragePrice() { // return averagePrice; // } // // public ArrayList<ZybezOffer> getOfferList() { // return offerList; // } // // } // Path: src/rsclient/market/ItemListPanel.java import java.awt.Color; import java.util.ArrayList; import javax.swing.BorderFactory; import javax.swing.JPanel; import javax.swing.border.Border; import javax.swing.border.EtchedBorder; import logic.ZybezItemListing; import net.miginfocom.swing.MigLayout; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package rsclient.market; /** * * @author ben */ public class ItemListPanel extends JPanel implements ItemListingRolloverListener { ItemResultPanel offerPanels[] = new ItemResultPanel[5]; private ItemResultPanel selectedPanel = null; private ItemListingRolloverListener rolloverListener; public boolean itemsFound; private final Border selectedBorder = BorderFactory.createEtchedBorder(Color.white, Color.blue); public ItemListPanel() { setup(); for (int x = 0; x < 5; x++) { offerPanels[x] = new ItemResultPanel(); offerPanels[x].setRolloverListener(this); } int i = 0; for (ItemResultPanel j : offerPanels) { add(j, "height 20%, width 100%, spanx, growx, cell 0 " + i); i++; } }
public void populateResultPanels(ArrayList<ZybezItemListing> itemsFound) {
bmoyer/osrsclient
src/rsclient/hiscores/LevelScorePanel.java
// Path: src/logic/RuneScapeAccount.java // public class RuneScapeAccount { // // private boolean isValidAccount; // public String username; // int overallLevel = 0; // private final String[] skillNames = {"overall", "attack", "defense", "strength", "hitpoints", // "ranged", "prayer", "magic", "cooking", "woodcutting", "fletching", // "fishing", "firemaking", "crafting", "smithing", "mining", "herblore", // "agility", "thieving", "slayer", "farming", "runecrafting", "hunter", "construction"}; // // public final HashMap<String, RuneScapeLevel> hiscores = new HashMap(); // // String baseUrl = "http://services.runescape.com/m=hiscore_oldschool/index_lite.ws?player="; // // public RuneScapeAccount(String u) { // // username = u; // isValidAccount = false; // } // // public void loadStats() throws IOException { // // String rsn = username.replaceAll(" ", "_"); // BufferedReader in = null; // try { // URL hiscoreUrl = new URL(baseUrl + username); // URLConnection yc = hiscoreUrl.openConnection(); // in = new BufferedReader(new InputStreamReader(yc.getInputStream())); // String inputLine; // int c = 0; // int totalLevel = 0; // int totalExp = 0; // while ((inputLine = in.readLine()) != null) { // String[] tokens = inputLine.split(","); // if (tokens.length == 3) { // RuneScapeLevel level = new RuneScapeLevel(Integer.parseInt(tokens[0]), Integer.parseInt(tokens[1]), Integer.parseInt(tokens[2])); // if (c <= skillNames.length) { // hiscores.put(skillNames[c], level); // totalLevel += level.level; // totalExp += level.experience; // } // c++; // } // } // RuneScapeLevel combatLevel = new RuneScapeLevel(0, (int) getCombatLevel(), 0); // hiscores.put("combat", combatLevel); // if(hiscores.get("overall").level == 0){ //will be 0 if player is unranked // hiscores.get("overall").level = totalLevel; // hiscores.get("overall").experience = totalExp; // } // isValidAccount = true; // } catch (IOException ex) { // //ex.printStackTrace(); // isValidAccount = false; // } finally { // if (in != null) { // in.close(); // } // } // // } // // public static boolean isValidRSN(String s) { // if (s.length() > 12) { // return false; // } // //determine if any non-alphanumeric characters are in the string, indicating invalid RSN // return !s.replace("-", "").replace(" ", "").replace("_", "").matches("^.*[^a-zA-Z0-9 ].*$"); // } // // public double getCombatLevel() { // // return Calculate.calculateCombatLevel(hiscores.get("attack").level, hiscores.get("strength").level, // hiscores.get("defense").level, hiscores.get("prayer").level, hiscores.get("ranged").level, // hiscores.get("magic").level, hiscores.get("hitpoints").level); // } // // public boolean isValidAccount() { // return isValidAccount; // } // // } // // Path: src/rsclient/coregui/Style.java // public class Style { // // public static final Color DEFAULT_GRAY = new Color(51,51,51); // // public final Color backgroundColor; // public final Color foregroundColor; // public final Font font; // // public Style(Color foregroundColor, Color backgroundColor, Font font){ // this.foregroundColor = foregroundColor; // this.backgroundColor = backgroundColor; // this.font = font; // } // // public static Style getDefaultStyle(){ // // return new Style(Color.white, DEFAULT_GRAY, new Font(new JLabel().getFont().getFontName(), Font.PLAIN, new JLabel().getFont().getSize() + 2)); // } // // } // // Path: src/logic/Calculate.java // public class Calculate { // // //Credits to Talon876/RSIRCBOT project for this function. // public static double calculateCombatLevel(int atk, int str, int def, int prayer, int range, int magic, int hp) { // // double baseLvl = (def + hp + Math.floor(prayer / 2)) * 0.25; // // double meleeLvl = (atk + str) * 0.325; // double rangerLvl = Math.floor(range * 1.5) * 0.325; // double mageLvl = Math.floor(magic * 1.5) * 0.325; // // baseLvl = baseLvl + Math.max(meleeLvl, (Math.max(rangerLvl, mageLvl))); // // return baseLvl; // } // // public static int xpForLevel(int level) { // double value = 0; // for (int i = 1; i < level; i++) { // value += Math.floor(i + 300f * Math.pow(2f, i / 7f)); // } // value = (int) Math.floor(.25 * value); // return (int) value; // } // // // }
import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.ImageIcon; import javax.swing.JLabel; import javax.swing.JPanel; import logic.RuneScapeAccount; import net.miginfocom.swing.MigLayout; import rsclient.coregui.Style; import logic.Calculate;
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package rsclient.hiscores; /** * * @author ben */ public class LevelScorePanel extends JPanel implements MouseListener { private String skill; private JLabel skillImageLabel; private JLabel skillLevelLabel; private StatRolloverListener rolloverListener;
// Path: src/logic/RuneScapeAccount.java // public class RuneScapeAccount { // // private boolean isValidAccount; // public String username; // int overallLevel = 0; // private final String[] skillNames = {"overall", "attack", "defense", "strength", "hitpoints", // "ranged", "prayer", "magic", "cooking", "woodcutting", "fletching", // "fishing", "firemaking", "crafting", "smithing", "mining", "herblore", // "agility", "thieving", "slayer", "farming", "runecrafting", "hunter", "construction"}; // // public final HashMap<String, RuneScapeLevel> hiscores = new HashMap(); // // String baseUrl = "http://services.runescape.com/m=hiscore_oldschool/index_lite.ws?player="; // // public RuneScapeAccount(String u) { // // username = u; // isValidAccount = false; // } // // public void loadStats() throws IOException { // // String rsn = username.replaceAll(" ", "_"); // BufferedReader in = null; // try { // URL hiscoreUrl = new URL(baseUrl + username); // URLConnection yc = hiscoreUrl.openConnection(); // in = new BufferedReader(new InputStreamReader(yc.getInputStream())); // String inputLine; // int c = 0; // int totalLevel = 0; // int totalExp = 0; // while ((inputLine = in.readLine()) != null) { // String[] tokens = inputLine.split(","); // if (tokens.length == 3) { // RuneScapeLevel level = new RuneScapeLevel(Integer.parseInt(tokens[0]), Integer.parseInt(tokens[1]), Integer.parseInt(tokens[2])); // if (c <= skillNames.length) { // hiscores.put(skillNames[c], level); // totalLevel += level.level; // totalExp += level.experience; // } // c++; // } // } // RuneScapeLevel combatLevel = new RuneScapeLevel(0, (int) getCombatLevel(), 0); // hiscores.put("combat", combatLevel); // if(hiscores.get("overall").level == 0){ //will be 0 if player is unranked // hiscores.get("overall").level = totalLevel; // hiscores.get("overall").experience = totalExp; // } // isValidAccount = true; // } catch (IOException ex) { // //ex.printStackTrace(); // isValidAccount = false; // } finally { // if (in != null) { // in.close(); // } // } // // } // // public static boolean isValidRSN(String s) { // if (s.length() > 12) { // return false; // } // //determine if any non-alphanumeric characters are in the string, indicating invalid RSN // return !s.replace("-", "").replace(" ", "").replace("_", "").matches("^.*[^a-zA-Z0-9 ].*$"); // } // // public double getCombatLevel() { // // return Calculate.calculateCombatLevel(hiscores.get("attack").level, hiscores.get("strength").level, // hiscores.get("defense").level, hiscores.get("prayer").level, hiscores.get("ranged").level, // hiscores.get("magic").level, hiscores.get("hitpoints").level); // } // // public boolean isValidAccount() { // return isValidAccount; // } // // } // // Path: src/rsclient/coregui/Style.java // public class Style { // // public static final Color DEFAULT_GRAY = new Color(51,51,51); // // public final Color backgroundColor; // public final Color foregroundColor; // public final Font font; // // public Style(Color foregroundColor, Color backgroundColor, Font font){ // this.foregroundColor = foregroundColor; // this.backgroundColor = backgroundColor; // this.font = font; // } // // public static Style getDefaultStyle(){ // // return new Style(Color.white, DEFAULT_GRAY, new Font(new JLabel().getFont().getFontName(), Font.PLAIN, new JLabel().getFont().getSize() + 2)); // } // // } // // Path: src/logic/Calculate.java // public class Calculate { // // //Credits to Talon876/RSIRCBOT project for this function. // public static double calculateCombatLevel(int atk, int str, int def, int prayer, int range, int magic, int hp) { // // double baseLvl = (def + hp + Math.floor(prayer / 2)) * 0.25; // // double meleeLvl = (atk + str) * 0.325; // double rangerLvl = Math.floor(range * 1.5) * 0.325; // double mageLvl = Math.floor(magic * 1.5) * 0.325; // // baseLvl = baseLvl + Math.max(meleeLvl, (Math.max(rangerLvl, mageLvl))); // // return baseLvl; // } // // public static int xpForLevel(int level) { // double value = 0; // for (int i = 1; i < level; i++) { // value += Math.floor(i + 300f * Math.pow(2f, i / 7f)); // } // value = (int) Math.floor(.25 * value); // return (int) value; // } // // // } // Path: src/rsclient/hiscores/LevelScorePanel.java import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.ImageIcon; import javax.swing.JLabel; import javax.swing.JPanel; import logic.RuneScapeAccount; import net.miginfocom.swing.MigLayout; import rsclient.coregui.Style; import logic.Calculate; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package rsclient.hiscores; /** * * @author ben */ public class LevelScorePanel extends JPanel implements MouseListener { private String skill; private JLabel skillImageLabel; private JLabel skillLevelLabel; private StatRolloverListener rolloverListener;
private Style style;
bmoyer/osrsclient
src/rsclient/coregui/RSClient.java
// Path: src/rsclient/toolbar/MainToolBar.java // public class MainToolBar extends JToolBar { // // public MainToolBar() { // setLayout(new MigLayout()); // setFloatable(false); // setBackground(new Color(24, 24, 24)); // setRollover(true); // // ToolBarButton optionsButton = new ToolBarButton("Options"); // ToolBarButton linksButton = new ToolBarButton("Links"); // ToolBarButton screenshotButton = new ToolBarButton("Screenshot"); // ToolBarButton helpButton = new ToolBarButton("Help"); // // final LinksMenu linksmenu = new LinksMenu(); // final HelpMenu helpmenu = new HelpMenu(); // // linksButton.addMouseListener(new MouseAdapter() { // public void mousePressed(MouseEvent e) { // linksmenu.show(e.getComponent(), e.getX(), e.getY()); // } // }); // // helpButton.addMouseListener(new MouseAdapter() { // public void mousePressed(MouseEvent e) { // helpmenu.show(e.getComponent(), e.getX(), e.getY()); // } // }); // // add(optionsButton); // add(linksButton); // add(screenshotButton); // add(helpButton); // // } // } // // Path: src/rsreflection/Reflector.java // public class Reflector extends URLClassLoader { // // // private HashMap<String, FieldInfo> hookMap; // // public Reflector(URL[] urls) { // super(urls); // } // // public Object getFieldValue(String identifier){ // FieldInfo f = hookMap.get(identifier); // return getFieldValueByDetails(f.getClassName(), f.getFieldName()); // } // // public Object getFieldValueByDetails(String className, String fieldName) { // // Object o = null; // try { // Field field = loadClass(className).getDeclaredField(fieldName); // field.setAccessible(true); // return field.get(null); // } catch (ClassNotFoundException ex) { // Logger.getLogger(Reflector.class.getName()).log(Level.SEVERE, null, ex); // } catch (IllegalArgumentException ex) { // Logger.getLogger(Reflector.class.getName()).log(Level.SEVERE, null, ex); // } catch (IllegalAccessException ex) { // Logger.getLogger(Reflector.class.getName()).log(Level.SEVERE, null, ex); // } catch (NoSuchFieldException ex) { // Logger.getLogger(Reflector.class.getName()).log(Level.SEVERE, null, ex); // } catch (SecurityException ex) { // Logger.getLogger(Reflector.class.getName()).log(Level.SEVERE, null, ex); // } // // return o; // } // // public void setHooks(HashMap<String, FieldInfo> hookMap) { // this.hookMap = hookMap; // } // // }
import java.awt.Color; import java.awt.Image; import java.awt.Toolkit; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.ImageIcon; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.UIManager; import net.miginfocom.swing.MigLayout; import org.pircbotx.exception.IrcException; import rsclient.toolbar.MainToolBar; import rsloader.Loader; import rsloader.Loader.Game; import rsreflection.Reflector;
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package rsclient.coregui; /** * * @author ben */ public class RSClient { public static Reflector reflector = null; public static void main(String[] args) throws IrcException, IOException { Toolkit.getDefaultToolkit().setDynamicLayout(true); System.setProperty("sun.awt.noerasebackground", "true"); JFrame.setDefaultLookAndFeelDecorated(true); JDialog.setDefaultLookAndFeelDecorated(true); try { UIManager.setLookAndFeel("de.muntjak.tinylookandfeel.TinyLookAndFeel"); } catch (Exception e) { e.printStackTrace(); } initUI(); } public static void initUI() { JFrame mainwnd = new JFrame("Luna - Open source OSRS Client"); Image icon = Toolkit.getDefaultToolkit().getImage("resources/lunaicon.png"); mainwnd.setIconImage(icon);
// Path: src/rsclient/toolbar/MainToolBar.java // public class MainToolBar extends JToolBar { // // public MainToolBar() { // setLayout(new MigLayout()); // setFloatable(false); // setBackground(new Color(24, 24, 24)); // setRollover(true); // // ToolBarButton optionsButton = new ToolBarButton("Options"); // ToolBarButton linksButton = new ToolBarButton("Links"); // ToolBarButton screenshotButton = new ToolBarButton("Screenshot"); // ToolBarButton helpButton = new ToolBarButton("Help"); // // final LinksMenu linksmenu = new LinksMenu(); // final HelpMenu helpmenu = new HelpMenu(); // // linksButton.addMouseListener(new MouseAdapter() { // public void mousePressed(MouseEvent e) { // linksmenu.show(e.getComponent(), e.getX(), e.getY()); // } // }); // // helpButton.addMouseListener(new MouseAdapter() { // public void mousePressed(MouseEvent e) { // helpmenu.show(e.getComponent(), e.getX(), e.getY()); // } // }); // // add(optionsButton); // add(linksButton); // add(screenshotButton); // add(helpButton); // // } // } // // Path: src/rsreflection/Reflector.java // public class Reflector extends URLClassLoader { // // // private HashMap<String, FieldInfo> hookMap; // // public Reflector(URL[] urls) { // super(urls); // } // // public Object getFieldValue(String identifier){ // FieldInfo f = hookMap.get(identifier); // return getFieldValueByDetails(f.getClassName(), f.getFieldName()); // } // // public Object getFieldValueByDetails(String className, String fieldName) { // // Object o = null; // try { // Field field = loadClass(className).getDeclaredField(fieldName); // field.setAccessible(true); // return field.get(null); // } catch (ClassNotFoundException ex) { // Logger.getLogger(Reflector.class.getName()).log(Level.SEVERE, null, ex); // } catch (IllegalArgumentException ex) { // Logger.getLogger(Reflector.class.getName()).log(Level.SEVERE, null, ex); // } catch (IllegalAccessException ex) { // Logger.getLogger(Reflector.class.getName()).log(Level.SEVERE, null, ex); // } catch (NoSuchFieldException ex) { // Logger.getLogger(Reflector.class.getName()).log(Level.SEVERE, null, ex); // } catch (SecurityException ex) { // Logger.getLogger(Reflector.class.getName()).log(Level.SEVERE, null, ex); // } // // return o; // } // // public void setHooks(HashMap<String, FieldInfo> hookMap) { // this.hookMap = hookMap; // } // // } // Path: src/rsclient/coregui/RSClient.java import java.awt.Color; import java.awt.Image; import java.awt.Toolkit; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.ImageIcon; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.UIManager; import net.miginfocom.swing.MigLayout; import org.pircbotx.exception.IrcException; import rsclient.toolbar.MainToolBar; import rsloader.Loader; import rsloader.Loader.Game; import rsreflection.Reflector; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package rsclient.coregui; /** * * @author ben */ public class RSClient { public static Reflector reflector = null; public static void main(String[] args) throws IrcException, IOException { Toolkit.getDefaultToolkit().setDynamicLayout(true); System.setProperty("sun.awt.noerasebackground", "true"); JFrame.setDefaultLookAndFeelDecorated(true); JDialog.setDefaultLookAndFeelDecorated(true); try { UIManager.setLookAndFeel("de.muntjak.tinylookandfeel.TinyLookAndFeel"); } catch (Exception e) { e.printStackTrace(); } initUI(); } public static void initUI() { JFrame mainwnd = new JFrame("Luna - Open source OSRS Client"); Image icon = Toolkit.getDefaultToolkit().getImage("resources/lunaicon.png"); mainwnd.setIconImage(icon);
MainToolBar toolbar = new MainToolBar();
bmoyer/osrsclient
src/rsclient/hiscores/HiscoresPanel.java
// Path: src/logic/Calculate.java // public class Calculate { // // //Credits to Talon876/RSIRCBOT project for this function. // public static double calculateCombatLevel(int atk, int str, int def, int prayer, int range, int magic, int hp) { // // double baseLvl = (def + hp + Math.floor(prayer / 2)) * 0.25; // // double meleeLvl = (atk + str) * 0.325; // double rangerLvl = Math.floor(range * 1.5) * 0.325; // double mageLvl = Math.floor(magic * 1.5) * 0.325; // // baseLvl = baseLvl + Math.max(meleeLvl, (Math.max(rangerLvl, mageLvl))); // // return baseLvl; // } // // public static int xpForLevel(int level) { // double value = 0; // for (int i = 1; i < level; i++) { // value += Math.floor(i + 300f * Math.pow(2f, i / 7f)); // } // value = (int) Math.floor(.25 * value); // return (int) value; // } // // // } // // Path: src/logic/RuneScapeAccount.java // public class RuneScapeAccount { // // private boolean isValidAccount; // public String username; // int overallLevel = 0; // private final String[] skillNames = {"overall", "attack", "defense", "strength", "hitpoints", // "ranged", "prayer", "magic", "cooking", "woodcutting", "fletching", // "fishing", "firemaking", "crafting", "smithing", "mining", "herblore", // "agility", "thieving", "slayer", "farming", "runecrafting", "hunter", "construction"}; // // public final HashMap<String, RuneScapeLevel> hiscores = new HashMap(); // // String baseUrl = "http://services.runescape.com/m=hiscore_oldschool/index_lite.ws?player="; // // public RuneScapeAccount(String u) { // // username = u; // isValidAccount = false; // } // // public void loadStats() throws IOException { // // String rsn = username.replaceAll(" ", "_"); // BufferedReader in = null; // try { // URL hiscoreUrl = new URL(baseUrl + username); // URLConnection yc = hiscoreUrl.openConnection(); // in = new BufferedReader(new InputStreamReader(yc.getInputStream())); // String inputLine; // int c = 0; // int totalLevel = 0; // int totalExp = 0; // while ((inputLine = in.readLine()) != null) { // String[] tokens = inputLine.split(","); // if (tokens.length == 3) { // RuneScapeLevel level = new RuneScapeLevel(Integer.parseInt(tokens[0]), Integer.parseInt(tokens[1]), Integer.parseInt(tokens[2])); // if (c <= skillNames.length) { // hiscores.put(skillNames[c], level); // totalLevel += level.level; // totalExp += level.experience; // } // c++; // } // } // RuneScapeLevel combatLevel = new RuneScapeLevel(0, (int) getCombatLevel(), 0); // hiscores.put("combat", combatLevel); // if(hiscores.get("overall").level == 0){ //will be 0 if player is unranked // hiscores.get("overall").level = totalLevel; // hiscores.get("overall").experience = totalExp; // } // isValidAccount = true; // } catch (IOException ex) { // //ex.printStackTrace(); // isValidAccount = false; // } finally { // if (in != null) { // in.close(); // } // } // // } // // public static boolean isValidRSN(String s) { // if (s.length() > 12) { // return false; // } // //determine if any non-alphanumeric characters are in the string, indicating invalid RSN // return !s.replace("-", "").replace(" ", "").replace("_", "").matches("^.*[^a-zA-Z0-9 ].*$"); // } // // public double getCombatLevel() { // // return Calculate.calculateCombatLevel(hiscores.get("attack").level, hiscores.get("strength").level, // hiscores.get("defense").level, hiscores.get("prayer").level, hiscores.get("ranged").level, // hiscores.get("magic").level, hiscores.get("hitpoints").level); // } // // public boolean isValidAccount() { // return isValidAccount; // } // // } // // Path: src/rsclient/coregui/LengthRestrictedDocument.java // public final class LengthRestrictedDocument extends PlainDocument { // // private final int limit; // // public LengthRestrictedDocument(int limit) { // this.limit = limit; // } // // @Override // public void insertString(int offs, String str, AttributeSet a) // throws BadLocationException { // if (str == null) // return; // // if ((getLength() + str.length()) <= limit) { // super.insertString(offs, str, a); // } // } // }
import java.awt.Color; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.io.IOException; import java.text.NumberFormat; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.border.EtchedBorder; import logic.Calculate; import logic.RuneScapeAccount; import net.miginfocom.swing.MigLayout; import org.pushingpixels.trident.Timeline; import rsclient.coregui.LengthRestrictedDocument;
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package rsclient.hiscores; /** * * @author ben */ public class HiscoresPanel extends JPanel implements StatRolloverListener { private JTextField usernameField; private JLabel xpDisplay, rsnLabel; private LevelsPanel levelsDisplayPanel;
// Path: src/logic/Calculate.java // public class Calculate { // // //Credits to Talon876/RSIRCBOT project for this function. // public static double calculateCombatLevel(int atk, int str, int def, int prayer, int range, int magic, int hp) { // // double baseLvl = (def + hp + Math.floor(prayer / 2)) * 0.25; // // double meleeLvl = (atk + str) * 0.325; // double rangerLvl = Math.floor(range * 1.5) * 0.325; // double mageLvl = Math.floor(magic * 1.5) * 0.325; // // baseLvl = baseLvl + Math.max(meleeLvl, (Math.max(rangerLvl, mageLvl))); // // return baseLvl; // } // // public static int xpForLevel(int level) { // double value = 0; // for (int i = 1; i < level; i++) { // value += Math.floor(i + 300f * Math.pow(2f, i / 7f)); // } // value = (int) Math.floor(.25 * value); // return (int) value; // } // // // } // // Path: src/logic/RuneScapeAccount.java // public class RuneScapeAccount { // // private boolean isValidAccount; // public String username; // int overallLevel = 0; // private final String[] skillNames = {"overall", "attack", "defense", "strength", "hitpoints", // "ranged", "prayer", "magic", "cooking", "woodcutting", "fletching", // "fishing", "firemaking", "crafting", "smithing", "mining", "herblore", // "agility", "thieving", "slayer", "farming", "runecrafting", "hunter", "construction"}; // // public final HashMap<String, RuneScapeLevel> hiscores = new HashMap(); // // String baseUrl = "http://services.runescape.com/m=hiscore_oldschool/index_lite.ws?player="; // // public RuneScapeAccount(String u) { // // username = u; // isValidAccount = false; // } // // public void loadStats() throws IOException { // // String rsn = username.replaceAll(" ", "_"); // BufferedReader in = null; // try { // URL hiscoreUrl = new URL(baseUrl + username); // URLConnection yc = hiscoreUrl.openConnection(); // in = new BufferedReader(new InputStreamReader(yc.getInputStream())); // String inputLine; // int c = 0; // int totalLevel = 0; // int totalExp = 0; // while ((inputLine = in.readLine()) != null) { // String[] tokens = inputLine.split(","); // if (tokens.length == 3) { // RuneScapeLevel level = new RuneScapeLevel(Integer.parseInt(tokens[0]), Integer.parseInt(tokens[1]), Integer.parseInt(tokens[2])); // if (c <= skillNames.length) { // hiscores.put(skillNames[c], level); // totalLevel += level.level; // totalExp += level.experience; // } // c++; // } // } // RuneScapeLevel combatLevel = new RuneScapeLevel(0, (int) getCombatLevel(), 0); // hiscores.put("combat", combatLevel); // if(hiscores.get("overall").level == 0){ //will be 0 if player is unranked // hiscores.get("overall").level = totalLevel; // hiscores.get("overall").experience = totalExp; // } // isValidAccount = true; // } catch (IOException ex) { // //ex.printStackTrace(); // isValidAccount = false; // } finally { // if (in != null) { // in.close(); // } // } // // } // // public static boolean isValidRSN(String s) { // if (s.length() > 12) { // return false; // } // //determine if any non-alphanumeric characters are in the string, indicating invalid RSN // return !s.replace("-", "").replace(" ", "").replace("_", "").matches("^.*[^a-zA-Z0-9 ].*$"); // } // // public double getCombatLevel() { // // return Calculate.calculateCombatLevel(hiscores.get("attack").level, hiscores.get("strength").level, // hiscores.get("defense").level, hiscores.get("prayer").level, hiscores.get("ranged").level, // hiscores.get("magic").level, hiscores.get("hitpoints").level); // } // // public boolean isValidAccount() { // return isValidAccount; // } // // } // // Path: src/rsclient/coregui/LengthRestrictedDocument.java // public final class LengthRestrictedDocument extends PlainDocument { // // private final int limit; // // public LengthRestrictedDocument(int limit) { // this.limit = limit; // } // // @Override // public void insertString(int offs, String str, AttributeSet a) // throws BadLocationException { // if (str == null) // return; // // if ((getLength() + str.length()) <= limit) { // super.insertString(offs, str, a); // } // } // } // Path: src/rsclient/hiscores/HiscoresPanel.java import java.awt.Color; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.io.IOException; import java.text.NumberFormat; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.border.EtchedBorder; import logic.Calculate; import logic.RuneScapeAccount; import net.miginfocom.swing.MigLayout; import org.pushingpixels.trident.Timeline; import rsclient.coregui.LengthRestrictedDocument; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package rsclient.hiscores; /** * * @author ben */ public class HiscoresPanel extends JPanel implements StatRolloverListener { private JTextField usernameField; private JLabel xpDisplay, rsnLabel; private LevelsPanel levelsDisplayPanel;
private RuneScapeAccount account;
bmoyer/osrsclient
src/rsclient/chat/NetworkSession.java
// Path: src/logic/IrcManager.java // public class IrcManager { // // NetworkSession networkSession; // ChatMainPane mainIrcPanel; // // public IrcManager() { // //called from gui // //mainIrcPanel = ircPanel; // } // // public void addConnection(String nick, ArrayList<String> chanNames) { // networkSession = new NetworkSession(nick, chanNames, this); // } // // public void startConnections() throws IOException, IrcException { // networkSession.startSession(); // } // // public void messageReceived(String channel, String message, String user) { // mainIrcPanel.addMessageToPanel(user, channel, message); // } // // public void onUserInput(String str) { // String lexed[] = str.split("\\s+"); // if (lexed.length == 2 && lexed[0].equals("/join")) { // if (mainIrcPanel.getMessagePanels().containsKey(lexed[1])) { // mainIrcPanel.clearInputField(); // mainIrcPanel.switchChanPanels(lexed[1]); // } else { // mainIrcPanel.clearInputField(); // joinChannel(lexed[1]); // } // } else { // mainIrcPanel.clearInputField(); // networkSession.sendMessage(mainIrcPanel.getCurrentChannel(), str); // } // // } // // public void onJoinEvent(Object[] users) { // for (Object o : users) { // System.out.println(); // } // } // // public void setIrcPanel(ChatMainPane ircPanel) { // mainIrcPanel = ircPanel; // } // // public void joinChannel(final String chanName) { // // mainIrcPanel.addChanPanel(chanName); // mainIrcPanel.switchChanPanels(chanName); // networkSession.joinChannel(chanName); // // } // }
import java.io.IOException; import java.util.ArrayList; import logic.IrcManager; import org.pircbotx.Configuration; import org.pircbotx.PircBotX; import org.pircbotx.exception.IrcException; import org.pircbotx.hooks.ListenerAdapter; import org.pircbotx.hooks.events.ConnectEvent; import org.pircbotx.hooks.events.JoinEvent; import org.pircbotx.hooks.events.MessageEvent; import org.pircbotx.hooks.events.PrivateMessageEvent;
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package rsclient.chat; /** * * @author ben */ public class NetworkSession extends ListenerAdapter<PircBotX> { private final PircBotX bot;
// Path: src/logic/IrcManager.java // public class IrcManager { // // NetworkSession networkSession; // ChatMainPane mainIrcPanel; // // public IrcManager() { // //called from gui // //mainIrcPanel = ircPanel; // } // // public void addConnection(String nick, ArrayList<String> chanNames) { // networkSession = new NetworkSession(nick, chanNames, this); // } // // public void startConnections() throws IOException, IrcException { // networkSession.startSession(); // } // // public void messageReceived(String channel, String message, String user) { // mainIrcPanel.addMessageToPanel(user, channel, message); // } // // public void onUserInput(String str) { // String lexed[] = str.split("\\s+"); // if (lexed.length == 2 && lexed[0].equals("/join")) { // if (mainIrcPanel.getMessagePanels().containsKey(lexed[1])) { // mainIrcPanel.clearInputField(); // mainIrcPanel.switchChanPanels(lexed[1]); // } else { // mainIrcPanel.clearInputField(); // joinChannel(lexed[1]); // } // } else { // mainIrcPanel.clearInputField(); // networkSession.sendMessage(mainIrcPanel.getCurrentChannel(), str); // } // // } // // public void onJoinEvent(Object[] users) { // for (Object o : users) { // System.out.println(); // } // } // // public void setIrcPanel(ChatMainPane ircPanel) { // mainIrcPanel = ircPanel; // } // // public void joinChannel(final String chanName) { // // mainIrcPanel.addChanPanel(chanName); // mainIrcPanel.switchChanPanels(chanName); // networkSession.joinChannel(chanName); // // } // } // Path: src/rsclient/chat/NetworkSession.java import java.io.IOException; import java.util.ArrayList; import logic.IrcManager; import org.pircbotx.Configuration; import org.pircbotx.PircBotX; import org.pircbotx.exception.IrcException; import org.pircbotx.hooks.ListenerAdapter; import org.pircbotx.hooks.events.ConnectEvent; import org.pircbotx.hooks.events.JoinEvent; import org.pircbotx.hooks.events.MessageEvent; import org.pircbotx.hooks.events.PrivateMessageEvent; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package rsclient.chat; /** * * @author ben */ public class NetworkSession extends ListenerAdapter<PircBotX> { private final PircBotX bot;
private final IrcManager manager;
bmoyer/osrsclient
src/rsclient/hiscores/LevelsPanel.java
// Path: src/logic/RuneScapeAccount.java // public class RuneScapeAccount { // // private boolean isValidAccount; // public String username; // int overallLevel = 0; // private final String[] skillNames = {"overall", "attack", "defense", "strength", "hitpoints", // "ranged", "prayer", "magic", "cooking", "woodcutting", "fletching", // "fishing", "firemaking", "crafting", "smithing", "mining", "herblore", // "agility", "thieving", "slayer", "farming", "runecrafting", "hunter", "construction"}; // // public final HashMap<String, RuneScapeLevel> hiscores = new HashMap(); // // String baseUrl = "http://services.runescape.com/m=hiscore_oldschool/index_lite.ws?player="; // // public RuneScapeAccount(String u) { // // username = u; // isValidAccount = false; // } // // public void loadStats() throws IOException { // // String rsn = username.replaceAll(" ", "_"); // BufferedReader in = null; // try { // URL hiscoreUrl = new URL(baseUrl + username); // URLConnection yc = hiscoreUrl.openConnection(); // in = new BufferedReader(new InputStreamReader(yc.getInputStream())); // String inputLine; // int c = 0; // int totalLevel = 0; // int totalExp = 0; // while ((inputLine = in.readLine()) != null) { // String[] tokens = inputLine.split(","); // if (tokens.length == 3) { // RuneScapeLevel level = new RuneScapeLevel(Integer.parseInt(tokens[0]), Integer.parseInt(tokens[1]), Integer.parseInt(tokens[2])); // if (c <= skillNames.length) { // hiscores.put(skillNames[c], level); // totalLevel += level.level; // totalExp += level.experience; // } // c++; // } // } // RuneScapeLevel combatLevel = new RuneScapeLevel(0, (int) getCombatLevel(), 0); // hiscores.put("combat", combatLevel); // if(hiscores.get("overall").level == 0){ //will be 0 if player is unranked // hiscores.get("overall").level = totalLevel; // hiscores.get("overall").experience = totalExp; // } // isValidAccount = true; // } catch (IOException ex) { // //ex.printStackTrace(); // isValidAccount = false; // } finally { // if (in != null) { // in.close(); // } // } // // } // // public static boolean isValidRSN(String s) { // if (s.length() > 12) { // return false; // } // //determine if any non-alphanumeric characters are in the string, indicating invalid RSN // return !s.replace("-", "").replace(" ", "").replace("_", "").matches("^.*[^a-zA-Z0-9 ].*$"); // } // // public double getCombatLevel() { // // return Calculate.calculateCombatLevel(hiscores.get("attack").level, hiscores.get("strength").level, // hiscores.get("defense").level, hiscores.get("prayer").level, hiscores.get("ranged").level, // hiscores.get("magic").level, hiscores.get("hitpoints").level); // } // // public boolean isValidAccount() { // return isValidAccount; // } // // } // // Path: src/rsclient/coregui/Style.java // public class Style { // // public static final Color DEFAULT_GRAY = new Color(51,51,51); // // public final Color backgroundColor; // public final Color foregroundColor; // public final Font font; // // public Style(Color foregroundColor, Color backgroundColor, Font font){ // this.foregroundColor = foregroundColor; // this.backgroundColor = backgroundColor; // this.font = font; // } // // public static Style getDefaultStyle(){ // // return new Style(Color.white, DEFAULT_GRAY, new Font(new JLabel().getFont().getFontName(), Font.PLAIN, new JLabel().getFont().getSize() + 2)); // } // // }
import java.awt.Color; import java.util.HashMap; import javax.swing.BorderFactory; import javax.swing.JPanel; import javax.swing.border.EtchedBorder; import logic.RuneScapeAccount; import net.miginfocom.swing.MigLayout; import rsclient.coregui.Style;
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package rsclient.hiscores; /** * * @author ben */ public class LevelsPanel extends JPanel implements StatRolloverListener { private static final String[] skillnames = {"attack", "hitpoints", "mining", "strength", "agility", "smithing", "defense", "herblore", "fishing", "ranged", "thieving", "cooking", "prayer", "crafting", "firemaking", "magic", "fletching", "woodcutting", "runecrafting", "slayer", "farming", "construction", "hunter", "overall", "combat"}; private final HashMap<String, LevelScorePanel> skillPanels; private StatRolloverListener rolloverListener; public LevelsPanel() { skillPanels = new HashMap<String, LevelScorePanel>(); setup(); } private void setup() { this.setLayout(new MigLayout(" center, fill, ins 0")); this.setBackground(new Color(51, 51, 51)); this.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.RAISED)); int i = 0; for (int row = 0; row < 7; row++) { for (int col = 0; col < 3; col++) {
// Path: src/logic/RuneScapeAccount.java // public class RuneScapeAccount { // // private boolean isValidAccount; // public String username; // int overallLevel = 0; // private final String[] skillNames = {"overall", "attack", "defense", "strength", "hitpoints", // "ranged", "prayer", "magic", "cooking", "woodcutting", "fletching", // "fishing", "firemaking", "crafting", "smithing", "mining", "herblore", // "agility", "thieving", "slayer", "farming", "runecrafting", "hunter", "construction"}; // // public final HashMap<String, RuneScapeLevel> hiscores = new HashMap(); // // String baseUrl = "http://services.runescape.com/m=hiscore_oldschool/index_lite.ws?player="; // // public RuneScapeAccount(String u) { // // username = u; // isValidAccount = false; // } // // public void loadStats() throws IOException { // // String rsn = username.replaceAll(" ", "_"); // BufferedReader in = null; // try { // URL hiscoreUrl = new URL(baseUrl + username); // URLConnection yc = hiscoreUrl.openConnection(); // in = new BufferedReader(new InputStreamReader(yc.getInputStream())); // String inputLine; // int c = 0; // int totalLevel = 0; // int totalExp = 0; // while ((inputLine = in.readLine()) != null) { // String[] tokens = inputLine.split(","); // if (tokens.length == 3) { // RuneScapeLevel level = new RuneScapeLevel(Integer.parseInt(tokens[0]), Integer.parseInt(tokens[1]), Integer.parseInt(tokens[2])); // if (c <= skillNames.length) { // hiscores.put(skillNames[c], level); // totalLevel += level.level; // totalExp += level.experience; // } // c++; // } // } // RuneScapeLevel combatLevel = new RuneScapeLevel(0, (int) getCombatLevel(), 0); // hiscores.put("combat", combatLevel); // if(hiscores.get("overall").level == 0){ //will be 0 if player is unranked // hiscores.get("overall").level = totalLevel; // hiscores.get("overall").experience = totalExp; // } // isValidAccount = true; // } catch (IOException ex) { // //ex.printStackTrace(); // isValidAccount = false; // } finally { // if (in != null) { // in.close(); // } // } // // } // // public static boolean isValidRSN(String s) { // if (s.length() > 12) { // return false; // } // //determine if any non-alphanumeric characters are in the string, indicating invalid RSN // return !s.replace("-", "").replace(" ", "").replace("_", "").matches("^.*[^a-zA-Z0-9 ].*$"); // } // // public double getCombatLevel() { // // return Calculate.calculateCombatLevel(hiscores.get("attack").level, hiscores.get("strength").level, // hiscores.get("defense").level, hiscores.get("prayer").level, hiscores.get("ranged").level, // hiscores.get("magic").level, hiscores.get("hitpoints").level); // } // // public boolean isValidAccount() { // return isValidAccount; // } // // } // // Path: src/rsclient/coregui/Style.java // public class Style { // // public static final Color DEFAULT_GRAY = new Color(51,51,51); // // public final Color backgroundColor; // public final Color foregroundColor; // public final Font font; // // public Style(Color foregroundColor, Color backgroundColor, Font font){ // this.foregroundColor = foregroundColor; // this.backgroundColor = backgroundColor; // this.font = font; // } // // public static Style getDefaultStyle(){ // // return new Style(Color.white, DEFAULT_GRAY, new Font(new JLabel().getFont().getFontName(), Font.PLAIN, new JLabel().getFont().getSize() + 2)); // } // // } // Path: src/rsclient/hiscores/LevelsPanel.java import java.awt.Color; import java.util.HashMap; import javax.swing.BorderFactory; import javax.swing.JPanel; import javax.swing.border.EtchedBorder; import logic.RuneScapeAccount; import net.miginfocom.swing.MigLayout; import rsclient.coregui.Style; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package rsclient.hiscores; /** * * @author ben */ public class LevelsPanel extends JPanel implements StatRolloverListener { private static final String[] skillnames = {"attack", "hitpoints", "mining", "strength", "agility", "smithing", "defense", "herblore", "fishing", "ranged", "thieving", "cooking", "prayer", "crafting", "firemaking", "magic", "fletching", "woodcutting", "runecrafting", "slayer", "farming", "construction", "hunter", "overall", "combat"}; private final HashMap<String, LevelScorePanel> skillPanels; private StatRolloverListener rolloverListener; public LevelsPanel() { skillPanels = new HashMap<String, LevelScorePanel>(); setup(); } private void setup() { this.setLayout(new MigLayout(" center, fill, ins 0")); this.setBackground(new Color(51, 51, 51)); this.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.RAISED)); int i = 0; for (int row = 0; row < 7; row++) { for (int col = 0; col < 3; col++) {
LevelScorePanel skillPanel = new LevelScorePanel(skillnames[i], Style.getDefaultStyle());
bmoyer/osrsclient
src/rsclient/hiscores/LevelsPanel.java
// Path: src/logic/RuneScapeAccount.java // public class RuneScapeAccount { // // private boolean isValidAccount; // public String username; // int overallLevel = 0; // private final String[] skillNames = {"overall", "attack", "defense", "strength", "hitpoints", // "ranged", "prayer", "magic", "cooking", "woodcutting", "fletching", // "fishing", "firemaking", "crafting", "smithing", "mining", "herblore", // "agility", "thieving", "slayer", "farming", "runecrafting", "hunter", "construction"}; // // public final HashMap<String, RuneScapeLevel> hiscores = new HashMap(); // // String baseUrl = "http://services.runescape.com/m=hiscore_oldschool/index_lite.ws?player="; // // public RuneScapeAccount(String u) { // // username = u; // isValidAccount = false; // } // // public void loadStats() throws IOException { // // String rsn = username.replaceAll(" ", "_"); // BufferedReader in = null; // try { // URL hiscoreUrl = new URL(baseUrl + username); // URLConnection yc = hiscoreUrl.openConnection(); // in = new BufferedReader(new InputStreamReader(yc.getInputStream())); // String inputLine; // int c = 0; // int totalLevel = 0; // int totalExp = 0; // while ((inputLine = in.readLine()) != null) { // String[] tokens = inputLine.split(","); // if (tokens.length == 3) { // RuneScapeLevel level = new RuneScapeLevel(Integer.parseInt(tokens[0]), Integer.parseInt(tokens[1]), Integer.parseInt(tokens[2])); // if (c <= skillNames.length) { // hiscores.put(skillNames[c], level); // totalLevel += level.level; // totalExp += level.experience; // } // c++; // } // } // RuneScapeLevel combatLevel = new RuneScapeLevel(0, (int) getCombatLevel(), 0); // hiscores.put("combat", combatLevel); // if(hiscores.get("overall").level == 0){ //will be 0 if player is unranked // hiscores.get("overall").level = totalLevel; // hiscores.get("overall").experience = totalExp; // } // isValidAccount = true; // } catch (IOException ex) { // //ex.printStackTrace(); // isValidAccount = false; // } finally { // if (in != null) { // in.close(); // } // } // // } // // public static boolean isValidRSN(String s) { // if (s.length() > 12) { // return false; // } // //determine if any non-alphanumeric characters are in the string, indicating invalid RSN // return !s.replace("-", "").replace(" ", "").replace("_", "").matches("^.*[^a-zA-Z0-9 ].*$"); // } // // public double getCombatLevel() { // // return Calculate.calculateCombatLevel(hiscores.get("attack").level, hiscores.get("strength").level, // hiscores.get("defense").level, hiscores.get("prayer").level, hiscores.get("ranged").level, // hiscores.get("magic").level, hiscores.get("hitpoints").level); // } // // public boolean isValidAccount() { // return isValidAccount; // } // // } // // Path: src/rsclient/coregui/Style.java // public class Style { // // public static final Color DEFAULT_GRAY = new Color(51,51,51); // // public final Color backgroundColor; // public final Color foregroundColor; // public final Font font; // // public Style(Color foregroundColor, Color backgroundColor, Font font){ // this.foregroundColor = foregroundColor; // this.backgroundColor = backgroundColor; // this.font = font; // } // // public static Style getDefaultStyle(){ // // return new Style(Color.white, DEFAULT_GRAY, new Font(new JLabel().getFont().getFontName(), Font.PLAIN, new JLabel().getFont().getSize() + 2)); // } // // }
import java.awt.Color; import java.util.HashMap; import javax.swing.BorderFactory; import javax.swing.JPanel; import javax.swing.border.EtchedBorder; import logic.RuneScapeAccount; import net.miginfocom.swing.MigLayout; import rsclient.coregui.Style;
skillPanels.put(skillnames[i], skillPanel); skillPanel.setRolloverListener(this); this.add(skillPanel, "cell " + col + " " + row + ",grow, gap 0,"); i++; } } for (int row = 7; row < 8; row++) { for (int col = 0; col < 2; col++) { LevelScorePanel skillPanel = new LevelScorePanel(skillnames[i], Style.getDefaultStyle()); skillPanels.put(skillnames[i], skillPanel); skillPanel.setRolloverListener(this); this.add(skillPanel, "cell " + col + " " + row + ",grow, gap 0, "); i++; } } for (int row = 8; row < 9; row++) { for (int col = 0; col < 2; col++) { LevelScorePanel skillPanel = new LevelScorePanel(skillnames[i], Style.getDefaultStyle()); skillPanels.put(skillnames[i], skillPanel); skillPanel.setRolloverListener(this); this.add(skillPanel, "cell " + col + " " + row + ",gap 40, align left ,spanx"); i++; } } }
// Path: src/logic/RuneScapeAccount.java // public class RuneScapeAccount { // // private boolean isValidAccount; // public String username; // int overallLevel = 0; // private final String[] skillNames = {"overall", "attack", "defense", "strength", "hitpoints", // "ranged", "prayer", "magic", "cooking", "woodcutting", "fletching", // "fishing", "firemaking", "crafting", "smithing", "mining", "herblore", // "agility", "thieving", "slayer", "farming", "runecrafting", "hunter", "construction"}; // // public final HashMap<String, RuneScapeLevel> hiscores = new HashMap(); // // String baseUrl = "http://services.runescape.com/m=hiscore_oldschool/index_lite.ws?player="; // // public RuneScapeAccount(String u) { // // username = u; // isValidAccount = false; // } // // public void loadStats() throws IOException { // // String rsn = username.replaceAll(" ", "_"); // BufferedReader in = null; // try { // URL hiscoreUrl = new URL(baseUrl + username); // URLConnection yc = hiscoreUrl.openConnection(); // in = new BufferedReader(new InputStreamReader(yc.getInputStream())); // String inputLine; // int c = 0; // int totalLevel = 0; // int totalExp = 0; // while ((inputLine = in.readLine()) != null) { // String[] tokens = inputLine.split(","); // if (tokens.length == 3) { // RuneScapeLevel level = new RuneScapeLevel(Integer.parseInt(tokens[0]), Integer.parseInt(tokens[1]), Integer.parseInt(tokens[2])); // if (c <= skillNames.length) { // hiscores.put(skillNames[c], level); // totalLevel += level.level; // totalExp += level.experience; // } // c++; // } // } // RuneScapeLevel combatLevel = new RuneScapeLevel(0, (int) getCombatLevel(), 0); // hiscores.put("combat", combatLevel); // if(hiscores.get("overall").level == 0){ //will be 0 if player is unranked // hiscores.get("overall").level = totalLevel; // hiscores.get("overall").experience = totalExp; // } // isValidAccount = true; // } catch (IOException ex) { // //ex.printStackTrace(); // isValidAccount = false; // } finally { // if (in != null) { // in.close(); // } // } // // } // // public static boolean isValidRSN(String s) { // if (s.length() > 12) { // return false; // } // //determine if any non-alphanumeric characters are in the string, indicating invalid RSN // return !s.replace("-", "").replace(" ", "").replace("_", "").matches("^.*[^a-zA-Z0-9 ].*$"); // } // // public double getCombatLevel() { // // return Calculate.calculateCombatLevel(hiscores.get("attack").level, hiscores.get("strength").level, // hiscores.get("defense").level, hiscores.get("prayer").level, hiscores.get("ranged").level, // hiscores.get("magic").level, hiscores.get("hitpoints").level); // } // // public boolean isValidAccount() { // return isValidAccount; // } // // } // // Path: src/rsclient/coregui/Style.java // public class Style { // // public static final Color DEFAULT_GRAY = new Color(51,51,51); // // public final Color backgroundColor; // public final Color foregroundColor; // public final Font font; // // public Style(Color foregroundColor, Color backgroundColor, Font font){ // this.foregroundColor = foregroundColor; // this.backgroundColor = backgroundColor; // this.font = font; // } // // public static Style getDefaultStyle(){ // // return new Style(Color.white, DEFAULT_GRAY, new Font(new JLabel().getFont().getFontName(), Font.PLAIN, new JLabel().getFont().getSize() + 2)); // } // // } // Path: src/rsclient/hiscores/LevelsPanel.java import java.awt.Color; import java.util.HashMap; import javax.swing.BorderFactory; import javax.swing.JPanel; import javax.swing.border.EtchedBorder; import logic.RuneScapeAccount; import net.miginfocom.swing.MigLayout; import rsclient.coregui.Style; skillPanels.put(skillnames[i], skillPanel); skillPanel.setRolloverListener(this); this.add(skillPanel, "cell " + col + " " + row + ",grow, gap 0,"); i++; } } for (int row = 7; row < 8; row++) { for (int col = 0; col < 2; col++) { LevelScorePanel skillPanel = new LevelScorePanel(skillnames[i], Style.getDefaultStyle()); skillPanels.put(skillnames[i], skillPanel); skillPanel.setRolloverListener(this); this.add(skillPanel, "cell " + col + " " + row + ",grow, gap 0, "); i++; } } for (int row = 8; row < 9; row++) { for (int col = 0; col < 2; col++) { LevelScorePanel skillPanel = new LevelScorePanel(skillnames[i], Style.getDefaultStyle()); skillPanels.put(skillnames[i], skillPanel); skillPanel.setRolloverListener(this); this.add(skillPanel, "cell " + col + " " + row + ",gap 40, align left ,spanx"); i++; } } }
public void updateLevels(RuneScapeAccount account) {