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
|
---|---|---|---|---|---|---|
xuyunqiang/MeiziAPP | app/src/main/java/com/yunq/gankio/ui/fragment/CustomWebViewDialog.java | // Path: app/src/main/java/com/yunq/gankio/GankApp.java
// public class GankApp extends Application {
//
// private RefWatcher refWatcher;
//
// ApplicationComponent mApplicationComponent;
//
// @Override
// public void onCreate() {
// super.onCreate();
// refWatcher = LeakCanary.install(this);
//
// if (BuildConfig.DEBUG) {
// //警告在主线程中执行耗时操作
// StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectAll().penaltyLog().build());
// StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectAll().penaltyLog().build());
//
// Timber.plant(new Timber.DebugTree());
// }
//
// }
//
// public static GankApp get(Context context) {
// return (GankApp) context.getApplicationContext();
// }
//
// public static RefWatcher getRefWatcher(Context context) {
// return ((GankApp) context.getApplicationContext()).refWatcher;
// }
//
// public ApplicationComponent getComponent() {
// if (mApplicationComponent == null) {
// mApplicationComponent = DaggerApplicationComponent.builder()
// .applicationModule(new ApplicationModule(this))
// .build();
// }
// return mApplicationComponent;
// }
//
//
// }
//
// Path: app/src/main/java/com/yunq/gankio/injection/module/FragmentModule.java
// @Module
// public class FragmentModule {
// private final Fragment mFragment;
//
// public FragmentModule(Fragment fragment) {
// mFragment = fragment;
// }
//
// @Provides
// @com.yunq.gankio.injection.Fragment
// Context provideContext() {
// return mFragment.getActivity();
// }
// }
//
// Path: app/src/main/java/com/yunq/gankio/presenter/CustomDialogPresenter.java
// public class CustomDialogPresenter extends BasePresenter<ICustomDialog> {
//
//
// private static final String KEY_UTF_8 = "UTF-8";
//
// private Context mContext;
//
// @Inject
// public CustomDialogPresenter(Context context) {
// mContext = context;
// }
//
// public AlertDialog makeDialog(Fragment fragment, View customView) {
//
// String dialogTitle = fragment.getArguments().getString(CustomWebViewDialog.EXTRA_DIALOG_TITLE);
// String htmlFileName = fragment.getArguments().getString(CustomWebViewDialog.EXTRA_HTML_FILE_NAME);
// int accentColor = fragment.getArguments().getInt(CustomWebViewDialog.EXTRA_ACCENT_COLOR);
//
// final WebView webView = (WebView) customView.findViewById(R.id.webView);
// webView.getSettings().setDefaultTextEncodingName(KEY_UTF_8);
// loadData(webView, htmlFileName, accentColor);
//
// AlertDialog dialog = new AlertDialog.Builder(mContext)
// .setTitle(dialogTitle)
// .setView(customView)
// .setPositiveButton(android.R.string.ok, null)
// .show();
// return dialog;
// }
//
// private void loadData(WebView webView, String htmlFileName, int accentColor) {
// try {
// StringBuilder buf = new StringBuilder();
// InputStream json = mContext.getAssets().open(htmlFileName);
// BufferedReader in = new BufferedReader(new InputStreamReader(json, KEY_UTF_8));
// String str;
// while ((str = in.readLine()) != null)
// buf.append(str);
// in.close();
//
// String formatLodString = buf.toString()
// .replace("{style-placeholder}", "body { background-color: #ffffff; color: #000; }")
// .replace("{link-color}", colorToHex(shiftColor(accentColor, true)))
// .replace("{link-color-active}", colorToHex(accentColor));
// webView.loadDataWithBaseURL(null, formatLodString, "text/html", KEY_UTF_8, null);
// } catch (Throwable e) {
// webView.loadData("<h1>Unable to load</h1><p>" + e.getLocalizedMessage() + "</p>", "text/html", KEY_UTF_8);
// }
// }
//
// private String colorToHex(int color) {
// return Integer.toHexString(color).substring(2);
// }
//
// private int shiftColor(int color, boolean up) {
// float[] hsv = new float[3];
// Color.colorToHSV(color, hsv);
// hsv[2] *= (up ? 1.1f : 0.9f); // value component
// return Color.HSVToColor(hsv);
// }
// }
//
// Path: app/src/main/java/com/yunq/gankio/presenter/view/ICustomDialog.java
// public interface ICustomDialog extends IBaseView {
// }
| import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.view.InflateException;
import android.view.LayoutInflater;
import android.view.View;
import com.yunq.gankio.GankApp;
import com.yunq.gankio.R;
import com.yunq.gankio.injection.component.DaggerFragmentComponent;
import com.yunq.gankio.injection.module.FragmentModule;
import com.yunq.gankio.presenter.CustomDialogPresenter;
import com.yunq.gankio.presenter.view.ICustomDialog;
import javax.inject.Inject; | package com.yunq.gankio.ui.fragment;
/**
* A simple {@link Fragment} subclass.
*/
public class CustomWebViewDialog extends DialogFragment implements ICustomDialog {
public static final String EXTRA_DIALOG_TITLE = "DIALOG_TITLE";
public static final String EXTRA_HTML_FILE_NAME = "HTML_FILE_NAME";
public static final String EXTRA_ACCENT_COLOR = "ACCENT_COLOR";
@Inject
CustomDialogPresenter mPresenter;
@Inject
Context mContext;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initInjection();
}
private void initInjection() {
DaggerFragmentComponent.builder()
.fragmentModule(new FragmentModule(this)) | // Path: app/src/main/java/com/yunq/gankio/GankApp.java
// public class GankApp extends Application {
//
// private RefWatcher refWatcher;
//
// ApplicationComponent mApplicationComponent;
//
// @Override
// public void onCreate() {
// super.onCreate();
// refWatcher = LeakCanary.install(this);
//
// if (BuildConfig.DEBUG) {
// //警告在主线程中执行耗时操作
// StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectAll().penaltyLog().build());
// StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectAll().penaltyLog().build());
//
// Timber.plant(new Timber.DebugTree());
// }
//
// }
//
// public static GankApp get(Context context) {
// return (GankApp) context.getApplicationContext();
// }
//
// public static RefWatcher getRefWatcher(Context context) {
// return ((GankApp) context.getApplicationContext()).refWatcher;
// }
//
// public ApplicationComponent getComponent() {
// if (mApplicationComponent == null) {
// mApplicationComponent = DaggerApplicationComponent.builder()
// .applicationModule(new ApplicationModule(this))
// .build();
// }
// return mApplicationComponent;
// }
//
//
// }
//
// Path: app/src/main/java/com/yunq/gankio/injection/module/FragmentModule.java
// @Module
// public class FragmentModule {
// private final Fragment mFragment;
//
// public FragmentModule(Fragment fragment) {
// mFragment = fragment;
// }
//
// @Provides
// @com.yunq.gankio.injection.Fragment
// Context provideContext() {
// return mFragment.getActivity();
// }
// }
//
// Path: app/src/main/java/com/yunq/gankio/presenter/CustomDialogPresenter.java
// public class CustomDialogPresenter extends BasePresenter<ICustomDialog> {
//
//
// private static final String KEY_UTF_8 = "UTF-8";
//
// private Context mContext;
//
// @Inject
// public CustomDialogPresenter(Context context) {
// mContext = context;
// }
//
// public AlertDialog makeDialog(Fragment fragment, View customView) {
//
// String dialogTitle = fragment.getArguments().getString(CustomWebViewDialog.EXTRA_DIALOG_TITLE);
// String htmlFileName = fragment.getArguments().getString(CustomWebViewDialog.EXTRA_HTML_FILE_NAME);
// int accentColor = fragment.getArguments().getInt(CustomWebViewDialog.EXTRA_ACCENT_COLOR);
//
// final WebView webView = (WebView) customView.findViewById(R.id.webView);
// webView.getSettings().setDefaultTextEncodingName(KEY_UTF_8);
// loadData(webView, htmlFileName, accentColor);
//
// AlertDialog dialog = new AlertDialog.Builder(mContext)
// .setTitle(dialogTitle)
// .setView(customView)
// .setPositiveButton(android.R.string.ok, null)
// .show();
// return dialog;
// }
//
// private void loadData(WebView webView, String htmlFileName, int accentColor) {
// try {
// StringBuilder buf = new StringBuilder();
// InputStream json = mContext.getAssets().open(htmlFileName);
// BufferedReader in = new BufferedReader(new InputStreamReader(json, KEY_UTF_8));
// String str;
// while ((str = in.readLine()) != null)
// buf.append(str);
// in.close();
//
// String formatLodString = buf.toString()
// .replace("{style-placeholder}", "body { background-color: #ffffff; color: #000; }")
// .replace("{link-color}", colorToHex(shiftColor(accentColor, true)))
// .replace("{link-color-active}", colorToHex(accentColor));
// webView.loadDataWithBaseURL(null, formatLodString, "text/html", KEY_UTF_8, null);
// } catch (Throwable e) {
// webView.loadData("<h1>Unable to load</h1><p>" + e.getLocalizedMessage() + "</p>", "text/html", KEY_UTF_8);
// }
// }
//
// private String colorToHex(int color) {
// return Integer.toHexString(color).substring(2);
// }
//
// private int shiftColor(int color, boolean up) {
// float[] hsv = new float[3];
// Color.colorToHSV(color, hsv);
// hsv[2] *= (up ? 1.1f : 0.9f); // value component
// return Color.HSVToColor(hsv);
// }
// }
//
// Path: app/src/main/java/com/yunq/gankio/presenter/view/ICustomDialog.java
// public interface ICustomDialog extends IBaseView {
// }
// Path: app/src/main/java/com/yunq/gankio/ui/fragment/CustomWebViewDialog.java
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.view.InflateException;
import android.view.LayoutInflater;
import android.view.View;
import com.yunq.gankio.GankApp;
import com.yunq.gankio.R;
import com.yunq.gankio.injection.component.DaggerFragmentComponent;
import com.yunq.gankio.injection.module.FragmentModule;
import com.yunq.gankio.presenter.CustomDialogPresenter;
import com.yunq.gankio.presenter.view.ICustomDialog;
import javax.inject.Inject;
package com.yunq.gankio.ui.fragment;
/**
* A simple {@link Fragment} subclass.
*/
public class CustomWebViewDialog extends DialogFragment implements ICustomDialog {
public static final String EXTRA_DIALOG_TITLE = "DIALOG_TITLE";
public static final String EXTRA_HTML_FILE_NAME = "HTML_FILE_NAME";
public static final String EXTRA_ACCENT_COLOR = "ACCENT_COLOR";
@Inject
CustomDialogPresenter mPresenter;
@Inject
Context mContext;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initInjection();
}
private void initInjection() {
DaggerFragmentComponent.builder()
.fragmentModule(new FragmentModule(this)) | .applicationComponent(GankApp.get(this.getActivity()).getComponent()) |
xuyunqiang/MeiziAPP | app/src/main/java/com/yunq/gankio/presenter/GirlFacePresenter.java | // Path: app/src/main/java/com/yunq/gankio/data/DataManager.java
// @Singleton
// public class DataManager {
// private final OkHttpClient mClient;
//
// private final MeiziService mMeiziService;
//
// @Inject
// public DataManager(OkHttpClient client) {
// mClient = client;
// mMeiziService = MeiziService.Creator.newGudongService(client);
// }
//
//
// public void cancelRequest() {
// mClient.dispatcher().cancelAll();
// }
//
// /**
// * MainActivity中获取所有Girls
// */
// public Observable<List<Girl>> getGirls(int pageSize, int currentPage) {
// return Observable.zip(mMeiziService.getPrettyGirlData(pageSize, currentPage),
// mMeiziService.get休息视频Data(pageSize, currentPage),
// new Func2<PrettyGirlData, 休息视频Data, PrettyGirlData>() {
// @Override
// public PrettyGirlData call(PrettyGirlData prettyGirlData, 休息视频Data 休息视频Data) {
// return DataUtils.createGirlInfoWith休息视频(prettyGirlData, 休息视频Data);
// }
// })
// .map(new Func1<PrettyGirlData, List<Girl>>() {
// @Override
// public List<Girl> call(PrettyGirlData girlData) {
// return girlData.results;
// }
// })
// .flatMap(new Func1<List<Girl>, Observable<Girl>>() {
// @Override
// public Observable<Girl> call(List<Girl> girls) {
// return Observable.from(girls);
// }
// })
// .toSortedList(new Func2<Girl, Girl, Integer>() {
// @Override
// public Integer call(Girl girl, Girl girl2) {
// return girl2.publishedAt.compareTo(girl.publishedAt);
// }
// });
// }
//
// /**
// * GankDetailActivity
// */
// public Observable<List<Gank>> getGankData(Date date) {
// Calendar calendar = Calendar.getInstance();
// calendar.setTime(date);
// int year = calendar.get(Calendar.YEAR);
// int month = calendar.get(Calendar.MONTH) + 1;
// int day = calendar.get(Calendar.DAY_OF_MONTH);
//
// return mMeiziService.getGankData(year, month, day)
// .map(new Func1<GankData, GankData.Result>() {
// @Override
// public GankData.Result call(GankData gankData) {
// return gankData.results;
// }
// })
// .map(new Func1<GankData.Result, List<Gank>>() {
// @Override
// public List<Gank> call(GankData.Result result) {
// return DataUtils.addAllResults(result);
// }
// });
// }
//
// }
//
// Path: app/src/main/java/com/yunq/gankio/presenter/view/IGirlFaceView.java
// public interface IGirlFaceView extends IBaseView {
//
// void saveSuccess(String message);
//
// void showFailInfo(String error);
// }
//
// Path: app/src/main/java/com/yunq/gankio/util/TaskUtils.java
// public class TaskUtils {
//
// @SafeVarargs
// public static <Params, Progress, Result> void executeAsyncTask(
// AsyncTask<Params, Progress, Result> task, Params... params) {
// if (Build.VERSION.SDK_INT >= 11) {
// task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params);
// } else {
// task.execute(params);
// }
//
// }
// }
| import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.widget.ImageView;
import com.squareup.picasso.Picasso;
import com.yunq.gankio.data.DataManager;
import com.yunq.gankio.R;
import com.yunq.gankio.presenter.view.IGirlFaceView;
import com.yunq.gankio.util.TaskUtils;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.inject.Inject;
import timber.log.Timber; | package com.yunq.gankio.presenter;
/**
* Created by admin on 16/1/6.
*/
public class GirlFacePresenter extends BasePresenter<IGirlFaceView> {
private final DataManager mDataManager;
private Context mContext;
@Inject
public GirlFacePresenter(Activity context,DataManager dataManager){
mContext = context;
mDataManager = dataManager;
}
public void loadGirl(String url, ImageView imageView) {
if (!TextUtils.isEmpty(url)) {
Picasso.with(mContext).load(url).into(imageView);
}
}
public void saveFace(String url) {
if (!TextUtils.isEmpty(url)) {
String fileName = url.substring(url.lastIndexOf("/") + 1);
saveImageToSdCard(mContext, url, fileName);
}
}
private void saveImageToSdCard(final Context context, final String url, final String fileName) { | // Path: app/src/main/java/com/yunq/gankio/data/DataManager.java
// @Singleton
// public class DataManager {
// private final OkHttpClient mClient;
//
// private final MeiziService mMeiziService;
//
// @Inject
// public DataManager(OkHttpClient client) {
// mClient = client;
// mMeiziService = MeiziService.Creator.newGudongService(client);
// }
//
//
// public void cancelRequest() {
// mClient.dispatcher().cancelAll();
// }
//
// /**
// * MainActivity中获取所有Girls
// */
// public Observable<List<Girl>> getGirls(int pageSize, int currentPage) {
// return Observable.zip(mMeiziService.getPrettyGirlData(pageSize, currentPage),
// mMeiziService.get休息视频Data(pageSize, currentPage),
// new Func2<PrettyGirlData, 休息视频Data, PrettyGirlData>() {
// @Override
// public PrettyGirlData call(PrettyGirlData prettyGirlData, 休息视频Data 休息视频Data) {
// return DataUtils.createGirlInfoWith休息视频(prettyGirlData, 休息视频Data);
// }
// })
// .map(new Func1<PrettyGirlData, List<Girl>>() {
// @Override
// public List<Girl> call(PrettyGirlData girlData) {
// return girlData.results;
// }
// })
// .flatMap(new Func1<List<Girl>, Observable<Girl>>() {
// @Override
// public Observable<Girl> call(List<Girl> girls) {
// return Observable.from(girls);
// }
// })
// .toSortedList(new Func2<Girl, Girl, Integer>() {
// @Override
// public Integer call(Girl girl, Girl girl2) {
// return girl2.publishedAt.compareTo(girl.publishedAt);
// }
// });
// }
//
// /**
// * GankDetailActivity
// */
// public Observable<List<Gank>> getGankData(Date date) {
// Calendar calendar = Calendar.getInstance();
// calendar.setTime(date);
// int year = calendar.get(Calendar.YEAR);
// int month = calendar.get(Calendar.MONTH) + 1;
// int day = calendar.get(Calendar.DAY_OF_MONTH);
//
// return mMeiziService.getGankData(year, month, day)
// .map(new Func1<GankData, GankData.Result>() {
// @Override
// public GankData.Result call(GankData gankData) {
// return gankData.results;
// }
// })
// .map(new Func1<GankData.Result, List<Gank>>() {
// @Override
// public List<Gank> call(GankData.Result result) {
// return DataUtils.addAllResults(result);
// }
// });
// }
//
// }
//
// Path: app/src/main/java/com/yunq/gankio/presenter/view/IGirlFaceView.java
// public interface IGirlFaceView extends IBaseView {
//
// void saveSuccess(String message);
//
// void showFailInfo(String error);
// }
//
// Path: app/src/main/java/com/yunq/gankio/util/TaskUtils.java
// public class TaskUtils {
//
// @SafeVarargs
// public static <Params, Progress, Result> void executeAsyncTask(
// AsyncTask<Params, Progress, Result> task, Params... params) {
// if (Build.VERSION.SDK_INT >= 11) {
// task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params);
// } else {
// task.execute(params);
// }
//
// }
// }
// Path: app/src/main/java/com/yunq/gankio/presenter/GirlFacePresenter.java
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.widget.ImageView;
import com.squareup.picasso.Picasso;
import com.yunq.gankio.data.DataManager;
import com.yunq.gankio.R;
import com.yunq.gankio.presenter.view.IGirlFaceView;
import com.yunq.gankio.util.TaskUtils;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.inject.Inject;
import timber.log.Timber;
package com.yunq.gankio.presenter;
/**
* Created by admin on 16/1/6.
*/
public class GirlFacePresenter extends BasePresenter<IGirlFaceView> {
private final DataManager mDataManager;
private Context mContext;
@Inject
public GirlFacePresenter(Activity context,DataManager dataManager){
mContext = context;
mDataManager = dataManager;
}
public void loadGirl(String url, ImageView imageView) {
if (!TextUtils.isEmpty(url)) {
Picasso.with(mContext).load(url).into(imageView);
}
}
public void saveFace(String url) {
if (!TextUtils.isEmpty(url)) {
String fileName = url.substring(url.lastIndexOf("/") + 1);
saveImageToSdCard(mContext, url, fileName);
}
}
private void saveImageToSdCard(final Context context, final String url, final String fileName) { | TaskUtils.executeAsyncTask(new AsyncTask<Object, Object, Boolean>() { |
xuyunqiang/MeiziAPP | app/src/main/java/com/yunq/gankio/presenter/MainPresenter.java | // Path: app/src/main/java/com/yunq/gankio/data/DataManager.java
// @Singleton
// public class DataManager {
// private final OkHttpClient mClient;
//
// private final MeiziService mMeiziService;
//
// @Inject
// public DataManager(OkHttpClient client) {
// mClient = client;
// mMeiziService = MeiziService.Creator.newGudongService(client);
// }
//
//
// public void cancelRequest() {
// mClient.dispatcher().cancelAll();
// }
//
// /**
// * MainActivity中获取所有Girls
// */
// public Observable<List<Girl>> getGirls(int pageSize, int currentPage) {
// return Observable.zip(mMeiziService.getPrettyGirlData(pageSize, currentPage),
// mMeiziService.get休息视频Data(pageSize, currentPage),
// new Func2<PrettyGirlData, 休息视频Data, PrettyGirlData>() {
// @Override
// public PrettyGirlData call(PrettyGirlData prettyGirlData, 休息视频Data 休息视频Data) {
// return DataUtils.createGirlInfoWith休息视频(prettyGirlData, 休息视频Data);
// }
// })
// .map(new Func1<PrettyGirlData, List<Girl>>() {
// @Override
// public List<Girl> call(PrettyGirlData girlData) {
// return girlData.results;
// }
// })
// .flatMap(new Func1<List<Girl>, Observable<Girl>>() {
// @Override
// public Observable<Girl> call(List<Girl> girls) {
// return Observable.from(girls);
// }
// })
// .toSortedList(new Func2<Girl, Girl, Integer>() {
// @Override
// public Integer call(Girl girl, Girl girl2) {
// return girl2.publishedAt.compareTo(girl.publishedAt);
// }
// });
// }
//
// /**
// * GankDetailActivity
// */
// public Observable<List<Gank>> getGankData(Date date) {
// Calendar calendar = Calendar.getInstance();
// calendar.setTime(date);
// int year = calendar.get(Calendar.YEAR);
// int month = calendar.get(Calendar.MONTH) + 1;
// int day = calendar.get(Calendar.DAY_OF_MONTH);
//
// return mMeiziService.getGankData(year, month, day)
// .map(new Func1<GankData, GankData.Result>() {
// @Override
// public GankData.Result call(GankData gankData) {
// return gankData.results;
// }
// })
// .map(new Func1<GankData.Result, List<Gank>>() {
// @Override
// public List<Gank> call(GankData.Result result) {
// return DataUtils.addAllResults(result);
// }
// });
// }
//
// }
//
// Path: app/src/main/java/com/yunq/gankio/data/entity/Girl.java
// public class Girl extends Soul {
//
// @Column("used")
// public boolean used;
// @Column("type")
// public String type;
// @Column("url")
// public String url;
// @Column("who")
// public String who;
// @Column("desc")
// public String desc;
// @Column("createdAt")
// public Date createdAt;
// @Column("publishedAt")
// public Date publishedAt;
// @Column("updatedAt")
// public Date updatedAt;
//
// }
//
// Path: app/src/main/java/com/yunq/gankio/presenter/view/IMainView.java
// public interface IMainView<T extends Soul> extends ISwipeRefreshView {
//
// void fillData(List<T> data);
//
// void appendMoreDataToView(List<T> data);
//
// void hasNoMoreData();
//
//
// }
| import com.yunq.gankio.data.DataManager;
import com.yunq.gankio.data.entity.Girl;
import com.yunq.gankio.presenter.view.IMainView;
import java.util.List;
import javax.inject.Inject;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;
import rx.functions.Action1;
import rx.schedulers.Schedulers; | package com.yunq.gankio.presenter;
/**
* Created by admin on 16/1/5.
*/
public class MainPresenter extends BasePresenter<IMainView> {
private final DataManager mDataManager;
private int mCurrentPage = 1;
private static final int PAGE_SIZE = 10;
@Inject
public MainPresenter(DataManager dataManager) {
mDataManager = dataManager;
}
@Override
public void attachView(IMainView view) {
super.attachView(view);
}
public void resetCurrentPage() {
mCurrentPage = 1;
}
public boolean shouldRefillGirls() {
return mCurrentPage <= 2;
}
public void refillGirls() {
addSubscription( mDataManager.getGirls(PAGE_SIZE, mCurrentPage)
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io()) | // Path: app/src/main/java/com/yunq/gankio/data/DataManager.java
// @Singleton
// public class DataManager {
// private final OkHttpClient mClient;
//
// private final MeiziService mMeiziService;
//
// @Inject
// public DataManager(OkHttpClient client) {
// mClient = client;
// mMeiziService = MeiziService.Creator.newGudongService(client);
// }
//
//
// public void cancelRequest() {
// mClient.dispatcher().cancelAll();
// }
//
// /**
// * MainActivity中获取所有Girls
// */
// public Observable<List<Girl>> getGirls(int pageSize, int currentPage) {
// return Observable.zip(mMeiziService.getPrettyGirlData(pageSize, currentPage),
// mMeiziService.get休息视频Data(pageSize, currentPage),
// new Func2<PrettyGirlData, 休息视频Data, PrettyGirlData>() {
// @Override
// public PrettyGirlData call(PrettyGirlData prettyGirlData, 休息视频Data 休息视频Data) {
// return DataUtils.createGirlInfoWith休息视频(prettyGirlData, 休息视频Data);
// }
// })
// .map(new Func1<PrettyGirlData, List<Girl>>() {
// @Override
// public List<Girl> call(PrettyGirlData girlData) {
// return girlData.results;
// }
// })
// .flatMap(new Func1<List<Girl>, Observable<Girl>>() {
// @Override
// public Observable<Girl> call(List<Girl> girls) {
// return Observable.from(girls);
// }
// })
// .toSortedList(new Func2<Girl, Girl, Integer>() {
// @Override
// public Integer call(Girl girl, Girl girl2) {
// return girl2.publishedAt.compareTo(girl.publishedAt);
// }
// });
// }
//
// /**
// * GankDetailActivity
// */
// public Observable<List<Gank>> getGankData(Date date) {
// Calendar calendar = Calendar.getInstance();
// calendar.setTime(date);
// int year = calendar.get(Calendar.YEAR);
// int month = calendar.get(Calendar.MONTH) + 1;
// int day = calendar.get(Calendar.DAY_OF_MONTH);
//
// return mMeiziService.getGankData(year, month, day)
// .map(new Func1<GankData, GankData.Result>() {
// @Override
// public GankData.Result call(GankData gankData) {
// return gankData.results;
// }
// })
// .map(new Func1<GankData.Result, List<Gank>>() {
// @Override
// public List<Gank> call(GankData.Result result) {
// return DataUtils.addAllResults(result);
// }
// });
// }
//
// }
//
// Path: app/src/main/java/com/yunq/gankio/data/entity/Girl.java
// public class Girl extends Soul {
//
// @Column("used")
// public boolean used;
// @Column("type")
// public String type;
// @Column("url")
// public String url;
// @Column("who")
// public String who;
// @Column("desc")
// public String desc;
// @Column("createdAt")
// public Date createdAt;
// @Column("publishedAt")
// public Date publishedAt;
// @Column("updatedAt")
// public Date updatedAt;
//
// }
//
// Path: app/src/main/java/com/yunq/gankio/presenter/view/IMainView.java
// public interface IMainView<T extends Soul> extends ISwipeRefreshView {
//
// void fillData(List<T> data);
//
// void appendMoreDataToView(List<T> data);
//
// void hasNoMoreData();
//
//
// }
// Path: app/src/main/java/com/yunq/gankio/presenter/MainPresenter.java
import com.yunq.gankio.data.DataManager;
import com.yunq.gankio.data.entity.Girl;
import com.yunq.gankio.presenter.view.IMainView;
import java.util.List;
import javax.inject.Inject;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;
import rx.functions.Action1;
import rx.schedulers.Schedulers;
package com.yunq.gankio.presenter;
/**
* Created by admin on 16/1/5.
*/
public class MainPresenter extends BasePresenter<IMainView> {
private final DataManager mDataManager;
private int mCurrentPage = 1;
private static final int PAGE_SIZE = 10;
@Inject
public MainPresenter(DataManager dataManager) {
mDataManager = dataManager;
}
@Override
public void attachView(IMainView view) {
super.attachView(view);
}
public void resetCurrentPage() {
mCurrentPage = 1;
}
public boolean shouldRefillGirls() {
return mCurrentPage <= 2;
}
public void refillGirls() {
addSubscription( mDataManager.getGirls(PAGE_SIZE, mCurrentPage)
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io()) | .subscribe(new Subscriber<List<Girl>>() { |
xuyunqiang/MeiziAPP | app/src/main/java/com/yunq/gankio/injection/component/GankDetailActivityComponent.java | // Path: app/src/main/java/com/yunq/gankio/injection/module/ActivityModule.java
// @Module
// public class ActivityModule {
//
// private android.app.Activity mActivity;
//
// public ActivityModule(android.app.Activity activity) {
// mActivity = activity;
// }
//
// @Provides
// android.app.Activity provideActivity() {
// return mActivity;
// }
//
// // @Provides
// // //@ActivityContext
// // Context provideContext() {
// // return mActivity;
// // }
// }
//
// Path: app/src/main/java/com/yunq/gankio/ui/activity/GirlDetailActivity.java
// public class GirlDetailActivity extends BaseSwipeRefreshActivity implements IGankDetailView<Gank> {
// private static final String TAG = GirlDetailActivity.class.getSimpleName();
// private static final String EXTRA_BUNDLE_DATE = "BUNDLE_DATE";
//
// @Bind(R.id.rv_gank)
// RecyclerView mRvGank;
//
// GankListAdapter mAdapter;
//
// Date mDate;
//
// @Inject
// GankDetailPresenter mPresenter;
//
// public static void gotoGankActivity(Context context, Date date) {
// Intent intent = new Intent(context, GirlDetailActivity.class);
// intent.putExtra(EXTRA_BUNDLE_DATE, date);
// context.startActivity(intent);
// }
//
// @Override
// protected int getLayout() {
// return R.layout.activity_gank;
// }
//
// @Override
// protected int getMenuRes() {
// return R.menu.menu_gank;
// }
//
// @Override
// protected void initInjection() {
// DaggerGankDetailActivityComponent.builder()
// .activityModule(new ActivityModule(this))
// .applicationComponent(GankApp.get(this).getComponent())
// .build()
// .inject(this);
//
// }
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// initInjection();
// mPresenter.attachView(this);
// mDate = (Date) getIntent().getSerializableExtra(EXTRA_BUNDLE_DATE);
// setTitle(DateUtils.toDate(mDate), true);
//
// initRecycleView();
// initData();
//
// }
//
// private void initRecycleView() {
// LinearLayoutManager layoutManager = new LinearLayoutManager(this);
// mRvGank.setLayoutManager(layoutManager);
// mAdapter = new GankListAdapter();
// mRvGank.setAdapter(mAdapter);
// }
//
// private void initData() {
// mPresenter.getData(mDate);
// }
//
// @Override
// protected void onRefreshStarted() {
// initData();
//
// }
//
// @Override
// public void showEmptyView() {
//
// }
//
// @Override
// public void showErrorView(Throwable throwable) {
// throwable.printStackTrace();
// }
//
// @Override
// public void showCancelRequest() {
//
// }
//
//
// @Override
// public void fillData(List<Gank> data) {
// mAdapter.updateWithClear(data);
// }
//
//
// @Override
// public boolean onOptionsItemSelected(MenuItem item) {
// int id = item.getItemId();
//
// if (id == R.id.action_settings) {
// return true;
// }
//
// return super.onOptionsItemSelected(item);
// }
//
// @Override
// protected void onDestroy() {
// super.onDestroy();
// mPresenter.detachView();
// }
//
// @Override
// public void onBackPressed() {
// if (isRefreshing()) {
// GankApp.get(this).getComponent().dataManager().cancelRequest();
// hideRefresh();
// return;
// }
// super.onBackPressed();
// }
// }
| import com.yunq.gankio.injection.Activity;
import com.yunq.gankio.injection.module.ActivityModule;
import com.yunq.gankio.ui.activity.GirlDetailActivity;
import dagger.Component; | package com.yunq.gankio.injection.component;
/**
* Created by admin on 16/1/25.
*/
@Activity
@Component(dependencies = ApplicationComponent.class, modules = ActivityModule.class)
public interface GankDetailActivityComponent extends ActivityComponent{ | // Path: app/src/main/java/com/yunq/gankio/injection/module/ActivityModule.java
// @Module
// public class ActivityModule {
//
// private android.app.Activity mActivity;
//
// public ActivityModule(android.app.Activity activity) {
// mActivity = activity;
// }
//
// @Provides
// android.app.Activity provideActivity() {
// return mActivity;
// }
//
// // @Provides
// // //@ActivityContext
// // Context provideContext() {
// // return mActivity;
// // }
// }
//
// Path: app/src/main/java/com/yunq/gankio/ui/activity/GirlDetailActivity.java
// public class GirlDetailActivity extends BaseSwipeRefreshActivity implements IGankDetailView<Gank> {
// private static final String TAG = GirlDetailActivity.class.getSimpleName();
// private static final String EXTRA_BUNDLE_DATE = "BUNDLE_DATE";
//
// @Bind(R.id.rv_gank)
// RecyclerView mRvGank;
//
// GankListAdapter mAdapter;
//
// Date mDate;
//
// @Inject
// GankDetailPresenter mPresenter;
//
// public static void gotoGankActivity(Context context, Date date) {
// Intent intent = new Intent(context, GirlDetailActivity.class);
// intent.putExtra(EXTRA_BUNDLE_DATE, date);
// context.startActivity(intent);
// }
//
// @Override
// protected int getLayout() {
// return R.layout.activity_gank;
// }
//
// @Override
// protected int getMenuRes() {
// return R.menu.menu_gank;
// }
//
// @Override
// protected void initInjection() {
// DaggerGankDetailActivityComponent.builder()
// .activityModule(new ActivityModule(this))
// .applicationComponent(GankApp.get(this).getComponent())
// .build()
// .inject(this);
//
// }
//
// @Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// initInjection();
// mPresenter.attachView(this);
// mDate = (Date) getIntent().getSerializableExtra(EXTRA_BUNDLE_DATE);
// setTitle(DateUtils.toDate(mDate), true);
//
// initRecycleView();
// initData();
//
// }
//
// private void initRecycleView() {
// LinearLayoutManager layoutManager = new LinearLayoutManager(this);
// mRvGank.setLayoutManager(layoutManager);
// mAdapter = new GankListAdapter();
// mRvGank.setAdapter(mAdapter);
// }
//
// private void initData() {
// mPresenter.getData(mDate);
// }
//
// @Override
// protected void onRefreshStarted() {
// initData();
//
// }
//
// @Override
// public void showEmptyView() {
//
// }
//
// @Override
// public void showErrorView(Throwable throwable) {
// throwable.printStackTrace();
// }
//
// @Override
// public void showCancelRequest() {
//
// }
//
//
// @Override
// public void fillData(List<Gank> data) {
// mAdapter.updateWithClear(data);
// }
//
//
// @Override
// public boolean onOptionsItemSelected(MenuItem item) {
// int id = item.getItemId();
//
// if (id == R.id.action_settings) {
// return true;
// }
//
// return super.onOptionsItemSelected(item);
// }
//
// @Override
// protected void onDestroy() {
// super.onDestroy();
// mPresenter.detachView();
// }
//
// @Override
// public void onBackPressed() {
// if (isRefreshing()) {
// GankApp.get(this).getComponent().dataManager().cancelRequest();
// hideRefresh();
// return;
// }
// super.onBackPressed();
// }
// }
// Path: app/src/main/java/com/yunq/gankio/injection/component/GankDetailActivityComponent.java
import com.yunq.gankio.injection.Activity;
import com.yunq.gankio.injection.module.ActivityModule;
import com.yunq.gankio.ui.activity.GirlDetailActivity;
import dagger.Component;
package com.yunq.gankio.injection.component;
/**
* Created by admin on 16/1/25.
*/
@Activity
@Component(dependencies = ApplicationComponent.class, modules = ActivityModule.class)
public interface GankDetailActivityComponent extends ActivityComponent{ | void inject(GirlDetailActivity activity); |
xuyunqiang/MeiziAPP | app/src/main/java/com/yunq/gankio/data/DataManager.java | // Path: app/src/main/java/com/yunq/gankio/core/MeiziService.java
// public interface MeiziService {
//
// /**
// * 数据主机地址
// */
// String HOST = "http://gank.avosapps.com/api/";
//
// @GET("data/福利/{pageSize}/{page}")
// Observable<PrettyGirlData> getPrettyGirlData(@Path("pageSize") int pageSize, @Path("page") int page);
//
// @GET("data/休息视频/{pageSize}/{page}")
// Observable<休息视频Data> get休息视频Data(@Path("pageSize") int pageSize, @Path("page") int page);
//
// @GET("day/{year}/{month}/{day}")
// Observable<GankData> getGankData(@Path("year") int year, @Path("month") int month, @Path("day") int day);
//
// class Creator {
// public static MeiziService newGudongService(OkHttpClient client) {
// Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").serializeNulls().create();
//
// Retrofit apiAdapter = new Retrofit.Builder()
// .baseUrl(HOST)
// .addConverterFactory(GsonConverterFactory.create(gson))
// .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
// .client(client)
// .build();
//
// return apiAdapter.create(MeiziService.class);
// }
// }
//
// }
//
// Path: app/src/main/java/com/yunq/gankio/data/entity/Gank.java
// @Table("ganks")
// public class Gank extends Soul {
//
// @Column("used")
// public boolean used;
// @Column("type")
// public String type;
// @Column("url")
// public String url;
// @Column("who")
// public String who;
// @Column("desc")
// public String desc;
// @Column("updatedAt")
// public Date updatedAt;
// @Column("createdAt")
// public Date createdAt;
// @Column("publishedAt")
// public Date publishedAt;
// }
//
// Path: app/src/main/java/com/yunq/gankio/data/entity/Girl.java
// public class Girl extends Soul {
//
// @Column("used")
// public boolean used;
// @Column("type")
// public String type;
// @Column("url")
// public String url;
// @Column("who")
// public String who;
// @Column("desc")
// public String desc;
// @Column("createdAt")
// public Date createdAt;
// @Column("publishedAt")
// public Date publishedAt;
// @Column("updatedAt")
// public Date updatedAt;
//
// }
//
// Path: app/src/main/java/com/yunq/gankio/data/parse/GankData.java
// public class GankData extends BaseData{
//
// public List<String> category;
// public Result results;
//
// public class Result {
// @SerializedName("Android")
// public List<Gank> androidList;
// @SerializedName("休息视频")
// public List<Gank> 休息视频List;
// @SerializedName("iOS")
// public List<Gank> iOSList;
// @SerializedName("福利")
// public List<Gank> 妹纸List;
// @SerializedName("拓展资源")
// public List<Gank> 拓展资源List;
// @SerializedName("瞎推荐")
// public List<Gank> 瞎推荐List;
// @SerializedName("App")
// public List<Gank> appList;
// }
// }
//
// Path: app/src/main/java/com/yunq/gankio/data/parse/PrettyGirlData.java
// public class PrettyGirlData extends BaseData {
//
// public List<Girl> results;
// }
| import com.yunq.gankio.core.MeiziService;
import com.yunq.gankio.data.entity.Gank;
import com.yunq.gankio.data.entity.Girl;
import com.yunq.gankio.data.parse.GankData;
import com.yunq.gankio.data.parse.PrettyGirlData;
import com.yunq.gankio.data.parse.休息视频Data;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.inject.Inject;
import javax.inject.Singleton;
import okhttp3.OkHttpClient;
import rx.Observable;
import rx.functions.Func1;
import rx.functions.Func2; | package com.yunq.gankio.data;
/**
* Model层数据管理类,所有的数据变换操作全部放到这个类中,
* 但随着数据操作的增多,这个类会变得越来越臃肿,
* 我们可以可以将每组相关的数据操作抽取出来放到另一个类中去管理
*/
@Singleton
public class DataManager {
private final OkHttpClient mClient;
| // Path: app/src/main/java/com/yunq/gankio/core/MeiziService.java
// public interface MeiziService {
//
// /**
// * 数据主机地址
// */
// String HOST = "http://gank.avosapps.com/api/";
//
// @GET("data/福利/{pageSize}/{page}")
// Observable<PrettyGirlData> getPrettyGirlData(@Path("pageSize") int pageSize, @Path("page") int page);
//
// @GET("data/休息视频/{pageSize}/{page}")
// Observable<休息视频Data> get休息视频Data(@Path("pageSize") int pageSize, @Path("page") int page);
//
// @GET("day/{year}/{month}/{day}")
// Observable<GankData> getGankData(@Path("year") int year, @Path("month") int month, @Path("day") int day);
//
// class Creator {
// public static MeiziService newGudongService(OkHttpClient client) {
// Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").serializeNulls().create();
//
// Retrofit apiAdapter = new Retrofit.Builder()
// .baseUrl(HOST)
// .addConverterFactory(GsonConverterFactory.create(gson))
// .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
// .client(client)
// .build();
//
// return apiAdapter.create(MeiziService.class);
// }
// }
//
// }
//
// Path: app/src/main/java/com/yunq/gankio/data/entity/Gank.java
// @Table("ganks")
// public class Gank extends Soul {
//
// @Column("used")
// public boolean used;
// @Column("type")
// public String type;
// @Column("url")
// public String url;
// @Column("who")
// public String who;
// @Column("desc")
// public String desc;
// @Column("updatedAt")
// public Date updatedAt;
// @Column("createdAt")
// public Date createdAt;
// @Column("publishedAt")
// public Date publishedAt;
// }
//
// Path: app/src/main/java/com/yunq/gankio/data/entity/Girl.java
// public class Girl extends Soul {
//
// @Column("used")
// public boolean used;
// @Column("type")
// public String type;
// @Column("url")
// public String url;
// @Column("who")
// public String who;
// @Column("desc")
// public String desc;
// @Column("createdAt")
// public Date createdAt;
// @Column("publishedAt")
// public Date publishedAt;
// @Column("updatedAt")
// public Date updatedAt;
//
// }
//
// Path: app/src/main/java/com/yunq/gankio/data/parse/GankData.java
// public class GankData extends BaseData{
//
// public List<String> category;
// public Result results;
//
// public class Result {
// @SerializedName("Android")
// public List<Gank> androidList;
// @SerializedName("休息视频")
// public List<Gank> 休息视频List;
// @SerializedName("iOS")
// public List<Gank> iOSList;
// @SerializedName("福利")
// public List<Gank> 妹纸List;
// @SerializedName("拓展资源")
// public List<Gank> 拓展资源List;
// @SerializedName("瞎推荐")
// public List<Gank> 瞎推荐List;
// @SerializedName("App")
// public List<Gank> appList;
// }
// }
//
// Path: app/src/main/java/com/yunq/gankio/data/parse/PrettyGirlData.java
// public class PrettyGirlData extends BaseData {
//
// public List<Girl> results;
// }
// Path: app/src/main/java/com/yunq/gankio/data/DataManager.java
import com.yunq.gankio.core.MeiziService;
import com.yunq.gankio.data.entity.Gank;
import com.yunq.gankio.data.entity.Girl;
import com.yunq.gankio.data.parse.GankData;
import com.yunq.gankio.data.parse.PrettyGirlData;
import com.yunq.gankio.data.parse.休息视频Data;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.inject.Inject;
import javax.inject.Singleton;
import okhttp3.OkHttpClient;
import rx.Observable;
import rx.functions.Func1;
import rx.functions.Func2;
package com.yunq.gankio.data;
/**
* Model层数据管理类,所有的数据变换操作全部放到这个类中,
* 但随着数据操作的增多,这个类会变得越来越臃肿,
* 我们可以可以将每组相关的数据操作抽取出来放到另一个类中去管理
*/
@Singleton
public class DataManager {
private final OkHttpClient mClient;
| private final MeiziService mMeiziService; |
xuyunqiang/MeiziAPP | app/src/main/java/com/yunq/gankio/data/DataManager.java | // Path: app/src/main/java/com/yunq/gankio/core/MeiziService.java
// public interface MeiziService {
//
// /**
// * 数据主机地址
// */
// String HOST = "http://gank.avosapps.com/api/";
//
// @GET("data/福利/{pageSize}/{page}")
// Observable<PrettyGirlData> getPrettyGirlData(@Path("pageSize") int pageSize, @Path("page") int page);
//
// @GET("data/休息视频/{pageSize}/{page}")
// Observable<休息视频Data> get休息视频Data(@Path("pageSize") int pageSize, @Path("page") int page);
//
// @GET("day/{year}/{month}/{day}")
// Observable<GankData> getGankData(@Path("year") int year, @Path("month") int month, @Path("day") int day);
//
// class Creator {
// public static MeiziService newGudongService(OkHttpClient client) {
// Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").serializeNulls().create();
//
// Retrofit apiAdapter = new Retrofit.Builder()
// .baseUrl(HOST)
// .addConverterFactory(GsonConverterFactory.create(gson))
// .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
// .client(client)
// .build();
//
// return apiAdapter.create(MeiziService.class);
// }
// }
//
// }
//
// Path: app/src/main/java/com/yunq/gankio/data/entity/Gank.java
// @Table("ganks")
// public class Gank extends Soul {
//
// @Column("used")
// public boolean used;
// @Column("type")
// public String type;
// @Column("url")
// public String url;
// @Column("who")
// public String who;
// @Column("desc")
// public String desc;
// @Column("updatedAt")
// public Date updatedAt;
// @Column("createdAt")
// public Date createdAt;
// @Column("publishedAt")
// public Date publishedAt;
// }
//
// Path: app/src/main/java/com/yunq/gankio/data/entity/Girl.java
// public class Girl extends Soul {
//
// @Column("used")
// public boolean used;
// @Column("type")
// public String type;
// @Column("url")
// public String url;
// @Column("who")
// public String who;
// @Column("desc")
// public String desc;
// @Column("createdAt")
// public Date createdAt;
// @Column("publishedAt")
// public Date publishedAt;
// @Column("updatedAt")
// public Date updatedAt;
//
// }
//
// Path: app/src/main/java/com/yunq/gankio/data/parse/GankData.java
// public class GankData extends BaseData{
//
// public List<String> category;
// public Result results;
//
// public class Result {
// @SerializedName("Android")
// public List<Gank> androidList;
// @SerializedName("休息视频")
// public List<Gank> 休息视频List;
// @SerializedName("iOS")
// public List<Gank> iOSList;
// @SerializedName("福利")
// public List<Gank> 妹纸List;
// @SerializedName("拓展资源")
// public List<Gank> 拓展资源List;
// @SerializedName("瞎推荐")
// public List<Gank> 瞎推荐List;
// @SerializedName("App")
// public List<Gank> appList;
// }
// }
//
// Path: app/src/main/java/com/yunq/gankio/data/parse/PrettyGirlData.java
// public class PrettyGirlData extends BaseData {
//
// public List<Girl> results;
// }
| import com.yunq.gankio.core.MeiziService;
import com.yunq.gankio.data.entity.Gank;
import com.yunq.gankio.data.entity.Girl;
import com.yunq.gankio.data.parse.GankData;
import com.yunq.gankio.data.parse.PrettyGirlData;
import com.yunq.gankio.data.parse.休息视频Data;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.inject.Inject;
import javax.inject.Singleton;
import okhttp3.OkHttpClient;
import rx.Observable;
import rx.functions.Func1;
import rx.functions.Func2; | package com.yunq.gankio.data;
/**
* Model层数据管理类,所有的数据变换操作全部放到这个类中,
* 但随着数据操作的增多,这个类会变得越来越臃肿,
* 我们可以可以将每组相关的数据操作抽取出来放到另一个类中去管理
*/
@Singleton
public class DataManager {
private final OkHttpClient mClient;
private final MeiziService mMeiziService;
@Inject
public DataManager(OkHttpClient client) {
mClient = client;
mMeiziService = MeiziService.Creator.newGudongService(client);
}
public void cancelRequest() {
mClient.dispatcher().cancelAll();
}
/**
* MainActivity中获取所有Girls
*/ | // Path: app/src/main/java/com/yunq/gankio/core/MeiziService.java
// public interface MeiziService {
//
// /**
// * 数据主机地址
// */
// String HOST = "http://gank.avosapps.com/api/";
//
// @GET("data/福利/{pageSize}/{page}")
// Observable<PrettyGirlData> getPrettyGirlData(@Path("pageSize") int pageSize, @Path("page") int page);
//
// @GET("data/休息视频/{pageSize}/{page}")
// Observable<休息视频Data> get休息视频Data(@Path("pageSize") int pageSize, @Path("page") int page);
//
// @GET("day/{year}/{month}/{day}")
// Observable<GankData> getGankData(@Path("year") int year, @Path("month") int month, @Path("day") int day);
//
// class Creator {
// public static MeiziService newGudongService(OkHttpClient client) {
// Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").serializeNulls().create();
//
// Retrofit apiAdapter = new Retrofit.Builder()
// .baseUrl(HOST)
// .addConverterFactory(GsonConverterFactory.create(gson))
// .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
// .client(client)
// .build();
//
// return apiAdapter.create(MeiziService.class);
// }
// }
//
// }
//
// Path: app/src/main/java/com/yunq/gankio/data/entity/Gank.java
// @Table("ganks")
// public class Gank extends Soul {
//
// @Column("used")
// public boolean used;
// @Column("type")
// public String type;
// @Column("url")
// public String url;
// @Column("who")
// public String who;
// @Column("desc")
// public String desc;
// @Column("updatedAt")
// public Date updatedAt;
// @Column("createdAt")
// public Date createdAt;
// @Column("publishedAt")
// public Date publishedAt;
// }
//
// Path: app/src/main/java/com/yunq/gankio/data/entity/Girl.java
// public class Girl extends Soul {
//
// @Column("used")
// public boolean used;
// @Column("type")
// public String type;
// @Column("url")
// public String url;
// @Column("who")
// public String who;
// @Column("desc")
// public String desc;
// @Column("createdAt")
// public Date createdAt;
// @Column("publishedAt")
// public Date publishedAt;
// @Column("updatedAt")
// public Date updatedAt;
//
// }
//
// Path: app/src/main/java/com/yunq/gankio/data/parse/GankData.java
// public class GankData extends BaseData{
//
// public List<String> category;
// public Result results;
//
// public class Result {
// @SerializedName("Android")
// public List<Gank> androidList;
// @SerializedName("休息视频")
// public List<Gank> 休息视频List;
// @SerializedName("iOS")
// public List<Gank> iOSList;
// @SerializedName("福利")
// public List<Gank> 妹纸List;
// @SerializedName("拓展资源")
// public List<Gank> 拓展资源List;
// @SerializedName("瞎推荐")
// public List<Gank> 瞎推荐List;
// @SerializedName("App")
// public List<Gank> appList;
// }
// }
//
// Path: app/src/main/java/com/yunq/gankio/data/parse/PrettyGirlData.java
// public class PrettyGirlData extends BaseData {
//
// public List<Girl> results;
// }
// Path: app/src/main/java/com/yunq/gankio/data/DataManager.java
import com.yunq.gankio.core.MeiziService;
import com.yunq.gankio.data.entity.Gank;
import com.yunq.gankio.data.entity.Girl;
import com.yunq.gankio.data.parse.GankData;
import com.yunq.gankio.data.parse.PrettyGirlData;
import com.yunq.gankio.data.parse.休息视频Data;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.inject.Inject;
import javax.inject.Singleton;
import okhttp3.OkHttpClient;
import rx.Observable;
import rx.functions.Func1;
import rx.functions.Func2;
package com.yunq.gankio.data;
/**
* Model层数据管理类,所有的数据变换操作全部放到这个类中,
* 但随着数据操作的增多,这个类会变得越来越臃肿,
* 我们可以可以将每组相关的数据操作抽取出来放到另一个类中去管理
*/
@Singleton
public class DataManager {
private final OkHttpClient mClient;
private final MeiziService mMeiziService;
@Inject
public DataManager(OkHttpClient client) {
mClient = client;
mMeiziService = MeiziService.Creator.newGudongService(client);
}
public void cancelRequest() {
mClient.dispatcher().cancelAll();
}
/**
* MainActivity中获取所有Girls
*/ | public Observable<List<Girl>> getGirls(int pageSize, int currentPage) { |
xuyunqiang/MeiziAPP | app/src/main/java/com/yunq/gankio/data/DataManager.java | // Path: app/src/main/java/com/yunq/gankio/core/MeiziService.java
// public interface MeiziService {
//
// /**
// * 数据主机地址
// */
// String HOST = "http://gank.avosapps.com/api/";
//
// @GET("data/福利/{pageSize}/{page}")
// Observable<PrettyGirlData> getPrettyGirlData(@Path("pageSize") int pageSize, @Path("page") int page);
//
// @GET("data/休息视频/{pageSize}/{page}")
// Observable<休息视频Data> get休息视频Data(@Path("pageSize") int pageSize, @Path("page") int page);
//
// @GET("day/{year}/{month}/{day}")
// Observable<GankData> getGankData(@Path("year") int year, @Path("month") int month, @Path("day") int day);
//
// class Creator {
// public static MeiziService newGudongService(OkHttpClient client) {
// Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").serializeNulls().create();
//
// Retrofit apiAdapter = new Retrofit.Builder()
// .baseUrl(HOST)
// .addConverterFactory(GsonConverterFactory.create(gson))
// .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
// .client(client)
// .build();
//
// return apiAdapter.create(MeiziService.class);
// }
// }
//
// }
//
// Path: app/src/main/java/com/yunq/gankio/data/entity/Gank.java
// @Table("ganks")
// public class Gank extends Soul {
//
// @Column("used")
// public boolean used;
// @Column("type")
// public String type;
// @Column("url")
// public String url;
// @Column("who")
// public String who;
// @Column("desc")
// public String desc;
// @Column("updatedAt")
// public Date updatedAt;
// @Column("createdAt")
// public Date createdAt;
// @Column("publishedAt")
// public Date publishedAt;
// }
//
// Path: app/src/main/java/com/yunq/gankio/data/entity/Girl.java
// public class Girl extends Soul {
//
// @Column("used")
// public boolean used;
// @Column("type")
// public String type;
// @Column("url")
// public String url;
// @Column("who")
// public String who;
// @Column("desc")
// public String desc;
// @Column("createdAt")
// public Date createdAt;
// @Column("publishedAt")
// public Date publishedAt;
// @Column("updatedAt")
// public Date updatedAt;
//
// }
//
// Path: app/src/main/java/com/yunq/gankio/data/parse/GankData.java
// public class GankData extends BaseData{
//
// public List<String> category;
// public Result results;
//
// public class Result {
// @SerializedName("Android")
// public List<Gank> androidList;
// @SerializedName("休息视频")
// public List<Gank> 休息视频List;
// @SerializedName("iOS")
// public List<Gank> iOSList;
// @SerializedName("福利")
// public List<Gank> 妹纸List;
// @SerializedName("拓展资源")
// public List<Gank> 拓展资源List;
// @SerializedName("瞎推荐")
// public List<Gank> 瞎推荐List;
// @SerializedName("App")
// public List<Gank> appList;
// }
// }
//
// Path: app/src/main/java/com/yunq/gankio/data/parse/PrettyGirlData.java
// public class PrettyGirlData extends BaseData {
//
// public List<Girl> results;
// }
| import com.yunq.gankio.core.MeiziService;
import com.yunq.gankio.data.entity.Gank;
import com.yunq.gankio.data.entity.Girl;
import com.yunq.gankio.data.parse.GankData;
import com.yunq.gankio.data.parse.PrettyGirlData;
import com.yunq.gankio.data.parse.休息视频Data;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.inject.Inject;
import javax.inject.Singleton;
import okhttp3.OkHttpClient;
import rx.Observable;
import rx.functions.Func1;
import rx.functions.Func2; | package com.yunq.gankio.data;
/**
* Model层数据管理类,所有的数据变换操作全部放到这个类中,
* 但随着数据操作的增多,这个类会变得越来越臃肿,
* 我们可以可以将每组相关的数据操作抽取出来放到另一个类中去管理
*/
@Singleton
public class DataManager {
private final OkHttpClient mClient;
private final MeiziService mMeiziService;
@Inject
public DataManager(OkHttpClient client) {
mClient = client;
mMeiziService = MeiziService.Creator.newGudongService(client);
}
public void cancelRequest() {
mClient.dispatcher().cancelAll();
}
/**
* MainActivity中获取所有Girls
*/
public Observable<List<Girl>> getGirls(int pageSize, int currentPage) {
return Observable.zip(mMeiziService.getPrettyGirlData(pageSize, currentPage),
mMeiziService.get休息视频Data(pageSize, currentPage), | // Path: app/src/main/java/com/yunq/gankio/core/MeiziService.java
// public interface MeiziService {
//
// /**
// * 数据主机地址
// */
// String HOST = "http://gank.avosapps.com/api/";
//
// @GET("data/福利/{pageSize}/{page}")
// Observable<PrettyGirlData> getPrettyGirlData(@Path("pageSize") int pageSize, @Path("page") int page);
//
// @GET("data/休息视频/{pageSize}/{page}")
// Observable<休息视频Data> get休息视频Data(@Path("pageSize") int pageSize, @Path("page") int page);
//
// @GET("day/{year}/{month}/{day}")
// Observable<GankData> getGankData(@Path("year") int year, @Path("month") int month, @Path("day") int day);
//
// class Creator {
// public static MeiziService newGudongService(OkHttpClient client) {
// Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").serializeNulls().create();
//
// Retrofit apiAdapter = new Retrofit.Builder()
// .baseUrl(HOST)
// .addConverterFactory(GsonConverterFactory.create(gson))
// .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
// .client(client)
// .build();
//
// return apiAdapter.create(MeiziService.class);
// }
// }
//
// }
//
// Path: app/src/main/java/com/yunq/gankio/data/entity/Gank.java
// @Table("ganks")
// public class Gank extends Soul {
//
// @Column("used")
// public boolean used;
// @Column("type")
// public String type;
// @Column("url")
// public String url;
// @Column("who")
// public String who;
// @Column("desc")
// public String desc;
// @Column("updatedAt")
// public Date updatedAt;
// @Column("createdAt")
// public Date createdAt;
// @Column("publishedAt")
// public Date publishedAt;
// }
//
// Path: app/src/main/java/com/yunq/gankio/data/entity/Girl.java
// public class Girl extends Soul {
//
// @Column("used")
// public boolean used;
// @Column("type")
// public String type;
// @Column("url")
// public String url;
// @Column("who")
// public String who;
// @Column("desc")
// public String desc;
// @Column("createdAt")
// public Date createdAt;
// @Column("publishedAt")
// public Date publishedAt;
// @Column("updatedAt")
// public Date updatedAt;
//
// }
//
// Path: app/src/main/java/com/yunq/gankio/data/parse/GankData.java
// public class GankData extends BaseData{
//
// public List<String> category;
// public Result results;
//
// public class Result {
// @SerializedName("Android")
// public List<Gank> androidList;
// @SerializedName("休息视频")
// public List<Gank> 休息视频List;
// @SerializedName("iOS")
// public List<Gank> iOSList;
// @SerializedName("福利")
// public List<Gank> 妹纸List;
// @SerializedName("拓展资源")
// public List<Gank> 拓展资源List;
// @SerializedName("瞎推荐")
// public List<Gank> 瞎推荐List;
// @SerializedName("App")
// public List<Gank> appList;
// }
// }
//
// Path: app/src/main/java/com/yunq/gankio/data/parse/PrettyGirlData.java
// public class PrettyGirlData extends BaseData {
//
// public List<Girl> results;
// }
// Path: app/src/main/java/com/yunq/gankio/data/DataManager.java
import com.yunq.gankio.core.MeiziService;
import com.yunq.gankio.data.entity.Gank;
import com.yunq.gankio.data.entity.Girl;
import com.yunq.gankio.data.parse.GankData;
import com.yunq.gankio.data.parse.PrettyGirlData;
import com.yunq.gankio.data.parse.休息视频Data;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.inject.Inject;
import javax.inject.Singleton;
import okhttp3.OkHttpClient;
import rx.Observable;
import rx.functions.Func1;
import rx.functions.Func2;
package com.yunq.gankio.data;
/**
* Model层数据管理类,所有的数据变换操作全部放到这个类中,
* 但随着数据操作的增多,这个类会变得越来越臃肿,
* 我们可以可以将每组相关的数据操作抽取出来放到另一个类中去管理
*/
@Singleton
public class DataManager {
private final OkHttpClient mClient;
private final MeiziService mMeiziService;
@Inject
public DataManager(OkHttpClient client) {
mClient = client;
mMeiziService = MeiziService.Creator.newGudongService(client);
}
public void cancelRequest() {
mClient.dispatcher().cancelAll();
}
/**
* MainActivity中获取所有Girls
*/
public Observable<List<Girl>> getGirls(int pageSize, int currentPage) {
return Observable.zip(mMeiziService.getPrettyGirlData(pageSize, currentPage),
mMeiziService.get休息视频Data(pageSize, currentPage), | new Func2<PrettyGirlData, 休息视频Data, PrettyGirlData>() { |
xuyunqiang/MeiziAPP | app/src/main/java/com/yunq/gankio/data/DataManager.java | // Path: app/src/main/java/com/yunq/gankio/core/MeiziService.java
// public interface MeiziService {
//
// /**
// * 数据主机地址
// */
// String HOST = "http://gank.avosapps.com/api/";
//
// @GET("data/福利/{pageSize}/{page}")
// Observable<PrettyGirlData> getPrettyGirlData(@Path("pageSize") int pageSize, @Path("page") int page);
//
// @GET("data/休息视频/{pageSize}/{page}")
// Observable<休息视频Data> get休息视频Data(@Path("pageSize") int pageSize, @Path("page") int page);
//
// @GET("day/{year}/{month}/{day}")
// Observable<GankData> getGankData(@Path("year") int year, @Path("month") int month, @Path("day") int day);
//
// class Creator {
// public static MeiziService newGudongService(OkHttpClient client) {
// Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").serializeNulls().create();
//
// Retrofit apiAdapter = new Retrofit.Builder()
// .baseUrl(HOST)
// .addConverterFactory(GsonConverterFactory.create(gson))
// .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
// .client(client)
// .build();
//
// return apiAdapter.create(MeiziService.class);
// }
// }
//
// }
//
// Path: app/src/main/java/com/yunq/gankio/data/entity/Gank.java
// @Table("ganks")
// public class Gank extends Soul {
//
// @Column("used")
// public boolean used;
// @Column("type")
// public String type;
// @Column("url")
// public String url;
// @Column("who")
// public String who;
// @Column("desc")
// public String desc;
// @Column("updatedAt")
// public Date updatedAt;
// @Column("createdAt")
// public Date createdAt;
// @Column("publishedAt")
// public Date publishedAt;
// }
//
// Path: app/src/main/java/com/yunq/gankio/data/entity/Girl.java
// public class Girl extends Soul {
//
// @Column("used")
// public boolean used;
// @Column("type")
// public String type;
// @Column("url")
// public String url;
// @Column("who")
// public String who;
// @Column("desc")
// public String desc;
// @Column("createdAt")
// public Date createdAt;
// @Column("publishedAt")
// public Date publishedAt;
// @Column("updatedAt")
// public Date updatedAt;
//
// }
//
// Path: app/src/main/java/com/yunq/gankio/data/parse/GankData.java
// public class GankData extends BaseData{
//
// public List<String> category;
// public Result results;
//
// public class Result {
// @SerializedName("Android")
// public List<Gank> androidList;
// @SerializedName("休息视频")
// public List<Gank> 休息视频List;
// @SerializedName("iOS")
// public List<Gank> iOSList;
// @SerializedName("福利")
// public List<Gank> 妹纸List;
// @SerializedName("拓展资源")
// public List<Gank> 拓展资源List;
// @SerializedName("瞎推荐")
// public List<Gank> 瞎推荐List;
// @SerializedName("App")
// public List<Gank> appList;
// }
// }
//
// Path: app/src/main/java/com/yunq/gankio/data/parse/PrettyGirlData.java
// public class PrettyGirlData extends BaseData {
//
// public List<Girl> results;
// }
| import com.yunq.gankio.core.MeiziService;
import com.yunq.gankio.data.entity.Gank;
import com.yunq.gankio.data.entity.Girl;
import com.yunq.gankio.data.parse.GankData;
import com.yunq.gankio.data.parse.PrettyGirlData;
import com.yunq.gankio.data.parse.休息视频Data;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.inject.Inject;
import javax.inject.Singleton;
import okhttp3.OkHttpClient;
import rx.Observable;
import rx.functions.Func1;
import rx.functions.Func2; | mMeiziService.get休息视频Data(pageSize, currentPage),
new Func2<PrettyGirlData, 休息视频Data, PrettyGirlData>() {
@Override
public PrettyGirlData call(PrettyGirlData prettyGirlData, 休息视频Data 休息视频Data) {
return DataUtils.createGirlInfoWith休息视频(prettyGirlData, 休息视频Data);
}
})
.map(new Func1<PrettyGirlData, List<Girl>>() {
@Override
public List<Girl> call(PrettyGirlData girlData) {
return girlData.results;
}
})
.flatMap(new Func1<List<Girl>, Observable<Girl>>() {
@Override
public Observable<Girl> call(List<Girl> girls) {
return Observable.from(girls);
}
})
.toSortedList(new Func2<Girl, Girl, Integer>() {
@Override
public Integer call(Girl girl, Girl girl2) {
return girl2.publishedAt.compareTo(girl.publishedAt);
}
});
}
/**
* GankDetailActivity
*/ | // Path: app/src/main/java/com/yunq/gankio/core/MeiziService.java
// public interface MeiziService {
//
// /**
// * 数据主机地址
// */
// String HOST = "http://gank.avosapps.com/api/";
//
// @GET("data/福利/{pageSize}/{page}")
// Observable<PrettyGirlData> getPrettyGirlData(@Path("pageSize") int pageSize, @Path("page") int page);
//
// @GET("data/休息视频/{pageSize}/{page}")
// Observable<休息视频Data> get休息视频Data(@Path("pageSize") int pageSize, @Path("page") int page);
//
// @GET("day/{year}/{month}/{day}")
// Observable<GankData> getGankData(@Path("year") int year, @Path("month") int month, @Path("day") int day);
//
// class Creator {
// public static MeiziService newGudongService(OkHttpClient client) {
// Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").serializeNulls().create();
//
// Retrofit apiAdapter = new Retrofit.Builder()
// .baseUrl(HOST)
// .addConverterFactory(GsonConverterFactory.create(gson))
// .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
// .client(client)
// .build();
//
// return apiAdapter.create(MeiziService.class);
// }
// }
//
// }
//
// Path: app/src/main/java/com/yunq/gankio/data/entity/Gank.java
// @Table("ganks")
// public class Gank extends Soul {
//
// @Column("used")
// public boolean used;
// @Column("type")
// public String type;
// @Column("url")
// public String url;
// @Column("who")
// public String who;
// @Column("desc")
// public String desc;
// @Column("updatedAt")
// public Date updatedAt;
// @Column("createdAt")
// public Date createdAt;
// @Column("publishedAt")
// public Date publishedAt;
// }
//
// Path: app/src/main/java/com/yunq/gankio/data/entity/Girl.java
// public class Girl extends Soul {
//
// @Column("used")
// public boolean used;
// @Column("type")
// public String type;
// @Column("url")
// public String url;
// @Column("who")
// public String who;
// @Column("desc")
// public String desc;
// @Column("createdAt")
// public Date createdAt;
// @Column("publishedAt")
// public Date publishedAt;
// @Column("updatedAt")
// public Date updatedAt;
//
// }
//
// Path: app/src/main/java/com/yunq/gankio/data/parse/GankData.java
// public class GankData extends BaseData{
//
// public List<String> category;
// public Result results;
//
// public class Result {
// @SerializedName("Android")
// public List<Gank> androidList;
// @SerializedName("休息视频")
// public List<Gank> 休息视频List;
// @SerializedName("iOS")
// public List<Gank> iOSList;
// @SerializedName("福利")
// public List<Gank> 妹纸List;
// @SerializedName("拓展资源")
// public List<Gank> 拓展资源List;
// @SerializedName("瞎推荐")
// public List<Gank> 瞎推荐List;
// @SerializedName("App")
// public List<Gank> appList;
// }
// }
//
// Path: app/src/main/java/com/yunq/gankio/data/parse/PrettyGirlData.java
// public class PrettyGirlData extends BaseData {
//
// public List<Girl> results;
// }
// Path: app/src/main/java/com/yunq/gankio/data/DataManager.java
import com.yunq.gankio.core.MeiziService;
import com.yunq.gankio.data.entity.Gank;
import com.yunq.gankio.data.entity.Girl;
import com.yunq.gankio.data.parse.GankData;
import com.yunq.gankio.data.parse.PrettyGirlData;
import com.yunq.gankio.data.parse.休息视频Data;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.inject.Inject;
import javax.inject.Singleton;
import okhttp3.OkHttpClient;
import rx.Observable;
import rx.functions.Func1;
import rx.functions.Func2;
mMeiziService.get休息视频Data(pageSize, currentPage),
new Func2<PrettyGirlData, 休息视频Data, PrettyGirlData>() {
@Override
public PrettyGirlData call(PrettyGirlData prettyGirlData, 休息视频Data 休息视频Data) {
return DataUtils.createGirlInfoWith休息视频(prettyGirlData, 休息视频Data);
}
})
.map(new Func1<PrettyGirlData, List<Girl>>() {
@Override
public List<Girl> call(PrettyGirlData girlData) {
return girlData.results;
}
})
.flatMap(new Func1<List<Girl>, Observable<Girl>>() {
@Override
public Observable<Girl> call(List<Girl> girls) {
return Observable.from(girls);
}
})
.toSortedList(new Func2<Girl, Girl, Integer>() {
@Override
public Integer call(Girl girl, Girl girl2) {
return girl2.publishedAt.compareTo(girl.publishedAt);
}
});
}
/**
* GankDetailActivity
*/ | public Observable<List<Gank>> getGankData(Date date) { |
xuyunqiang/MeiziAPP | app/src/main/java/com/yunq/gankio/data/DataManager.java | // Path: app/src/main/java/com/yunq/gankio/core/MeiziService.java
// public interface MeiziService {
//
// /**
// * 数据主机地址
// */
// String HOST = "http://gank.avosapps.com/api/";
//
// @GET("data/福利/{pageSize}/{page}")
// Observable<PrettyGirlData> getPrettyGirlData(@Path("pageSize") int pageSize, @Path("page") int page);
//
// @GET("data/休息视频/{pageSize}/{page}")
// Observable<休息视频Data> get休息视频Data(@Path("pageSize") int pageSize, @Path("page") int page);
//
// @GET("day/{year}/{month}/{day}")
// Observable<GankData> getGankData(@Path("year") int year, @Path("month") int month, @Path("day") int day);
//
// class Creator {
// public static MeiziService newGudongService(OkHttpClient client) {
// Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").serializeNulls().create();
//
// Retrofit apiAdapter = new Retrofit.Builder()
// .baseUrl(HOST)
// .addConverterFactory(GsonConverterFactory.create(gson))
// .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
// .client(client)
// .build();
//
// return apiAdapter.create(MeiziService.class);
// }
// }
//
// }
//
// Path: app/src/main/java/com/yunq/gankio/data/entity/Gank.java
// @Table("ganks")
// public class Gank extends Soul {
//
// @Column("used")
// public boolean used;
// @Column("type")
// public String type;
// @Column("url")
// public String url;
// @Column("who")
// public String who;
// @Column("desc")
// public String desc;
// @Column("updatedAt")
// public Date updatedAt;
// @Column("createdAt")
// public Date createdAt;
// @Column("publishedAt")
// public Date publishedAt;
// }
//
// Path: app/src/main/java/com/yunq/gankio/data/entity/Girl.java
// public class Girl extends Soul {
//
// @Column("used")
// public boolean used;
// @Column("type")
// public String type;
// @Column("url")
// public String url;
// @Column("who")
// public String who;
// @Column("desc")
// public String desc;
// @Column("createdAt")
// public Date createdAt;
// @Column("publishedAt")
// public Date publishedAt;
// @Column("updatedAt")
// public Date updatedAt;
//
// }
//
// Path: app/src/main/java/com/yunq/gankio/data/parse/GankData.java
// public class GankData extends BaseData{
//
// public List<String> category;
// public Result results;
//
// public class Result {
// @SerializedName("Android")
// public List<Gank> androidList;
// @SerializedName("休息视频")
// public List<Gank> 休息视频List;
// @SerializedName("iOS")
// public List<Gank> iOSList;
// @SerializedName("福利")
// public List<Gank> 妹纸List;
// @SerializedName("拓展资源")
// public List<Gank> 拓展资源List;
// @SerializedName("瞎推荐")
// public List<Gank> 瞎推荐List;
// @SerializedName("App")
// public List<Gank> appList;
// }
// }
//
// Path: app/src/main/java/com/yunq/gankio/data/parse/PrettyGirlData.java
// public class PrettyGirlData extends BaseData {
//
// public List<Girl> results;
// }
| import com.yunq.gankio.core.MeiziService;
import com.yunq.gankio.data.entity.Gank;
import com.yunq.gankio.data.entity.Girl;
import com.yunq.gankio.data.parse.GankData;
import com.yunq.gankio.data.parse.PrettyGirlData;
import com.yunq.gankio.data.parse.休息视频Data;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.inject.Inject;
import javax.inject.Singleton;
import okhttp3.OkHttpClient;
import rx.Observable;
import rx.functions.Func1;
import rx.functions.Func2; | @Override
public List<Girl> call(PrettyGirlData girlData) {
return girlData.results;
}
})
.flatMap(new Func1<List<Girl>, Observable<Girl>>() {
@Override
public Observable<Girl> call(List<Girl> girls) {
return Observable.from(girls);
}
})
.toSortedList(new Func2<Girl, Girl, Integer>() {
@Override
public Integer call(Girl girl, Girl girl2) {
return girl2.publishedAt.compareTo(girl.publishedAt);
}
});
}
/**
* GankDetailActivity
*/
public Observable<List<Gank>> getGankData(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH) + 1;
int day = calendar.get(Calendar.DAY_OF_MONTH);
return mMeiziService.getGankData(year, month, day) | // Path: app/src/main/java/com/yunq/gankio/core/MeiziService.java
// public interface MeiziService {
//
// /**
// * 数据主机地址
// */
// String HOST = "http://gank.avosapps.com/api/";
//
// @GET("data/福利/{pageSize}/{page}")
// Observable<PrettyGirlData> getPrettyGirlData(@Path("pageSize") int pageSize, @Path("page") int page);
//
// @GET("data/休息视频/{pageSize}/{page}")
// Observable<休息视频Data> get休息视频Data(@Path("pageSize") int pageSize, @Path("page") int page);
//
// @GET("day/{year}/{month}/{day}")
// Observable<GankData> getGankData(@Path("year") int year, @Path("month") int month, @Path("day") int day);
//
// class Creator {
// public static MeiziService newGudongService(OkHttpClient client) {
// Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").serializeNulls().create();
//
// Retrofit apiAdapter = new Retrofit.Builder()
// .baseUrl(HOST)
// .addConverterFactory(GsonConverterFactory.create(gson))
// .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
// .client(client)
// .build();
//
// return apiAdapter.create(MeiziService.class);
// }
// }
//
// }
//
// Path: app/src/main/java/com/yunq/gankio/data/entity/Gank.java
// @Table("ganks")
// public class Gank extends Soul {
//
// @Column("used")
// public boolean used;
// @Column("type")
// public String type;
// @Column("url")
// public String url;
// @Column("who")
// public String who;
// @Column("desc")
// public String desc;
// @Column("updatedAt")
// public Date updatedAt;
// @Column("createdAt")
// public Date createdAt;
// @Column("publishedAt")
// public Date publishedAt;
// }
//
// Path: app/src/main/java/com/yunq/gankio/data/entity/Girl.java
// public class Girl extends Soul {
//
// @Column("used")
// public boolean used;
// @Column("type")
// public String type;
// @Column("url")
// public String url;
// @Column("who")
// public String who;
// @Column("desc")
// public String desc;
// @Column("createdAt")
// public Date createdAt;
// @Column("publishedAt")
// public Date publishedAt;
// @Column("updatedAt")
// public Date updatedAt;
//
// }
//
// Path: app/src/main/java/com/yunq/gankio/data/parse/GankData.java
// public class GankData extends BaseData{
//
// public List<String> category;
// public Result results;
//
// public class Result {
// @SerializedName("Android")
// public List<Gank> androidList;
// @SerializedName("休息视频")
// public List<Gank> 休息视频List;
// @SerializedName("iOS")
// public List<Gank> iOSList;
// @SerializedName("福利")
// public List<Gank> 妹纸List;
// @SerializedName("拓展资源")
// public List<Gank> 拓展资源List;
// @SerializedName("瞎推荐")
// public List<Gank> 瞎推荐List;
// @SerializedName("App")
// public List<Gank> appList;
// }
// }
//
// Path: app/src/main/java/com/yunq/gankio/data/parse/PrettyGirlData.java
// public class PrettyGirlData extends BaseData {
//
// public List<Girl> results;
// }
// Path: app/src/main/java/com/yunq/gankio/data/DataManager.java
import com.yunq.gankio.core.MeiziService;
import com.yunq.gankio.data.entity.Gank;
import com.yunq.gankio.data.entity.Girl;
import com.yunq.gankio.data.parse.GankData;
import com.yunq.gankio.data.parse.PrettyGirlData;
import com.yunq.gankio.data.parse.休息视频Data;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.inject.Inject;
import javax.inject.Singleton;
import okhttp3.OkHttpClient;
import rx.Observable;
import rx.functions.Func1;
import rx.functions.Func2;
@Override
public List<Girl> call(PrettyGirlData girlData) {
return girlData.results;
}
})
.flatMap(new Func1<List<Girl>, Observable<Girl>>() {
@Override
public Observable<Girl> call(List<Girl> girls) {
return Observable.from(girls);
}
})
.toSortedList(new Func2<Girl, Girl, Integer>() {
@Override
public Integer call(Girl girl, Girl girl2) {
return girl2.publishedAt.compareTo(girl.publishedAt);
}
});
}
/**
* GankDetailActivity
*/
public Observable<List<Gank>> getGankData(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH) + 1;
int day = calendar.get(Calendar.DAY_OF_MONTH);
return mMeiziService.getGankData(year, month, day) | .map(new Func1<GankData, GankData.Result>() { |
xuyunqiang/MeiziAPP | app/src/main/java/com/yunq/gankio/data/parse/GankData.java | // Path: app/src/main/java/com/yunq/gankio/data/entity/Gank.java
// @Table("ganks")
// public class Gank extends Soul {
//
// @Column("used")
// public boolean used;
// @Column("type")
// public String type;
// @Column("url")
// public String url;
// @Column("who")
// public String who;
// @Column("desc")
// public String desc;
// @Column("updatedAt")
// public Date updatedAt;
// @Column("createdAt")
// public Date createdAt;
// @Column("publishedAt")
// public Date publishedAt;
// }
| import com.google.gson.annotations.SerializedName;
import com.yunq.gankio.data.entity.Gank;
import java.util.List; | package com.yunq.gankio.data.parse;
/**
* Created by admin on 16/1/5.
*/
public class GankData extends BaseData{
public List<String> category;
public Result results;
public class Result {
@SerializedName("Android") | // Path: app/src/main/java/com/yunq/gankio/data/entity/Gank.java
// @Table("ganks")
// public class Gank extends Soul {
//
// @Column("used")
// public boolean used;
// @Column("type")
// public String type;
// @Column("url")
// public String url;
// @Column("who")
// public String who;
// @Column("desc")
// public String desc;
// @Column("updatedAt")
// public Date updatedAt;
// @Column("createdAt")
// public Date createdAt;
// @Column("publishedAt")
// public Date publishedAt;
// }
// Path: app/src/main/java/com/yunq/gankio/data/parse/GankData.java
import com.google.gson.annotations.SerializedName;
import com.yunq.gankio.data.entity.Gank;
import java.util.List;
package com.yunq.gankio.data.parse;
/**
* Created by admin on 16/1/5.
*/
public class GankData extends BaseData{
public List<String> category;
public Result results;
public class Result {
@SerializedName("Android") | public List<Gank> androidList; |
bluedenim/log4j-s3-search | appender-core/src/main/java/com/van/logging/solr/SolrPublishHelper.java | // Path: appender-core/src/main/java/com/van/logging/Event.java
// public class Event implements Serializable {
//
// static final long serialVersionUID = 1000L;
//
// private final String source;
// private final String type;
// private final String threadName;
//
// private final String message;
//
// public Event(String source, String type, String message) {
// this(source, type, message, Thread.currentThread().getName());
// }
//
// public Event(String source, String type, String message, String threadName) {
// Objects.requireNonNull(source);
// Objects.requireNonNull(type);
// Objects.requireNonNull(message);
// Objects.requireNonNull(threadName);
// this.source = source;
// this.type = type;
// this.threadName = threadName;
// this.message = message;
// }
//
// public String getSource() {
// return source;
// }
//
// public String getType() {
// return type;
// }
//
// public String getThreadName() {
// return threadName;
// }
//
// public String getMessage() {
// return message;
// }
//
// @Override
// public String toString() {
// return String.format("%s %s:%s:%s", threadName, source, type, message);
// }
// }
//
// Path: appender-core/src/main/java/com/van/logging/IPublishHelper.java
// public interface IPublishHelper<T> {
// /**
// * A publish batch is starting. This is a good place to (re)initialize
// * a buffer.
// *
// * @param context publish context providing useful properties for the
// * publish operation
// */
// void start(PublishContext context);
//
// /**
// * A log event should be published. Implementations may want to accumulate
// * this in a batch until {{@link #end(PublishContext)}
// *
// * @param context publish context providing useful properties for the
// * publish operation
// * @param sequence counter of the sequence of this event in the batch
// * @param event the log event
// */
// void publish(PublishContext context, int sequence, T event);
//
// /**
// * A publish batch has ended. Implementations should conclude a batch
// * and clean up resources here.
// *
// * @param context publish context providing useful properties for the
// * publish operation
// */
// void end(PublishContext context);
// }
//
// Path: appender-core/src/main/java/com/van/logging/PublishContext.java
// public class PublishContext {
// private final String cacheName;
// private final String hostName;
// private final String[] tags;
//
// /**
// * Creates an instance with the data provided
// *
// * @param cacheName name of the cache used to distinguish it from other caches
// * @param hostName the host name where the logs are collected (typically
// * the name of the local host)
// * @param tags additional tags for the event that the logger was initialized with
// */
// public PublishContext(String cacheName, String hostName, String[] tags) {
// this.cacheName = cacheName;
// this.hostName = hostName;
// this.tags = tags;
// }
//
// public String getCacheName() {
// return cacheName;
// }
//
// public String getHostName() {
// return hostName;
// }
//
// public String[] getTags() {
// return tags;
// }
//
// }
| import com.van.logging.Event;
import com.van.logging.IPublishHelper;
import com.van.logging.PublishContext;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.common.SolrInputDocument;
import java.net.URL;
import java.util.Date;
import java.util.LinkedList;
import java.util.List; | package com.van.logging.solr;
/**
* Publish helper to publish logs to Solr
*
* @author vly
*
*/
public class SolrPublishHelper implements IPublishHelper<Event> {
private final SolrClient client;
private int offset;
private Date timeStamp;
private List<SolrInputDocument> docs;
public SolrPublishHelper(URL collectionUrl) {
this.client = new HttpSolrClient.Builder()
.withBaseSolrUrl(collectionUrl.toExternalForm())
.build();
}
| // Path: appender-core/src/main/java/com/van/logging/Event.java
// public class Event implements Serializable {
//
// static final long serialVersionUID = 1000L;
//
// private final String source;
// private final String type;
// private final String threadName;
//
// private final String message;
//
// public Event(String source, String type, String message) {
// this(source, type, message, Thread.currentThread().getName());
// }
//
// public Event(String source, String type, String message, String threadName) {
// Objects.requireNonNull(source);
// Objects.requireNonNull(type);
// Objects.requireNonNull(message);
// Objects.requireNonNull(threadName);
// this.source = source;
// this.type = type;
// this.threadName = threadName;
// this.message = message;
// }
//
// public String getSource() {
// return source;
// }
//
// public String getType() {
// return type;
// }
//
// public String getThreadName() {
// return threadName;
// }
//
// public String getMessage() {
// return message;
// }
//
// @Override
// public String toString() {
// return String.format("%s %s:%s:%s", threadName, source, type, message);
// }
// }
//
// Path: appender-core/src/main/java/com/van/logging/IPublishHelper.java
// public interface IPublishHelper<T> {
// /**
// * A publish batch is starting. This is a good place to (re)initialize
// * a buffer.
// *
// * @param context publish context providing useful properties for the
// * publish operation
// */
// void start(PublishContext context);
//
// /**
// * A log event should be published. Implementations may want to accumulate
// * this in a batch until {{@link #end(PublishContext)}
// *
// * @param context publish context providing useful properties for the
// * publish operation
// * @param sequence counter of the sequence of this event in the batch
// * @param event the log event
// */
// void publish(PublishContext context, int sequence, T event);
//
// /**
// * A publish batch has ended. Implementations should conclude a batch
// * and clean up resources here.
// *
// * @param context publish context providing useful properties for the
// * publish operation
// */
// void end(PublishContext context);
// }
//
// Path: appender-core/src/main/java/com/van/logging/PublishContext.java
// public class PublishContext {
// private final String cacheName;
// private final String hostName;
// private final String[] tags;
//
// /**
// * Creates an instance with the data provided
// *
// * @param cacheName name of the cache used to distinguish it from other caches
// * @param hostName the host name where the logs are collected (typically
// * the name of the local host)
// * @param tags additional tags for the event that the logger was initialized with
// */
// public PublishContext(String cacheName, String hostName, String[] tags) {
// this.cacheName = cacheName;
// this.hostName = hostName;
// this.tags = tags;
// }
//
// public String getCacheName() {
// return cacheName;
// }
//
// public String getHostName() {
// return hostName;
// }
//
// public String[] getTags() {
// return tags;
// }
//
// }
// Path: appender-core/src/main/java/com/van/logging/solr/SolrPublishHelper.java
import com.van.logging.Event;
import com.van.logging.IPublishHelper;
import com.van.logging.PublishContext;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.common.SolrInputDocument;
import java.net.URL;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
package com.van.logging.solr;
/**
* Publish helper to publish logs to Solr
*
* @author vly
*
*/
public class SolrPublishHelper implements IPublishHelper<Event> {
private final SolrClient client;
private int offset;
private Date timeStamp;
private List<SolrInputDocument> docs;
public SolrPublishHelper(URL collectionUrl) {
this.client = new HttpSolrClient.Builder()
.withBaseSolrUrl(collectionUrl.toExternalForm())
.build();
}
| public void publish(PublishContext context, int sequence, Event event) { |
bluedenim/log4j-s3-search | appender-log4j2/src/main/java/com/van/logging/log4j2/PatternedPathAdjuster.java | // Path: appender-core/src/main/java/com/van/logging/IStorageDestinationAdjuster.java
// public interface IStorageDestinationAdjuster {
//
// /**
// * Given the path that is about to be used, the implementation may replace it with a totally
// * different path (perhaps based on the path provided).
// *
// * @param path the path that is about to be used.
// *
// * @return a new path to be used (or null if the provided path is acceptable)
// */
// public String adjustPath(String path);
// }
//
// Path: appender-core/src/main/java/com/van/logging/utils/StringUtils.java
// public class StringUtils {
//
// /**
// * Checks to see if a String is defined and not empty after trimming
// *
// * @param s the String to test
// *
// * @return true if the string is not null and is not empty
// */
// public static boolean isTruthy(String s) {
// return (null != s && !s.trim().isEmpty());
// }
//
// /**
// * If the string passed in is not blank or null and did not end with the trailing value, then the trailing value
// * will be appended to it in the returned value.
// *
// * @param s the string to conditionally add the trailing value to. If null, then null will be returned.
// * @param trailing the trailing value to append. If null, then s will be returned unmodified.
// *
// * @return the string s with the trailing value appended as necessary.
// */
// public static String addTrailingIfNeeded(String s, String trailing) {
// String value = s;
// if ((null != s) && (null != trailing)) {
// if (isTruthy(s) && !s.endsWith(trailing)) {
// value = s + trailing;
// }
// }
// return value;
// }
// }
| import com.van.logging.IStorageDestinationAdjuster;
import com.van.logging.utils.StringUtils;
import org.apache.logging.log4j.core.impl.MutableLogEvent;
import org.apache.logging.log4j.core.layout.PatternLayout; | package com.van.logging.log4j2;
/**
* A path adjuster that assumes the original path is a template to expand using a limited-scoped implementation of
* PatternLayout.
* Currently, only the date (i.e. %d{...}) template is supported.
*/
public class PatternedPathAdjuster implements IStorageDestinationAdjuster {
@Override
public String adjustPath(String path) {
String adjusted = path; | // Path: appender-core/src/main/java/com/van/logging/IStorageDestinationAdjuster.java
// public interface IStorageDestinationAdjuster {
//
// /**
// * Given the path that is about to be used, the implementation may replace it with a totally
// * different path (perhaps based on the path provided).
// *
// * @param path the path that is about to be used.
// *
// * @return a new path to be used (or null if the provided path is acceptable)
// */
// public String adjustPath(String path);
// }
//
// Path: appender-core/src/main/java/com/van/logging/utils/StringUtils.java
// public class StringUtils {
//
// /**
// * Checks to see if a String is defined and not empty after trimming
// *
// * @param s the String to test
// *
// * @return true if the string is not null and is not empty
// */
// public static boolean isTruthy(String s) {
// return (null != s && !s.trim().isEmpty());
// }
//
// /**
// * If the string passed in is not blank or null and did not end with the trailing value, then the trailing value
// * will be appended to it in the returned value.
// *
// * @param s the string to conditionally add the trailing value to. If null, then null will be returned.
// * @param trailing the trailing value to append. If null, then s will be returned unmodified.
// *
// * @return the string s with the trailing value appended as necessary.
// */
// public static String addTrailingIfNeeded(String s, String trailing) {
// String value = s;
// if ((null != s) && (null != trailing)) {
// if (isTruthy(s) && !s.endsWith(trailing)) {
// value = s + trailing;
// }
// }
// return value;
// }
// }
// Path: appender-log4j2/src/main/java/com/van/logging/log4j2/PatternedPathAdjuster.java
import com.van.logging.IStorageDestinationAdjuster;
import com.van.logging.utils.StringUtils;
import org.apache.logging.log4j.core.impl.MutableLogEvent;
import org.apache.logging.log4j.core.layout.PatternLayout;
package com.van.logging.log4j2;
/**
* A path adjuster that assumes the original path is a template to expand using a limited-scoped implementation of
* PatternLayout.
* Currently, only the date (i.e. %d{...}) template is supported.
*/
public class PatternedPathAdjuster implements IStorageDestinationAdjuster {
@Override
public String adjustPath(String path) {
String adjusted = path; | if (StringUtils.isTruthy(path)) { |
bluedenim/log4j-s3-search | appender-core/src/main/java/com/van/logging/aws/S3Configuration.java | // Path: appender-core/src/main/java/com/van/logging/utils/StringUtils.java
// public class StringUtils {
//
// /**
// * Checks to see if a String is defined and not empty after trimming
// *
// * @param s the String to test
// *
// * @return true if the string is not null and is not empty
// */
// public static boolean isTruthy(String s) {
// return (null != s && !s.trim().isEmpty());
// }
//
// /**
// * If the string passed in is not blank or null and did not end with the trailing value, then the trailing value
// * will be appended to it in the returned value.
// *
// * @param s the string to conditionally add the trailing value to. If null, then null will be returned.
// * @param trailing the trailing value to append. If null, then s will be returned unmodified.
// *
// * @return the string s with the trailing value appended as necessary.
// */
// public static String addTrailingIfNeeded(String s, String trailing) {
// String value = s;
// if ((null != s) && (null != trailing)) {
// if (isTruthy(s) && !s.endsWith(trailing)) {
// value = s + trailing;
// }
// }
// return value;
// }
// }
| import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.model.CannedAccessControlList;
import com.van.logging.utils.StringUtils; | }
public boolean isCompressionEnabled() {
return compressionEnabled;
}
public boolean isKeyGzSuffixEnabled() {
return keyGzSuffixEnabled;
}
public void setCompressionEnabled(boolean compressionEnabled) {
this.compressionEnabled = compressionEnabled;
}
public void setKeyGzSuffixEnabled(boolean gzSuffix) {
this.keyGzSuffixEnabled = gzSuffix;
}
/**
* Best-effort to map a region name to an actual Region instance. The input
* string can be either the public region name (e.g. "us-west-1") or the
* Regions enum ordinal name (e.g. "US_WEST_1").
*
* @param str the region name to map to a Region
*
* @return the mapped Region
*
* @throws IllegalArgumentException if the input name cannot be mapped to a
* Region.
*/
static Region resolveRegion(String str) {
Region region = null; | // Path: appender-core/src/main/java/com/van/logging/utils/StringUtils.java
// public class StringUtils {
//
// /**
// * Checks to see if a String is defined and not empty after trimming
// *
// * @param s the String to test
// *
// * @return true if the string is not null and is not empty
// */
// public static boolean isTruthy(String s) {
// return (null != s && !s.trim().isEmpty());
// }
//
// /**
// * If the string passed in is not blank or null and did not end with the trailing value, then the trailing value
// * will be appended to it in the returned value.
// *
// * @param s the string to conditionally add the trailing value to. If null, then null will be returned.
// * @param trailing the trailing value to append. If null, then s will be returned unmodified.
// *
// * @return the string s with the trailing value appended as necessary.
// */
// public static String addTrailingIfNeeded(String s, String trailing) {
// String value = s;
// if ((null != s) && (null != trailing)) {
// if (isTruthy(s) && !s.endsWith(trailing)) {
// value = s + trailing;
// }
// }
// return value;
// }
// }
// Path: appender-core/src/main/java/com/van/logging/aws/S3Configuration.java
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.model.CannedAccessControlList;
import com.van.logging.utils.StringUtils;
}
public boolean isCompressionEnabled() {
return compressionEnabled;
}
public boolean isKeyGzSuffixEnabled() {
return keyGzSuffixEnabled;
}
public void setCompressionEnabled(boolean compressionEnabled) {
this.compressionEnabled = compressionEnabled;
}
public void setKeyGzSuffixEnabled(boolean gzSuffix) {
this.keyGzSuffixEnabled = gzSuffix;
}
/**
* Best-effort to map a region name to an actual Region instance. The input
* string can be either the public region name (e.g. "us-west-1") or the
* Regions enum ordinal name (e.g. "US_WEST_1").
*
* @param str the region name to map to a Region
*
* @return the mapped Region
*
* @throws IllegalArgumentException if the input name cannot be mapped to a
* Region.
*/
static Region resolveRegion(String str) {
Region region = null; | if (StringUtils.isTruthy(str)) { |
bluedenim/log4j-s3-search | appender-core/src/main/java/com/van/logging/aws/AwsClientHelpers.java | // Path: appender-core/src/main/java/com/van/logging/utils/StringUtils.java
// public class StringUtils {
//
// /**
// * Checks to see if a String is defined and not empty after trimming
// *
// * @param s the String to test
// *
// * @return true if the string is not null and is not empty
// */
// public static boolean isTruthy(String s) {
// return (null != s && !s.trim().isEmpty());
// }
//
// /**
// * If the string passed in is not blank or null and did not end with the trailing value, then the trailing value
// * will be appended to it in the returned value.
// *
// * @param s the string to conditionally add the trailing value to. If null, then null will be returned.
// * @param trailing the trailing value to append. If null, then s will be returned unmodified.
// *
// * @return the string s with the trailing value appended as necessary.
// */
// public static String addTrailingIfNeeded(String s, String trailing) {
// String value = s;
// if ((null != s) && (null != trailing)) {
// if (isTruthy(s) && !s.endsWith(trailing)) {
// value = s + trailing;
// }
// }
// return value;
// }
// }
| import com.amazonaws.auth.*;
import com.amazonaws.client.builder.AwsClientBuilder;
import com.amazonaws.regions.Region;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.van.logging.utils.StringUtils; | * secretKey are null, then the default credential configuration for AWS is used.
*
* Similarly, if region is null, then the default region is used.
*
* See https://docs.aws.amazon.com/sdk-for-java/v1/developer-guide/credentials.html and
* https://docs.aws.amazon.com/sdk-for-java/v1/developer-guide/java-dg-region-selection.html
*
* @param accessKey optional access key for S3 access.
* @param secretKey optional secret key for S3 access.
* @param sessionToken optional session token for S3 access.
* @param region optional region to use.
* @param serviceEndpoint optional service endpoint to use when initializing the S3 Client.
* @param signingRegion optional signing region to use when initializing the S3 Client.
* @param pathStyleAccess optional boolean indicating if path style URL should be used
*
* @return the client class to use for S3 access.
*/
public static AmazonS3 buildClient(
String accessKey, String secretKey, String sessionToken,
Region region,
String serviceEndpoint, String signingRegion, boolean pathStyleAccess
) {
AWSCredentialsProvider credentialsProvider =
getCredentialsProvider(accessKey, secretKey, sessionToken);
AmazonS3ClientBuilder builder = getS3ClientBuilder()
.withCredentials(credentialsProvider)
.withPathStyleAccessEnabled(pathStyleAccess);
if (region != null) {
builder = builder.withRegion(region.getName());
} | // Path: appender-core/src/main/java/com/van/logging/utils/StringUtils.java
// public class StringUtils {
//
// /**
// * Checks to see if a String is defined and not empty after trimming
// *
// * @param s the String to test
// *
// * @return true if the string is not null and is not empty
// */
// public static boolean isTruthy(String s) {
// return (null != s && !s.trim().isEmpty());
// }
//
// /**
// * If the string passed in is not blank or null and did not end with the trailing value, then the trailing value
// * will be appended to it in the returned value.
// *
// * @param s the string to conditionally add the trailing value to. If null, then null will be returned.
// * @param trailing the trailing value to append. If null, then s will be returned unmodified.
// *
// * @return the string s with the trailing value appended as necessary.
// */
// public static String addTrailingIfNeeded(String s, String trailing) {
// String value = s;
// if ((null != s) && (null != trailing)) {
// if (isTruthy(s) && !s.endsWith(trailing)) {
// value = s + trailing;
// }
// }
// return value;
// }
// }
// Path: appender-core/src/main/java/com/van/logging/aws/AwsClientHelpers.java
import com.amazonaws.auth.*;
import com.amazonaws.client.builder.AwsClientBuilder;
import com.amazonaws.regions.Region;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.van.logging.utils.StringUtils;
* secretKey are null, then the default credential configuration for AWS is used.
*
* Similarly, if region is null, then the default region is used.
*
* See https://docs.aws.amazon.com/sdk-for-java/v1/developer-guide/credentials.html and
* https://docs.aws.amazon.com/sdk-for-java/v1/developer-guide/java-dg-region-selection.html
*
* @param accessKey optional access key for S3 access.
* @param secretKey optional secret key for S3 access.
* @param sessionToken optional session token for S3 access.
* @param region optional region to use.
* @param serviceEndpoint optional service endpoint to use when initializing the S3 Client.
* @param signingRegion optional signing region to use when initializing the S3 Client.
* @param pathStyleAccess optional boolean indicating if path style URL should be used
*
* @return the client class to use for S3 access.
*/
public static AmazonS3 buildClient(
String accessKey, String secretKey, String sessionToken,
Region region,
String serviceEndpoint, String signingRegion, boolean pathStyleAccess
) {
AWSCredentialsProvider credentialsProvider =
getCredentialsProvider(accessKey, secretKey, sessionToken);
AmazonS3ClientBuilder builder = getS3ClientBuilder()
.withCredentials(credentialsProvider)
.withPathStyleAccessEnabled(pathStyleAccess);
if (region != null) {
builder = builder.withRegion(region.getName());
} | if (StringUtils.isTruthy(serviceEndpoint)) { |
bluedenim/log4j-s3-search | appender-core/src/main/java/com/van/logging/solr/SolrConfiguration.java | // Path: appender-core/src/main/java/com/van/logging/utils/StringUtils.java
// public class StringUtils {
//
// /**
// * Checks to see if a String is defined and not empty after trimming
// *
// * @param s the String to test
// *
// * @return true if the string is not null and is not empty
// */
// public static boolean isTruthy(String s) {
// return (null != s && !s.trim().isEmpty());
// }
//
// /**
// * If the string passed in is not blank or null and did not end with the trailing value, then the trailing value
// * will be appended to it in the returned value.
// *
// * @param s the string to conditionally add the trailing value to. If null, then null will be returned.
// * @param trailing the trailing value to append. If null, then s will be returned unmodified.
// *
// * @return the string s with the trailing value appended as necessary.
// */
// public static String addTrailingIfNeeded(String s, String trailing) {
// String value = s;
// if ((null != s) && (null != trailing)) {
// if (isTruthy(s) && !s.endsWith(trailing)) {
// value = s + trailing;
// }
// }
// return value;
// }
// }
| import com.van.logging.utils.StringUtils;
import java.net.MalformedURLException;
import java.net.URL; | package com.van.logging.solr;
/**
* Solr configuration
*
* @author vly
*
*/
public class SolrConfiguration {
private URL url;
public URL getUrl() {
return url;
}
public void setUrl(String solrUrl) { | // Path: appender-core/src/main/java/com/van/logging/utils/StringUtils.java
// public class StringUtils {
//
// /**
// * Checks to see if a String is defined and not empty after trimming
// *
// * @param s the String to test
// *
// * @return true if the string is not null and is not empty
// */
// public static boolean isTruthy(String s) {
// return (null != s && !s.trim().isEmpty());
// }
//
// /**
// * If the string passed in is not blank or null and did not end with the trailing value, then the trailing value
// * will be appended to it in the returned value.
// *
// * @param s the string to conditionally add the trailing value to. If null, then null will be returned.
// * @param trailing the trailing value to append. If null, then s will be returned unmodified.
// *
// * @return the string s with the trailing value appended as necessary.
// */
// public static String addTrailingIfNeeded(String s, String trailing) {
// String value = s;
// if ((null != s) && (null != trailing)) {
// if (isTruthy(s) && !s.endsWith(trailing)) {
// value = s + trailing;
// }
// }
// return value;
// }
// }
// Path: appender-core/src/main/java/com/van/logging/solr/SolrConfiguration.java
import com.van.logging.utils.StringUtils;
import java.net.MalformedURLException;
import java.net.URL;
package com.van.logging.solr;
/**
* Solr configuration
*
* @author vly
*
*/
public class SolrConfiguration {
private URL url;
public URL getUrl() {
return url;
}
public void setUrl(String solrUrl) { | if (StringUtils.isTruthy(solrUrl)) { |
bluedenim/log4j-s3-search | appender-log4j/src/main/java/com/van/logging/log4j/PatternedPathAdjuster.java | // Path: appender-core/src/main/java/com/van/logging/IStorageDestinationAdjuster.java
// public interface IStorageDestinationAdjuster {
//
// /**
// * Given the path that is about to be used, the implementation may replace it with a totally
// * different path (perhaps based on the path provided).
// *
// * @param path the path that is about to be used.
// *
// * @return a new path to be used (or null if the provided path is acceptable)
// */
// public String adjustPath(String path);
// }
//
// Path: appender-core/src/main/java/com/van/logging/utils/StringUtils.java
// public class StringUtils {
//
// /**
// * Checks to see if a String is defined and not empty after trimming
// *
// * @param s the String to test
// *
// * @return true if the string is not null and is not empty
// */
// public static boolean isTruthy(String s) {
// return (null != s && !s.trim().isEmpty());
// }
//
// /**
// * If the string passed in is not blank or null and did not end with the trailing value, then the trailing value
// * will be appended to it in the returned value.
// *
// * @param s the string to conditionally add the trailing value to. If null, then null will be returned.
// * @param trailing the trailing value to append. If null, then s will be returned unmodified.
// *
// * @return the string s with the trailing value appended as necessary.
// */
// public static String addTrailingIfNeeded(String s, String trailing) {
// String value = s;
// if ((null != s) && (null != trailing)) {
// if (isTruthy(s) && !s.endsWith(trailing)) {
// value = s + trailing;
// }
// }
// return value;
// }
// }
| import com.van.logging.IStorageDestinationAdjuster;
import com.van.logging.utils.StringUtils;
import org.apache.log4j.Level;
import org.apache.log4j.PatternLayout;
import org.apache.log4j.spi.LoggingEvent; | package com.van.logging.log4j;
/**
* A path adjuster that assumes the original path is a template to expand using a limited-scoped implementation of
* PatternLayout.
* Currently, only the date (i.e. %d{...}) template is supported.
*/
public class PatternedPathAdjuster implements IStorageDestinationAdjuster {
@Override
public String adjustPath(String path) {
String adjusted = path; | // Path: appender-core/src/main/java/com/van/logging/IStorageDestinationAdjuster.java
// public interface IStorageDestinationAdjuster {
//
// /**
// * Given the path that is about to be used, the implementation may replace it with a totally
// * different path (perhaps based on the path provided).
// *
// * @param path the path that is about to be used.
// *
// * @return a new path to be used (or null if the provided path is acceptable)
// */
// public String adjustPath(String path);
// }
//
// Path: appender-core/src/main/java/com/van/logging/utils/StringUtils.java
// public class StringUtils {
//
// /**
// * Checks to see if a String is defined and not empty after trimming
// *
// * @param s the String to test
// *
// * @return true if the string is not null and is not empty
// */
// public static boolean isTruthy(String s) {
// return (null != s && !s.trim().isEmpty());
// }
//
// /**
// * If the string passed in is not blank or null and did not end with the trailing value, then the trailing value
// * will be appended to it in the returned value.
// *
// * @param s the string to conditionally add the trailing value to. If null, then null will be returned.
// * @param trailing the trailing value to append. If null, then s will be returned unmodified.
// *
// * @return the string s with the trailing value appended as necessary.
// */
// public static String addTrailingIfNeeded(String s, String trailing) {
// String value = s;
// if ((null != s) && (null != trailing)) {
// if (isTruthy(s) && !s.endsWith(trailing)) {
// value = s + trailing;
// }
// }
// return value;
// }
// }
// Path: appender-log4j/src/main/java/com/van/logging/log4j/PatternedPathAdjuster.java
import com.van.logging.IStorageDestinationAdjuster;
import com.van.logging.utils.StringUtils;
import org.apache.log4j.Level;
import org.apache.log4j.PatternLayout;
import org.apache.log4j.spi.LoggingEvent;
package com.van.logging.log4j;
/**
* A path adjuster that assumes the original path is a template to expand using a limited-scoped implementation of
* PatternLayout.
* Currently, only the date (i.e. %d{...}) template is supported.
*/
public class PatternedPathAdjuster implements IStorageDestinationAdjuster {
@Override
public String adjustPath(String path) {
String adjusted = path; | if (StringUtils.isTruthy(path)) { |
bluedenim/log4j-s3-search | appender-core/src/main/java/com/van/logging/elasticsearch/ElasticsearchPublishHelper.java | // Path: appender-core/src/main/java/com/van/logging/IPublishHelper.java
// public interface IPublishHelper<T> {
// /**
// * A publish batch is starting. This is a good place to (re)initialize
// * a buffer.
// *
// * @param context publish context providing useful properties for the
// * publish operation
// */
// void start(PublishContext context);
//
// /**
// * A log event should be published. Implementations may want to accumulate
// * this in a batch until {{@link #end(PublishContext)}
// *
// * @param context publish context providing useful properties for the
// * publish operation
// * @param sequence counter of the sequence of this event in the batch
// * @param event the log event
// */
// void publish(PublishContext context, int sequence, T event);
//
// /**
// * A publish batch has ended. Implementations should conclude a batch
// * and clean up resources here.
// *
// * @param context publish context providing useful properties for the
// * publish operation
// */
// void end(PublishContext context);
// }
//
// Path: appender-core/src/main/java/com/van/logging/PublishContext.java
// public class PublishContext {
// private final String cacheName;
// private final String hostName;
// private final String[] tags;
//
// /**
// * Creates an instance with the data provided
// *
// * @param cacheName name of the cache used to distinguish it from other caches
// * @param hostName the host name where the logs are collected (typically
// * the name of the local host)
// * @param tags additional tags for the event that the logger was initialized with
// */
// public PublishContext(String cacheName, String hostName, String[] tags) {
// this.cacheName = cacheName;
// this.hostName = hostName;
// this.tags = tags;
// }
//
// public String getCacheName() {
// return cacheName;
// }
//
// public String getHostName() {
// return hostName;
// }
//
// public String[] getTags() {
// return tags;
// }
//
// }
//
// Path: appender-core/src/main/java/com/van/logging/utils/StringUtils.java
// public class StringUtils {
//
// /**
// * Checks to see if a String is defined and not empty after trimming
// *
// * @param s the String to test
// *
// * @return true if the string is not null and is not empty
// */
// public static boolean isTruthy(String s) {
// return (null != s && !s.trim().isEmpty());
// }
//
// /**
// * If the string passed in is not blank or null and did not end with the trailing value, then the trailing value
// * will be appended to it in the returned value.
// *
// * @param s the string to conditionally add the trailing value to. If null, then null will be returned.
// * @param trailing the trailing value to append. If null, then s will be returned unmodified.
// *
// * @return the string s with the trailing value appended as necessary.
// */
// public static String addTrailingIfNeeded(String s, String trailing) {
// String value = s;
// if ((null != s) && (null != trailing)) {
// if (isTruthy(s) && !s.endsWith(trailing)) {
// value = s + trailing;
// }
// }
// return value;
// }
// }
//
// Path: appender-core/src/main/java/com/van/logging/Event.java
// public class Event implements Serializable {
//
// static final long serialVersionUID = 1000L;
//
// private final String source;
// private final String type;
// private final String threadName;
//
// private final String message;
//
// public Event(String source, String type, String message) {
// this(source, type, message, Thread.currentThread().getName());
// }
//
// public Event(String source, String type, String message, String threadName) {
// Objects.requireNonNull(source);
// Objects.requireNonNull(type);
// Objects.requireNonNull(message);
// Objects.requireNonNull(threadName);
// this.source = source;
// this.type = type;
// this.threadName = threadName;
// this.message = message;
// }
//
// public String getSource() {
// return source;
// }
//
// public String getType() {
// return type;
// }
//
// public String getThreadName() {
// return threadName;
// }
//
// public String getMessage() {
// return message;
// }
//
// @Override
// public String toString() {
// return String.format("%s %s:%s:%s", threadName, source, type, message);
// }
// }
| import com.van.logging.IPublishHelper;
import com.van.logging.PublishContext;
import com.van.logging.utils.StringUtils;
import org.apache.http.HttpHost;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.*;
import org.elasticsearch.common.xcontent.XContentBuilder;
import com.van.logging.Event;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; | public void end(PublishContext context) {
try {
if ((null != client) && (null != bulkRequest)) {
BulkResponse response = client.bulk(bulkRequest, RequestOptions.DEFAULT);
if (response.hasFailures()) {
System.err.println("Elasticsearch publish failures: " + response.buildFailureMessage());
}
}
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
if (null != client) {
client.close();
}
bulkRequest = null;
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static IElasticsearchPublishHelper getPublishHelper(
String publishHelperNameSpec, ClassLoader classLoader) {
return getPublishHelper(publishHelperNameSpec, classLoader, false);
}
public static IElasticsearchPublishHelper getPublishHelper(
String publishHelperNameSpec, ClassLoader classLoader, boolean verbose) {
ElasticsearchPublishHelper helper = null; | // Path: appender-core/src/main/java/com/van/logging/IPublishHelper.java
// public interface IPublishHelper<T> {
// /**
// * A publish batch is starting. This is a good place to (re)initialize
// * a buffer.
// *
// * @param context publish context providing useful properties for the
// * publish operation
// */
// void start(PublishContext context);
//
// /**
// * A log event should be published. Implementations may want to accumulate
// * this in a batch until {{@link #end(PublishContext)}
// *
// * @param context publish context providing useful properties for the
// * publish operation
// * @param sequence counter of the sequence of this event in the batch
// * @param event the log event
// */
// void publish(PublishContext context, int sequence, T event);
//
// /**
// * A publish batch has ended. Implementations should conclude a batch
// * and clean up resources here.
// *
// * @param context publish context providing useful properties for the
// * publish operation
// */
// void end(PublishContext context);
// }
//
// Path: appender-core/src/main/java/com/van/logging/PublishContext.java
// public class PublishContext {
// private final String cacheName;
// private final String hostName;
// private final String[] tags;
//
// /**
// * Creates an instance with the data provided
// *
// * @param cacheName name of the cache used to distinguish it from other caches
// * @param hostName the host name where the logs are collected (typically
// * the name of the local host)
// * @param tags additional tags for the event that the logger was initialized with
// */
// public PublishContext(String cacheName, String hostName, String[] tags) {
// this.cacheName = cacheName;
// this.hostName = hostName;
// this.tags = tags;
// }
//
// public String getCacheName() {
// return cacheName;
// }
//
// public String getHostName() {
// return hostName;
// }
//
// public String[] getTags() {
// return tags;
// }
//
// }
//
// Path: appender-core/src/main/java/com/van/logging/utils/StringUtils.java
// public class StringUtils {
//
// /**
// * Checks to see if a String is defined and not empty after trimming
// *
// * @param s the String to test
// *
// * @return true if the string is not null and is not empty
// */
// public static boolean isTruthy(String s) {
// return (null != s && !s.trim().isEmpty());
// }
//
// /**
// * If the string passed in is not blank or null and did not end with the trailing value, then the trailing value
// * will be appended to it in the returned value.
// *
// * @param s the string to conditionally add the trailing value to. If null, then null will be returned.
// * @param trailing the trailing value to append. If null, then s will be returned unmodified.
// *
// * @return the string s with the trailing value appended as necessary.
// */
// public static String addTrailingIfNeeded(String s, String trailing) {
// String value = s;
// if ((null != s) && (null != trailing)) {
// if (isTruthy(s) && !s.endsWith(trailing)) {
// value = s + trailing;
// }
// }
// return value;
// }
// }
//
// Path: appender-core/src/main/java/com/van/logging/Event.java
// public class Event implements Serializable {
//
// static final long serialVersionUID = 1000L;
//
// private final String source;
// private final String type;
// private final String threadName;
//
// private final String message;
//
// public Event(String source, String type, String message) {
// this(source, type, message, Thread.currentThread().getName());
// }
//
// public Event(String source, String type, String message, String threadName) {
// Objects.requireNonNull(source);
// Objects.requireNonNull(type);
// Objects.requireNonNull(message);
// Objects.requireNonNull(threadName);
// this.source = source;
// this.type = type;
// this.threadName = threadName;
// this.message = message;
// }
//
// public String getSource() {
// return source;
// }
//
// public String getType() {
// return type;
// }
//
// public String getThreadName() {
// return threadName;
// }
//
// public String getMessage() {
// return message;
// }
//
// @Override
// public String toString() {
// return String.format("%s %s:%s:%s", threadName, source, type, message);
// }
// }
// Path: appender-core/src/main/java/com/van/logging/elasticsearch/ElasticsearchPublishHelper.java
import com.van.logging.IPublishHelper;
import com.van.logging.PublishContext;
import com.van.logging.utils.StringUtils;
import org.apache.http.HttpHost;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.*;
import org.elasticsearch.common.xcontent.XContentBuilder;
import com.van.logging.Event;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
public void end(PublishContext context) {
try {
if ((null != client) && (null != bulkRequest)) {
BulkResponse response = client.bulk(bulkRequest, RequestOptions.DEFAULT);
if (response.hasFailures()) {
System.err.println("Elasticsearch publish failures: " + response.buildFailureMessage());
}
}
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
if (null != client) {
client.close();
}
bulkRequest = null;
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static IElasticsearchPublishHelper getPublishHelper(
String publishHelperNameSpec, ClassLoader classLoader) {
return getPublishHelper(publishHelperNameSpec, classLoader, false);
}
public static IElasticsearchPublishHelper getPublishHelper(
String publishHelperNameSpec, ClassLoader classLoader, boolean verbose) {
ElasticsearchPublishHelper helper = null; | if (StringUtils.isTruthy(publishHelperNameSpec)) { |
release-engineering/pom-version-manipulator | src/test/java/com/redhat/rcm/version/util/PomPeekTest.java | // Path: src/test/java/com/redhat/rcm/version/testutil/TestProjectFixture.java
// public static File getResourceFile( final String path )
// {
// final URL resource = Thread.currentThread()
// .getContextClassLoader()
// .getResource( path );
// if ( resource == null )
// {
// fail( "Resource not found: " + path );
// }
//
// return new File( resource.getPath() );
// }
| import static com.redhat.rcm.version.testutil.TestProjectFixture.getResourceFile;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.junit.Assert.assertThat;
import java.io.File;
import java.util.Set;
import org.apache.maven.mae.project.key.FullProjectKey;
import org.junit.BeforeClass;
import org.junit.Test;
import com.redhat.rcm.version.fixture.LoggingFixture; | package com.redhat.rcm.version.util;
public class PomPeekTest
{
private static final String BASE = "pom-peek/";
@BeforeClass
public static void logging()
{
LoggingFixture.setupLogging();
}
@Test
public void findModules()
{ | // Path: src/test/java/com/redhat/rcm/version/testutil/TestProjectFixture.java
// public static File getResourceFile( final String path )
// {
// final URL resource = Thread.currentThread()
// .getContextClassLoader()
// .getResource( path );
// if ( resource == null )
// {
// fail( "Resource not found: " + path );
// }
//
// return new File( resource.getPath() );
// }
// Path: src/test/java/com/redhat/rcm/version/util/PomPeekTest.java
import static com.redhat.rcm.version.testutil.TestProjectFixture.getResourceFile;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.junit.Assert.assertThat;
import java.io.File;
import java.util.Set;
import org.apache.maven.mae.project.key.FullProjectKey;
import org.junit.BeforeClass;
import org.junit.Test;
import com.redhat.rcm.version.fixture.LoggingFixture;
package com.redhat.rcm.version.util;
public class PomPeekTest
{
private static final String BASE = "pom-peek/";
@BeforeClass
public static void logging()
{
LoggingFixture.setupLogging();
}
@Test
public void findModules()
{ | final File pom = getResourceFile( BASE + "contains-modules.pom" ); |
release-engineering/pom-version-manipulator | src/main/java/com/redhat/rcm/version/mgr/mod/PropertyModder.java | // Path: src/main/java/com/redhat/rcm/version/mgr/session/PropertyMappings.java
// public class PropertyMappings
// {
// private final Logger logger = LoggerFactory.getLogger( getClass() );
//
// private static final String EXPRESSION_PATTERN = "@([^@]+)@";
//
// private final Map<String, String> mappings = new HashMap<String, String>();
//
// private final Map<String, String> expressions = new HashMap<String, String>();
//
// public PropertyMappings( final Map<String, String> newMappings )
// {
// addMappings( null, newMappings );
// }
//
// PropertyMappings addBomPropertyMappings( final File bom, final Properties properties )
// {
// return addBomPropertyMappings( bom, properties, mappings );
// }
//
// PropertyMappings addBomPropertyMappings( final File bom, final Properties properties,
// final Map<String, String> newMappings )
// {
// addMappings( properties, newMappings );
//
// final Map<String, String> fromProps = new HashMap<String, String>();
// for ( final String key : properties.stringPropertyNames() )
// {
// fromProps.put( key, properties.getProperty( key ) );
// }
//
// // Add the BOM's own properties into the mappings...
// addMappings( properties, fromProps );
//
// return this;
// }
//
// public String getMappedValue( final String key, final VersionManagerSession session )
// {
// final String raw = mappings.get( key );
//
// if ( raw == null )
// {
// return null;
// }
//
// final StringSearchInterpolator interpolator = new StringSearchInterpolator( "@", "@" );
// interpolator.addValueSource( new MapBasedValueSource( mappings ) );
// try
// {
// return interpolator.interpolate( raw );
// }
// catch ( final InterpolationException e )
// {
// logger.error( "Invalid expression: '%s'. Reason: %s", e, raw, e.getMessage() );
// session.addError( new VManException( "Invalid expression: '%s'. Reason: %s", e, raw, e.getMessage() ) );
// }
//
// return null;
// }
//
// private void addMappings( final Properties properties, final Map<String, String> newMappings )
// {
// final Pattern pattern = Pattern.compile( EXPRESSION_PATTERN );
//
// if ( newMappings != null )
// {
// for ( final Map.Entry<String, String> entry : newMappings.entrySet() )
// {
// final String val = entry.getValue();
// final Matcher matcher = pattern.matcher( val );
//
// if ( matcher.matches() )
// {
// final String k = matcher.group( 1 );
// if ( ( !mappings.containsKey( k ) && !newMappings.containsKey( k ) ) ||
// // Its also an expression if the property exists in the global properties map.
// ( properties != null && properties.containsKey( k ) ) )
// {
// expressions.put( entry.getKey(), matcher.group( 1 ) );
// }
// else
// {
// mappings.put( entry.getKey(), val );
// }
// }
// // Only add the mapping if a previous BOM has not already added it.
// else if ( !mappings.containsKey( entry.getKey() ))
// {
// mappings.put( entry.getKey(), val );
// }
// }
// }
// }
//
// public Set<String> getKeys()
// {
// return mappings.keySet();
// }
//
// /*
// * This method should take a properties from a BOM and look through that to update the mappings value with the real
// * value.
// */
// void updateProjectMap( final Properties properties )
// {
// final Set<Map.Entry<String, String>> contents = expressions.entrySet();
// for ( final Iterator<Map.Entry<String, String>> i = contents.iterator(); i.hasNext(); )
// {
// final Map.Entry<String, String> v = i.next();
// final String value = properties.getProperty( v.getValue() );
//
// if ( value == null )
// {
// continue;
// }
//
// mappings.put( v.getKey(), value );
//
// logger.info( "Replacing " + v.getKey() + " with value from " + v.getValue() + '('
// + mappings.get( v.getKey() ) + ')' );
//
// i.remove();
// }
// }
// }
| import java.util.Properties;
import java.util.Set;
import org.apache.maven.model.Model;
import org.codehaus.plexus.component.annotations.Component;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.redhat.rcm.version.mgr.session.PropertyMappings;
import com.redhat.rcm.version.mgr.session.VersionManagerSession;
import com.redhat.rcm.version.model.Project; | /*
* Copyright (c) 2012 Red Hat, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see
* <http://www.gnu.org/licenses>.
*/
package com.redhat.rcm.version.mgr.mod;
@Component( role = ProjectModder.class, hint = "property" )
public class PropertyModder
implements ProjectModder
{
private final Logger logger = LoggerFactory.getLogger( getClass() );
@Override
public String getDescription()
{
return "Change property mappings to use those declared in the supplied BOM file(s).";
}
@Override
public boolean inject( final Project project, final VersionManagerSession session )
{
final Model model = project.getModel();
boolean changed = false;
final Properties currentModel = model.getProperties();
final Set<String> commonKeys = currentModel.stringPropertyNames();
| // Path: src/main/java/com/redhat/rcm/version/mgr/session/PropertyMappings.java
// public class PropertyMappings
// {
// private final Logger logger = LoggerFactory.getLogger( getClass() );
//
// private static final String EXPRESSION_PATTERN = "@([^@]+)@";
//
// private final Map<String, String> mappings = new HashMap<String, String>();
//
// private final Map<String, String> expressions = new HashMap<String, String>();
//
// public PropertyMappings( final Map<String, String> newMappings )
// {
// addMappings( null, newMappings );
// }
//
// PropertyMappings addBomPropertyMappings( final File bom, final Properties properties )
// {
// return addBomPropertyMappings( bom, properties, mappings );
// }
//
// PropertyMappings addBomPropertyMappings( final File bom, final Properties properties,
// final Map<String, String> newMappings )
// {
// addMappings( properties, newMappings );
//
// final Map<String, String> fromProps = new HashMap<String, String>();
// for ( final String key : properties.stringPropertyNames() )
// {
// fromProps.put( key, properties.getProperty( key ) );
// }
//
// // Add the BOM's own properties into the mappings...
// addMappings( properties, fromProps );
//
// return this;
// }
//
// public String getMappedValue( final String key, final VersionManagerSession session )
// {
// final String raw = mappings.get( key );
//
// if ( raw == null )
// {
// return null;
// }
//
// final StringSearchInterpolator interpolator = new StringSearchInterpolator( "@", "@" );
// interpolator.addValueSource( new MapBasedValueSource( mappings ) );
// try
// {
// return interpolator.interpolate( raw );
// }
// catch ( final InterpolationException e )
// {
// logger.error( "Invalid expression: '%s'. Reason: %s", e, raw, e.getMessage() );
// session.addError( new VManException( "Invalid expression: '%s'. Reason: %s", e, raw, e.getMessage() ) );
// }
//
// return null;
// }
//
// private void addMappings( final Properties properties, final Map<String, String> newMappings )
// {
// final Pattern pattern = Pattern.compile( EXPRESSION_PATTERN );
//
// if ( newMappings != null )
// {
// for ( final Map.Entry<String, String> entry : newMappings.entrySet() )
// {
// final String val = entry.getValue();
// final Matcher matcher = pattern.matcher( val );
//
// if ( matcher.matches() )
// {
// final String k = matcher.group( 1 );
// if ( ( !mappings.containsKey( k ) && !newMappings.containsKey( k ) ) ||
// // Its also an expression if the property exists in the global properties map.
// ( properties != null && properties.containsKey( k ) ) )
// {
// expressions.put( entry.getKey(), matcher.group( 1 ) );
// }
// else
// {
// mappings.put( entry.getKey(), val );
// }
// }
// // Only add the mapping if a previous BOM has not already added it.
// else if ( !mappings.containsKey( entry.getKey() ))
// {
// mappings.put( entry.getKey(), val );
// }
// }
// }
// }
//
// public Set<String> getKeys()
// {
// return mappings.keySet();
// }
//
// /*
// * This method should take a properties from a BOM and look through that to update the mappings value with the real
// * value.
// */
// void updateProjectMap( final Properties properties )
// {
// final Set<Map.Entry<String, String>> contents = expressions.entrySet();
// for ( final Iterator<Map.Entry<String, String>> i = contents.iterator(); i.hasNext(); )
// {
// final Map.Entry<String, String> v = i.next();
// final String value = properties.getProperty( v.getValue() );
//
// if ( value == null )
// {
// continue;
// }
//
// mappings.put( v.getKey(), value );
//
// logger.info( "Replacing " + v.getKey() + " with value from " + v.getValue() + '('
// + mappings.get( v.getKey() ) + ')' );
//
// i.remove();
// }
// }
// }
// Path: src/main/java/com/redhat/rcm/version/mgr/mod/PropertyModder.java
import java.util.Properties;
import java.util.Set;
import org.apache.maven.model.Model;
import org.codehaus.plexus.component.annotations.Component;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.redhat.rcm.version.mgr.session.PropertyMappings;
import com.redhat.rcm.version.mgr.session.VersionManagerSession;
import com.redhat.rcm.version.model.Project;
/*
* Copyright (c) 2012 Red Hat, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see
* <http://www.gnu.org/licenses>.
*/
package com.redhat.rcm.version.mgr.mod;
@Component( role = ProjectModder.class, hint = "property" )
public class PropertyModder
implements ProjectModder
{
private final Logger logger = LoggerFactory.getLogger( getClass() );
@Override
public String getDescription()
{
return "Change property mappings to use those declared in the supplied BOM file(s).";
}
@Override
public boolean inject( final Project project, final VersionManagerSession session )
{
final Model model = project.getModel();
boolean changed = false;
final Properties currentModel = model.getProperties();
final Set<String> commonKeys = currentModel.stringPropertyNames();
| final PropertyMappings propertyMappings = session.getPropertyMappings(); |
release-engineering/pom-version-manipulator | src/main/java/com/redhat/rcm/version/mgr/verify/BomVerifier.java | // Path: src/main/java/com/redhat/rcm/version/util/CollectionToString.java
// public class CollectionToString<T>
// {
//
// private final Collection<T> coll;
//
// private final ToStringProcessor<T> itemProc;
//
// public CollectionToString( final Collection<T> coll )
// {
// this.coll = coll;
// this.itemProc = new ObjectToString<T>();
// }
//
// public CollectionToString( final Collection<T> coll, final ToStringProcessor<T> itemProc )
// {
// this.coll = coll;
// this.itemProc = itemProc;
// }
//
// @Override
// public String toString()
// {
// if ( coll == null || coll.isEmpty() )
// {
// return "-NONE-";
// }
// else
// {
// StringBuilder sb = new StringBuilder();
// for ( T item : coll )
// {
// if ( sb.length() > 0 )
// {
// sb.append( '\n' );
// }
//
// sb.append( itemProc.render( item ) );
// }
//
// return sb.toString();
// }
// }
//
// }
//
// Path: src/main/java/com/redhat/rcm/version/util/ObjectToString.java
// public class ObjectToString<T>
// implements ToStringProcessor<T>
// {
//
// @Override
// public String render( final T value )
// {
// return String.valueOf( value );
// }
//
// }
| import java.util.Set;
import org.apache.maven.mae.project.key.VersionlessProjectKey;
import org.codehaus.plexus.component.annotations.Component;
import com.redhat.rcm.version.VManException;
import com.redhat.rcm.version.mgr.session.VersionManagerSession;
import com.redhat.rcm.version.model.Project;
import com.redhat.rcm.version.util.CollectionToString;
import com.redhat.rcm.version.util.ObjectToString; | /*
* Copyright (c) 2010 Red Hat, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see
* <http://www.gnu.org/licenses>.
*/
package com.redhat.rcm.version.mgr.verify;
@Component( role = ProjectVerifier.class, hint = "bom-realignment" )
public class BomVerifier
implements ProjectVerifier
{
@Override
public void verify( final Project project, final VersionManagerSession session )
{
final Set<VersionlessProjectKey> missing = session.getMissingVersions( project.getKey() );
if ( missing != null && !missing.isEmpty() )
{
session.addError( new VManException( "The following dependencies were NOT found in a BOM.\nProject: %s\nFile: %s\nDependencies:\n\n%s\n",
project.getKey(), project.getPom(), | // Path: src/main/java/com/redhat/rcm/version/util/CollectionToString.java
// public class CollectionToString<T>
// {
//
// private final Collection<T> coll;
//
// private final ToStringProcessor<T> itemProc;
//
// public CollectionToString( final Collection<T> coll )
// {
// this.coll = coll;
// this.itemProc = new ObjectToString<T>();
// }
//
// public CollectionToString( final Collection<T> coll, final ToStringProcessor<T> itemProc )
// {
// this.coll = coll;
// this.itemProc = itemProc;
// }
//
// @Override
// public String toString()
// {
// if ( coll == null || coll.isEmpty() )
// {
// return "-NONE-";
// }
// else
// {
// StringBuilder sb = new StringBuilder();
// for ( T item : coll )
// {
// if ( sb.length() > 0 )
// {
// sb.append( '\n' );
// }
//
// sb.append( itemProc.render( item ) );
// }
//
// return sb.toString();
// }
// }
//
// }
//
// Path: src/main/java/com/redhat/rcm/version/util/ObjectToString.java
// public class ObjectToString<T>
// implements ToStringProcessor<T>
// {
//
// @Override
// public String render( final T value )
// {
// return String.valueOf( value );
// }
//
// }
// Path: src/main/java/com/redhat/rcm/version/mgr/verify/BomVerifier.java
import java.util.Set;
import org.apache.maven.mae.project.key.VersionlessProjectKey;
import org.codehaus.plexus.component.annotations.Component;
import com.redhat.rcm.version.VManException;
import com.redhat.rcm.version.mgr.session.VersionManagerSession;
import com.redhat.rcm.version.model.Project;
import com.redhat.rcm.version.util.CollectionToString;
import com.redhat.rcm.version.util.ObjectToString;
/*
* Copyright (c) 2010 Red Hat, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see
* <http://www.gnu.org/licenses>.
*/
package com.redhat.rcm.version.mgr.verify;
@Component( role = ProjectVerifier.class, hint = "bom-realignment" )
public class BomVerifier
implements ProjectVerifier
{
@Override
public void verify( final Project project, final VersionManagerSession session )
{
final Set<VersionlessProjectKey> missing = session.getMissingVersions( project.getKey() );
if ( missing != null && !missing.isEmpty() )
{
session.addError( new VManException( "The following dependencies were NOT found in a BOM.\nProject: %s\nFile: %s\nDependencies:\n\n%s\n",
project.getKey(), project.getPom(), | new CollectionToString<VersionlessProjectKey>( missing, new ObjectToString<VersionlessProjectKey>() ) ) ); |
release-engineering/pom-version-manipulator | src/main/java/com/redhat/rcm/version/mgr/verify/BomVerifier.java | // Path: src/main/java/com/redhat/rcm/version/util/CollectionToString.java
// public class CollectionToString<T>
// {
//
// private final Collection<T> coll;
//
// private final ToStringProcessor<T> itemProc;
//
// public CollectionToString( final Collection<T> coll )
// {
// this.coll = coll;
// this.itemProc = new ObjectToString<T>();
// }
//
// public CollectionToString( final Collection<T> coll, final ToStringProcessor<T> itemProc )
// {
// this.coll = coll;
// this.itemProc = itemProc;
// }
//
// @Override
// public String toString()
// {
// if ( coll == null || coll.isEmpty() )
// {
// return "-NONE-";
// }
// else
// {
// StringBuilder sb = new StringBuilder();
// for ( T item : coll )
// {
// if ( sb.length() > 0 )
// {
// sb.append( '\n' );
// }
//
// sb.append( itemProc.render( item ) );
// }
//
// return sb.toString();
// }
// }
//
// }
//
// Path: src/main/java/com/redhat/rcm/version/util/ObjectToString.java
// public class ObjectToString<T>
// implements ToStringProcessor<T>
// {
//
// @Override
// public String render( final T value )
// {
// return String.valueOf( value );
// }
//
// }
| import java.util.Set;
import org.apache.maven.mae.project.key.VersionlessProjectKey;
import org.codehaus.plexus.component.annotations.Component;
import com.redhat.rcm.version.VManException;
import com.redhat.rcm.version.mgr.session.VersionManagerSession;
import com.redhat.rcm.version.model.Project;
import com.redhat.rcm.version.util.CollectionToString;
import com.redhat.rcm.version.util.ObjectToString; | /*
* Copyright (c) 2010 Red Hat, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see
* <http://www.gnu.org/licenses>.
*/
package com.redhat.rcm.version.mgr.verify;
@Component( role = ProjectVerifier.class, hint = "bom-realignment" )
public class BomVerifier
implements ProjectVerifier
{
@Override
public void verify( final Project project, final VersionManagerSession session )
{
final Set<VersionlessProjectKey> missing = session.getMissingVersions( project.getKey() );
if ( missing != null && !missing.isEmpty() )
{
session.addError( new VManException( "The following dependencies were NOT found in a BOM.\nProject: %s\nFile: %s\nDependencies:\n\n%s\n",
project.getKey(), project.getPom(), | // Path: src/main/java/com/redhat/rcm/version/util/CollectionToString.java
// public class CollectionToString<T>
// {
//
// private final Collection<T> coll;
//
// private final ToStringProcessor<T> itemProc;
//
// public CollectionToString( final Collection<T> coll )
// {
// this.coll = coll;
// this.itemProc = new ObjectToString<T>();
// }
//
// public CollectionToString( final Collection<T> coll, final ToStringProcessor<T> itemProc )
// {
// this.coll = coll;
// this.itemProc = itemProc;
// }
//
// @Override
// public String toString()
// {
// if ( coll == null || coll.isEmpty() )
// {
// return "-NONE-";
// }
// else
// {
// StringBuilder sb = new StringBuilder();
// for ( T item : coll )
// {
// if ( sb.length() > 0 )
// {
// sb.append( '\n' );
// }
//
// sb.append( itemProc.render( item ) );
// }
//
// return sb.toString();
// }
// }
//
// }
//
// Path: src/main/java/com/redhat/rcm/version/util/ObjectToString.java
// public class ObjectToString<T>
// implements ToStringProcessor<T>
// {
//
// @Override
// public String render( final T value )
// {
// return String.valueOf( value );
// }
//
// }
// Path: src/main/java/com/redhat/rcm/version/mgr/verify/BomVerifier.java
import java.util.Set;
import org.apache.maven.mae.project.key.VersionlessProjectKey;
import org.codehaus.plexus.component.annotations.Component;
import com.redhat.rcm.version.VManException;
import com.redhat.rcm.version.mgr.session.VersionManagerSession;
import com.redhat.rcm.version.model.Project;
import com.redhat.rcm.version.util.CollectionToString;
import com.redhat.rcm.version.util.ObjectToString;
/*
* Copyright (c) 2010 Red Hat, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see
* <http://www.gnu.org/licenses>.
*/
package com.redhat.rcm.version.mgr.verify;
@Component( role = ProjectVerifier.class, hint = "bom-realignment" )
public class BomVerifier
implements ProjectVerifier
{
@Override
public void verify( final Project project, final VersionManagerSession session )
{
final Set<VersionlessProjectKey> missing = session.getMissingVersions( project.getKey() );
if ( missing != null && !missing.isEmpty() )
{
session.addError( new VManException( "The following dependencies were NOT found in a BOM.\nProject: %s\nFile: %s\nDependencies:\n\n%s\n",
project.getKey(), project.getPom(), | new CollectionToString<VersionlessProjectKey>( missing, new ObjectToString<VersionlessProjectKey>() ) ) ); |
release-engineering/pom-version-manipulator | src/test/java/com/redhat/rcm/version/mgr/VersionSuffixManagementTest.java | // Path: src/test/java/com/redhat/rcm/version/testutil/TestProjectFixture.java
// public static void dumpModel( final Model model )
// throws IOException
// {
// final StringWriter writer = new StringWriter();
// new MavenXpp3Writer().write( writer, model );
//
// System.out.println( "\n\n" + writer.toString() + "\n\n" );
// }
//
// Path: src/test/java/com/redhat/rcm/version/testutil/TestProjectFixture.java
// public static File getResourceFile( final String path )
// {
// final URL resource = Thread.currentThread()
// .getContextClassLoader()
// .getResource( path );
// if ( resource == null )
// {
// fail( "Resource not found: " + path );
// }
//
// return new File( resource.getPath() );
// }
//
// Path: src/test/java/com/redhat/rcm/version/testutil/TestProjectFixture.java
// public static Model loadModel( final String path )
// throws IOException
// {
// final File pom = getResourceFile( path );
// return loadModel( pom );
// }
//
// Path: src/test/java/com/redhat/rcm/version/testutil/TestProjectFixture.java
// public static Set<Model> loadModels( final Set<File> poms )
// throws VManException, IOException
// {
// final Set<Model> models = new LinkedHashSet<Model>( poms.size() );
// for ( final File pom : poms )
// {
// models.add( loadModel( pom ) );
// }
//
// return models;
// }
//
// Path: src/test/java/com/redhat/rcm/version/testutil/TestProjectFixture.java
// public static VersionManagerSession newVersionManagerSession( final File workspace, final File reports, final String suffix, final String modifier )
// {
// return new SessionBuilder( workspace, reports ).withVersionSuffix( suffix )
// .withVersionModifier( modifier )
// .build();
// }
| import static com.redhat.rcm.version.testutil.TestProjectFixture.dumpModel;
import static com.redhat.rcm.version.testutil.TestProjectFixture.getResourceFile;
import static com.redhat.rcm.version.testutil.TestProjectFixture.loadModel;
import static com.redhat.rcm.version.testutil.TestProjectFixture.loadModels;
import static com.redhat.rcm.version.testutil.TestProjectFixture.newVersionManagerSession;
import static org.apache.commons.io.FileUtils.copyDirectory;
import static org.apache.commons.io.FileUtils.copyFile;
import static org.apache.commons.io.FileUtils.readFileToString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.Assert.assertThat;
import java.io.File;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.apache.maven.mae.project.key.FullProjectKey;
import org.apache.maven.model.Model;
import org.apache.maven.model.Parent;
import org.apache.maven.project.MavenProject;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import com.redhat.rcm.version.fixture.LoggingFixture;
import com.redhat.rcm.version.mgr.mod.VersionSuffixModder;
import com.redhat.rcm.version.mgr.session.VersionManagerSession;
import com.redhat.rcm.version.model.Project; | @Test
public void adjustMultiple_BothVersions_ChildHasSeparateVersion()
throws Throwable
{
final String path = "modules-separateVersions/pom.xml";
final Map<FullProjectKey, Project> result =
adjustMultiple( "Adjust both POMs when parent and child have separate versions", path );
FullProjectKey key = new FullProjectKey( "test", "parent", "1" + SUFFIX );
Project project = result.get( key );
assertThat( "Parent POM cannot be found in result map: " + key, project, notNullValue() );
assertThat( "Parent has wrong version!", project.getModel()
.getVersion(), equalTo( key.getVersion() ) );
key = new FullProjectKey( "test", "child", "2" + SUFFIX );
project = result.get( key );
assertThat( "Child POM cannot be found in result map: " + key, project, notNullValue() );
assertParent( project.getModel(), null, null, "1" + SUFFIX, true );
assertThat( "Child has wrong version!", project.getModel()
.getVersion(), equalTo( key.getVersion() ) );
}
@Test
public void dontAdjustVersion_InheritedVersion_ToolchainParent()
throws Throwable
{
final String path = "child-inheritedVersion-1.0.pom"; | // Path: src/test/java/com/redhat/rcm/version/testutil/TestProjectFixture.java
// public static void dumpModel( final Model model )
// throws IOException
// {
// final StringWriter writer = new StringWriter();
// new MavenXpp3Writer().write( writer, model );
//
// System.out.println( "\n\n" + writer.toString() + "\n\n" );
// }
//
// Path: src/test/java/com/redhat/rcm/version/testutil/TestProjectFixture.java
// public static File getResourceFile( final String path )
// {
// final URL resource = Thread.currentThread()
// .getContextClassLoader()
// .getResource( path );
// if ( resource == null )
// {
// fail( "Resource not found: " + path );
// }
//
// return new File( resource.getPath() );
// }
//
// Path: src/test/java/com/redhat/rcm/version/testutil/TestProjectFixture.java
// public static Model loadModel( final String path )
// throws IOException
// {
// final File pom = getResourceFile( path );
// return loadModel( pom );
// }
//
// Path: src/test/java/com/redhat/rcm/version/testutil/TestProjectFixture.java
// public static Set<Model> loadModels( final Set<File> poms )
// throws VManException, IOException
// {
// final Set<Model> models = new LinkedHashSet<Model>( poms.size() );
// for ( final File pom : poms )
// {
// models.add( loadModel( pom ) );
// }
//
// return models;
// }
//
// Path: src/test/java/com/redhat/rcm/version/testutil/TestProjectFixture.java
// public static VersionManagerSession newVersionManagerSession( final File workspace, final File reports, final String suffix, final String modifier )
// {
// return new SessionBuilder( workspace, reports ).withVersionSuffix( suffix )
// .withVersionModifier( modifier )
// .build();
// }
// Path: src/test/java/com/redhat/rcm/version/mgr/VersionSuffixManagementTest.java
import static com.redhat.rcm.version.testutil.TestProjectFixture.dumpModel;
import static com.redhat.rcm.version.testutil.TestProjectFixture.getResourceFile;
import static com.redhat.rcm.version.testutil.TestProjectFixture.loadModel;
import static com.redhat.rcm.version.testutil.TestProjectFixture.loadModels;
import static com.redhat.rcm.version.testutil.TestProjectFixture.newVersionManagerSession;
import static org.apache.commons.io.FileUtils.copyDirectory;
import static org.apache.commons.io.FileUtils.copyFile;
import static org.apache.commons.io.FileUtils.readFileToString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.Assert.assertThat;
import java.io.File;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.apache.maven.mae.project.key.FullProjectKey;
import org.apache.maven.model.Model;
import org.apache.maven.model.Parent;
import org.apache.maven.project.MavenProject;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import com.redhat.rcm.version.fixture.LoggingFixture;
import com.redhat.rcm.version.mgr.mod.VersionSuffixModder;
import com.redhat.rcm.version.mgr.session.VersionManagerSession;
import com.redhat.rcm.version.model.Project;
@Test
public void adjustMultiple_BothVersions_ChildHasSeparateVersion()
throws Throwable
{
final String path = "modules-separateVersions/pom.xml";
final Map<FullProjectKey, Project> result =
adjustMultiple( "Adjust both POMs when parent and child have separate versions", path );
FullProjectKey key = new FullProjectKey( "test", "parent", "1" + SUFFIX );
Project project = result.get( key );
assertThat( "Parent POM cannot be found in result map: " + key, project, notNullValue() );
assertThat( "Parent has wrong version!", project.getModel()
.getVersion(), equalTo( key.getVersion() ) );
key = new FullProjectKey( "test", "child", "2" + SUFFIX );
project = result.get( key );
assertThat( "Child POM cannot be found in result map: " + key, project, notNullValue() );
assertParent( project.getModel(), null, null, "1" + SUFFIX, true );
assertThat( "Child has wrong version!", project.getModel()
.getVersion(), equalTo( key.getVersion() ) );
}
@Test
public void dontAdjustVersion_InheritedVersion_ToolchainParent()
throws Throwable
{
final String path = "child-inheritedVersion-1.0.pom"; | final Model original = loadModel( TEST_POMS + path ); |
release-engineering/pom-version-manipulator | src/test/java/com/redhat/rcm/version/mgr/VersionSuffixManagementTest.java | // Path: src/test/java/com/redhat/rcm/version/testutil/TestProjectFixture.java
// public static void dumpModel( final Model model )
// throws IOException
// {
// final StringWriter writer = new StringWriter();
// new MavenXpp3Writer().write( writer, model );
//
// System.out.println( "\n\n" + writer.toString() + "\n\n" );
// }
//
// Path: src/test/java/com/redhat/rcm/version/testutil/TestProjectFixture.java
// public static File getResourceFile( final String path )
// {
// final URL resource = Thread.currentThread()
// .getContextClassLoader()
// .getResource( path );
// if ( resource == null )
// {
// fail( "Resource not found: " + path );
// }
//
// return new File( resource.getPath() );
// }
//
// Path: src/test/java/com/redhat/rcm/version/testutil/TestProjectFixture.java
// public static Model loadModel( final String path )
// throws IOException
// {
// final File pom = getResourceFile( path );
// return loadModel( pom );
// }
//
// Path: src/test/java/com/redhat/rcm/version/testutil/TestProjectFixture.java
// public static Set<Model> loadModels( final Set<File> poms )
// throws VManException, IOException
// {
// final Set<Model> models = new LinkedHashSet<Model>( poms.size() );
// for ( final File pom : poms )
// {
// models.add( loadModel( pom ) );
// }
//
// return models;
// }
//
// Path: src/test/java/com/redhat/rcm/version/testutil/TestProjectFixture.java
// public static VersionManagerSession newVersionManagerSession( final File workspace, final File reports, final String suffix, final String modifier )
// {
// return new SessionBuilder( workspace, reports ).withVersionSuffix( suffix )
// .withVersionModifier( modifier )
// .build();
// }
| import static com.redhat.rcm.version.testutil.TestProjectFixture.dumpModel;
import static com.redhat.rcm.version.testutil.TestProjectFixture.getResourceFile;
import static com.redhat.rcm.version.testutil.TestProjectFixture.loadModel;
import static com.redhat.rcm.version.testutil.TestProjectFixture.loadModels;
import static com.redhat.rcm.version.testutil.TestProjectFixture.newVersionManagerSession;
import static org.apache.commons.io.FileUtils.copyDirectory;
import static org.apache.commons.io.FileUtils.copyFile;
import static org.apache.commons.io.FileUtils.readFileToString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.Assert.assertThat;
import java.io.File;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.apache.maven.mae.project.key.FullProjectKey;
import org.apache.maven.model.Model;
import org.apache.maven.model.Parent;
import org.apache.maven.project.MavenProject;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import com.redhat.rcm.version.fixture.LoggingFixture;
import com.redhat.rcm.version.mgr.mod.VersionSuffixModder;
import com.redhat.rcm.version.mgr.session.VersionManagerSession;
import com.redhat.rcm.version.model.Project; | final String path = "modules-separateVersions/pom.xml";
final Map<FullProjectKey, Project> result =
adjustMultiple( "Adjust both POMs when parent and child have separate versions", path );
FullProjectKey key = new FullProjectKey( "test", "parent", "1" + SUFFIX );
Project project = result.get( key );
assertThat( "Parent POM cannot be found in result map: " + key, project, notNullValue() );
assertThat( "Parent has wrong version!", project.getModel()
.getVersion(), equalTo( key.getVersion() ) );
key = new FullProjectKey( "test", "child", "2" + SUFFIX );
project = result.get( key );
assertThat( "Child POM cannot be found in result map: " + key, project, notNullValue() );
assertParent( project.getModel(), null, null, "1" + SUFFIX, true );
assertThat( "Child has wrong version!", project.getModel()
.getVersion(), equalTo( key.getVersion() ) );
}
@Test
public void dontAdjustVersion_InheritedVersion_ToolchainParent()
throws Throwable
{
final String path = "child-inheritedVersion-1.0.pom";
final Model original = loadModel( TEST_POMS + path );
assertParent( original, null, null, "1.0", true );
| // Path: src/test/java/com/redhat/rcm/version/testutil/TestProjectFixture.java
// public static void dumpModel( final Model model )
// throws IOException
// {
// final StringWriter writer = new StringWriter();
// new MavenXpp3Writer().write( writer, model );
//
// System.out.println( "\n\n" + writer.toString() + "\n\n" );
// }
//
// Path: src/test/java/com/redhat/rcm/version/testutil/TestProjectFixture.java
// public static File getResourceFile( final String path )
// {
// final URL resource = Thread.currentThread()
// .getContextClassLoader()
// .getResource( path );
// if ( resource == null )
// {
// fail( "Resource not found: " + path );
// }
//
// return new File( resource.getPath() );
// }
//
// Path: src/test/java/com/redhat/rcm/version/testutil/TestProjectFixture.java
// public static Model loadModel( final String path )
// throws IOException
// {
// final File pom = getResourceFile( path );
// return loadModel( pom );
// }
//
// Path: src/test/java/com/redhat/rcm/version/testutil/TestProjectFixture.java
// public static Set<Model> loadModels( final Set<File> poms )
// throws VManException, IOException
// {
// final Set<Model> models = new LinkedHashSet<Model>( poms.size() );
// for ( final File pom : poms )
// {
// models.add( loadModel( pom ) );
// }
//
// return models;
// }
//
// Path: src/test/java/com/redhat/rcm/version/testutil/TestProjectFixture.java
// public static VersionManagerSession newVersionManagerSession( final File workspace, final File reports, final String suffix, final String modifier )
// {
// return new SessionBuilder( workspace, reports ).withVersionSuffix( suffix )
// .withVersionModifier( modifier )
// .build();
// }
// Path: src/test/java/com/redhat/rcm/version/mgr/VersionSuffixManagementTest.java
import static com.redhat.rcm.version.testutil.TestProjectFixture.dumpModel;
import static com.redhat.rcm.version.testutil.TestProjectFixture.getResourceFile;
import static com.redhat.rcm.version.testutil.TestProjectFixture.loadModel;
import static com.redhat.rcm.version.testutil.TestProjectFixture.loadModels;
import static com.redhat.rcm.version.testutil.TestProjectFixture.newVersionManagerSession;
import static org.apache.commons.io.FileUtils.copyDirectory;
import static org.apache.commons.io.FileUtils.copyFile;
import static org.apache.commons.io.FileUtils.readFileToString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.Assert.assertThat;
import java.io.File;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.apache.maven.mae.project.key.FullProjectKey;
import org.apache.maven.model.Model;
import org.apache.maven.model.Parent;
import org.apache.maven.project.MavenProject;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import com.redhat.rcm.version.fixture.LoggingFixture;
import com.redhat.rcm.version.mgr.mod.VersionSuffixModder;
import com.redhat.rcm.version.mgr.session.VersionManagerSession;
import com.redhat.rcm.version.model.Project;
final String path = "modules-separateVersions/pom.xml";
final Map<FullProjectKey, Project> result =
adjustMultiple( "Adjust both POMs when parent and child have separate versions", path );
FullProjectKey key = new FullProjectKey( "test", "parent", "1" + SUFFIX );
Project project = result.get( key );
assertThat( "Parent POM cannot be found in result map: " + key, project, notNullValue() );
assertThat( "Parent has wrong version!", project.getModel()
.getVersion(), equalTo( key.getVersion() ) );
key = new FullProjectKey( "test", "child", "2" + SUFFIX );
project = result.get( key );
assertThat( "Child POM cannot be found in result map: " + key, project, notNullValue() );
assertParent( project.getModel(), null, null, "1" + SUFFIX, true );
assertThat( "Child has wrong version!", project.getModel()
.getVersion(), equalTo( key.getVersion() ) );
}
@Test
public void dontAdjustVersion_InheritedVersion_ToolchainParent()
throws Throwable
{
final String path = "child-inheritedVersion-1.0.pom";
final Model original = loadModel( TEST_POMS + path );
assertParent( original, null, null, "1.0", true );
| final File toolchain = getResourceFile( TOOLCHAIN_PATH ); |
release-engineering/pom-version-manipulator | src/test/java/com/redhat/rcm/version/mgr/VersionSuffixManagementTest.java | // Path: src/test/java/com/redhat/rcm/version/testutil/TestProjectFixture.java
// public static void dumpModel( final Model model )
// throws IOException
// {
// final StringWriter writer = new StringWriter();
// new MavenXpp3Writer().write( writer, model );
//
// System.out.println( "\n\n" + writer.toString() + "\n\n" );
// }
//
// Path: src/test/java/com/redhat/rcm/version/testutil/TestProjectFixture.java
// public static File getResourceFile( final String path )
// {
// final URL resource = Thread.currentThread()
// .getContextClassLoader()
// .getResource( path );
// if ( resource == null )
// {
// fail( "Resource not found: " + path );
// }
//
// return new File( resource.getPath() );
// }
//
// Path: src/test/java/com/redhat/rcm/version/testutil/TestProjectFixture.java
// public static Model loadModel( final String path )
// throws IOException
// {
// final File pom = getResourceFile( path );
// return loadModel( pom );
// }
//
// Path: src/test/java/com/redhat/rcm/version/testutil/TestProjectFixture.java
// public static Set<Model> loadModels( final Set<File> poms )
// throws VManException, IOException
// {
// final Set<Model> models = new LinkedHashSet<Model>( poms.size() );
// for ( final File pom : poms )
// {
// models.add( loadModel( pom ) );
// }
//
// return models;
// }
//
// Path: src/test/java/com/redhat/rcm/version/testutil/TestProjectFixture.java
// public static VersionManagerSession newVersionManagerSession( final File workspace, final File reports, final String suffix, final String modifier )
// {
// return new SessionBuilder( workspace, reports ).withVersionSuffix( suffix )
// .withVersionModifier( modifier )
// .build();
// }
| import static com.redhat.rcm.version.testutil.TestProjectFixture.dumpModel;
import static com.redhat.rcm.version.testutil.TestProjectFixture.getResourceFile;
import static com.redhat.rcm.version.testutil.TestProjectFixture.loadModel;
import static com.redhat.rcm.version.testutil.TestProjectFixture.loadModels;
import static com.redhat.rcm.version.testutil.TestProjectFixture.newVersionManagerSession;
import static org.apache.commons.io.FileUtils.copyDirectory;
import static org.apache.commons.io.FileUtils.copyFile;
import static org.apache.commons.io.FileUtils.readFileToString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.Assert.assertThat;
import java.io.File;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.apache.maven.mae.project.key.FullProjectKey;
import org.apache.maven.model.Model;
import org.apache.maven.model.Parent;
import org.apache.maven.project.MavenProject;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import com.redhat.rcm.version.fixture.LoggingFixture;
import com.redhat.rcm.version.mgr.mod.VersionSuffixModder;
import com.redhat.rcm.version.mgr.session.VersionManagerSession;
import com.redhat.rcm.version.model.Project; |
assertThat( "Parent POM cannot be found in result map: " + key, project, notNullValue() );
assertThat( "Parent has wrong version!", project.getModel()
.getVersion(), equalTo( key.getVersion() ) );
key = new FullProjectKey( "test", "child", "2" + SUFFIX );
project = result.get( key );
assertThat( "Child POM cannot be found in result map: " + key, project, notNullValue() );
assertParent( project.getModel(), null, null, "1" + SUFFIX, true );
assertThat( "Child has wrong version!", project.getModel()
.getVersion(), equalTo( key.getVersion() ) );
}
@Test
public void dontAdjustVersion_InheritedVersion_ToolchainParent()
throws Throwable
{
final String path = "child-inheritedVersion-1.0.pom";
final Model original = loadModel( TEST_POMS + path );
assertParent( original, null, null, "1.0", true );
final File toolchain = getResourceFile( TOOLCHAIN_PATH );
final Model toolchainModel = loadModel( toolchain );
final MavenProject toolchainProject = new MavenProject( toolchainModel );
toolchainProject.setOriginalModel( toolchainModel );
| // Path: src/test/java/com/redhat/rcm/version/testutil/TestProjectFixture.java
// public static void dumpModel( final Model model )
// throws IOException
// {
// final StringWriter writer = new StringWriter();
// new MavenXpp3Writer().write( writer, model );
//
// System.out.println( "\n\n" + writer.toString() + "\n\n" );
// }
//
// Path: src/test/java/com/redhat/rcm/version/testutil/TestProjectFixture.java
// public static File getResourceFile( final String path )
// {
// final URL resource = Thread.currentThread()
// .getContextClassLoader()
// .getResource( path );
// if ( resource == null )
// {
// fail( "Resource not found: " + path );
// }
//
// return new File( resource.getPath() );
// }
//
// Path: src/test/java/com/redhat/rcm/version/testutil/TestProjectFixture.java
// public static Model loadModel( final String path )
// throws IOException
// {
// final File pom = getResourceFile( path );
// return loadModel( pom );
// }
//
// Path: src/test/java/com/redhat/rcm/version/testutil/TestProjectFixture.java
// public static Set<Model> loadModels( final Set<File> poms )
// throws VManException, IOException
// {
// final Set<Model> models = new LinkedHashSet<Model>( poms.size() );
// for ( final File pom : poms )
// {
// models.add( loadModel( pom ) );
// }
//
// return models;
// }
//
// Path: src/test/java/com/redhat/rcm/version/testutil/TestProjectFixture.java
// public static VersionManagerSession newVersionManagerSession( final File workspace, final File reports, final String suffix, final String modifier )
// {
// return new SessionBuilder( workspace, reports ).withVersionSuffix( suffix )
// .withVersionModifier( modifier )
// .build();
// }
// Path: src/test/java/com/redhat/rcm/version/mgr/VersionSuffixManagementTest.java
import static com.redhat.rcm.version.testutil.TestProjectFixture.dumpModel;
import static com.redhat.rcm.version.testutil.TestProjectFixture.getResourceFile;
import static com.redhat.rcm.version.testutil.TestProjectFixture.loadModel;
import static com.redhat.rcm.version.testutil.TestProjectFixture.loadModels;
import static com.redhat.rcm.version.testutil.TestProjectFixture.newVersionManagerSession;
import static org.apache.commons.io.FileUtils.copyDirectory;
import static org.apache.commons.io.FileUtils.copyFile;
import static org.apache.commons.io.FileUtils.readFileToString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.Assert.assertThat;
import java.io.File;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.apache.maven.mae.project.key.FullProjectKey;
import org.apache.maven.model.Model;
import org.apache.maven.model.Parent;
import org.apache.maven.project.MavenProject;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import com.redhat.rcm.version.fixture.LoggingFixture;
import com.redhat.rcm.version.mgr.mod.VersionSuffixModder;
import com.redhat.rcm.version.mgr.session.VersionManagerSession;
import com.redhat.rcm.version.model.Project;
assertThat( "Parent POM cannot be found in result map: " + key, project, notNullValue() );
assertThat( "Parent has wrong version!", project.getModel()
.getVersion(), equalTo( key.getVersion() ) );
key = new FullProjectKey( "test", "child", "2" + SUFFIX );
project = result.get( key );
assertThat( "Child POM cannot be found in result map: " + key, project, notNullValue() );
assertParent( project.getModel(), null, null, "1" + SUFFIX, true );
assertThat( "Child has wrong version!", project.getModel()
.getVersion(), equalTo( key.getVersion() ) );
}
@Test
public void dontAdjustVersion_InheritedVersion_ToolchainParent()
throws Throwable
{
final String path = "child-inheritedVersion-1.0.pom";
final Model original = loadModel( TEST_POMS + path );
assertParent( original, null, null, "1.0", true );
final File toolchain = getResourceFile( TOOLCHAIN_PATH );
final Model toolchainModel = loadModel( toolchain );
final MavenProject toolchainProject = new MavenProject( toolchainModel );
toolchainProject.setOriginalModel( toolchainModel );
| final VersionManagerSession session = newVersionManagerSession( workspace, reports, SUFFIX ); |
release-engineering/pom-version-manipulator | src/test/java/com/redhat/rcm/version/mgr/VersionSuffixManagementTest.java | // Path: src/test/java/com/redhat/rcm/version/testutil/TestProjectFixture.java
// public static void dumpModel( final Model model )
// throws IOException
// {
// final StringWriter writer = new StringWriter();
// new MavenXpp3Writer().write( writer, model );
//
// System.out.println( "\n\n" + writer.toString() + "\n\n" );
// }
//
// Path: src/test/java/com/redhat/rcm/version/testutil/TestProjectFixture.java
// public static File getResourceFile( final String path )
// {
// final URL resource = Thread.currentThread()
// .getContextClassLoader()
// .getResource( path );
// if ( resource == null )
// {
// fail( "Resource not found: " + path );
// }
//
// return new File( resource.getPath() );
// }
//
// Path: src/test/java/com/redhat/rcm/version/testutil/TestProjectFixture.java
// public static Model loadModel( final String path )
// throws IOException
// {
// final File pom = getResourceFile( path );
// return loadModel( pom );
// }
//
// Path: src/test/java/com/redhat/rcm/version/testutil/TestProjectFixture.java
// public static Set<Model> loadModels( final Set<File> poms )
// throws VManException, IOException
// {
// final Set<Model> models = new LinkedHashSet<Model>( poms.size() );
// for ( final File pom : poms )
// {
// models.add( loadModel( pom ) );
// }
//
// return models;
// }
//
// Path: src/test/java/com/redhat/rcm/version/testutil/TestProjectFixture.java
// public static VersionManagerSession newVersionManagerSession( final File workspace, final File reports, final String suffix, final String modifier )
// {
// return new SessionBuilder( workspace, reports ).withVersionSuffix( suffix )
// .withVersionModifier( modifier )
// .build();
// }
| import static com.redhat.rcm.version.testutil.TestProjectFixture.dumpModel;
import static com.redhat.rcm.version.testutil.TestProjectFixture.getResourceFile;
import static com.redhat.rcm.version.testutil.TestProjectFixture.loadModel;
import static com.redhat.rcm.version.testutil.TestProjectFixture.loadModels;
import static com.redhat.rcm.version.testutil.TestProjectFixture.newVersionManagerSession;
import static org.apache.commons.io.FileUtils.copyDirectory;
import static org.apache.commons.io.FileUtils.copyFile;
import static org.apache.commons.io.FileUtils.readFileToString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.Assert.assertThat;
import java.io.File;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.apache.maven.mae.project.key.FullProjectKey;
import org.apache.maven.model.Model;
import org.apache.maven.model.Parent;
import org.apache.maven.project.MavenProject;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import com.redhat.rcm.version.fixture.LoggingFixture;
import com.redhat.rcm.version.mgr.mod.VersionSuffixModder;
import com.redhat.rcm.version.mgr.session.VersionManagerSession;
import com.redhat.rcm.version.model.Project; | .getVersion(), equalTo( "1.0" + SUFFIX ) );
}
private Project adjustSingle( final String description, final String pomPath )
throws Throwable
{
try
{
System.out.println( "ADJUSTING: " + description + "\nPOM: " + pomPath + "\nToolchain: " + TOOLCHAIN_PATH );
final File srcPom = getResourceFile( TEST_POMS + pomPath );
final String toolchain = getResourceFile( TOOLCHAIN_PATH ).getAbsolutePath();
final File pom = new File( repo, srcPom.getName() );
copyFile( srcPom, pom );
final VersionManagerSession session = newVersionManagerSession( workspace, reports, SUFFIX );
final File remoteRepo = getResourceFile( TEST_POMS + "repo" );
session.setRemoteRepositories( remoteRepo.toURI()
.normalize()
.toURL()
.toExternalForm() );
final Set<File> modified =
vman.modifyVersions( pom,
Collections.singletonList( getResourceFile( PARENT_VERSION_BOM ).getAbsolutePath() ),
toolchain, session );
assertNoErrors( session );
| // Path: src/test/java/com/redhat/rcm/version/testutil/TestProjectFixture.java
// public static void dumpModel( final Model model )
// throws IOException
// {
// final StringWriter writer = new StringWriter();
// new MavenXpp3Writer().write( writer, model );
//
// System.out.println( "\n\n" + writer.toString() + "\n\n" );
// }
//
// Path: src/test/java/com/redhat/rcm/version/testutil/TestProjectFixture.java
// public static File getResourceFile( final String path )
// {
// final URL resource = Thread.currentThread()
// .getContextClassLoader()
// .getResource( path );
// if ( resource == null )
// {
// fail( "Resource not found: " + path );
// }
//
// return new File( resource.getPath() );
// }
//
// Path: src/test/java/com/redhat/rcm/version/testutil/TestProjectFixture.java
// public static Model loadModel( final String path )
// throws IOException
// {
// final File pom = getResourceFile( path );
// return loadModel( pom );
// }
//
// Path: src/test/java/com/redhat/rcm/version/testutil/TestProjectFixture.java
// public static Set<Model> loadModels( final Set<File> poms )
// throws VManException, IOException
// {
// final Set<Model> models = new LinkedHashSet<Model>( poms.size() );
// for ( final File pom : poms )
// {
// models.add( loadModel( pom ) );
// }
//
// return models;
// }
//
// Path: src/test/java/com/redhat/rcm/version/testutil/TestProjectFixture.java
// public static VersionManagerSession newVersionManagerSession( final File workspace, final File reports, final String suffix, final String modifier )
// {
// return new SessionBuilder( workspace, reports ).withVersionSuffix( suffix )
// .withVersionModifier( modifier )
// .build();
// }
// Path: src/test/java/com/redhat/rcm/version/mgr/VersionSuffixManagementTest.java
import static com.redhat.rcm.version.testutil.TestProjectFixture.dumpModel;
import static com.redhat.rcm.version.testutil.TestProjectFixture.getResourceFile;
import static com.redhat.rcm.version.testutil.TestProjectFixture.loadModel;
import static com.redhat.rcm.version.testutil.TestProjectFixture.loadModels;
import static com.redhat.rcm.version.testutil.TestProjectFixture.newVersionManagerSession;
import static org.apache.commons.io.FileUtils.copyDirectory;
import static org.apache.commons.io.FileUtils.copyFile;
import static org.apache.commons.io.FileUtils.readFileToString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.Assert.assertThat;
import java.io.File;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.apache.maven.mae.project.key.FullProjectKey;
import org.apache.maven.model.Model;
import org.apache.maven.model.Parent;
import org.apache.maven.project.MavenProject;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import com.redhat.rcm.version.fixture.LoggingFixture;
import com.redhat.rcm.version.mgr.mod.VersionSuffixModder;
import com.redhat.rcm.version.mgr.session.VersionManagerSession;
import com.redhat.rcm.version.model.Project;
.getVersion(), equalTo( "1.0" + SUFFIX ) );
}
private Project adjustSingle( final String description, final String pomPath )
throws Throwable
{
try
{
System.out.println( "ADJUSTING: " + description + "\nPOM: " + pomPath + "\nToolchain: " + TOOLCHAIN_PATH );
final File srcPom = getResourceFile( TEST_POMS + pomPath );
final String toolchain = getResourceFile( TOOLCHAIN_PATH ).getAbsolutePath();
final File pom = new File( repo, srcPom.getName() );
copyFile( srcPom, pom );
final VersionManagerSession session = newVersionManagerSession( workspace, reports, SUFFIX );
final File remoteRepo = getResourceFile( TEST_POMS + "repo" );
session.setRemoteRepositories( remoteRepo.toURI()
.normalize()
.toURL()
.toExternalForm() );
final Set<File> modified =
vman.modifyVersions( pom,
Collections.singletonList( getResourceFile( PARENT_VERSION_BOM ).getAbsolutePath() ),
toolchain, session );
assertNoErrors( session );
| final Set<Model> changedModels = loadModels( modified ); |
release-engineering/pom-version-manipulator | src/test/java/com/redhat/rcm/version/mgr/VersionSuffixManagementTest.java | // Path: src/test/java/com/redhat/rcm/version/testutil/TestProjectFixture.java
// public static void dumpModel( final Model model )
// throws IOException
// {
// final StringWriter writer = new StringWriter();
// new MavenXpp3Writer().write( writer, model );
//
// System.out.println( "\n\n" + writer.toString() + "\n\n" );
// }
//
// Path: src/test/java/com/redhat/rcm/version/testutil/TestProjectFixture.java
// public static File getResourceFile( final String path )
// {
// final URL resource = Thread.currentThread()
// .getContextClassLoader()
// .getResource( path );
// if ( resource == null )
// {
// fail( "Resource not found: " + path );
// }
//
// return new File( resource.getPath() );
// }
//
// Path: src/test/java/com/redhat/rcm/version/testutil/TestProjectFixture.java
// public static Model loadModel( final String path )
// throws IOException
// {
// final File pom = getResourceFile( path );
// return loadModel( pom );
// }
//
// Path: src/test/java/com/redhat/rcm/version/testutil/TestProjectFixture.java
// public static Set<Model> loadModels( final Set<File> poms )
// throws VManException, IOException
// {
// final Set<Model> models = new LinkedHashSet<Model>( poms.size() );
// for ( final File pom : poms )
// {
// models.add( loadModel( pom ) );
// }
//
// return models;
// }
//
// Path: src/test/java/com/redhat/rcm/version/testutil/TestProjectFixture.java
// public static VersionManagerSession newVersionManagerSession( final File workspace, final File reports, final String suffix, final String modifier )
// {
// return new SessionBuilder( workspace, reports ).withVersionSuffix( suffix )
// .withVersionModifier( modifier )
// .build();
// }
| import static com.redhat.rcm.version.testutil.TestProjectFixture.dumpModel;
import static com.redhat.rcm.version.testutil.TestProjectFixture.getResourceFile;
import static com.redhat.rcm.version.testutil.TestProjectFixture.loadModel;
import static com.redhat.rcm.version.testutil.TestProjectFixture.loadModels;
import static com.redhat.rcm.version.testutil.TestProjectFixture.newVersionManagerSession;
import static org.apache.commons.io.FileUtils.copyDirectory;
import static org.apache.commons.io.FileUtils.copyFile;
import static org.apache.commons.io.FileUtils.readFileToString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.Assert.assertThat;
import java.io.File;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.apache.maven.mae.project.key.FullProjectKey;
import org.apache.maven.model.Model;
import org.apache.maven.model.Parent;
import org.apache.maven.project.MavenProject;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import com.redhat.rcm.version.fixture.LoggingFixture;
import com.redhat.rcm.version.mgr.mod.VersionSuffixModder;
import com.redhat.rcm.version.mgr.session.VersionManagerSession;
import com.redhat.rcm.version.model.Project; | {
try
{
System.out.println( "ADJUSTING: " + description + "\nPOM: " + pomPath + "\nToolchain: " + TOOLCHAIN_PATH );
final File srcPom = getResourceFile( TEST_POMS + pomPath );
final String toolchain = getResourceFile( TOOLCHAIN_PATH ).getAbsolutePath();
final File pom = new File( repo, srcPom.getName() );
copyFile( srcPom, pom );
final VersionManagerSession session = newVersionManagerSession( workspace, reports, SUFFIX );
final File remoteRepo = getResourceFile( TEST_POMS + "repo" );
session.setRemoteRepositories( remoteRepo.toURI()
.normalize()
.toURL()
.toExternalForm() );
final Set<File> modified =
vman.modifyVersions( pom,
Collections.singletonList( getResourceFile( PARENT_VERSION_BOM ).getAbsolutePath() ),
toolchain, session );
assertNoErrors( session );
final Set<Model> changedModels = loadModels( modified );
assertThat( "POM: " + pomPath + " was not modified!", changedModels.size(), equalTo( 1 ) );
final Model model = changedModels.iterator()
.next(); | // Path: src/test/java/com/redhat/rcm/version/testutil/TestProjectFixture.java
// public static void dumpModel( final Model model )
// throws IOException
// {
// final StringWriter writer = new StringWriter();
// new MavenXpp3Writer().write( writer, model );
//
// System.out.println( "\n\n" + writer.toString() + "\n\n" );
// }
//
// Path: src/test/java/com/redhat/rcm/version/testutil/TestProjectFixture.java
// public static File getResourceFile( final String path )
// {
// final URL resource = Thread.currentThread()
// .getContextClassLoader()
// .getResource( path );
// if ( resource == null )
// {
// fail( "Resource not found: " + path );
// }
//
// return new File( resource.getPath() );
// }
//
// Path: src/test/java/com/redhat/rcm/version/testutil/TestProjectFixture.java
// public static Model loadModel( final String path )
// throws IOException
// {
// final File pom = getResourceFile( path );
// return loadModel( pom );
// }
//
// Path: src/test/java/com/redhat/rcm/version/testutil/TestProjectFixture.java
// public static Set<Model> loadModels( final Set<File> poms )
// throws VManException, IOException
// {
// final Set<Model> models = new LinkedHashSet<Model>( poms.size() );
// for ( final File pom : poms )
// {
// models.add( loadModel( pom ) );
// }
//
// return models;
// }
//
// Path: src/test/java/com/redhat/rcm/version/testutil/TestProjectFixture.java
// public static VersionManagerSession newVersionManagerSession( final File workspace, final File reports, final String suffix, final String modifier )
// {
// return new SessionBuilder( workspace, reports ).withVersionSuffix( suffix )
// .withVersionModifier( modifier )
// .build();
// }
// Path: src/test/java/com/redhat/rcm/version/mgr/VersionSuffixManagementTest.java
import static com.redhat.rcm.version.testutil.TestProjectFixture.dumpModel;
import static com.redhat.rcm.version.testutil.TestProjectFixture.getResourceFile;
import static com.redhat.rcm.version.testutil.TestProjectFixture.loadModel;
import static com.redhat.rcm.version.testutil.TestProjectFixture.loadModels;
import static com.redhat.rcm.version.testutil.TestProjectFixture.newVersionManagerSession;
import static org.apache.commons.io.FileUtils.copyDirectory;
import static org.apache.commons.io.FileUtils.copyFile;
import static org.apache.commons.io.FileUtils.readFileToString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
import static org.junit.Assert.assertThat;
import java.io.File;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.apache.maven.mae.project.key.FullProjectKey;
import org.apache.maven.model.Model;
import org.apache.maven.model.Parent;
import org.apache.maven.project.MavenProject;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import com.redhat.rcm.version.fixture.LoggingFixture;
import com.redhat.rcm.version.mgr.mod.VersionSuffixModder;
import com.redhat.rcm.version.mgr.session.VersionManagerSession;
import com.redhat.rcm.version.model.Project;
{
try
{
System.out.println( "ADJUSTING: " + description + "\nPOM: " + pomPath + "\nToolchain: " + TOOLCHAIN_PATH );
final File srcPom = getResourceFile( TEST_POMS + pomPath );
final String toolchain = getResourceFile( TOOLCHAIN_PATH ).getAbsolutePath();
final File pom = new File( repo, srcPom.getName() );
copyFile( srcPom, pom );
final VersionManagerSession session = newVersionManagerSession( workspace, reports, SUFFIX );
final File remoteRepo = getResourceFile( TEST_POMS + "repo" );
session.setRemoteRepositories( remoteRepo.toURI()
.normalize()
.toURL()
.toExternalForm() );
final Set<File> modified =
vman.modifyVersions( pom,
Collections.singletonList( getResourceFile( PARENT_VERSION_BOM ).getAbsolutePath() ),
toolchain, session );
assertNoErrors( session );
final Set<Model> changedModels = loadModels( modified );
assertThat( "POM: " + pomPath + " was not modified!", changedModels.size(), equalTo( 1 ) );
final Model model = changedModels.iterator()
.next(); | dumpModel( model ); |
release-engineering/pom-version-manipulator | src/test/java/com/redhat/rcm/version/mgr/mod/VersionModderTest.java | // Path: src/test/java/com/redhat/rcm/version/testutil/TestProjectFixture.java
// public static Model loadModel( final String path )
// throws IOException
// {
// final File pom = getResourceFile( path );
// return loadModel( pom );
// }
//
// Path: src/test/java/com/redhat/rcm/version/testutil/TestProjectFixture.java
// public static VersionManagerSession newVersionManagerSession( final File workspace, final File reports, final String suffix, final String modifier )
// {
// return new SessionBuilder( workspace, reports ).withVersionSuffix( suffix )
// .withVersionModifier( modifier )
// .build();
// }
| import static com.redhat.rcm.version.testutil.TestProjectFixture.loadModel;
import static com.redhat.rcm.version.testutil.TestProjectFixture.newVersionManagerSession;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat;
import org.apache.maven.model.Model;
import org.junit.Test;
import com.redhat.rcm.version.model.Project; | /*
* Copyright (c) 2012 Red Hat, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.redhat.rcm.version.mgr.mod;
public class VersionModderTest
extends AbstractModderTest
{
@Test
public void testVersionReplaceVersion()
throws Exception
{ | // Path: src/test/java/com/redhat/rcm/version/testutil/TestProjectFixture.java
// public static Model loadModel( final String path )
// throws IOException
// {
// final File pom = getResourceFile( path );
// return loadModel( pom );
// }
//
// Path: src/test/java/com/redhat/rcm/version/testutil/TestProjectFixture.java
// public static VersionManagerSession newVersionManagerSession( final File workspace, final File reports, final String suffix, final String modifier )
// {
// return new SessionBuilder( workspace, reports ).withVersionSuffix( suffix )
// .withVersionModifier( modifier )
// .build();
// }
// Path: src/test/java/com/redhat/rcm/version/mgr/mod/VersionModderTest.java
import static com.redhat.rcm.version.testutil.TestProjectFixture.loadModel;
import static com.redhat.rcm.version.testutil.TestProjectFixture.newVersionManagerSession;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat;
import org.apache.maven.model.Model;
import org.junit.Test;
import com.redhat.rcm.version.model.Project;
/*
* Copyright (c) 2012 Red Hat, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.redhat.rcm.version.mgr.mod;
public class VersionModderTest
extends AbstractModderTest
{
@Test
public void testVersionReplaceVersion()
throws Exception
{ | final Model model = loadModel( "suffix/child-separateVersion-1.0.1.pom" ); |
release-engineering/pom-version-manipulator | src/test/java/com/redhat/rcm/version/mgr/mod/VersionModderTest.java | // Path: src/test/java/com/redhat/rcm/version/testutil/TestProjectFixture.java
// public static Model loadModel( final String path )
// throws IOException
// {
// final File pom = getResourceFile( path );
// return loadModel( pom );
// }
//
// Path: src/test/java/com/redhat/rcm/version/testutil/TestProjectFixture.java
// public static VersionManagerSession newVersionManagerSession( final File workspace, final File reports, final String suffix, final String modifier )
// {
// return new SessionBuilder( workspace, reports ).withVersionSuffix( suffix )
// .withVersionModifier( modifier )
// .build();
// }
| import static com.redhat.rcm.version.testutil.TestProjectFixture.loadModel;
import static com.redhat.rcm.version.testutil.TestProjectFixture.newVersionManagerSession;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat;
import org.apache.maven.model.Model;
import org.junit.Test;
import com.redhat.rcm.version.model.Project; | /*
* Copyright (c) 2012 Red Hat, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.redhat.rcm.version.mgr.mod;
public class VersionModderTest
extends AbstractModderTest
{
@Test
public void testVersionReplaceVersion()
throws Exception
{
final Model model = loadModel( "suffix/child-separateVersion-1.0.1.pom" );
assertThat( model.getVersion(), equalTo( "1.0.1" ) );
final boolean changed =
new VersionModder().inject( new Project( model ), | // Path: src/test/java/com/redhat/rcm/version/testutil/TestProjectFixture.java
// public static Model loadModel( final String path )
// throws IOException
// {
// final File pom = getResourceFile( path );
// return loadModel( pom );
// }
//
// Path: src/test/java/com/redhat/rcm/version/testutil/TestProjectFixture.java
// public static VersionManagerSession newVersionManagerSession( final File workspace, final File reports, final String suffix, final String modifier )
// {
// return new SessionBuilder( workspace, reports ).withVersionSuffix( suffix )
// .withVersionModifier( modifier )
// .build();
// }
// Path: src/test/java/com/redhat/rcm/version/mgr/mod/VersionModderTest.java
import static com.redhat.rcm.version.testutil.TestProjectFixture.loadModel;
import static com.redhat.rcm.version.testutil.TestProjectFixture.newVersionManagerSession;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat;
import org.apache.maven.model.Model;
import org.junit.Test;
import com.redhat.rcm.version.model.Project;
/*
* Copyright (c) 2012 Red Hat, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.redhat.rcm.version.mgr.mod;
public class VersionModderTest
extends AbstractModderTest
{
@Test
public void testVersionReplaceVersion()
throws Exception
{
final Model model = loadModel( "suffix/child-separateVersion-1.0.1.pom" );
assertThat( model.getVersion(), equalTo( "1.0.1" ) );
final boolean changed =
new VersionModder().inject( new Project( model ), | newVersionManagerSession( workspace, reports, "dummy-suffix", "1.0.1:Alpha1" ) ); |
release-engineering/pom-version-manipulator | src/test/java/com/redhat/rcm/version/util/InputUtilsTest.java | // Path: src/test/java/com/redhat/rcm/version/testutil/TestProjectFixture.java
// public static File getResourceFile( final String path )
// {
// final URL resource = Thread.currentThread()
// .getContextClassLoader()
// .getResource( path );
// if ( resource == null )
// {
// fail( "Resource not found: " + path );
// }
//
// return new File( resource.getPath() );
// }
| import static com.redhat.rcm.version.testutil.TestProjectFixture.getResourceFile;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat;
import java.io.File;
import java.util.Map;
import org.junit.BeforeClass;
import org.junit.Test;
import com.redhat.rcm.version.VManException;
import com.redhat.rcm.version.fixture.LoggingFixture; | /*
* Copyright (c) 2011 Red Hat, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see
* <http://www.gnu.org/licenses>.
*/
package com.redhat.rcm.version.util;
public class InputUtilsTest
{
@BeforeClass
public static void enableLogging()
{
LoggingFixture.setupLogging();
}
@Test
public void parsePropertiesFile_HandlingOfCoordinates_Comments_AndCommaSeparatedProps()
throws VManException
{ | // Path: src/test/java/com/redhat/rcm/version/testutil/TestProjectFixture.java
// public static File getResourceFile( final String path )
// {
// final URL resource = Thread.currentThread()
// .getContextClassLoader()
// .getResource( path );
// if ( resource == null )
// {
// fail( "Resource not found: " + path );
// }
//
// return new File( resource.getPath() );
// }
// Path: src/test/java/com/redhat/rcm/version/util/InputUtilsTest.java
import static com.redhat.rcm.version.testutil.TestProjectFixture.getResourceFile;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat;
import java.io.File;
import java.util.Map;
import org.junit.BeforeClass;
import org.junit.Test;
import com.redhat.rcm.version.VManException;
import com.redhat.rcm.version.fixture.LoggingFixture;
/*
* Copyright (c) 2011 Red Hat, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see
* <http://www.gnu.org/licenses>.
*/
package com.redhat.rcm.version.util;
public class InputUtilsTest
{
@BeforeClass
public static void enableLogging()
{
LoggingFixture.setupLogging();
}
@Test
public void parsePropertiesFile_HandlingOfCoordinates_Comments_AndCommaSeparatedProps()
throws VManException
{ | final File relocations = getResourceFile( "relocations.properties" ); |
release-engineering/pom-version-manipulator | src/test/java/com/redhat/rcm/version/util/PomUtilsTest.java | // Path: src/test/java/com/redhat/rcm/version/testutil/TestProjectFixture.java
// public static File getResourceFile( final String path )
// {
// final URL resource = Thread.currentThread()
// .getContextClassLoader()
// .getResource( path );
// if ( resource == null )
// {
// fail( "Resource not found: " + path );
// }
//
// return new File( resource.getPath() );
// }
//
// Path: src/test/java/com/redhat/rcm/version/testutil/TestProjectFixture.java
// public static Model loadModel( final String path )
// throws IOException
// {
// final File pom = getResourceFile( path );
// return loadModel( pom );
// }
//
// Path: src/test/java/com/redhat/rcm/version/testutil/TestProjectFixture.java
// public static VersionManagerSession newVersionManagerSession( final File workspace, final File reports, final String suffix, final String modifier )
// {
// return new SessionBuilder( workspace, reports ).withVersionSuffix( suffix )
// .withVersionModifier( modifier )
// .build();
// }
| import static com.redhat.rcm.version.testutil.TestProjectFixture.getResourceFile;
import static com.redhat.rcm.version.testutil.TestProjectFixture.loadModel;
import static com.redhat.rcm.version.testutil.TestProjectFixture.newVersionManagerSession;
import static org.apache.commons.io.FileUtils.readFileToString;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.junit.Assert.assertThat;
import org.apache.maven.mae.project.key.FullProjectKey;
import org.apache.maven.model.Model;
import org.apache.maven.model.Plugin;
import org.codehaus.plexus.util.FileUtils;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestName;
import com.redhat.rcm.version.fixture.LoggingFixture;
import com.redhat.rcm.version.mgr.AbstractVersionManagerTest;
import com.redhat.rcm.version.mgr.session.VersionManagerSession;
import java.io.File;
import java.util.List; | /*
* Copyright (C) 2011 John Casey.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.redhat.rcm.version.util;
public class PomUtilsTest
extends AbstractVersionManagerTest
{
private static final String BASE = "pom-formats/";
@Rule
public final TestName name = new TestName();
@Test
public void pomRewritePreservesXMLAttributesInPluginConfiguration()
throws Exception
{ | // Path: src/test/java/com/redhat/rcm/version/testutil/TestProjectFixture.java
// public static File getResourceFile( final String path )
// {
// final URL resource = Thread.currentThread()
// .getContextClassLoader()
// .getResource( path );
// if ( resource == null )
// {
// fail( "Resource not found: " + path );
// }
//
// return new File( resource.getPath() );
// }
//
// Path: src/test/java/com/redhat/rcm/version/testutil/TestProjectFixture.java
// public static Model loadModel( final String path )
// throws IOException
// {
// final File pom = getResourceFile( path );
// return loadModel( pom );
// }
//
// Path: src/test/java/com/redhat/rcm/version/testutil/TestProjectFixture.java
// public static VersionManagerSession newVersionManagerSession( final File workspace, final File reports, final String suffix, final String modifier )
// {
// return new SessionBuilder( workspace, reports ).withVersionSuffix( suffix )
// .withVersionModifier( modifier )
// .build();
// }
// Path: src/test/java/com/redhat/rcm/version/util/PomUtilsTest.java
import static com.redhat.rcm.version.testutil.TestProjectFixture.getResourceFile;
import static com.redhat.rcm.version.testutil.TestProjectFixture.loadModel;
import static com.redhat.rcm.version.testutil.TestProjectFixture.newVersionManagerSession;
import static org.apache.commons.io.FileUtils.readFileToString;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.junit.Assert.assertThat;
import org.apache.maven.mae.project.key.FullProjectKey;
import org.apache.maven.model.Model;
import org.apache.maven.model.Plugin;
import org.codehaus.plexus.util.FileUtils;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestName;
import com.redhat.rcm.version.fixture.LoggingFixture;
import com.redhat.rcm.version.mgr.AbstractVersionManagerTest;
import com.redhat.rcm.version.mgr.session.VersionManagerSession;
import java.io.File;
import java.util.List;
/*
* Copyright (C) 2011 John Casey.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.redhat.rcm.version.util;
public class PomUtilsTest
extends AbstractVersionManagerTest
{
private static final String BASE = "pom-formats/";
@Rule
public final TestName name = new TestName();
@Test
public void pomRewritePreservesXMLAttributesInPluginConfiguration()
throws Exception
{ | final File srcPom = getResourceFile( BASE + "plugin-config-attributes.pom" ); |
release-engineering/pom-version-manipulator | src/test/java/com/redhat/rcm/version/util/PomUtilsTest.java | // Path: src/test/java/com/redhat/rcm/version/testutil/TestProjectFixture.java
// public static File getResourceFile( final String path )
// {
// final URL resource = Thread.currentThread()
// .getContextClassLoader()
// .getResource( path );
// if ( resource == null )
// {
// fail( "Resource not found: " + path );
// }
//
// return new File( resource.getPath() );
// }
//
// Path: src/test/java/com/redhat/rcm/version/testutil/TestProjectFixture.java
// public static Model loadModel( final String path )
// throws IOException
// {
// final File pom = getResourceFile( path );
// return loadModel( pom );
// }
//
// Path: src/test/java/com/redhat/rcm/version/testutil/TestProjectFixture.java
// public static VersionManagerSession newVersionManagerSession( final File workspace, final File reports, final String suffix, final String modifier )
// {
// return new SessionBuilder( workspace, reports ).withVersionSuffix( suffix )
// .withVersionModifier( modifier )
// .build();
// }
| import static com.redhat.rcm.version.testutil.TestProjectFixture.getResourceFile;
import static com.redhat.rcm.version.testutil.TestProjectFixture.loadModel;
import static com.redhat.rcm.version.testutil.TestProjectFixture.newVersionManagerSession;
import static org.apache.commons.io.FileUtils.readFileToString;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.junit.Assert.assertThat;
import org.apache.maven.mae.project.key.FullProjectKey;
import org.apache.maven.model.Model;
import org.apache.maven.model.Plugin;
import org.codehaus.plexus.util.FileUtils;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestName;
import com.redhat.rcm.version.fixture.LoggingFixture;
import com.redhat.rcm.version.mgr.AbstractVersionManagerTest;
import com.redhat.rcm.version.mgr.session.VersionManagerSession;
import java.io.File;
import java.util.List; | /*
* Copyright (C) 2011 John Casey.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.redhat.rcm.version.util;
public class PomUtilsTest
extends AbstractVersionManagerTest
{
private static final String BASE = "pom-formats/";
@Rule
public final TestName name = new TestName();
@Test
public void pomRewritePreservesXMLAttributesInPluginConfiguration()
throws Exception
{
final File srcPom = getResourceFile( BASE + "plugin-config-attributes.pom" );
final File pom = new File( repo, srcPom.getName() );
FileUtils.copyFile( srcPom, pom );
| // Path: src/test/java/com/redhat/rcm/version/testutil/TestProjectFixture.java
// public static File getResourceFile( final String path )
// {
// final URL resource = Thread.currentThread()
// .getContextClassLoader()
// .getResource( path );
// if ( resource == null )
// {
// fail( "Resource not found: " + path );
// }
//
// return new File( resource.getPath() );
// }
//
// Path: src/test/java/com/redhat/rcm/version/testutil/TestProjectFixture.java
// public static Model loadModel( final String path )
// throws IOException
// {
// final File pom = getResourceFile( path );
// return loadModel( pom );
// }
//
// Path: src/test/java/com/redhat/rcm/version/testutil/TestProjectFixture.java
// public static VersionManagerSession newVersionManagerSession( final File workspace, final File reports, final String suffix, final String modifier )
// {
// return new SessionBuilder( workspace, reports ).withVersionSuffix( suffix )
// .withVersionModifier( modifier )
// .build();
// }
// Path: src/test/java/com/redhat/rcm/version/util/PomUtilsTest.java
import static com.redhat.rcm.version.testutil.TestProjectFixture.getResourceFile;
import static com.redhat.rcm.version.testutil.TestProjectFixture.loadModel;
import static com.redhat.rcm.version.testutil.TestProjectFixture.newVersionManagerSession;
import static org.apache.commons.io.FileUtils.readFileToString;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.junit.Assert.assertThat;
import org.apache.maven.mae.project.key.FullProjectKey;
import org.apache.maven.model.Model;
import org.apache.maven.model.Plugin;
import org.codehaus.plexus.util.FileUtils;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestName;
import com.redhat.rcm.version.fixture.LoggingFixture;
import com.redhat.rcm.version.mgr.AbstractVersionManagerTest;
import com.redhat.rcm.version.mgr.session.VersionManagerSession;
import java.io.File;
import java.util.List;
/*
* Copyright (C) 2011 John Casey.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.redhat.rcm.version.util;
public class PomUtilsTest
extends AbstractVersionManagerTest
{
private static final String BASE = "pom-formats/";
@Rule
public final TestName name = new TestName();
@Test
public void pomRewritePreservesXMLAttributesInPluginConfiguration()
throws Exception
{
final File srcPom = getResourceFile( BASE + "plugin-config-attributes.pom" );
final File pom = new File( repo, srcPom.getName() );
FileUtils.copyFile( srcPom, pom );
| final Model model = loadModel( pom ); |
release-engineering/pom-version-manipulator | src/test/java/com/redhat/rcm/version/util/PomUtilsTest.java | // Path: src/test/java/com/redhat/rcm/version/testutil/TestProjectFixture.java
// public static File getResourceFile( final String path )
// {
// final URL resource = Thread.currentThread()
// .getContextClassLoader()
// .getResource( path );
// if ( resource == null )
// {
// fail( "Resource not found: " + path );
// }
//
// return new File( resource.getPath() );
// }
//
// Path: src/test/java/com/redhat/rcm/version/testutil/TestProjectFixture.java
// public static Model loadModel( final String path )
// throws IOException
// {
// final File pom = getResourceFile( path );
// return loadModel( pom );
// }
//
// Path: src/test/java/com/redhat/rcm/version/testutil/TestProjectFixture.java
// public static VersionManagerSession newVersionManagerSession( final File workspace, final File reports, final String suffix, final String modifier )
// {
// return new SessionBuilder( workspace, reports ).withVersionSuffix( suffix )
// .withVersionModifier( modifier )
// .build();
// }
| import static com.redhat.rcm.version.testutil.TestProjectFixture.getResourceFile;
import static com.redhat.rcm.version.testutil.TestProjectFixture.loadModel;
import static com.redhat.rcm.version.testutil.TestProjectFixture.newVersionManagerSession;
import static org.apache.commons.io.FileUtils.readFileToString;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.junit.Assert.assertThat;
import org.apache.maven.mae.project.key.FullProjectKey;
import org.apache.maven.model.Model;
import org.apache.maven.model.Plugin;
import org.codehaus.plexus.util.FileUtils;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestName;
import com.redhat.rcm.version.fixture.LoggingFixture;
import com.redhat.rcm.version.mgr.AbstractVersionManagerTest;
import com.redhat.rcm.version.mgr.session.VersionManagerSession;
import java.io.File;
import java.util.List; | /*
* Copyright (C) 2011 John Casey.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.redhat.rcm.version.util;
public class PomUtilsTest
extends AbstractVersionManagerTest
{
private static final String BASE = "pom-formats/";
@Rule
public final TestName name = new TestName();
@Test
public void pomRewritePreservesXMLAttributesInPluginConfiguration()
throws Exception
{
final File srcPom = getResourceFile( BASE + "plugin-config-attributes.pom" );
final File pom = new File( repo, srcPom.getName() );
FileUtils.copyFile( srcPom, pom );
final Model model = loadModel( pom );
assertThat( model.getBuild(), notNullValue() );
List<Plugin> plugins = model.getBuild().getPlugins();
assertThat( plugins, notNullValue() );
assertThat( plugins.size(), equalTo( 1 ) );
Plugin plugin = plugins.get( 0 );
Object config = plugin.getConfiguration();
assertThat( config, notNullValue() );
assertThat( config.toString().contains( "<delete dir=\"foobar\"" ), equalTo( true ) );
| // Path: src/test/java/com/redhat/rcm/version/testutil/TestProjectFixture.java
// public static File getResourceFile( final String path )
// {
// final URL resource = Thread.currentThread()
// .getContextClassLoader()
// .getResource( path );
// if ( resource == null )
// {
// fail( "Resource not found: " + path );
// }
//
// return new File( resource.getPath() );
// }
//
// Path: src/test/java/com/redhat/rcm/version/testutil/TestProjectFixture.java
// public static Model loadModel( final String path )
// throws IOException
// {
// final File pom = getResourceFile( path );
// return loadModel( pom );
// }
//
// Path: src/test/java/com/redhat/rcm/version/testutil/TestProjectFixture.java
// public static VersionManagerSession newVersionManagerSession( final File workspace, final File reports, final String suffix, final String modifier )
// {
// return new SessionBuilder( workspace, reports ).withVersionSuffix( suffix )
// .withVersionModifier( modifier )
// .build();
// }
// Path: src/test/java/com/redhat/rcm/version/util/PomUtilsTest.java
import static com.redhat.rcm.version.testutil.TestProjectFixture.getResourceFile;
import static com.redhat.rcm.version.testutil.TestProjectFixture.loadModel;
import static com.redhat.rcm.version.testutil.TestProjectFixture.newVersionManagerSession;
import static org.apache.commons.io.FileUtils.readFileToString;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.junit.Assert.assertThat;
import org.apache.maven.mae.project.key.FullProjectKey;
import org.apache.maven.model.Model;
import org.apache.maven.model.Plugin;
import org.codehaus.plexus.util.FileUtils;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestName;
import com.redhat.rcm.version.fixture.LoggingFixture;
import com.redhat.rcm.version.mgr.AbstractVersionManagerTest;
import com.redhat.rcm.version.mgr.session.VersionManagerSession;
import java.io.File;
import java.util.List;
/*
* Copyright (C) 2011 John Casey.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.redhat.rcm.version.util;
public class PomUtilsTest
extends AbstractVersionManagerTest
{
private static final String BASE = "pom-formats/";
@Rule
public final TestName name = new TestName();
@Test
public void pomRewritePreservesXMLAttributesInPluginConfiguration()
throws Exception
{
final File srcPom = getResourceFile( BASE + "plugin-config-attributes.pom" );
final File pom = new File( repo, srcPom.getName() );
FileUtils.copyFile( srcPom, pom );
final Model model = loadModel( pom );
assertThat( model.getBuild(), notNullValue() );
List<Plugin> plugins = model.getBuild().getPlugins();
assertThat( plugins, notNullValue() );
assertThat( plugins.size(), equalTo( 1 ) );
Plugin plugin = plugins.get( 0 );
Object config = plugin.getConfiguration();
assertThat( config, notNullValue() );
assertThat( config.toString().contains( "<delete dir=\"foobar\"" ), equalTo( true ) );
| final VersionManagerSession session = newVersionManagerSession( workspace, reports, null ); |
danekja/jdk-serializable-functional | src/main/java/org/danekja/java/misc/serializable/SerializableComparator.java | // Path: src/main/java/org/danekja/java/util/function/serializable/SerializableFunction.java
// @FunctionalInterface
// public interface SerializableFunction<T, R> extends Function<T, R>, Serializable {
// /**
// * Returns a composed function that first applies the {@code before}
// * function to its input, and then applies this function to the result.
// * If evaluation of either function throws an exception, it is relayed to
// * the caller of the composed function.
// *
// * @param <V> the type of input to the {@code before} function, and to the
// * composed function
// * @param before the function to apply before this function is applied
// * @return a composed function that first applies the {@code before}
// * function and then applies this function
// * @throws NullPointerException if before is null
// *
// * @see #andThen(Function)
// */
// default <V> SerializableFunction<V, R> compose(SerializableFunction<? super V, ? extends T> before) {
// Objects.requireNonNull(before);
// return (V v) -> apply(before.apply(v));
// }
//
// /**
// * Returns a composed function that first applies this function to
// * its input, and then applies the {@code after} function to the result.
// * If evaluation of either function throws an exception, it is relayed to
// * the caller of the composed function.
// *
// * @param <V> the type of output of the {@code after} function, and of the
// * composed function
// * @param after the function to apply after this function is applied
// * @return a composed function that first applies this function and then
// * applies the {@code after} function
// * @throws NullPointerException if after is null
// *
// * @see #compose(Function)
// */
// default <V> SerializableFunction<T, V> andThen(SerializableFunction<? super R, ? extends V> after) {
// Objects.requireNonNull(after);
// return (T t) -> after.apply(apply(t));
// }
//
// /**
// * Returns a function that always returns its input argument.
// *
// * @param <T> the type of the input and output objects to the function
// * @return a function that always returns its input argument
// */
// static <T> SerializableFunction<T, T> identity() {
// return t -> t;
// }
// }
//
// Path: src/main/java/org/danekja/java/util/function/serializable/SerializableToDoubleFunction.java
// @FunctionalInterface
// public interface SerializableToDoubleFunction<T> extends ToDoubleFunction<T>, Serializable {
//
// }
//
// Path: src/main/java/org/danekja/java/util/function/serializable/SerializableToIntFunction.java
// @FunctionalInterface
// public interface SerializableToIntFunction<T> extends ToIntFunction<T>, Serializable {
//
// }
//
// Path: src/main/java/org/danekja/java/util/function/serializable/SerializableToLongFunction.java
// @FunctionalInterface
// public interface SerializableToLongFunction<T> extends ToLongFunction<T>, Serializable {
//
// }
| import java.io.Serializable;
import java.util.Collections;
import java.util.Comparator;
import java.util.Objects;
import org.danekja.java.util.function.serializable.SerializableFunction;
import org.danekja.java.util.function.serializable.SerializableToDoubleFunction;
import org.danekja.java.util.function.serializable.SerializableToIntFunction;
import org.danekja.java.util.function.serializable.SerializableToLongFunction; | *
* @param keyExtractor the function used to extract the long sort key
* @return a lexicographic-order comparator composed of this and then the
* {@code long} sort key
* @throws NullPointerException if the argument is null.
* @see #comparingLong(SerializableToLongFunction)
* @see #thenComparing(SerializableComparator)
* @since 1.8
*/
default SerializableComparator<T> thenComparingLong(
SerializableToLongFunction<? super T> keyExtractor) {
return thenComparing(comparingLong(keyExtractor));
}
/**
* Returns a lexicographic-order comparator with a function that
* extracts a {@code double} sort key.
*
* @implSpec This default implementation behaves as if {@code
* thenComparing(comparingDouble(keyExtractor))}.
*
* @param keyExtractor the function used to extract the double sort key
* @return a lexicographic-order comparator composed of this and then the
* {@code double} sort key
* @throws NullPointerException if the argument is null.
* @see #comparingDouble(SerializableToDoubleFunction)
* @see #thenComparing(SerializableComparator)
* @since 1.8
*/
default SerializableComparator<T> thenComparingDouble( | // Path: src/main/java/org/danekja/java/util/function/serializable/SerializableFunction.java
// @FunctionalInterface
// public interface SerializableFunction<T, R> extends Function<T, R>, Serializable {
// /**
// * Returns a composed function that first applies the {@code before}
// * function to its input, and then applies this function to the result.
// * If evaluation of either function throws an exception, it is relayed to
// * the caller of the composed function.
// *
// * @param <V> the type of input to the {@code before} function, and to the
// * composed function
// * @param before the function to apply before this function is applied
// * @return a composed function that first applies the {@code before}
// * function and then applies this function
// * @throws NullPointerException if before is null
// *
// * @see #andThen(Function)
// */
// default <V> SerializableFunction<V, R> compose(SerializableFunction<? super V, ? extends T> before) {
// Objects.requireNonNull(before);
// return (V v) -> apply(before.apply(v));
// }
//
// /**
// * Returns a composed function that first applies this function to
// * its input, and then applies the {@code after} function to the result.
// * If evaluation of either function throws an exception, it is relayed to
// * the caller of the composed function.
// *
// * @param <V> the type of output of the {@code after} function, and of the
// * composed function
// * @param after the function to apply after this function is applied
// * @return a composed function that first applies this function and then
// * applies the {@code after} function
// * @throws NullPointerException if after is null
// *
// * @see #compose(Function)
// */
// default <V> SerializableFunction<T, V> andThen(SerializableFunction<? super R, ? extends V> after) {
// Objects.requireNonNull(after);
// return (T t) -> after.apply(apply(t));
// }
//
// /**
// * Returns a function that always returns its input argument.
// *
// * @param <T> the type of the input and output objects to the function
// * @return a function that always returns its input argument
// */
// static <T> SerializableFunction<T, T> identity() {
// return t -> t;
// }
// }
//
// Path: src/main/java/org/danekja/java/util/function/serializable/SerializableToDoubleFunction.java
// @FunctionalInterface
// public interface SerializableToDoubleFunction<T> extends ToDoubleFunction<T>, Serializable {
//
// }
//
// Path: src/main/java/org/danekja/java/util/function/serializable/SerializableToIntFunction.java
// @FunctionalInterface
// public interface SerializableToIntFunction<T> extends ToIntFunction<T>, Serializable {
//
// }
//
// Path: src/main/java/org/danekja/java/util/function/serializable/SerializableToLongFunction.java
// @FunctionalInterface
// public interface SerializableToLongFunction<T> extends ToLongFunction<T>, Serializable {
//
// }
// Path: src/main/java/org/danekja/java/misc/serializable/SerializableComparator.java
import java.io.Serializable;
import java.util.Collections;
import java.util.Comparator;
import java.util.Objects;
import org.danekja.java.util.function.serializable.SerializableFunction;
import org.danekja.java.util.function.serializable.SerializableToDoubleFunction;
import org.danekja.java.util.function.serializable.SerializableToIntFunction;
import org.danekja.java.util.function.serializable.SerializableToLongFunction;
*
* @param keyExtractor the function used to extract the long sort key
* @return a lexicographic-order comparator composed of this and then the
* {@code long} sort key
* @throws NullPointerException if the argument is null.
* @see #comparingLong(SerializableToLongFunction)
* @see #thenComparing(SerializableComparator)
* @since 1.8
*/
default SerializableComparator<T> thenComparingLong(
SerializableToLongFunction<? super T> keyExtractor) {
return thenComparing(comparingLong(keyExtractor));
}
/**
* Returns a lexicographic-order comparator with a function that
* extracts a {@code double} sort key.
*
* @implSpec This default implementation behaves as if {@code
* thenComparing(comparingDouble(keyExtractor))}.
*
* @param keyExtractor the function used to extract the double sort key
* @return a lexicographic-order comparator composed of this and then the
* {@code double} sort key
* @throws NullPointerException if the argument is null.
* @see #comparingDouble(SerializableToDoubleFunction)
* @see #thenComparing(SerializableComparator)
* @since 1.8
*/
default SerializableComparator<T> thenComparingDouble( | SerializableToDoubleFunction<? super T> keyExtractor) { |
danekja/jdk-serializable-functional | src/main/java/org/danekja/java/misc/serializable/SerializableComparatorWrapperClass.java | // Path: src/main/java/org/danekja/java/util/function/serializable/SerializableSupplier.java
// @FunctionalInterface
// public interface SerializableSupplier<T> extends Supplier<T>, Serializable {
//
// }
| import java.util.Comparator;
import org.danekja.java.util.function.serializable.SerializableSupplier;
import java.text.Collator; | /*
*
* The MIT License (MIT)
*
* Copyright (c) 2015 Jakub Danek
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*
* Please visit https://github.com/danekja/jdk-function-serializable if you need additional information or have any
* questions.
*
*/
package org.danekja.java.misc.serializable;
/**
* Wrapper for a non-serializable subclass of {@link Comparator}, such as {@link Collator}.
* This way you can still use such comparators in a serializable way.
*
* This wrapper calls the given {@link SerializableSupplier} to retrieve a delegate {@link Comparator} which it
* uses for all calls to its {@link #compare(Object, Object)}-method. It caches the retrieved {@link Comparator}
* in a transient field for efficiency.
*
* Usage example:
*
* <blockquote><pre>
* SerializableComparator<Object> collator = new SerializableComparatorWrapper<>(() -> Collator.getInstance(Locale.UK));
* SerializableComparator<Object> objectComparator = SerializableComparator.comparing(Object::toString, collator);
* </pre></blockquote>
*
* (Note that Collator is an instance of Comparator typed with Object, not with a generic type variable.)
*
* @author haster
*
* @param <T> comparable type
*/
public class SerializableComparatorWrapperClass<T> implements SerializableComparator<T>
{
private static final long serialVersionUID = 1L;
| // Path: src/main/java/org/danekja/java/util/function/serializable/SerializableSupplier.java
// @FunctionalInterface
// public interface SerializableSupplier<T> extends Supplier<T>, Serializable {
//
// }
// Path: src/main/java/org/danekja/java/misc/serializable/SerializableComparatorWrapperClass.java
import java.util.Comparator;
import org.danekja.java.util.function.serializable.SerializableSupplier;
import java.text.Collator;
/*
*
* The MIT License (MIT)
*
* Copyright (c) 2015 Jakub Danek
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*
* Please visit https://github.com/danekja/jdk-function-serializable if you need additional information or have any
* questions.
*
*/
package org.danekja.java.misc.serializable;
/**
* Wrapper for a non-serializable subclass of {@link Comparator}, such as {@link Collator}.
* This way you can still use such comparators in a serializable way.
*
* This wrapper calls the given {@link SerializableSupplier} to retrieve a delegate {@link Comparator} which it
* uses for all calls to its {@link #compare(Object, Object)}-method. It caches the retrieved {@link Comparator}
* in a transient field for efficiency.
*
* Usage example:
*
* <blockquote><pre>
* SerializableComparator<Object> collator = new SerializableComparatorWrapper<>(() -> Collator.getInstance(Locale.UK));
* SerializableComparator<Object> objectComparator = SerializableComparator.comparing(Object::toString, collator);
* </pre></blockquote>
*
* (Note that Collator is an instance of Comparator typed with Object, not with a generic type variable.)
*
* @author haster
*
* @param <T> comparable type
*/
public class SerializableComparatorWrapperClass<T> implements SerializableComparator<T>
{
private static final long serialVersionUID = 1L;
| private SerializableSupplier<Comparator<T>> comparatorSupplier; |
nicknux/onedrive4j | src/main/java/com/nickdsantos/onedrive4j/AlbumService.java | // Path: src/main/java/com/nickdsantos/onedrive4j/Resource.java
// public enum SharedWith {
// Selected("People I selected"),
// JustMe("Just me"),
// Everyone("Everyone (public)"),
// Friends("Friends"),
// FriendsOfFriends("My friends and their friends"),
// PeopleWithLink("People with a link");
//
// private final String _val;
// private SharedWith(String val) {
// _val = val;
// }
//
// @Override
// public String toString() {
// return _val;
// }
//
// public static SharedWith parse(String value) throws Exception {
// switch (value.toLowerCase()) {
// case "people i selected":
// return SharedWith.Selected;
// case "just me":
// return SharedWith.JustMe;
// case "everyone (public)":
// return SharedWith.Everyone;
// case "friends":
// return SharedWith.Friends;
// case "my friends and their friends":
// return SharedWith.FriendsOfFriends;
// case "people with a link":
// return SharedWith.PeopleWithLink;
// default:
// throw new Exception("Unsupported value: " + value);
// }
// }
// }
| import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.nickdsantos.onedrive4j.Resource.SharedWith;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.log4j.Logger;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map; | Gson gson = new GsonBuilder().create();
String jsonString = gson.toJson(params);
StringEntity jsonEntity = new StringEntity(jsonString);
jsonEntity.setContentType(new BasicHeader("Content-Type", "application/json"));
HttpPost httpPost = new HttpPost(uri);
httpPost.setHeader("Authorization", "Bearer " + accessToken);
httpPost.setEntity(jsonEntity);
Map<Object, Object> rawResponse = httpClient.execute(httpPost, new OneDriveJsonToMapResponseHandler());
if (rawResponse != null) {
updatedAlbum = createAlbumFromMap(rawResponse);
// Do not get the updated id. revert to the original prior to the update
updatedAlbum.setId(albumId);
}
}
return updatedAlbum;
}
private Album createAlbumFromMap(Map<Object, Object> responseMap) {
SimpleDateFormat dtFormat = new SimpleDateFormat("YYYY-MM-dd'T'HH:mm:ssZ");
Album album;
try {
Map<String, String> fromUserMap = (Map<String, String>) responseMap.get("from");
User fromUser = new User();
fromUser.setId(fromUserMap.get("id").toString());
fromUser.setName(fromUserMap.get("name").toString());
Map<String, String> sharedWithMap = (Map<String, String>) responseMap.get("shared_with"); | // Path: src/main/java/com/nickdsantos/onedrive4j/Resource.java
// public enum SharedWith {
// Selected("People I selected"),
// JustMe("Just me"),
// Everyone("Everyone (public)"),
// Friends("Friends"),
// FriendsOfFriends("My friends and their friends"),
// PeopleWithLink("People with a link");
//
// private final String _val;
// private SharedWith(String val) {
// _val = val;
// }
//
// @Override
// public String toString() {
// return _val;
// }
//
// public static SharedWith parse(String value) throws Exception {
// switch (value.toLowerCase()) {
// case "people i selected":
// return SharedWith.Selected;
// case "just me":
// return SharedWith.JustMe;
// case "everyone (public)":
// return SharedWith.Everyone;
// case "friends":
// return SharedWith.Friends;
// case "my friends and their friends":
// return SharedWith.FriendsOfFriends;
// case "people with a link":
// return SharedWith.PeopleWithLink;
// default:
// throw new Exception("Unsupported value: " + value);
// }
// }
// }
// Path: src/main/java/com/nickdsantos/onedrive4j/AlbumService.java
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.nickdsantos.onedrive4j.Resource.SharedWith;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.log4j.Logger;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
Gson gson = new GsonBuilder().create();
String jsonString = gson.toJson(params);
StringEntity jsonEntity = new StringEntity(jsonString);
jsonEntity.setContentType(new BasicHeader("Content-Type", "application/json"));
HttpPost httpPost = new HttpPost(uri);
httpPost.setHeader("Authorization", "Bearer " + accessToken);
httpPost.setEntity(jsonEntity);
Map<Object, Object> rawResponse = httpClient.execute(httpPost, new OneDriveJsonToMapResponseHandler());
if (rawResponse != null) {
updatedAlbum = createAlbumFromMap(rawResponse);
// Do not get the updated id. revert to the original prior to the update
updatedAlbum.setId(albumId);
}
}
return updatedAlbum;
}
private Album createAlbumFromMap(Map<Object, Object> responseMap) {
SimpleDateFormat dtFormat = new SimpleDateFormat("YYYY-MM-dd'T'HH:mm:ssZ");
Album album;
try {
Map<String, String> fromUserMap = (Map<String, String>) responseMap.get("from");
User fromUser = new User();
fromUser.setId(fromUserMap.get("id").toString());
fromUser.setName(fromUserMap.get("name").toString());
Map<String, String> sharedWithMap = (Map<String, String>) responseMap.get("shared_with"); | SharedWith sharedWith = SharedWith.parse(sharedWithMap.get("access").toString()); |
nicknux/onedrive4j | src/main/java/com/nickdsantos/onedrive4j/PhotoService.java | // Path: src/main/java/com/nickdsantos/onedrive4j/Resource.java
// public enum SharedWith {
// Selected("People I selected"),
// JustMe("Just me"),
// Everyone("Everyone (public)"),
// Friends("Friends"),
// FriendsOfFriends("My friends and their friends"),
// PeopleWithLink("People with a link");
//
// private final String _val;
// private SharedWith(String val) {
// _val = val;
// }
//
// @Override
// public String toString() {
// return _val;
// }
//
// public static SharedWith parse(String value) throws Exception {
// switch (value.toLowerCase()) {
// case "people i selected":
// return SharedWith.Selected;
// case "just me":
// return SharedWith.JustMe;
// case "everyone (public)":
// return SharedWith.Everyone;
// case "friends":
// return SharedWith.Friends;
// case "my friends and their friends":
// return SharedWith.FriendsOfFriends;
// case "people with a link":
// return SharedWith.PeopleWithLink;
// default:
// throw new Exception("Unsupported value: " + value);
// }
// }
// }
| import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.nickdsantos.onedrive4j.Resource.SharedWith;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.log4j.Logger;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.util.*; | }
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpDelete httpDelete = new HttpDelete(uri);
Map<Object, Object> rawResponse = httpClient.execute(httpDelete, new OneDriveJsonToMapResponseHandler());
if (rawResponse != null) {
System.out.println(rawResponse);
}
}
}
private Photo createPhotoFromMap(Map<Object, Object> responseMap) {
if (logger.isDebugEnabled()) {
for (Object k : responseMap.keySet()) {
logger.debug(k + " : " + responseMap.get(k));
}
}
SimpleDateFormat dtFormat = new SimpleDateFormat("YYYY-MM-dd'T'HH:mm:ssZ");
Photo photo = null;
if (responseMap.get("type").equals("photo")) {
try {
// Get embedded from JSON
Map<String, String> fromUserMap = (Map<String, String>) responseMap.get("from");
User fromUser = new User();
fromUser.setId(fromUserMap.get("id"));
fromUser.setName(fromUserMap.get("name"));
// Get embedded shared_with JSON
Map<String, String> sharedWithMap = (Map<String, String>) responseMap.get("shared_with"); | // Path: src/main/java/com/nickdsantos/onedrive4j/Resource.java
// public enum SharedWith {
// Selected("People I selected"),
// JustMe("Just me"),
// Everyone("Everyone (public)"),
// Friends("Friends"),
// FriendsOfFriends("My friends and their friends"),
// PeopleWithLink("People with a link");
//
// private final String _val;
// private SharedWith(String val) {
// _val = val;
// }
//
// @Override
// public String toString() {
// return _val;
// }
//
// public static SharedWith parse(String value) throws Exception {
// switch (value.toLowerCase()) {
// case "people i selected":
// return SharedWith.Selected;
// case "just me":
// return SharedWith.JustMe;
// case "everyone (public)":
// return SharedWith.Everyone;
// case "friends":
// return SharedWith.Friends;
// case "my friends and their friends":
// return SharedWith.FriendsOfFriends;
// case "people with a link":
// return SharedWith.PeopleWithLink;
// default:
// throw new Exception("Unsupported value: " + value);
// }
// }
// }
// Path: src/main/java/com/nickdsantos/onedrive4j/PhotoService.java
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.nickdsantos.onedrive4j.Resource.SharedWith;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.log4j.Logger;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.util.*;
}
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpDelete httpDelete = new HttpDelete(uri);
Map<Object, Object> rawResponse = httpClient.execute(httpDelete, new OneDriveJsonToMapResponseHandler());
if (rawResponse != null) {
System.out.println(rawResponse);
}
}
}
private Photo createPhotoFromMap(Map<Object, Object> responseMap) {
if (logger.isDebugEnabled()) {
for (Object k : responseMap.keySet()) {
logger.debug(k + " : " + responseMap.get(k));
}
}
SimpleDateFormat dtFormat = new SimpleDateFormat("YYYY-MM-dd'T'HH:mm:ssZ");
Photo photo = null;
if (responseMap.get("type").equals("photo")) {
try {
// Get embedded from JSON
Map<String, String> fromUserMap = (Map<String, String>) responseMap.get("from");
User fromUser = new User();
fromUser.setId(fromUserMap.get("id"));
fromUser.setName(fromUserMap.get("name"));
// Get embedded shared_with JSON
Map<String, String> sharedWithMap = (Map<String, String>) responseMap.get("shared_with"); | SharedWith sharedWith = SharedWith.parse(sharedWithMap.get("access")); |
freedomofme/Netease | app/src/main/java/com/hhxplaying/neteasedemo/netease/factory/RequestSingletonFactory.java | // Path: app/src/main/java/com/hhxplaying/neteasedemo/netease/config/ErrorCode.java
// public class ErrorCode {
// public static final String TAG = "ErrorCode";
// public static HashMap<Integer, String> errorCodeMap = new HashMap<>();
// static {
// errorCodeMap.put(0, "服务器无响应");
// errorCodeMap.put(-7, "网络超时,请检查您的网络");
// errorCodeMap.put(-1, "网络错误,请检查您的网络");
// errorCodeMap.put(-2, "服务器错误");
// errorCodeMap.put(-3, "非法参数");
// errorCodeMap.put(-8, "非法解析错误");
// errorCodeMap.put(-4, "解析异常");
// errorCodeMap.put(-5, "解析数字异常");
// errorCodeMap.put(-6, "授权异常");
// }
// }
| import android.content.Context;
import android.util.Log;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.NetworkError;
import com.android.volley.NetworkResponse;
import com.android.volley.NoConnectionError;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.ServerError;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.hhxplaying.neteasedemo.netease.config.ErrorCode;
import java.util.HashMap;
import java.util.Map; |
} catch (Exception e) {
e.printStackTrace();
}
}
class DefaultErrorListener implements Response.ErrorListener {
private Context contextHold;
public DefaultErrorListener(Context context) {
contextHold = context;
}
@Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
Log.d("RVA", "error:" + error);
int errorCode = 0;
if (error instanceof TimeoutError) {
errorCode = -7;
} else if (error instanceof NoConnectionError) {
errorCode = -1;
} else if (error instanceof AuthFailureError) {
errorCode = -6;
} else if (error instanceof ServerError) {
errorCode = 0;
} else if (error instanceof NetworkError) {
errorCode = -1;
} else if (error instanceof ParseError) {
errorCode = -8;
} | // Path: app/src/main/java/com/hhxplaying/neteasedemo/netease/config/ErrorCode.java
// public class ErrorCode {
// public static final String TAG = "ErrorCode";
// public static HashMap<Integer, String> errorCodeMap = new HashMap<>();
// static {
// errorCodeMap.put(0, "服务器无响应");
// errorCodeMap.put(-7, "网络超时,请检查您的网络");
// errorCodeMap.put(-1, "网络错误,请检查您的网络");
// errorCodeMap.put(-2, "服务器错误");
// errorCodeMap.put(-3, "非法参数");
// errorCodeMap.put(-8, "非法解析错误");
// errorCodeMap.put(-4, "解析异常");
// errorCodeMap.put(-5, "解析数字异常");
// errorCodeMap.put(-6, "授权异常");
// }
// }
// Path: app/src/main/java/com/hhxplaying/neteasedemo/netease/factory/RequestSingletonFactory.java
import android.content.Context;
import android.util.Log;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.NetworkError;
import com.android.volley.NetworkResponse;
import com.android.volley.NoConnectionError;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.ServerError;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.hhxplaying.neteasedemo.netease.config.ErrorCode;
import java.util.HashMap;
import java.util.Map;
} catch (Exception e) {
e.printStackTrace();
}
}
class DefaultErrorListener implements Response.ErrorListener {
private Context contextHold;
public DefaultErrorListener(Context context) {
contextHold = context;
}
@Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
Log.d("RVA", "error:" + error);
int errorCode = 0;
if (error instanceof TimeoutError) {
errorCode = -7;
} else if (error instanceof NoConnectionError) {
errorCode = -1;
} else if (error instanceof AuthFailureError) {
errorCode = -6;
} else if (error instanceof ServerError) {
errorCode = 0;
} else if (error instanceof NetworkError) {
errorCode = -1;
} else if (error instanceof ParseError) {
errorCode = -8;
} | Toast.makeText(contextHold, ErrorCode.errorCodeMap.get(errorCode), Toast.LENGTH_SHORT).show(); |
freedomofme/Netease | app/src/main/java/com/hhxplaying/neteasedemo/netease/MyApplication.java | // Path: app/src/main/java/com/hhxplaying/neteasedemo/netease/util/ScreenUtil.java
// public class ScreenUtil
// {
// static DisplayMetrics dm = new DisplayMetrics();
//
// private static void setDisplayMetrics(Activity activity)
// {
// activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
// }
//
// public static int getWidth(Activity activity)
// {
// setDisplayMetrics(activity);
// return dm.widthPixels;
// }
//
// public static int getHeight(Activity activity)
// {
// setDisplayMetrics(activity);
// return dm.heightPixels;
// }
//
// public static int px2dp(float pxValue, float scale)
// {
// return (int) (pxValue / scale + 0.5f);
// }
//
// public static int px2dp(float pxValue)
// {
// return (int) (pxValue / dm.scaledDensity + 0.5f);
// }
//
// public static int dp2px(Activity activity, float dp)
// {
// setDisplayMetrics(activity);
// return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
// activity.getResources().getDisplayMetrics());
// }
//
// public static int getSW(Activity activity)
// {
// setDisplayMetrics(activity);
// return px2dp(dm.widthPixels, dm.scaledDensity);
// }
//
// public static int getWidth(Application application) {
// ContextWrapper ctx=new ContextWrapper(application);
// WindowManager wm = (WindowManager)ctx.getSystemService(Context.WINDOW_SERVICE);
// Display display = wm.getDefaultDisplay();
//
// return display.getWidth();
// }
//
// public static int getHeight(Application application) {
// ContextWrapper ctx=new ContextWrapper(application);
// WindowManager wm = (WindowManager)ctx.getSystemService(Context.WINDOW_SERVICE);
// Display display = wm.getDefaultDisplay();
//
// return display.getHeight();
// }
//
// private static void setDisplayMetrics(Context context)
// {
// dm = context.getResources().getDisplayMetrics();
// }
//
// public static int dp2px(Context context, float dp)
// {
// setDisplayMetrics(context);
// return (int)(dm.density * dp);
// }
//
// public static float getDensity(Context context) {
// setDisplayMetrics(context);
// return (int)(dm.density);
// }
//
// }
| import android.app.Application;
import com.android.volley.VolleyLog;
import com.hhxplaying.neteasedemo.netease.util.ScreenUtil; | package com.hhxplaying.neteasedemo.netease;
/**
* Created by HHX on 15/9/12.
*/
public class MyApplication extends Application {
public static int width = 0;
public static int height = 0;
public static float density = 0;
public void onCreate() {
super.onCreate(); | // Path: app/src/main/java/com/hhxplaying/neteasedemo/netease/util/ScreenUtil.java
// public class ScreenUtil
// {
// static DisplayMetrics dm = new DisplayMetrics();
//
// private static void setDisplayMetrics(Activity activity)
// {
// activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
// }
//
// public static int getWidth(Activity activity)
// {
// setDisplayMetrics(activity);
// return dm.widthPixels;
// }
//
// public static int getHeight(Activity activity)
// {
// setDisplayMetrics(activity);
// return dm.heightPixels;
// }
//
// public static int px2dp(float pxValue, float scale)
// {
// return (int) (pxValue / scale + 0.5f);
// }
//
// public static int px2dp(float pxValue)
// {
// return (int) (pxValue / dm.scaledDensity + 0.5f);
// }
//
// public static int dp2px(Activity activity, float dp)
// {
// setDisplayMetrics(activity);
// return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
// activity.getResources().getDisplayMetrics());
// }
//
// public static int getSW(Activity activity)
// {
// setDisplayMetrics(activity);
// return px2dp(dm.widthPixels, dm.scaledDensity);
// }
//
// public static int getWidth(Application application) {
// ContextWrapper ctx=new ContextWrapper(application);
// WindowManager wm = (WindowManager)ctx.getSystemService(Context.WINDOW_SERVICE);
// Display display = wm.getDefaultDisplay();
//
// return display.getWidth();
// }
//
// public static int getHeight(Application application) {
// ContextWrapper ctx=new ContextWrapper(application);
// WindowManager wm = (WindowManager)ctx.getSystemService(Context.WINDOW_SERVICE);
// Display display = wm.getDefaultDisplay();
//
// return display.getHeight();
// }
//
// private static void setDisplayMetrics(Context context)
// {
// dm = context.getResources().getDisplayMetrics();
// }
//
// public static int dp2px(Context context, float dp)
// {
// setDisplayMetrics(context);
// return (int)(dm.density * dp);
// }
//
// public static float getDensity(Context context) {
// setDisplayMetrics(context);
// return (int)(dm.density);
// }
//
// }
// Path: app/src/main/java/com/hhxplaying/neteasedemo/netease/MyApplication.java
import android.app.Application;
import com.android.volley.VolleyLog;
import com.hhxplaying.neteasedemo.netease.util.ScreenUtil;
package com.hhxplaying.neteasedemo.netease;
/**
* Created by HHX on 15/9/12.
*/
public class MyApplication extends Application {
public static int width = 0;
public static int height = 0;
public static float density = 0;
public void onCreate() {
super.onCreate(); | width = ScreenUtil.getWidth(this); |
freedomofme/Netease | app/src/main/java/com/hhxplaying/neteasedemo/netease/util/URLImageParser.java | // Path: app/src/main/java/com/hhxplaying/neteasedemo/netease/MyApplication.java
// public class MyApplication extends Application {
// public static int width = 0;
// public static int height = 0;
// public static float density = 0;
// public void onCreate() {
// super.onCreate();
// width = ScreenUtil.getWidth(this);
// height = ScreenUtil.getHeight(this);
// density = ScreenUtil.getDensity(this);
// System.out.println(width);
// System.out.println(height);
// System.out.println(density);
//
// VolleyLog.DEBUG = true;
// }
//
// }
| import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.text.Html;
import android.util.Log;
import android.widget.TextView;
import com.hhxplaying.neteasedemo.netease.MyApplication;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection; | package com.hhxplaying.neteasedemo.netease.util;
/**
* Created by netease on 16/2/18.
*/
public class URLImageParser implements Html.ImageGetter {
Context c;
TextView container;
/***
* Construct the URLImageParser which will execute AsyncTask and refresh the container
* @param t
* @param c
*/
public URLImageParser(TextView t, Context c) {
this.c = c;
this.container = t;
}
@Override
public Drawable getDrawable(String source) {
URLDrawable urlDrawable = new URLDrawable();
// get the actual source
ImageGetterAsyncTask asyncTask =
new ImageGetterAsyncTask( urlDrawable);
asyncTask.execute(source);
// return reference to URLDrawable where I will change with actual image from
// the src tag
return urlDrawable;
}
public class ImageGetterAsyncTask extends AsyncTask<String, Void, Drawable> {
URLDrawable urlDrawable;
public ImageGetterAsyncTask(URLDrawable d) {
this.urlDrawable = d;
}
@Override
protected Drawable doInBackground(String... params) {
String source = params[0];
return fetchDrawable(source);
}
@Override
protected void onPostExecute(Drawable result) {
// set the correct bound according to the result from HTTP call
Log.i("RVA","height"+result.getIntrinsicHeight());
Log.i("RVA", "wight" + result.getIntrinsicWidth());
//设置图片显示占据的高度 | // Path: app/src/main/java/com/hhxplaying/neteasedemo/netease/MyApplication.java
// public class MyApplication extends Application {
// public static int width = 0;
// public static int height = 0;
// public static float density = 0;
// public void onCreate() {
// super.onCreate();
// width = ScreenUtil.getWidth(this);
// height = ScreenUtil.getHeight(this);
// density = ScreenUtil.getDensity(this);
// System.out.println(width);
// System.out.println(height);
// System.out.println(density);
//
// VolleyLog.DEBUG = true;
// }
//
// }
// Path: app/src/main/java/com/hhxplaying/neteasedemo/netease/util/URLImageParser.java
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.text.Html;
import android.util.Log;
import android.widget.TextView;
import com.hhxplaying.neteasedemo.netease.MyApplication;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
package com.hhxplaying.neteasedemo.netease.util;
/**
* Created by netease on 16/2/18.
*/
public class URLImageParser implements Html.ImageGetter {
Context c;
TextView container;
/***
* Construct the URLImageParser which will execute AsyncTask and refresh the container
* @param t
* @param c
*/
public URLImageParser(TextView t, Context c) {
this.c = c;
this.container = t;
}
@Override
public Drawable getDrawable(String source) {
URLDrawable urlDrawable = new URLDrawable();
// get the actual source
ImageGetterAsyncTask asyncTask =
new ImageGetterAsyncTask( urlDrawable);
asyncTask.execute(source);
// return reference to URLDrawable where I will change with actual image from
// the src tag
return urlDrawable;
}
public class ImageGetterAsyncTask extends AsyncTask<String, Void, Drawable> {
URLDrawable urlDrawable;
public ImageGetterAsyncTask(URLDrawable d) {
this.urlDrawable = d;
}
@Override
protected Drawable doInBackground(String... params) {
String source = params[0];
return fetchDrawable(source);
}
@Override
protected void onPostExecute(Drawable result) {
// set the correct bound according to the result from HTTP call
Log.i("RVA","height"+result.getIntrinsicHeight());
Log.i("RVA", "wight" + result.getIntrinsicWidth());
//设置图片显示占据的高度 | int imageWight = MyApplication.width; |
rdoeffinger/Dictionary | src/com/hughes/android/dictionary/IsoUtils.java | // Path: src/com/hughes/android/dictionary/DictionaryInfo.java
// public static final class IndexInfo implements Serializable {
// private static final long serialVersionUID = 6524751236198309438L;
//
// static final int NUM_CSV_FIELDS = 3;
//
// public final String shortName; // Often LangISO.
// final int allTokenCount;
// public final int mainTokenCount;
//
// public IndexInfo(String shortName, int allTokenCount, int mainTokenCount) {
// this.shortName = shortName;
// this.allTokenCount = allTokenCount;
// this.mainTokenCount = mainTokenCount;
// }
//
// void append(StringBuilder result) {
// result.append(shortName);
// result.append("\t").append(allTokenCount);
// result.append("\t").append(mainTokenCount);
// }
//
// public IndexInfo(final String[] fields, int i) {
// shortName = fields[i++];
// allTokenCount = Integer.parseInt(fields[i++]);
// mainTokenCount = Integer.parseInt(fields[i++]);
// }
// }
//
// Path: src/com/hughes/android/dictionary/engine/Language.java
// public static final class LanguageResources {
// final String englishName;
// public final int nameId;
// public final int flagId;
//
// public LanguageResources(final String englishName, int nameId, int flagId) {
// this.englishName = englishName;
// this.nameId = nameId;
// this.flagId = flagId;
// }
//
// public LanguageResources(final String englishName, int nameId) {
// this(englishName, nameId, 0);
// }
// }
| import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import android.content.Context;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import com.hughes.android.dictionary.DictionaryInfo.IndexInfo;
import com.hughes.android.dictionary.engine.Language.LanguageResources; | // Copyright 2011 Google Inc. All Rights Reserved.
// Copyright 2017 Reimar Döffinger. All Rights Reserved.
//
// 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.hughes.android.dictionary;
public enum IsoUtils {
INSTANCE;
// Useful:
// http://www.loc.gov/standards/iso639-2/php/code_list.php | // Path: src/com/hughes/android/dictionary/DictionaryInfo.java
// public static final class IndexInfo implements Serializable {
// private static final long serialVersionUID = 6524751236198309438L;
//
// static final int NUM_CSV_FIELDS = 3;
//
// public final String shortName; // Often LangISO.
// final int allTokenCount;
// public final int mainTokenCount;
//
// public IndexInfo(String shortName, int allTokenCount, int mainTokenCount) {
// this.shortName = shortName;
// this.allTokenCount = allTokenCount;
// this.mainTokenCount = mainTokenCount;
// }
//
// void append(StringBuilder result) {
// result.append(shortName);
// result.append("\t").append(allTokenCount);
// result.append("\t").append(mainTokenCount);
// }
//
// public IndexInfo(final String[] fields, int i) {
// shortName = fields[i++];
// allTokenCount = Integer.parseInt(fields[i++]);
// mainTokenCount = Integer.parseInt(fields[i++]);
// }
// }
//
// Path: src/com/hughes/android/dictionary/engine/Language.java
// public static final class LanguageResources {
// final String englishName;
// public final int nameId;
// public final int flagId;
//
// public LanguageResources(final String englishName, int nameId, int flagId) {
// this.englishName = englishName;
// this.nameId = nameId;
// this.flagId = flagId;
// }
//
// public LanguageResources(final String englishName, int nameId) {
// this(englishName, nameId, 0);
// }
// }
// Path: src/com/hughes/android/dictionary/IsoUtils.java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import android.content.Context;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import com.hughes.android.dictionary.DictionaryInfo.IndexInfo;
import com.hughes.android.dictionary.engine.Language.LanguageResources;
// Copyright 2011 Google Inc. All Rights Reserved.
// Copyright 2017 Reimar Döffinger. All Rights Reserved.
//
// 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.hughes.android.dictionary;
public enum IsoUtils {
INSTANCE;
// Useful:
// http://www.loc.gov/standards/iso639-2/php/code_list.php | private final Map<String, LanguageResources> isoCodeToResources = new HashMap<>(); |
rdoeffinger/Dictionary | src/com/hughes/android/dictionary/IsoUtils.java | // Path: src/com/hughes/android/dictionary/DictionaryInfo.java
// public static final class IndexInfo implements Serializable {
// private static final long serialVersionUID = 6524751236198309438L;
//
// static final int NUM_CSV_FIELDS = 3;
//
// public final String shortName; // Often LangISO.
// final int allTokenCount;
// public final int mainTokenCount;
//
// public IndexInfo(String shortName, int allTokenCount, int mainTokenCount) {
// this.shortName = shortName;
// this.allTokenCount = allTokenCount;
// this.mainTokenCount = mainTokenCount;
// }
//
// void append(StringBuilder result) {
// result.append(shortName);
// result.append("\t").append(allTokenCount);
// result.append("\t").append(mainTokenCount);
// }
//
// public IndexInfo(final String[] fields, int i) {
// shortName = fields[i++];
// allTokenCount = Integer.parseInt(fields[i++]);
// mainTokenCount = Integer.parseInt(fields[i++]);
// }
// }
//
// Path: src/com/hughes/android/dictionary/engine/Language.java
// public static final class LanguageResources {
// final String englishName;
// public final int nameId;
// public final int flagId;
//
// public LanguageResources(final String englishName, int nameId, int flagId) {
// this.englishName = englishName;
// this.nameId = nameId;
// this.flagId = flagId;
// }
//
// public LanguageResources(final String englishName, int nameId) {
// this(englishName, nameId, 0);
// }
// }
| import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import android.content.Context;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import com.hughes.android.dictionary.DictionaryInfo.IndexInfo;
import com.hughes.android.dictionary.engine.Language.LanguageResources; | isoCodeToResources.put("TA", new LanguageResources("Tamil", R.string.TA));
isoCodeToResources.put("SH", new LanguageResources("Serbo-Croatian", R.string.SH));
isoCodeToResources.put("SD", new LanguageResources("Sindhi", R.string.SD));
// Hack to allow lower-case ISO codes to work:
for (final String isoCode : new ArrayList<>(isoCodeToResources.keySet())) {
isoCodeToResources.put(isoCode.toLowerCase(), isoCodeToResources.get(isoCode));
}
}
public int getFlagIdForIsoCode(final String isoCode) {
LanguageResources res = isoCodeToResources.get(isoCode);
return res == null ? 0 : res.flagId;
}
public String isoCodeToLocalizedLanguageName(final Context context, final String isoCode) {
String lang = new Locale(isoCode).getDisplayLanguage();
if (!lang.equals("") && !lang.equals(isoCode))
{
return lang;
}
final LanguageResources languageResources = isoCodeToResources.get(isoCode);
if (languageResources != null)
{
lang = context.getString(languageResources.nameId);
}
return lang;
}
public View createButton(final Context context, | // Path: src/com/hughes/android/dictionary/DictionaryInfo.java
// public static final class IndexInfo implements Serializable {
// private static final long serialVersionUID = 6524751236198309438L;
//
// static final int NUM_CSV_FIELDS = 3;
//
// public final String shortName; // Often LangISO.
// final int allTokenCount;
// public final int mainTokenCount;
//
// public IndexInfo(String shortName, int allTokenCount, int mainTokenCount) {
// this.shortName = shortName;
// this.allTokenCount = allTokenCount;
// this.mainTokenCount = mainTokenCount;
// }
//
// void append(StringBuilder result) {
// result.append(shortName);
// result.append("\t").append(allTokenCount);
// result.append("\t").append(mainTokenCount);
// }
//
// public IndexInfo(final String[] fields, int i) {
// shortName = fields[i++];
// allTokenCount = Integer.parseInt(fields[i++]);
// mainTokenCount = Integer.parseInt(fields[i++]);
// }
// }
//
// Path: src/com/hughes/android/dictionary/engine/Language.java
// public static final class LanguageResources {
// final String englishName;
// public final int nameId;
// public final int flagId;
//
// public LanguageResources(final String englishName, int nameId, int flagId) {
// this.englishName = englishName;
// this.nameId = nameId;
// this.flagId = flagId;
// }
//
// public LanguageResources(final String englishName, int nameId) {
// this(englishName, nameId, 0);
// }
// }
// Path: src/com/hughes/android/dictionary/IsoUtils.java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import android.content.Context;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import com.hughes.android.dictionary.DictionaryInfo.IndexInfo;
import com.hughes.android.dictionary.engine.Language.LanguageResources;
isoCodeToResources.put("TA", new LanguageResources("Tamil", R.string.TA));
isoCodeToResources.put("SH", new LanguageResources("Serbo-Croatian", R.string.SH));
isoCodeToResources.put("SD", new LanguageResources("Sindhi", R.string.SD));
// Hack to allow lower-case ISO codes to work:
for (final String isoCode : new ArrayList<>(isoCodeToResources.keySet())) {
isoCodeToResources.put(isoCode.toLowerCase(), isoCodeToResources.get(isoCode));
}
}
public int getFlagIdForIsoCode(final String isoCode) {
LanguageResources res = isoCodeToResources.get(isoCode);
return res == null ? 0 : res.flagId;
}
public String isoCodeToLocalizedLanguageName(final Context context, final String isoCode) {
String lang = new Locale(isoCode).getDisplayLanguage();
if (!lang.equals("") && !lang.equals(isoCode))
{
return lang;
}
final LanguageResources languageResources = isoCodeToResources.get(isoCode);
if (languageResources != null)
{
lang = context.getString(languageResources.nameId);
}
return lang;
}
public View createButton(final Context context, | final IndexInfo indexInfo, int size) { |
rdoeffinger/Dictionary | src/com/hughes/android/dictionary/engine/TokenRow.java | // Path: src/com/hughes/android/dictionary/engine/Index.java
// public static final class IndexEntry {
// public final String token;
// private final String normalizedToken;
// public final int startRow;
// final int numRows; // doesn't count the token row!
// public List<HtmlEntry> htmlEntries;
//
// public IndexEntry(final Index index, final String token, final String normalizedToken,
// final int startRow, final int numRows, final List<HtmlEntry> htmlEntries) {
// assert token.equals(token.trim());
// assert !token.isEmpty();
// this.token = token;
// this.normalizedToken = normalizedToken;
// this.startRow = startRow;
// this.numRows = numRows;
// this.htmlEntries = htmlEntries;
// }
//
// IndexEntry(final Index index, final DataInput raf) throws IOException {
// token = raf.readUTF();
// if (index.dict.dictFileVersion >= 7) {
// startRow = StringUtil.readVarInt(raf);
// numRows = StringUtil.readVarInt(raf);
// } else {
// startRow = raf.readInt();
// numRows = raf.readInt();
// }
// final boolean hasNormalizedForm = raf.readBoolean();
// normalizedToken = hasNormalizedForm ? raf.readUTF() : token;
// if (index.dict.dictFileVersion >= 7) {
// int size = StringUtil.readVarInt(raf);
// if (size == 0) {
// this.htmlEntries = Collections.emptyList();
// } else {
// final int[] htmlEntryIndices = new int[size];
// for (int i = 0; i < size; ++i) {
// htmlEntryIndices[i] = StringUtil.readVarInt(raf);
// }
// this.htmlEntries = new AbstractList<HtmlEntry>() {
// @Override
// public HtmlEntry get(int i) {
// return index.dict.htmlEntries.get(htmlEntryIndices[i]);
// }
//
// @Override
// public int size() {
// return htmlEntryIndices.length;
// }
// };
// }
// } else if (index.dict.dictFileVersion >= 6) {
// this.htmlEntries = CachingList.create(
// RAFList.create((DataInputBuffer)raf, index.dict.htmlEntryIndexSerializer,
// index.dict.dictFileVersion,
// index.dict.dictInfo + " htmlEntries: "), 1, false);
// } else {
// this.htmlEntries = Collections.emptyList();
// }
// }
//
// public void write(DataOutput raf) throws IOException {
// raf.writeUTF(token);
// StringUtil.writeVarInt(raf, startRow);
// StringUtil.writeVarInt(raf, numRows);
// final boolean hasNormalizedForm = !token.equals(normalizedToken);
// raf.writeBoolean(hasNormalizedForm);
// if (hasNormalizedForm) {
// raf.writeUTF(normalizedToken);
// }
// StringUtil.writeVarInt(raf, htmlEntries.size());
// for (HtmlEntry e : htmlEntries)
// StringUtil.writeVarInt(raf, e.index());
// }
//
// public String toString() {
// return String.format("%s@%d(%d)", token, startRow, numRows);
// }
//
// String normalizedToken() {
// return normalizedToken;
// }
// }
| import java.io.DataInput;
import java.io.IOException;
import java.io.PrintStream;
import java.util.List;
import java.util.regex.Pattern;
import com.hughes.android.dictionary.engine.Index.IndexEntry;
import com.ibm.icu.text.Transliterator; | // Copyright 2011 Google Inc. All Rights Reserved.
//
// 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.hughes.android.dictionary.engine;
public class TokenRow extends RowBase {
public final boolean hasMainEntry;
TokenRow(final DataInput raf, final int thisRowIndex, final Index index,
final boolean hasMainEntry, int extra) throws IOException {
super(raf, thisRowIndex, index, extra);
this.hasMainEntry = hasMainEntry;
}
TokenRow(final int referenceIndex, final int thisRowIndex, final Index index,
final boolean hasMainEntry) {
super(referenceIndex, thisRowIndex, index);
this.hasMainEntry = hasMainEntry;
}
public String toString() {
return getToken() + "@" + referenceIndex;
}
@Override
public TokenRow getTokenRow(final boolean search) {
return this;
}
@Override
public void setTokenRow(TokenRow tokenRow) {
throw new RuntimeException("Shouldn't be setting TokenRow's TokenRow!");
}
public String getToken() {
return getIndexEntry().token;
}
| // Path: src/com/hughes/android/dictionary/engine/Index.java
// public static final class IndexEntry {
// public final String token;
// private final String normalizedToken;
// public final int startRow;
// final int numRows; // doesn't count the token row!
// public List<HtmlEntry> htmlEntries;
//
// public IndexEntry(final Index index, final String token, final String normalizedToken,
// final int startRow, final int numRows, final List<HtmlEntry> htmlEntries) {
// assert token.equals(token.trim());
// assert !token.isEmpty();
// this.token = token;
// this.normalizedToken = normalizedToken;
// this.startRow = startRow;
// this.numRows = numRows;
// this.htmlEntries = htmlEntries;
// }
//
// IndexEntry(final Index index, final DataInput raf) throws IOException {
// token = raf.readUTF();
// if (index.dict.dictFileVersion >= 7) {
// startRow = StringUtil.readVarInt(raf);
// numRows = StringUtil.readVarInt(raf);
// } else {
// startRow = raf.readInt();
// numRows = raf.readInt();
// }
// final boolean hasNormalizedForm = raf.readBoolean();
// normalizedToken = hasNormalizedForm ? raf.readUTF() : token;
// if (index.dict.dictFileVersion >= 7) {
// int size = StringUtil.readVarInt(raf);
// if (size == 0) {
// this.htmlEntries = Collections.emptyList();
// } else {
// final int[] htmlEntryIndices = new int[size];
// for (int i = 0; i < size; ++i) {
// htmlEntryIndices[i] = StringUtil.readVarInt(raf);
// }
// this.htmlEntries = new AbstractList<HtmlEntry>() {
// @Override
// public HtmlEntry get(int i) {
// return index.dict.htmlEntries.get(htmlEntryIndices[i]);
// }
//
// @Override
// public int size() {
// return htmlEntryIndices.length;
// }
// };
// }
// } else if (index.dict.dictFileVersion >= 6) {
// this.htmlEntries = CachingList.create(
// RAFList.create((DataInputBuffer)raf, index.dict.htmlEntryIndexSerializer,
// index.dict.dictFileVersion,
// index.dict.dictInfo + " htmlEntries: "), 1, false);
// } else {
// this.htmlEntries = Collections.emptyList();
// }
// }
//
// public void write(DataOutput raf) throws IOException {
// raf.writeUTF(token);
// StringUtil.writeVarInt(raf, startRow);
// StringUtil.writeVarInt(raf, numRows);
// final boolean hasNormalizedForm = !token.equals(normalizedToken);
// raf.writeBoolean(hasNormalizedForm);
// if (hasNormalizedForm) {
// raf.writeUTF(normalizedToken);
// }
// StringUtil.writeVarInt(raf, htmlEntries.size());
// for (HtmlEntry e : htmlEntries)
// StringUtil.writeVarInt(raf, e.index());
// }
//
// public String toString() {
// return String.format("%s@%d(%d)", token, startRow, numRows);
// }
//
// String normalizedToken() {
// return normalizedToken;
// }
// }
// Path: src/com/hughes/android/dictionary/engine/TokenRow.java
import java.io.DataInput;
import java.io.IOException;
import java.io.PrintStream;
import java.util.List;
import java.util.regex.Pattern;
import com.hughes.android.dictionary.engine.Index.IndexEntry;
import com.ibm.icu.text.Transliterator;
// Copyright 2011 Google Inc. All Rights Reserved.
//
// 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.hughes.android.dictionary.engine;
public class TokenRow extends RowBase {
public final boolean hasMainEntry;
TokenRow(final DataInput raf, final int thisRowIndex, final Index index,
final boolean hasMainEntry, int extra) throws IOException {
super(raf, thisRowIndex, index, extra);
this.hasMainEntry = hasMainEntry;
}
TokenRow(final int referenceIndex, final int thisRowIndex, final Index index,
final boolean hasMainEntry) {
super(referenceIndex, thisRowIndex, index);
this.hasMainEntry = hasMainEntry;
}
public String toString() {
return getToken() + "@" + referenceIndex;
}
@Override
public TokenRow getTokenRow(final boolean search) {
return this;
}
@Override
public void setTokenRow(TokenRow tokenRow) {
throw new RuntimeException("Shouldn't be setting TokenRow's TokenRow!");
}
public String getToken() {
return getIndexEntry().token;
}
| public IndexEntry getIndexEntry() { |
rdoeffinger/Dictionary | src/com/hughes/android/dictionary/engine/Dictionary.java | // Path: src/com/hughes/android/dictionary/DictionaryInfo.java
// public class DictionaryInfo implements Serializable {
//
// private static final long serialVersionUID = -6850863377577700388L;
//
// public static final class IndexInfo implements Serializable {
// private static final long serialVersionUID = 6524751236198309438L;
//
// static final int NUM_CSV_FIELDS = 3;
//
// public final String shortName; // Often LangISO.
// final int allTokenCount;
// public final int mainTokenCount;
//
// public IndexInfo(String shortName, int allTokenCount, int mainTokenCount) {
// this.shortName = shortName;
// this.allTokenCount = allTokenCount;
// this.mainTokenCount = mainTokenCount;
// }
//
// void append(StringBuilder result) {
// result.append(shortName);
// result.append("\t").append(allTokenCount);
// result.append("\t").append(mainTokenCount);
// }
//
// public IndexInfo(final String[] fields, int i) {
// shortName = fields[i++];
// allTokenCount = Integer.parseInt(fields[i++]);
// mainTokenCount = Integer.parseInt(fields[i++]);
// }
// }
//
// // Stuff populated from the text file.
// public String uncompressedFilename; // used as a key throughout the program.
// public String downloadUrl;
// public long uncompressedBytes;
// public long zipBytes;
// public long creationMillis;
// public final ArrayList<IndexInfo> indexInfos = new ArrayList<>();
// public String dictInfo;
//
// public DictionaryInfo() {
// // Blank object.
// }
//
// public boolean isValid() {
// return !indexInfos.isEmpty();
// }
//
// public StringBuilder append(final StringBuilder result) {
// result.append(uncompressedFilename);
// result.append("\t").append(downloadUrl);
// result.append("\t").append(creationMillis);
// result.append("\t").append(uncompressedBytes);
// result.append("\t").append(zipBytes);
// result.append("\t").append(indexInfos.size());
// for (final IndexInfo indexInfo : indexInfos) {
// indexInfo.append(result.append("\t"));
// }
// result.append("\t").append(dictInfo.replace("\n", "\\\\n"));
// return result;
// }
//
// public DictionaryInfo(final String line) {
// final String[] fields = line.split("\t");
// int i = 0;
// uncompressedFilename = fields[i++];
// downloadUrl = fields[i++];
// creationMillis = Long.parseLong(fields[i++]);
// uncompressedBytes = Long.parseLong(fields[i++]);
// zipBytes = Long.parseLong(fields[i++]);
// final int size = Integer.parseInt(fields[i++]);
// indexInfos.ensureCapacity(size);
// for (int j = 0; j < size; ++j) {
// indexInfos.add(new IndexInfo(fields, i));
// i += IndexInfo.NUM_CSV_FIELDS;
// }
// dictInfo = fields[i++].replace("\\\\n", "\n");
// }
//
// @Override
// public String toString() {
// return uncompressedFilename;
// }
//
// }
| import com.hughes.util.DataInputBuffer;
import com.hughes.util.raf.RAFList;
import com.hughes.util.raf.RAFListSerializer;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.io.RandomAccessFile;
import java.nio.BufferUnderflowException;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import com.hughes.android.dictionary.DictionaryInfo;
import com.hughes.util.CachingList; | public void write(DataOutput raf, Index t) throws IOException {
t.write(raf);
}
}
final RAFListSerializer<HtmlEntry> htmlEntryIndexSerializer = new RAFListSerializer<HtmlEntry>() {
@Override
public void write(DataOutput raf, HtmlEntry t) {
assert false;
}
@Override
public HtmlEntry read(DataInput raf, int readIndex) throws IOException {
return htmlEntries.get(raf.readInt());
}
};
public void print(final PrintStream out) {
out.println("dictInfo=" + dictInfo);
for (final EntrySource entrySource : sources) {
out.printf("EntrySource: %s %d\n", entrySource.name, entrySource.numEntries);
}
out.println();
for (final Index index : indices) {
out.printf("Index: %s %s\n", index.shortName, index.longName);
index.print(out);
out.println();
}
}
| // Path: src/com/hughes/android/dictionary/DictionaryInfo.java
// public class DictionaryInfo implements Serializable {
//
// private static final long serialVersionUID = -6850863377577700388L;
//
// public static final class IndexInfo implements Serializable {
// private static final long serialVersionUID = 6524751236198309438L;
//
// static final int NUM_CSV_FIELDS = 3;
//
// public final String shortName; // Often LangISO.
// final int allTokenCount;
// public final int mainTokenCount;
//
// public IndexInfo(String shortName, int allTokenCount, int mainTokenCount) {
// this.shortName = shortName;
// this.allTokenCount = allTokenCount;
// this.mainTokenCount = mainTokenCount;
// }
//
// void append(StringBuilder result) {
// result.append(shortName);
// result.append("\t").append(allTokenCount);
// result.append("\t").append(mainTokenCount);
// }
//
// public IndexInfo(final String[] fields, int i) {
// shortName = fields[i++];
// allTokenCount = Integer.parseInt(fields[i++]);
// mainTokenCount = Integer.parseInt(fields[i++]);
// }
// }
//
// // Stuff populated from the text file.
// public String uncompressedFilename; // used as a key throughout the program.
// public String downloadUrl;
// public long uncompressedBytes;
// public long zipBytes;
// public long creationMillis;
// public final ArrayList<IndexInfo> indexInfos = new ArrayList<>();
// public String dictInfo;
//
// public DictionaryInfo() {
// // Blank object.
// }
//
// public boolean isValid() {
// return !indexInfos.isEmpty();
// }
//
// public StringBuilder append(final StringBuilder result) {
// result.append(uncompressedFilename);
// result.append("\t").append(downloadUrl);
// result.append("\t").append(creationMillis);
// result.append("\t").append(uncompressedBytes);
// result.append("\t").append(zipBytes);
// result.append("\t").append(indexInfos.size());
// for (final IndexInfo indexInfo : indexInfos) {
// indexInfo.append(result.append("\t"));
// }
// result.append("\t").append(dictInfo.replace("\n", "\\\\n"));
// return result;
// }
//
// public DictionaryInfo(final String line) {
// final String[] fields = line.split("\t");
// int i = 0;
// uncompressedFilename = fields[i++];
// downloadUrl = fields[i++];
// creationMillis = Long.parseLong(fields[i++]);
// uncompressedBytes = Long.parseLong(fields[i++]);
// zipBytes = Long.parseLong(fields[i++]);
// final int size = Integer.parseInt(fields[i++]);
// indexInfos.ensureCapacity(size);
// for (int j = 0; j < size; ++j) {
// indexInfos.add(new IndexInfo(fields, i));
// i += IndexInfo.NUM_CSV_FIELDS;
// }
// dictInfo = fields[i++].replace("\\\\n", "\n");
// }
//
// @Override
// public String toString() {
// return uncompressedFilename;
// }
//
// }
// Path: src/com/hughes/android/dictionary/engine/Dictionary.java
import com.hughes.util.DataInputBuffer;
import com.hughes.util.raf.RAFList;
import com.hughes.util.raf.RAFListSerializer;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.io.RandomAccessFile;
import java.nio.BufferUnderflowException;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import com.hughes.android.dictionary.DictionaryInfo;
import com.hughes.util.CachingList;
public void write(DataOutput raf, Index t) throws IOException {
t.write(raf);
}
}
final RAFListSerializer<HtmlEntry> htmlEntryIndexSerializer = new RAFListSerializer<HtmlEntry>() {
@Override
public void write(DataOutput raf, HtmlEntry t) {
assert false;
}
@Override
public HtmlEntry read(DataInput raf, int readIndex) throws IOException {
return htmlEntries.get(raf.readInt());
}
};
public void print(final PrintStream out) {
out.println("dictInfo=" + dictInfo);
for (final EntrySource entrySource : sources) {
out.printf("EntrySource: %s %d\n", entrySource.name, entrySource.numEntries);
}
out.println();
for (final Index index : indices) {
out.printf("Index: %s %s\n", index.shortName, index.longName);
index.print(out);
out.println();
}
}
| public DictionaryInfo getDictionaryInfo() { |
rdoeffinger/Dictionary | src/com/hughes/android/dictionary/DictionaryManagerActivity.java | // Path: src/com/hughes/android/dictionary/DictionaryInfo.java
// public static final class IndexInfo implements Serializable {
// private static final long serialVersionUID = 6524751236198309438L;
//
// static final int NUM_CSV_FIELDS = 3;
//
// public final String shortName; // Often LangISO.
// final int allTokenCount;
// public final int mainTokenCount;
//
// public IndexInfo(String shortName, int allTokenCount, int mainTokenCount) {
// this.shortName = shortName;
// this.allTokenCount = allTokenCount;
// this.mainTokenCount = mainTokenCount;
// }
//
// void append(StringBuilder result) {
// result.append(shortName);
// result.append("\t").append(allTokenCount);
// result.append("\t").append(mainTokenCount);
// }
//
// public IndexInfo(final String[] fields, int i) {
// shortName = fields[i++];
// allTokenCount = Integer.parseInt(fields[i++]);
// mainTokenCount = Integer.parseInt(fields[i++]);
// }
// }
//
// Path: src/com/hughes/android/util/IntentLauncher.java
// public class IntentLauncher implements OnClickListener {
//
// private final Context context;
// private final Intent intent;
//
// public IntentLauncher(final Context context, final Intent intent) {
// this.context = context;
// this.intent = intent;
// }
//
// protected void onGo() {
// }
//
// private void go() {
// onGo();
// context.startActivity(intent);
// }
//
// @Override
// public void onClick(View v) {
// go();
// }
//
// }
| import android.Manifest;
import android.app.AlertDialog;
import android.app.DownloadManager;
import android.app.DownloadManager.Request;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.v4.provider.DocumentFile;
import android.support.v7.preference.PreferenceManager;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.SearchView.OnQueryTextListener;
import android.support.v7.widget.Toolbar;
import android.text.InputType;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import com.hughes.android.dictionary.DictionaryInfo.IndexInfo;
import com.hughes.android.util.IntentLauncher;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream; | final boolean updateAvailable = application.updateAvailable(dictionaryInfo);
final Button downloadButton = row.findViewById(R.id.downloadButton);
final DictionaryInfo downloadable = application.getDownloadable(dictionaryInfo.uncompressedFilename);
boolean broken = false;
if (!dictionaryInfo.isValid()) {
broken = true;
canLaunch = false;
}
if (downloadable != null && (!canLaunch || updateAvailable)) {
downloadButton
.setText(getString(
R.string.downloadButton,
downloadable.zipBytes / 1024.0 / 1024.0));
downloadButton.setMinWidth(application.languageButtonPixels * 3 / 2);
downloadButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
downloadDictionary(downloadable.downloadUrl, downloadable.zipBytes, downloadButton);
}
});
downloadButton.setVisibility(View.VISIBLE);
if (isDownloadActive(downloadable.downloadUrl, false))
downloadButton.setText("X");
} else {
downloadButton.setVisibility(View.GONE);
}
LinearLayout buttons = row.findViewById(R.id.dictionaryLauncherButtons);
| // Path: src/com/hughes/android/dictionary/DictionaryInfo.java
// public static final class IndexInfo implements Serializable {
// private static final long serialVersionUID = 6524751236198309438L;
//
// static final int NUM_CSV_FIELDS = 3;
//
// public final String shortName; // Often LangISO.
// final int allTokenCount;
// public final int mainTokenCount;
//
// public IndexInfo(String shortName, int allTokenCount, int mainTokenCount) {
// this.shortName = shortName;
// this.allTokenCount = allTokenCount;
// this.mainTokenCount = mainTokenCount;
// }
//
// void append(StringBuilder result) {
// result.append(shortName);
// result.append("\t").append(allTokenCount);
// result.append("\t").append(mainTokenCount);
// }
//
// public IndexInfo(final String[] fields, int i) {
// shortName = fields[i++];
// allTokenCount = Integer.parseInt(fields[i++]);
// mainTokenCount = Integer.parseInt(fields[i++]);
// }
// }
//
// Path: src/com/hughes/android/util/IntentLauncher.java
// public class IntentLauncher implements OnClickListener {
//
// private final Context context;
// private final Intent intent;
//
// public IntentLauncher(final Context context, final Intent intent) {
// this.context = context;
// this.intent = intent;
// }
//
// protected void onGo() {
// }
//
// private void go() {
// onGo();
// context.startActivity(intent);
// }
//
// @Override
// public void onClick(View v) {
// go();
// }
//
// }
// Path: src/com/hughes/android/dictionary/DictionaryManagerActivity.java
import android.Manifest;
import android.app.AlertDialog;
import android.app.DownloadManager;
import android.app.DownloadManager.Request;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.v4.provider.DocumentFile;
import android.support.v7.preference.PreferenceManager;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.SearchView.OnQueryTextListener;
import android.support.v7.widget.Toolbar;
import android.text.InputType;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import com.hughes.android.dictionary.DictionaryInfo.IndexInfo;
import com.hughes.android.util.IntentLauncher;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
final boolean updateAvailable = application.updateAvailable(dictionaryInfo);
final Button downloadButton = row.findViewById(R.id.downloadButton);
final DictionaryInfo downloadable = application.getDownloadable(dictionaryInfo.uncompressedFilename);
boolean broken = false;
if (!dictionaryInfo.isValid()) {
broken = true;
canLaunch = false;
}
if (downloadable != null && (!canLaunch || updateAvailable)) {
downloadButton
.setText(getString(
R.string.downloadButton,
downloadable.zipBytes / 1024.0 / 1024.0));
downloadButton.setMinWidth(application.languageButtonPixels * 3 / 2);
downloadButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
downloadDictionary(downloadable.downloadUrl, downloadable.zipBytes, downloadButton);
}
});
downloadButton.setVisibility(View.VISIBLE);
if (isDownloadActive(downloadable.downloadUrl, false))
downloadButton.setText("X");
} else {
downloadButton.setVisibility(View.GONE);
}
LinearLayout buttons = row.findViewById(R.id.dictionaryLauncherButtons);
| final List<IndexInfo> sortedIndexInfos = application |
rdoeffinger/Dictionary | src/com/hughes/android/dictionary/DictionaryManagerActivity.java | // Path: src/com/hughes/android/dictionary/DictionaryInfo.java
// public static final class IndexInfo implements Serializable {
// private static final long serialVersionUID = 6524751236198309438L;
//
// static final int NUM_CSV_FIELDS = 3;
//
// public final String shortName; // Often LangISO.
// final int allTokenCount;
// public final int mainTokenCount;
//
// public IndexInfo(String shortName, int allTokenCount, int mainTokenCount) {
// this.shortName = shortName;
// this.allTokenCount = allTokenCount;
// this.mainTokenCount = mainTokenCount;
// }
//
// void append(StringBuilder result) {
// result.append(shortName);
// result.append("\t").append(allTokenCount);
// result.append("\t").append(mainTokenCount);
// }
//
// public IndexInfo(final String[] fields, int i) {
// shortName = fields[i++];
// allTokenCount = Integer.parseInt(fields[i++]);
// mainTokenCount = Integer.parseInt(fields[i++]);
// }
// }
//
// Path: src/com/hughes/android/util/IntentLauncher.java
// public class IntentLauncher implements OnClickListener {
//
// private final Context context;
// private final Intent intent;
//
// public IntentLauncher(final Context context, final Intent intent) {
// this.context = context;
// this.intent = intent;
// }
//
// protected void onGo() {
// }
//
// private void go() {
// onGo();
// context.startActivity(intent);
// }
//
// @Override
// public void onClick(View v) {
// go();
// }
//
// }
| import android.Manifest;
import android.app.AlertDialog;
import android.app.DownloadManager;
import android.app.DownloadManager.Request;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.v4.provider.DocumentFile;
import android.support.v7.preference.PreferenceManager;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.SearchView.OnQueryTextListener;
import android.support.v7.widget.Toolbar;
import android.text.InputType;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import com.hughes.android.dictionary.DictionaryInfo.IndexInfo;
import com.hughes.android.util.IntentLauncher;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream; |
if (isDownloadActive(downloadable.downloadUrl, false))
downloadButton.setText("X");
} else {
downloadButton.setVisibility(View.GONE);
}
LinearLayout buttons = row.findViewById(R.id.dictionaryLauncherButtons);
final List<IndexInfo> sortedIndexInfos = application
.sortedIndexInfos(dictionaryInfo.indexInfos);
final StringBuilder builder = new StringBuilder();
if (updateAvailable) {
builder.append(getString(R.string.updateAvailable));
}
assert buttons.getChildCount() == 4;
for (int i = 0; i < 2; i++) {
final Button textButton = (Button)buttons.getChildAt(2*i);
final ImageButton imageButton = (ImageButton)buttons.getChildAt(2*i + 1);
if (i >= sortedIndexInfos.size()) {
textButton.setVisibility(View.GONE);
imageButton.setVisibility(View.GONE);
continue;
}
final IndexInfo indexInfo = sortedIndexInfos.get(i);
final View button = IsoUtils.INSTANCE.setupButton(textButton, imageButton,
indexInfo);
if (canLaunch) {
button.setOnClickListener( | // Path: src/com/hughes/android/dictionary/DictionaryInfo.java
// public static final class IndexInfo implements Serializable {
// private static final long serialVersionUID = 6524751236198309438L;
//
// static final int NUM_CSV_FIELDS = 3;
//
// public final String shortName; // Often LangISO.
// final int allTokenCount;
// public final int mainTokenCount;
//
// public IndexInfo(String shortName, int allTokenCount, int mainTokenCount) {
// this.shortName = shortName;
// this.allTokenCount = allTokenCount;
// this.mainTokenCount = mainTokenCount;
// }
//
// void append(StringBuilder result) {
// result.append(shortName);
// result.append("\t").append(allTokenCount);
// result.append("\t").append(mainTokenCount);
// }
//
// public IndexInfo(final String[] fields, int i) {
// shortName = fields[i++];
// allTokenCount = Integer.parseInt(fields[i++]);
// mainTokenCount = Integer.parseInt(fields[i++]);
// }
// }
//
// Path: src/com/hughes/android/util/IntentLauncher.java
// public class IntentLauncher implements OnClickListener {
//
// private final Context context;
// private final Intent intent;
//
// public IntentLauncher(final Context context, final Intent intent) {
// this.context = context;
// this.intent = intent;
// }
//
// protected void onGo() {
// }
//
// private void go() {
// onGo();
// context.startActivity(intent);
// }
//
// @Override
// public void onClick(View v) {
// go();
// }
//
// }
// Path: src/com/hughes/android/dictionary/DictionaryManagerActivity.java
import android.Manifest;
import android.app.AlertDialog;
import android.app.DownloadManager;
import android.app.DownloadManager.Request;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.v4.provider.DocumentFile;
import android.support.v7.preference.PreferenceManager;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.SearchView.OnQueryTextListener;
import android.support.v7.widget.Toolbar;
import android.text.InputType;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import com.hughes.android.dictionary.DictionaryInfo.IndexInfo;
import com.hughes.android.util.IntentLauncher;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
if (isDownloadActive(downloadable.downloadUrl, false))
downloadButton.setText("X");
} else {
downloadButton.setVisibility(View.GONE);
}
LinearLayout buttons = row.findViewById(R.id.dictionaryLauncherButtons);
final List<IndexInfo> sortedIndexInfos = application
.sortedIndexInfos(dictionaryInfo.indexInfos);
final StringBuilder builder = new StringBuilder();
if (updateAvailable) {
builder.append(getString(R.string.updateAvailable));
}
assert buttons.getChildCount() == 4;
for (int i = 0; i < 2; i++) {
final Button textButton = (Button)buttons.getChildAt(2*i);
final ImageButton imageButton = (ImageButton)buttons.getChildAt(2*i + 1);
if (i >= sortedIndexInfos.size()) {
textButton.setVisibility(View.GONE);
imageButton.setVisibility(View.GONE);
continue;
}
final IndexInfo indexInfo = sortedIndexInfos.get(i);
final View button = IsoUtils.INSTANCE.setupButton(textButton, imageButton,
indexInfo);
if (canLaunch) {
button.setOnClickListener( | new IntentLauncher(buttons.getContext(), |
sivaprasadreddy/jblogger | src/main/java/com/sivalabs/jblogger/services/TagService.java | // Path: src/main/java/com/sivalabs/jblogger/entities/Tag.java
// @Entity
// @Table(name = "TAGS")
// @Data
// public class Tag implements Serializable, Comparable<Tag>
// {
// private static final long serialVersionUID = 1L;
//
// @Id
// @SequenceGenerator(name="tag_id_generator", sequenceName="tag_id_seq", initialValue = 100, allocationSize=1)
// @GeneratedValue(generator = "tag_id_generator")
// private Long id;
//
// @Column(name = "label", unique=true, nullable = false, length = 150)
// private String label;
//
// @JsonIgnore
// @ManyToMany(mappedBy="tags")
// private List<Post> posts;
//
// @Override
// public int compareTo(Tag other)
// {
// return this.label.compareToIgnoreCase(other.label);
// }
//
// }
//
// Path: src/main/java/com/sivalabs/jblogger/exceptions/JBloggerException.java
// public class JBloggerException extends RuntimeException
// {
//
// private static final long serialVersionUID = 1L;
//
// public JBloggerException()
// {
// }
//
// public JBloggerException(String message)
// {
// super(message);
// }
//
// public JBloggerException(Throwable cause)
// {
// super(cause);
// }
//
// public JBloggerException(String message, Throwable cause)
// {
// super(message, cause);
// }
//
// }
//
// Path: src/main/java/com/sivalabs/jblogger/repositories/TagRepository.java
// @Repository
// public interface TagRepository extends JpaRepository<Tag, Long>
// {
//
// List<Tag> findByLabelLike(String query);
//
// Optional<Tag> findByLabel(String trim);
//
// @Query("SELECT t.id, t.label, COUNT(post_id) as count FROM Tag t JOIN t.posts p GROUP BY t.id")
// List<Object[]> getTagsWithCount();
//
// }
| import com.sivalabs.jblogger.entities.Tag;
import com.sivalabs.jblogger.exceptions.JBloggerException;
import com.sivalabs.jblogger.repositories.TagRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.TreeMap; | package com.sivalabs.jblogger.services;
@Service
@Transactional
public class TagService
{ | // Path: src/main/java/com/sivalabs/jblogger/entities/Tag.java
// @Entity
// @Table(name = "TAGS")
// @Data
// public class Tag implements Serializable, Comparable<Tag>
// {
// private static final long serialVersionUID = 1L;
//
// @Id
// @SequenceGenerator(name="tag_id_generator", sequenceName="tag_id_seq", initialValue = 100, allocationSize=1)
// @GeneratedValue(generator = "tag_id_generator")
// private Long id;
//
// @Column(name = "label", unique=true, nullable = false, length = 150)
// private String label;
//
// @JsonIgnore
// @ManyToMany(mappedBy="tags")
// private List<Post> posts;
//
// @Override
// public int compareTo(Tag other)
// {
// return this.label.compareToIgnoreCase(other.label);
// }
//
// }
//
// Path: src/main/java/com/sivalabs/jblogger/exceptions/JBloggerException.java
// public class JBloggerException extends RuntimeException
// {
//
// private static final long serialVersionUID = 1L;
//
// public JBloggerException()
// {
// }
//
// public JBloggerException(String message)
// {
// super(message);
// }
//
// public JBloggerException(Throwable cause)
// {
// super(cause);
// }
//
// public JBloggerException(String message, Throwable cause)
// {
// super(message, cause);
// }
//
// }
//
// Path: src/main/java/com/sivalabs/jblogger/repositories/TagRepository.java
// @Repository
// public interface TagRepository extends JpaRepository<Tag, Long>
// {
//
// List<Tag> findByLabelLike(String query);
//
// Optional<Tag> findByLabel(String trim);
//
// @Query("SELECT t.id, t.label, COUNT(post_id) as count FROM Tag t JOIN t.posts p GROUP BY t.id")
// List<Object[]> getTagsWithCount();
//
// }
// Path: src/main/java/com/sivalabs/jblogger/services/TagService.java
import com.sivalabs.jblogger.entities.Tag;
import com.sivalabs.jblogger.exceptions.JBloggerException;
import com.sivalabs.jblogger.repositories.TagRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.TreeMap;
package com.sivalabs.jblogger.services;
@Service
@Transactional
public class TagService
{ | private TagRepository tagRepository; |
sivaprasadreddy/jblogger | src/main/java/com/sivalabs/jblogger/services/TagService.java | // Path: src/main/java/com/sivalabs/jblogger/entities/Tag.java
// @Entity
// @Table(name = "TAGS")
// @Data
// public class Tag implements Serializable, Comparable<Tag>
// {
// private static final long serialVersionUID = 1L;
//
// @Id
// @SequenceGenerator(name="tag_id_generator", sequenceName="tag_id_seq", initialValue = 100, allocationSize=1)
// @GeneratedValue(generator = "tag_id_generator")
// private Long id;
//
// @Column(name = "label", unique=true, nullable = false, length = 150)
// private String label;
//
// @JsonIgnore
// @ManyToMany(mappedBy="tags")
// private List<Post> posts;
//
// @Override
// public int compareTo(Tag other)
// {
// return this.label.compareToIgnoreCase(other.label);
// }
//
// }
//
// Path: src/main/java/com/sivalabs/jblogger/exceptions/JBloggerException.java
// public class JBloggerException extends RuntimeException
// {
//
// private static final long serialVersionUID = 1L;
//
// public JBloggerException()
// {
// }
//
// public JBloggerException(String message)
// {
// super(message);
// }
//
// public JBloggerException(Throwable cause)
// {
// super(cause);
// }
//
// public JBloggerException(String message, Throwable cause)
// {
// super(message, cause);
// }
//
// }
//
// Path: src/main/java/com/sivalabs/jblogger/repositories/TagRepository.java
// @Repository
// public interface TagRepository extends JpaRepository<Tag, Long>
// {
//
// List<Tag> findByLabelLike(String query);
//
// Optional<Tag> findByLabel(String trim);
//
// @Query("SELECT t.id, t.label, COUNT(post_id) as count FROM Tag t JOIN t.posts p GROUP BY t.id")
// List<Object[]> getTagsWithCount();
//
// }
| import com.sivalabs.jblogger.entities.Tag;
import com.sivalabs.jblogger.exceptions.JBloggerException;
import com.sivalabs.jblogger.repositories.TagRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.TreeMap; | package com.sivalabs.jblogger.services;
@Service
@Transactional
public class TagService
{
private TagRepository tagRepository;
@Autowired
public TagService(TagRepository tagRepository) {
this.tagRepository = tagRepository;
}
| // Path: src/main/java/com/sivalabs/jblogger/entities/Tag.java
// @Entity
// @Table(name = "TAGS")
// @Data
// public class Tag implements Serializable, Comparable<Tag>
// {
// private static final long serialVersionUID = 1L;
//
// @Id
// @SequenceGenerator(name="tag_id_generator", sequenceName="tag_id_seq", initialValue = 100, allocationSize=1)
// @GeneratedValue(generator = "tag_id_generator")
// private Long id;
//
// @Column(name = "label", unique=true, nullable = false, length = 150)
// private String label;
//
// @JsonIgnore
// @ManyToMany(mappedBy="tags")
// private List<Post> posts;
//
// @Override
// public int compareTo(Tag other)
// {
// return this.label.compareToIgnoreCase(other.label);
// }
//
// }
//
// Path: src/main/java/com/sivalabs/jblogger/exceptions/JBloggerException.java
// public class JBloggerException extends RuntimeException
// {
//
// private static final long serialVersionUID = 1L;
//
// public JBloggerException()
// {
// }
//
// public JBloggerException(String message)
// {
// super(message);
// }
//
// public JBloggerException(Throwable cause)
// {
// super(cause);
// }
//
// public JBloggerException(String message, Throwable cause)
// {
// super(message, cause);
// }
//
// }
//
// Path: src/main/java/com/sivalabs/jblogger/repositories/TagRepository.java
// @Repository
// public interface TagRepository extends JpaRepository<Tag, Long>
// {
//
// List<Tag> findByLabelLike(String query);
//
// Optional<Tag> findByLabel(String trim);
//
// @Query("SELECT t.id, t.label, COUNT(post_id) as count FROM Tag t JOIN t.posts p GROUP BY t.id")
// List<Object[]> getTagsWithCount();
//
// }
// Path: src/main/java/com/sivalabs/jblogger/services/TagService.java
import com.sivalabs.jblogger.entities.Tag;
import com.sivalabs.jblogger.exceptions.JBloggerException;
import com.sivalabs.jblogger.repositories.TagRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.TreeMap;
package com.sivalabs.jblogger.services;
@Service
@Transactional
public class TagService
{
private TagRepository tagRepository;
@Autowired
public TagService(TagRepository tagRepository) {
this.tagRepository = tagRepository;
}
| public List<Tag> search(String query){ |
sivaprasadreddy/jblogger | src/main/java/com/sivalabs/jblogger/services/TagService.java | // Path: src/main/java/com/sivalabs/jblogger/entities/Tag.java
// @Entity
// @Table(name = "TAGS")
// @Data
// public class Tag implements Serializable, Comparable<Tag>
// {
// private static final long serialVersionUID = 1L;
//
// @Id
// @SequenceGenerator(name="tag_id_generator", sequenceName="tag_id_seq", initialValue = 100, allocationSize=1)
// @GeneratedValue(generator = "tag_id_generator")
// private Long id;
//
// @Column(name = "label", unique=true, nullable = false, length = 150)
// private String label;
//
// @JsonIgnore
// @ManyToMany(mappedBy="tags")
// private List<Post> posts;
//
// @Override
// public int compareTo(Tag other)
// {
// return this.label.compareToIgnoreCase(other.label);
// }
//
// }
//
// Path: src/main/java/com/sivalabs/jblogger/exceptions/JBloggerException.java
// public class JBloggerException extends RuntimeException
// {
//
// private static final long serialVersionUID = 1L;
//
// public JBloggerException()
// {
// }
//
// public JBloggerException(String message)
// {
// super(message);
// }
//
// public JBloggerException(Throwable cause)
// {
// super(cause);
// }
//
// public JBloggerException(String message, Throwable cause)
// {
// super(message, cause);
// }
//
// }
//
// Path: src/main/java/com/sivalabs/jblogger/repositories/TagRepository.java
// @Repository
// public interface TagRepository extends JpaRepository<Tag, Long>
// {
//
// List<Tag> findByLabelLike(String query);
//
// Optional<Tag> findByLabel(String trim);
//
// @Query("SELECT t.id, t.label, COUNT(post_id) as count FROM Tag t JOIN t.posts p GROUP BY t.id")
// List<Object[]> getTagsWithCount();
//
// }
| import com.sivalabs.jblogger.entities.Tag;
import com.sivalabs.jblogger.exceptions.JBloggerException;
import com.sivalabs.jblogger.repositories.TagRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.TreeMap; | package com.sivalabs.jblogger.services;
@Service
@Transactional
public class TagService
{
private TagRepository tagRepository;
@Autowired
public TagService(TagRepository tagRepository) {
this.tagRepository = tagRepository;
}
public List<Tag> search(String query){
return tagRepository.findByLabelLike(query+"%");
}
public Optional<Tag> findById(Long id){
return tagRepository.findById(id);
}
@Cacheable(value = "tags.item")
public Optional<Tag> findByLabel(String label){
return tagRepository.findByLabel(label.trim());
}
@CacheEvict(value = {"tags.counts", "tags.all"}, allEntries=true)
public Tag createTag(Tag tag){
if(findByLabel(tag.getLabel()).isPresent()){ | // Path: src/main/java/com/sivalabs/jblogger/entities/Tag.java
// @Entity
// @Table(name = "TAGS")
// @Data
// public class Tag implements Serializable, Comparable<Tag>
// {
// private static final long serialVersionUID = 1L;
//
// @Id
// @SequenceGenerator(name="tag_id_generator", sequenceName="tag_id_seq", initialValue = 100, allocationSize=1)
// @GeneratedValue(generator = "tag_id_generator")
// private Long id;
//
// @Column(name = "label", unique=true, nullable = false, length = 150)
// private String label;
//
// @JsonIgnore
// @ManyToMany(mappedBy="tags")
// private List<Post> posts;
//
// @Override
// public int compareTo(Tag other)
// {
// return this.label.compareToIgnoreCase(other.label);
// }
//
// }
//
// Path: src/main/java/com/sivalabs/jblogger/exceptions/JBloggerException.java
// public class JBloggerException extends RuntimeException
// {
//
// private static final long serialVersionUID = 1L;
//
// public JBloggerException()
// {
// }
//
// public JBloggerException(String message)
// {
// super(message);
// }
//
// public JBloggerException(Throwable cause)
// {
// super(cause);
// }
//
// public JBloggerException(String message, Throwable cause)
// {
// super(message, cause);
// }
//
// }
//
// Path: src/main/java/com/sivalabs/jblogger/repositories/TagRepository.java
// @Repository
// public interface TagRepository extends JpaRepository<Tag, Long>
// {
//
// List<Tag> findByLabelLike(String query);
//
// Optional<Tag> findByLabel(String trim);
//
// @Query("SELECT t.id, t.label, COUNT(post_id) as count FROM Tag t JOIN t.posts p GROUP BY t.id")
// List<Object[]> getTagsWithCount();
//
// }
// Path: src/main/java/com/sivalabs/jblogger/services/TagService.java
import com.sivalabs.jblogger.entities.Tag;
import com.sivalabs.jblogger.exceptions.JBloggerException;
import com.sivalabs.jblogger.repositories.TagRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.TreeMap;
package com.sivalabs.jblogger.services;
@Service
@Transactional
public class TagService
{
private TagRepository tagRepository;
@Autowired
public TagService(TagRepository tagRepository) {
this.tagRepository = tagRepository;
}
public List<Tag> search(String query){
return tagRepository.findByLabelLike(query+"%");
}
public Optional<Tag> findById(Long id){
return tagRepository.findById(id);
}
@Cacheable(value = "tags.item")
public Optional<Tag> findByLabel(String label){
return tagRepository.findByLabel(label.trim());
}
@CacheEvict(value = {"tags.counts", "tags.all"}, allEntries=true)
public Tag createTag(Tag tag){
if(findByLabel(tag.getLabel()).isPresent()){ | throw new JBloggerException("Tag ["+tag.getLabel()+"] already exists"); |
sivaprasadreddy/jblogger | src/main/java/com/sivalabs/jblogger/domain/BlogOverview.java | // Path: src/main/java/com/sivalabs/jblogger/entities/PageView.java
// @Entity
// @Table(name="pageviews")
// @Data
// public class PageView implements Serializable
// {
// private static final long serialVersionUID = 1L;
//
// @Id
// @SequenceGenerator(name="pageview_id_generator", sequenceName="pageview_id_seq", initialValue = 100, allocationSize=1)
// @GeneratedValue(generator = "pageview_id_generator")
// private Long id;
//
// private String url;
//
// private String referrer;
//
// @Column(name="visit_time")
// private LocalDateTime visitTime = LocalDateTime.now();
//
// @ManyToOne
// @JoinColumn(name="post_id")
// private Post post;
//
// }
//
// Path: src/main/java/com/sivalabs/jblogger/entities/Post.java
// @Entity
// @Table(name = "POSTS")
// @Data
// public class Post implements Serializable
// {
// private static final long serialVersionUID = 1L;
//
// @Id
// @SequenceGenerator(name="post_id_generator", sequenceName="post_id_seq", initialValue = 100, allocationSize=1)
// @GeneratedValue(generator = "post_id_generator")
// private Long id;
//
// @Column(name = "title", nullable = false, length = 150)
// @NotEmpty
// private String title;
//
// @Column(name = "url", length = 255)
// private String url;
//
// @Lob
// @Type(type = "org.hibernate.type.TextType")
// @Column(name = "content", nullable = false)
// @NotEmpty
// private String content;
//
// @Column(name = "short_desc", length=500)
// @NotEmpty
// private String shortDescription;
//
// @ManyToOne
// @JoinColumn(name = "created_by", nullable = false)
// private User createdBy;
//
// @Column(name = "created_on")
// private LocalDateTime createdOn = LocalDateTime.now();
//
// @Column(name = "updated_on")
// private LocalDateTime updatedOn;
//
// @Column(name = "view_count", columnDefinition="bigint default 0")
// private Long viewCount = 0L;
//
// @ManyToMany(cascade=CascadeType.MERGE)
// @JoinTable(
// name="post_tag",
// joinColumns={@JoinColumn(name="POST_ID", referencedColumnName="ID")},
// inverseJoinColumns={@JoinColumn(name="TAG_ID", referencedColumnName="ID")})
// private Set<Tag> tags;
//
// @OneToMany(mappedBy = "post", cascade = CascadeType.REMOVE)
// private List<Comment> comments = new ArrayList<>();
//
// public String getTagIdsAsString()
// {
// if(tags == null || tags.isEmpty()) return "";
//
// StringBuilder sb = new StringBuilder();
// for (Tag tag : tags) {
// sb.append(","+tag.getId());
// }
// return sb.substring(1);
// }
//
// public String getTagsAsString()
// {
// if(tags == null || tags.isEmpty()) return "";
//
// StringBuilder sb = new StringBuilder();
// for (Tag tag : tags) {
// sb.append(","+tag.getLabel());
// }
// return sb.substring(1);
// }
//
// public String[] getTagsAsStringArray()
// {
// if(tags == null || tags.isEmpty()) return new String[]{};
//
// String[] arr = new String[tags.size()];
// int i = 0;
// for (Tag tag : tags)
// {
// arr[i++] = tag.getLabel();
// }
//
// return arr;
// }
//
// public String[] getTagIdsAsStringArray()
// {
// if(tags == null || tags.isEmpty()) return new String[]{};
//
// String[] arr = new String[tags.size()];
// int i = 0;
// for (Tag tag : tags)
// {
// arr[i++] = ""+tag.getId();
// }
//
// return arr;
// }
//
// }
| import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.sivalabs.jblogger.entities.PageView;
import com.sivalabs.jblogger.entities.Post;
import lombok.Data; | package com.sivalabs.jblogger.domain;
@Data
public class BlogOverview
{
private long postsCount;
private long commentsCount;
private long todayViewCount;
private long yesterdayViewCount;
private long thisWeekViewCount;
private long thisMonthViewCount;
private long alltimeViewCount; | // Path: src/main/java/com/sivalabs/jblogger/entities/PageView.java
// @Entity
// @Table(name="pageviews")
// @Data
// public class PageView implements Serializable
// {
// private static final long serialVersionUID = 1L;
//
// @Id
// @SequenceGenerator(name="pageview_id_generator", sequenceName="pageview_id_seq", initialValue = 100, allocationSize=1)
// @GeneratedValue(generator = "pageview_id_generator")
// private Long id;
//
// private String url;
//
// private String referrer;
//
// @Column(name="visit_time")
// private LocalDateTime visitTime = LocalDateTime.now();
//
// @ManyToOne
// @JoinColumn(name="post_id")
// private Post post;
//
// }
//
// Path: src/main/java/com/sivalabs/jblogger/entities/Post.java
// @Entity
// @Table(name = "POSTS")
// @Data
// public class Post implements Serializable
// {
// private static final long serialVersionUID = 1L;
//
// @Id
// @SequenceGenerator(name="post_id_generator", sequenceName="post_id_seq", initialValue = 100, allocationSize=1)
// @GeneratedValue(generator = "post_id_generator")
// private Long id;
//
// @Column(name = "title", nullable = false, length = 150)
// @NotEmpty
// private String title;
//
// @Column(name = "url", length = 255)
// private String url;
//
// @Lob
// @Type(type = "org.hibernate.type.TextType")
// @Column(name = "content", nullable = false)
// @NotEmpty
// private String content;
//
// @Column(name = "short_desc", length=500)
// @NotEmpty
// private String shortDescription;
//
// @ManyToOne
// @JoinColumn(name = "created_by", nullable = false)
// private User createdBy;
//
// @Column(name = "created_on")
// private LocalDateTime createdOn = LocalDateTime.now();
//
// @Column(name = "updated_on")
// private LocalDateTime updatedOn;
//
// @Column(name = "view_count", columnDefinition="bigint default 0")
// private Long viewCount = 0L;
//
// @ManyToMany(cascade=CascadeType.MERGE)
// @JoinTable(
// name="post_tag",
// joinColumns={@JoinColumn(name="POST_ID", referencedColumnName="ID")},
// inverseJoinColumns={@JoinColumn(name="TAG_ID", referencedColumnName="ID")})
// private Set<Tag> tags;
//
// @OneToMany(mappedBy = "post", cascade = CascadeType.REMOVE)
// private List<Comment> comments = new ArrayList<>();
//
// public String getTagIdsAsString()
// {
// if(tags == null || tags.isEmpty()) return "";
//
// StringBuilder sb = new StringBuilder();
// for (Tag tag : tags) {
// sb.append(","+tag.getId());
// }
// return sb.substring(1);
// }
//
// public String getTagsAsString()
// {
// if(tags == null || tags.isEmpty()) return "";
//
// StringBuilder sb = new StringBuilder();
// for (Tag tag : tags) {
// sb.append(","+tag.getLabel());
// }
// return sb.substring(1);
// }
//
// public String[] getTagsAsStringArray()
// {
// if(tags == null || tags.isEmpty()) return new String[]{};
//
// String[] arr = new String[tags.size()];
// int i = 0;
// for (Tag tag : tags)
// {
// arr[i++] = tag.getLabel();
// }
//
// return arr;
// }
//
// public String[] getTagIdsAsStringArray()
// {
// if(tags == null || tags.isEmpty()) return new String[]{};
//
// String[] arr = new String[tags.size()];
// int i = 0;
// for (Tag tag : tags)
// {
// arr[i++] = ""+tag.getId();
// }
//
// return arr;
// }
//
// }
// Path: src/main/java/com/sivalabs/jblogger/domain/BlogOverview.java
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.sivalabs.jblogger.entities.PageView;
import com.sivalabs.jblogger.entities.Post;
import lombok.Data;
package com.sivalabs.jblogger.domain;
@Data
public class BlogOverview
{
private long postsCount;
private long commentsCount;
private long todayViewCount;
private long yesterdayViewCount;
private long thisWeekViewCount;
private long thisMonthViewCount;
private long alltimeViewCount; | private List<PageView> pageViews; |
sivaprasadreddy/jblogger | src/main/java/com/sivalabs/jblogger/domain/BlogOverview.java | // Path: src/main/java/com/sivalabs/jblogger/entities/PageView.java
// @Entity
// @Table(name="pageviews")
// @Data
// public class PageView implements Serializable
// {
// private static final long serialVersionUID = 1L;
//
// @Id
// @SequenceGenerator(name="pageview_id_generator", sequenceName="pageview_id_seq", initialValue = 100, allocationSize=1)
// @GeneratedValue(generator = "pageview_id_generator")
// private Long id;
//
// private String url;
//
// private String referrer;
//
// @Column(name="visit_time")
// private LocalDateTime visitTime = LocalDateTime.now();
//
// @ManyToOne
// @JoinColumn(name="post_id")
// private Post post;
//
// }
//
// Path: src/main/java/com/sivalabs/jblogger/entities/Post.java
// @Entity
// @Table(name = "POSTS")
// @Data
// public class Post implements Serializable
// {
// private static final long serialVersionUID = 1L;
//
// @Id
// @SequenceGenerator(name="post_id_generator", sequenceName="post_id_seq", initialValue = 100, allocationSize=1)
// @GeneratedValue(generator = "post_id_generator")
// private Long id;
//
// @Column(name = "title", nullable = false, length = 150)
// @NotEmpty
// private String title;
//
// @Column(name = "url", length = 255)
// private String url;
//
// @Lob
// @Type(type = "org.hibernate.type.TextType")
// @Column(name = "content", nullable = false)
// @NotEmpty
// private String content;
//
// @Column(name = "short_desc", length=500)
// @NotEmpty
// private String shortDescription;
//
// @ManyToOne
// @JoinColumn(name = "created_by", nullable = false)
// private User createdBy;
//
// @Column(name = "created_on")
// private LocalDateTime createdOn = LocalDateTime.now();
//
// @Column(name = "updated_on")
// private LocalDateTime updatedOn;
//
// @Column(name = "view_count", columnDefinition="bigint default 0")
// private Long viewCount = 0L;
//
// @ManyToMany(cascade=CascadeType.MERGE)
// @JoinTable(
// name="post_tag",
// joinColumns={@JoinColumn(name="POST_ID", referencedColumnName="ID")},
// inverseJoinColumns={@JoinColumn(name="TAG_ID", referencedColumnName="ID")})
// private Set<Tag> tags;
//
// @OneToMany(mappedBy = "post", cascade = CascadeType.REMOVE)
// private List<Comment> comments = new ArrayList<>();
//
// public String getTagIdsAsString()
// {
// if(tags == null || tags.isEmpty()) return "";
//
// StringBuilder sb = new StringBuilder();
// for (Tag tag : tags) {
// sb.append(","+tag.getId());
// }
// return sb.substring(1);
// }
//
// public String getTagsAsString()
// {
// if(tags == null || tags.isEmpty()) return "";
//
// StringBuilder sb = new StringBuilder();
// for (Tag tag : tags) {
// sb.append(","+tag.getLabel());
// }
// return sb.substring(1);
// }
//
// public String[] getTagsAsStringArray()
// {
// if(tags == null || tags.isEmpty()) return new String[]{};
//
// String[] arr = new String[tags.size()];
// int i = 0;
// for (Tag tag : tags)
// {
// arr[i++] = tag.getLabel();
// }
//
// return arr;
// }
//
// public String[] getTagIdsAsStringArray()
// {
// if(tags == null || tags.isEmpty()) return new String[]{};
//
// String[] arr = new String[tags.size()];
// int i = 0;
// for (Tag tag : tags)
// {
// arr[i++] = ""+tag.getId();
// }
//
// return arr;
// }
//
// }
| import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.sivalabs.jblogger.entities.PageView;
import com.sivalabs.jblogger.entities.Post;
import lombok.Data; | package com.sivalabs.jblogger.domain;
@Data
public class BlogOverview
{
private long postsCount;
private long commentsCount;
private long todayViewCount;
private long yesterdayViewCount;
private long thisWeekViewCount;
private long thisMonthViewCount;
private long alltimeViewCount;
private List<PageView> pageViews;
| // Path: src/main/java/com/sivalabs/jblogger/entities/PageView.java
// @Entity
// @Table(name="pageviews")
// @Data
// public class PageView implements Serializable
// {
// private static final long serialVersionUID = 1L;
//
// @Id
// @SequenceGenerator(name="pageview_id_generator", sequenceName="pageview_id_seq", initialValue = 100, allocationSize=1)
// @GeneratedValue(generator = "pageview_id_generator")
// private Long id;
//
// private String url;
//
// private String referrer;
//
// @Column(name="visit_time")
// private LocalDateTime visitTime = LocalDateTime.now();
//
// @ManyToOne
// @JoinColumn(name="post_id")
// private Post post;
//
// }
//
// Path: src/main/java/com/sivalabs/jblogger/entities/Post.java
// @Entity
// @Table(name = "POSTS")
// @Data
// public class Post implements Serializable
// {
// private static final long serialVersionUID = 1L;
//
// @Id
// @SequenceGenerator(name="post_id_generator", sequenceName="post_id_seq", initialValue = 100, allocationSize=1)
// @GeneratedValue(generator = "post_id_generator")
// private Long id;
//
// @Column(name = "title", nullable = false, length = 150)
// @NotEmpty
// private String title;
//
// @Column(name = "url", length = 255)
// private String url;
//
// @Lob
// @Type(type = "org.hibernate.type.TextType")
// @Column(name = "content", nullable = false)
// @NotEmpty
// private String content;
//
// @Column(name = "short_desc", length=500)
// @NotEmpty
// private String shortDescription;
//
// @ManyToOne
// @JoinColumn(name = "created_by", nullable = false)
// private User createdBy;
//
// @Column(name = "created_on")
// private LocalDateTime createdOn = LocalDateTime.now();
//
// @Column(name = "updated_on")
// private LocalDateTime updatedOn;
//
// @Column(name = "view_count", columnDefinition="bigint default 0")
// private Long viewCount = 0L;
//
// @ManyToMany(cascade=CascadeType.MERGE)
// @JoinTable(
// name="post_tag",
// joinColumns={@JoinColumn(name="POST_ID", referencedColumnName="ID")},
// inverseJoinColumns={@JoinColumn(name="TAG_ID", referencedColumnName="ID")})
// private Set<Tag> tags;
//
// @OneToMany(mappedBy = "post", cascade = CascadeType.REMOVE)
// private List<Comment> comments = new ArrayList<>();
//
// public String getTagIdsAsString()
// {
// if(tags == null || tags.isEmpty()) return "";
//
// StringBuilder sb = new StringBuilder();
// for (Tag tag : tags) {
// sb.append(","+tag.getId());
// }
// return sb.substring(1);
// }
//
// public String getTagsAsString()
// {
// if(tags == null || tags.isEmpty()) return "";
//
// StringBuilder sb = new StringBuilder();
// for (Tag tag : tags) {
// sb.append(","+tag.getLabel());
// }
// return sb.substring(1);
// }
//
// public String[] getTagsAsStringArray()
// {
// if(tags == null || tags.isEmpty()) return new String[]{};
//
// String[] arr = new String[tags.size()];
// int i = 0;
// for (Tag tag : tags)
// {
// arr[i++] = tag.getLabel();
// }
//
// return arr;
// }
//
// public String[] getTagIdsAsStringArray()
// {
// if(tags == null || tags.isEmpty()) return new String[]{};
//
// String[] arr = new String[tags.size()];
// int i = 0;
// for (Tag tag : tags)
// {
// arr[i++] = ""+tag.getId();
// }
//
// return arr;
// }
//
// }
// Path: src/main/java/com/sivalabs/jblogger/domain/BlogOverview.java
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.sivalabs.jblogger.entities.PageView;
import com.sivalabs.jblogger.entities.Post;
import lombok.Data;
package com.sivalabs.jblogger.domain;
@Data
public class BlogOverview
{
private long postsCount;
private long commentsCount;
private long todayViewCount;
private long yesterdayViewCount;
private long thisWeekViewCount;
private long thisMonthViewCount;
private long alltimeViewCount;
private List<PageView> pageViews;
| public Map<Post, Long> getPostViewCountMap() |
sivaprasadreddy/jblogger | src/main/java/com/sivalabs/jblogger/config/WebMvcConfig.java | // Path: src/main/java/com/sivalabs/jblogger/web/interceptors/WebRequestLogger.java
// @Component
// public class WebRequestLogger extends HandlerInterceptorAdapter
// {
// private static final String USER_CONTEXT_KEY = "UserContextKey";
// private Logger logger = LoggerFactory.getLogger(getClass());
//
// @Override
// public boolean preHandle(
// HttpServletRequest request,
// HttpServletResponse response,
// Object handler) throws Exception {
//
// String mdcUserContextKey = "["+request.getRemoteHost()+":"+request.getSession().getId()+"]";
// MDC.put(USER_CONTEXT_KEY, mdcUserContextKey);
//
// Calendar cal = Calendar.getInstance();
// String url = request.getRequestURI();
// String referrer = request.getHeader("referer");
// logger.debug("Incoming Request: "+cal.getTime());
// logger.debug("URL: "+url);
// logger.debug("Referrer: "+referrer);
// return true;
// }
//
// @Override
// public void postHandle(HttpServletRequest request,
// HttpServletResponse response,
// Object handler,
// ModelAndView modelAndView) throws Exception
// {
// super.postHandle(request, response, handler, modelAndView);
// MDC.remove(USER_CONTEXT_KEY);
// }
// }
| import com.sivalabs.jblogger.web.interceptors.WebRequestLogger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.validation.Validator;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.thymeleaf.extras.java8time.dialect.Java8TimeDialect;
import org.thymeleaf.extras.springsecurity5.dialect.SpringSecurityDialect; | package com.sivalabs.jblogger.config;
@Configuration
public class WebMvcConfig implements WebMvcConfigurer
{
@Autowired
private MessageSource messageSource;
@Autowired | // Path: src/main/java/com/sivalabs/jblogger/web/interceptors/WebRequestLogger.java
// @Component
// public class WebRequestLogger extends HandlerInterceptorAdapter
// {
// private static final String USER_CONTEXT_KEY = "UserContextKey";
// private Logger logger = LoggerFactory.getLogger(getClass());
//
// @Override
// public boolean preHandle(
// HttpServletRequest request,
// HttpServletResponse response,
// Object handler) throws Exception {
//
// String mdcUserContextKey = "["+request.getRemoteHost()+":"+request.getSession().getId()+"]";
// MDC.put(USER_CONTEXT_KEY, mdcUserContextKey);
//
// Calendar cal = Calendar.getInstance();
// String url = request.getRequestURI();
// String referrer = request.getHeader("referer");
// logger.debug("Incoming Request: "+cal.getTime());
// logger.debug("URL: "+url);
// logger.debug("Referrer: "+referrer);
// return true;
// }
//
// @Override
// public void postHandle(HttpServletRequest request,
// HttpServletResponse response,
// Object handler,
// ModelAndView modelAndView) throws Exception
// {
// super.postHandle(request, response, handler, modelAndView);
// MDC.remove(USER_CONTEXT_KEY);
// }
// }
// Path: src/main/java/com/sivalabs/jblogger/config/WebMvcConfig.java
import com.sivalabs.jblogger.web.interceptors.WebRequestLogger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.validation.Validator;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.thymeleaf.extras.java8time.dialect.Java8TimeDialect;
import org.thymeleaf.extras.springsecurity5.dialect.SpringSecurityDialect;
package com.sivalabs.jblogger.config;
@Configuration
public class WebMvcConfig implements WebMvcConfigurer
{
@Autowired
private MessageSource messageSource;
@Autowired | private WebRequestLogger webRequestLogger; |
sivaprasadreddy/jblogger | src/test/java/com/sivalabs/jblogger/security/SecurityUserDetailsServiceTest.java | // Path: src/main/java/com/sivalabs/jblogger/entities/User.java
// @Entity
// @Table(name="users")
// @Data
// public class User implements Serializable
// {
// private static final long serialVersionUID = 1L;
//
// @Id
// @SequenceGenerator(name="user_id_generator", sequenceName="user_id_seq", initialValue = 100, allocationSize=1)
// @GeneratedValue(generator = "user_id_generator")
// private Long id;
//
// @Column(nullable=false)
// @NotEmpty()
// private String name;
//
// @Column(nullable=false, unique=true)
// @NotEmpty
// @Email(message="{errors.invalid_email}")
// private String email;
//
// @Column(nullable=false)
// @NotEmpty
// @Size(min=4)
// private String password;
//
// @ManyToMany(cascade=CascadeType.MERGE)
// @JoinTable(
// name="user_role",
// joinColumns={@JoinColumn(name="USER_ID", referencedColumnName="ID")},
// inverseJoinColumns={@JoinColumn(name="ROLE_ID", referencedColumnName="ID")})
// private List<Role> roles = new ArrayList<>();
//
// }
//
// Path: src/main/java/com/sivalabs/jblogger/repositories/UserRepository.java
// @Repository
// public interface UserRepository extends JpaRepository<User, Long>
// {
// Optional<User> findByEmail(String email);
// }
| import com.sivalabs.jblogger.entities.User;
import com.sivalabs.jblogger.repositories.UserRepository;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import java.util.Optional;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.when; | package com.sivalabs.jblogger.security;
@ExtendWith(MockitoExtension.class)
class SecurityUserDetailsServiceTest {
@Mock | // Path: src/main/java/com/sivalabs/jblogger/entities/User.java
// @Entity
// @Table(name="users")
// @Data
// public class User implements Serializable
// {
// private static final long serialVersionUID = 1L;
//
// @Id
// @SequenceGenerator(name="user_id_generator", sequenceName="user_id_seq", initialValue = 100, allocationSize=1)
// @GeneratedValue(generator = "user_id_generator")
// private Long id;
//
// @Column(nullable=false)
// @NotEmpty()
// private String name;
//
// @Column(nullable=false, unique=true)
// @NotEmpty
// @Email(message="{errors.invalid_email}")
// private String email;
//
// @Column(nullable=false)
// @NotEmpty
// @Size(min=4)
// private String password;
//
// @ManyToMany(cascade=CascadeType.MERGE)
// @JoinTable(
// name="user_role",
// joinColumns={@JoinColumn(name="USER_ID", referencedColumnName="ID")},
// inverseJoinColumns={@JoinColumn(name="ROLE_ID", referencedColumnName="ID")})
// private List<Role> roles = new ArrayList<>();
//
// }
//
// Path: src/main/java/com/sivalabs/jblogger/repositories/UserRepository.java
// @Repository
// public interface UserRepository extends JpaRepository<User, Long>
// {
// Optional<User> findByEmail(String email);
// }
// Path: src/test/java/com/sivalabs/jblogger/security/SecurityUserDetailsServiceTest.java
import com.sivalabs.jblogger.entities.User;
import com.sivalabs.jblogger.repositories.UserRepository;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import java.util.Optional;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.when;
package com.sivalabs.jblogger.security;
@ExtendWith(MockitoExtension.class)
class SecurityUserDetailsServiceTest {
@Mock | UserRepository userRepository; |
sivaprasadreddy/jblogger | src/test/java/com/sivalabs/jblogger/security/SecurityUserDetailsServiceTest.java | // Path: src/main/java/com/sivalabs/jblogger/entities/User.java
// @Entity
// @Table(name="users")
// @Data
// public class User implements Serializable
// {
// private static final long serialVersionUID = 1L;
//
// @Id
// @SequenceGenerator(name="user_id_generator", sequenceName="user_id_seq", initialValue = 100, allocationSize=1)
// @GeneratedValue(generator = "user_id_generator")
// private Long id;
//
// @Column(nullable=false)
// @NotEmpty()
// private String name;
//
// @Column(nullable=false, unique=true)
// @NotEmpty
// @Email(message="{errors.invalid_email}")
// private String email;
//
// @Column(nullable=false)
// @NotEmpty
// @Size(min=4)
// private String password;
//
// @ManyToMany(cascade=CascadeType.MERGE)
// @JoinTable(
// name="user_role",
// joinColumns={@JoinColumn(name="USER_ID", referencedColumnName="ID")},
// inverseJoinColumns={@JoinColumn(name="ROLE_ID", referencedColumnName="ID")})
// private List<Role> roles = new ArrayList<>();
//
// }
//
// Path: src/main/java/com/sivalabs/jblogger/repositories/UserRepository.java
// @Repository
// public interface UserRepository extends JpaRepository<User, Long>
// {
// Optional<User> findByEmail(String email);
// }
| import com.sivalabs.jblogger.entities.User;
import com.sivalabs.jblogger.repositories.UserRepository;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import java.util.Optional;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.when; | package com.sivalabs.jblogger.security;
@ExtendWith(MockitoExtension.class)
class SecurityUserDetailsServiceTest {
@Mock
UserRepository userRepository;
@InjectMocks
SecurityUserDetailsService securityUserDetailsService;
@Test
void loadUserByUsername() throws Exception {
String email = "[email protected]"; | // Path: src/main/java/com/sivalabs/jblogger/entities/User.java
// @Entity
// @Table(name="users")
// @Data
// public class User implements Serializable
// {
// private static final long serialVersionUID = 1L;
//
// @Id
// @SequenceGenerator(name="user_id_generator", sequenceName="user_id_seq", initialValue = 100, allocationSize=1)
// @GeneratedValue(generator = "user_id_generator")
// private Long id;
//
// @Column(nullable=false)
// @NotEmpty()
// private String name;
//
// @Column(nullable=false, unique=true)
// @NotEmpty
// @Email(message="{errors.invalid_email}")
// private String email;
//
// @Column(nullable=false)
// @NotEmpty
// @Size(min=4)
// private String password;
//
// @ManyToMany(cascade=CascadeType.MERGE)
// @JoinTable(
// name="user_role",
// joinColumns={@JoinColumn(name="USER_ID", referencedColumnName="ID")},
// inverseJoinColumns={@JoinColumn(name="ROLE_ID", referencedColumnName="ID")})
// private List<Role> roles = new ArrayList<>();
//
// }
//
// Path: src/main/java/com/sivalabs/jblogger/repositories/UserRepository.java
// @Repository
// public interface UserRepository extends JpaRepository<User, Long>
// {
// Optional<User> findByEmail(String email);
// }
// Path: src/test/java/com/sivalabs/jblogger/security/SecurityUserDetailsServiceTest.java
import com.sivalabs.jblogger.entities.User;
import com.sivalabs.jblogger.repositories.UserRepository;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import java.util.Optional;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.when;
package com.sivalabs.jblogger.security;
@ExtendWith(MockitoExtension.class)
class SecurityUserDetailsServiceTest {
@Mock
UserRepository userRepository;
@InjectMocks
SecurityUserDetailsService securityUserDetailsService;
@Test
void loadUserByUsername() throws Exception {
String email = "[email protected]"; | final User domainUser = new User(); |
sivaprasadreddy/jblogger | src/main/java/com/sivalabs/jblogger/security/SecurityUserDetailsService.java | // Path: src/main/java/com/sivalabs/jblogger/repositories/UserRepository.java
// @Repository
// public interface UserRepository extends JpaRepository<User, Long>
// {
// Optional<User> findByEmail(String email);
// }
//
// Path: src/main/java/com/sivalabs/jblogger/entities/User.java
// @Entity
// @Table(name="users")
// @Data
// public class User implements Serializable
// {
// private static final long serialVersionUID = 1L;
//
// @Id
// @SequenceGenerator(name="user_id_generator", sequenceName="user_id_seq", initialValue = 100, allocationSize=1)
// @GeneratedValue(generator = "user_id_generator")
// private Long id;
//
// @Column(nullable=false)
// @NotEmpty()
// private String name;
//
// @Column(nullable=false, unique=true)
// @NotEmpty
// @Email(message="{errors.invalid_email}")
// private String email;
//
// @Column(nullable=false)
// @NotEmpty
// @Size(min=4)
// private String password;
//
// @ManyToMany(cascade=CascadeType.MERGE)
// @JoinTable(
// name="user_role",
// joinColumns={@JoinColumn(name="USER_ID", referencedColumnName="ID")},
// inverseJoinColumns={@JoinColumn(name="ROLE_ID", referencedColumnName="ID")})
// private List<Role> roles = new ArrayList<>();
//
// }
| import com.sivalabs.jblogger.repositories.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.sivalabs.jblogger.entities.User;
import java.util.Optional; | package com.sivalabs.jblogger.security;
@Service("userDetailsService")
@Transactional
public class SecurityUserDetailsService implements UserDetailsService
{ | // Path: src/main/java/com/sivalabs/jblogger/repositories/UserRepository.java
// @Repository
// public interface UserRepository extends JpaRepository<User, Long>
// {
// Optional<User> findByEmail(String email);
// }
//
// Path: src/main/java/com/sivalabs/jblogger/entities/User.java
// @Entity
// @Table(name="users")
// @Data
// public class User implements Serializable
// {
// private static final long serialVersionUID = 1L;
//
// @Id
// @SequenceGenerator(name="user_id_generator", sequenceName="user_id_seq", initialValue = 100, allocationSize=1)
// @GeneratedValue(generator = "user_id_generator")
// private Long id;
//
// @Column(nullable=false)
// @NotEmpty()
// private String name;
//
// @Column(nullable=false, unique=true)
// @NotEmpty
// @Email(message="{errors.invalid_email}")
// private String email;
//
// @Column(nullable=false)
// @NotEmpty
// @Size(min=4)
// private String password;
//
// @ManyToMany(cascade=CascadeType.MERGE)
// @JoinTable(
// name="user_role",
// joinColumns={@JoinColumn(name="USER_ID", referencedColumnName="ID")},
// inverseJoinColumns={@JoinColumn(name="ROLE_ID", referencedColumnName="ID")})
// private List<Role> roles = new ArrayList<>();
//
// }
// Path: src/main/java/com/sivalabs/jblogger/security/SecurityUserDetailsService.java
import com.sivalabs.jblogger.repositories.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.sivalabs.jblogger.entities.User;
import java.util.Optional;
package com.sivalabs.jblogger.security;
@Service("userDetailsService")
@Transactional
public class SecurityUserDetailsService implements UserDetailsService
{ | private UserRepository userRepository; |
sivaprasadreddy/jblogger | src/main/java/com/sivalabs/jblogger/security/SecurityUserDetailsService.java | // Path: src/main/java/com/sivalabs/jblogger/repositories/UserRepository.java
// @Repository
// public interface UserRepository extends JpaRepository<User, Long>
// {
// Optional<User> findByEmail(String email);
// }
//
// Path: src/main/java/com/sivalabs/jblogger/entities/User.java
// @Entity
// @Table(name="users")
// @Data
// public class User implements Serializable
// {
// private static final long serialVersionUID = 1L;
//
// @Id
// @SequenceGenerator(name="user_id_generator", sequenceName="user_id_seq", initialValue = 100, allocationSize=1)
// @GeneratedValue(generator = "user_id_generator")
// private Long id;
//
// @Column(nullable=false)
// @NotEmpty()
// private String name;
//
// @Column(nullable=false, unique=true)
// @NotEmpty
// @Email(message="{errors.invalid_email}")
// private String email;
//
// @Column(nullable=false)
// @NotEmpty
// @Size(min=4)
// private String password;
//
// @ManyToMany(cascade=CascadeType.MERGE)
// @JoinTable(
// name="user_role",
// joinColumns={@JoinColumn(name="USER_ID", referencedColumnName="ID")},
// inverseJoinColumns={@JoinColumn(name="ROLE_ID", referencedColumnName="ID")})
// private List<Role> roles = new ArrayList<>();
//
// }
| import com.sivalabs.jblogger.repositories.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.sivalabs.jblogger.entities.User;
import java.util.Optional; | package com.sivalabs.jblogger.security;
@Service("userDetailsService")
@Transactional
public class SecurityUserDetailsService implements UserDetailsService
{
private UserRepository userRepository;
@Autowired
public SecurityUserDetailsService(UserRepository userRepository) {
this.userRepository = userRepository;
}
@Override
public UserDetails loadUserByUsername(String userName) { | // Path: src/main/java/com/sivalabs/jblogger/repositories/UserRepository.java
// @Repository
// public interface UserRepository extends JpaRepository<User, Long>
// {
// Optional<User> findByEmail(String email);
// }
//
// Path: src/main/java/com/sivalabs/jblogger/entities/User.java
// @Entity
// @Table(name="users")
// @Data
// public class User implements Serializable
// {
// private static final long serialVersionUID = 1L;
//
// @Id
// @SequenceGenerator(name="user_id_generator", sequenceName="user_id_seq", initialValue = 100, allocationSize=1)
// @GeneratedValue(generator = "user_id_generator")
// private Long id;
//
// @Column(nullable=false)
// @NotEmpty()
// private String name;
//
// @Column(nullable=false, unique=true)
// @NotEmpty
// @Email(message="{errors.invalid_email}")
// private String email;
//
// @Column(nullable=false)
// @NotEmpty
// @Size(min=4)
// private String password;
//
// @ManyToMany(cascade=CascadeType.MERGE)
// @JoinTable(
// name="user_role",
// joinColumns={@JoinColumn(name="USER_ID", referencedColumnName="ID")},
// inverseJoinColumns={@JoinColumn(name="ROLE_ID", referencedColumnName="ID")})
// private List<Role> roles = new ArrayList<>();
//
// }
// Path: src/main/java/com/sivalabs/jblogger/security/SecurityUserDetailsService.java
import com.sivalabs.jblogger.repositories.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.sivalabs.jblogger.entities.User;
import java.util.Optional;
package com.sivalabs.jblogger.security;
@Service("userDetailsService")
@Transactional
public class SecurityUserDetailsService implements UserDetailsService
{
private UserRepository userRepository;
@Autowired
public SecurityUserDetailsService(UserRepository userRepository) {
this.userRepository = userRepository;
}
@Override
public UserDetails loadUserByUsername(String userName) { | Optional<User> user = userRepository.findByEmail(userName); |
sivaprasadreddy/jblogger | src/test/java/com/sivalabs/jblogger/security/AuthenticatedUserTest.java | // Path: src/main/java/com/sivalabs/jblogger/entities/Role.java
// @Entity
// @Table(name="roles")
// @Data
// public class Role implements Serializable
// {
// private static final long serialVersionUID = 1L;
//
// @Id
// @SequenceGenerator(name="role_id_generator", sequenceName="role_id_seq", initialValue = 100, allocationSize=1)
// @GeneratedValue(generator = "role_id_generator")
// private Long id;
//
// @Column(nullable=false, unique=true)
// @NotEmpty
// private String name;
//
// @ManyToMany(mappedBy="roles")
// private List<User> users;
//
// }
//
// Path: src/main/java/com/sivalabs/jblogger/entities/User.java
// @Entity
// @Table(name="users")
// @Data
// public class User implements Serializable
// {
// private static final long serialVersionUID = 1L;
//
// @Id
// @SequenceGenerator(name="user_id_generator", sequenceName="user_id_seq", initialValue = 100, allocationSize=1)
// @GeneratedValue(generator = "user_id_generator")
// private Long id;
//
// @Column(nullable=false)
// @NotEmpty()
// private String name;
//
// @Column(nullable=false, unique=true)
// @NotEmpty
// @Email(message="{errors.invalid_email}")
// private String email;
//
// @Column(nullable=false)
// @NotEmpty
// @Size(min=4)
// private String password;
//
// @ManyToMany(cascade=CascadeType.MERGE)
// @JoinTable(
// name="user_role",
// joinColumns={@JoinColumn(name="USER_ID", referencedColumnName="ID")},
// inverseJoinColumns={@JoinColumn(name="ROLE_ID", referencedColumnName="ID")})
// private List<Role> roles = new ArrayList<>();
//
// }
| import com.sivalabs.jblogger.entities.Role;
import com.sivalabs.jblogger.entities.User;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat; | package com.sivalabs.jblogger.security;
class AuthenticatedUserTest {
@Test
void hasNoAuthorities() { | // Path: src/main/java/com/sivalabs/jblogger/entities/Role.java
// @Entity
// @Table(name="roles")
// @Data
// public class Role implements Serializable
// {
// private static final long serialVersionUID = 1L;
//
// @Id
// @SequenceGenerator(name="role_id_generator", sequenceName="role_id_seq", initialValue = 100, allocationSize=1)
// @GeneratedValue(generator = "role_id_generator")
// private Long id;
//
// @Column(nullable=false, unique=true)
// @NotEmpty
// private String name;
//
// @ManyToMany(mappedBy="roles")
// private List<User> users;
//
// }
//
// Path: src/main/java/com/sivalabs/jblogger/entities/User.java
// @Entity
// @Table(name="users")
// @Data
// public class User implements Serializable
// {
// private static final long serialVersionUID = 1L;
//
// @Id
// @SequenceGenerator(name="user_id_generator", sequenceName="user_id_seq", initialValue = 100, allocationSize=1)
// @GeneratedValue(generator = "user_id_generator")
// private Long id;
//
// @Column(nullable=false)
// @NotEmpty()
// private String name;
//
// @Column(nullable=false, unique=true)
// @NotEmpty
// @Email(message="{errors.invalid_email}")
// private String email;
//
// @Column(nullable=false)
// @NotEmpty
// @Size(min=4)
// private String password;
//
// @ManyToMany(cascade=CascadeType.MERGE)
// @JoinTable(
// name="user_role",
// joinColumns={@JoinColumn(name="USER_ID", referencedColumnName="ID")},
// inverseJoinColumns={@JoinColumn(name="ROLE_ID", referencedColumnName="ID")})
// private List<Role> roles = new ArrayList<>();
//
// }
// Path: src/test/java/com/sivalabs/jblogger/security/AuthenticatedUserTest.java
import com.sivalabs.jblogger.entities.Role;
import com.sivalabs.jblogger.entities.User;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
package com.sivalabs.jblogger.security;
class AuthenticatedUserTest {
@Test
void hasNoAuthorities() { | User user = new User(); |
sivaprasadreddy/jblogger | src/test/java/com/sivalabs/jblogger/security/AuthenticatedUserTest.java | // Path: src/main/java/com/sivalabs/jblogger/entities/Role.java
// @Entity
// @Table(name="roles")
// @Data
// public class Role implements Serializable
// {
// private static final long serialVersionUID = 1L;
//
// @Id
// @SequenceGenerator(name="role_id_generator", sequenceName="role_id_seq", initialValue = 100, allocationSize=1)
// @GeneratedValue(generator = "role_id_generator")
// private Long id;
//
// @Column(nullable=false, unique=true)
// @NotEmpty
// private String name;
//
// @ManyToMany(mappedBy="roles")
// private List<User> users;
//
// }
//
// Path: src/main/java/com/sivalabs/jblogger/entities/User.java
// @Entity
// @Table(name="users")
// @Data
// public class User implements Serializable
// {
// private static final long serialVersionUID = 1L;
//
// @Id
// @SequenceGenerator(name="user_id_generator", sequenceName="user_id_seq", initialValue = 100, allocationSize=1)
// @GeneratedValue(generator = "user_id_generator")
// private Long id;
//
// @Column(nullable=false)
// @NotEmpty()
// private String name;
//
// @Column(nullable=false, unique=true)
// @NotEmpty
// @Email(message="{errors.invalid_email}")
// private String email;
//
// @Column(nullable=false)
// @NotEmpty
// @Size(min=4)
// private String password;
//
// @ManyToMany(cascade=CascadeType.MERGE)
// @JoinTable(
// name="user_role",
// joinColumns={@JoinColumn(name="USER_ID", referencedColumnName="ID")},
// inverseJoinColumns={@JoinColumn(name="ROLE_ID", referencedColumnName="ID")})
// private List<Role> roles = new ArrayList<>();
//
// }
| import com.sivalabs.jblogger.entities.Role;
import com.sivalabs.jblogger.entities.User;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat; | package com.sivalabs.jblogger.security;
class AuthenticatedUserTest {
@Test
void hasNoAuthorities() {
User user = new User();
user.setEmail("[email protected]");
user.setPassword("pwd");
final AuthenticatedUser authenticatedUser = new AuthenticatedUser(user);
assertThat(authenticatedUser.getUsername()).isEqualTo("[email protected]");
assertThat(authenticatedUser.getPassword()).isEqualTo("pwd");
assertThat(authenticatedUser.getAuthorities()).hasSize(0);
}
@Test
void hasAuthorities() {
User user = new User();
user.setEmail("[email protected]");
user.setPassword("pwd"); | // Path: src/main/java/com/sivalabs/jblogger/entities/Role.java
// @Entity
// @Table(name="roles")
// @Data
// public class Role implements Serializable
// {
// private static final long serialVersionUID = 1L;
//
// @Id
// @SequenceGenerator(name="role_id_generator", sequenceName="role_id_seq", initialValue = 100, allocationSize=1)
// @GeneratedValue(generator = "role_id_generator")
// private Long id;
//
// @Column(nullable=false, unique=true)
// @NotEmpty
// private String name;
//
// @ManyToMany(mappedBy="roles")
// private List<User> users;
//
// }
//
// Path: src/main/java/com/sivalabs/jblogger/entities/User.java
// @Entity
// @Table(name="users")
// @Data
// public class User implements Serializable
// {
// private static final long serialVersionUID = 1L;
//
// @Id
// @SequenceGenerator(name="user_id_generator", sequenceName="user_id_seq", initialValue = 100, allocationSize=1)
// @GeneratedValue(generator = "user_id_generator")
// private Long id;
//
// @Column(nullable=false)
// @NotEmpty()
// private String name;
//
// @Column(nullable=false, unique=true)
// @NotEmpty
// @Email(message="{errors.invalid_email}")
// private String email;
//
// @Column(nullable=false)
// @NotEmpty
// @Size(min=4)
// private String password;
//
// @ManyToMany(cascade=CascadeType.MERGE)
// @JoinTable(
// name="user_role",
// joinColumns={@JoinColumn(name="USER_ID", referencedColumnName="ID")},
// inverseJoinColumns={@JoinColumn(name="ROLE_ID", referencedColumnName="ID")})
// private List<Role> roles = new ArrayList<>();
//
// }
// Path: src/test/java/com/sivalabs/jblogger/security/AuthenticatedUserTest.java
import com.sivalabs.jblogger.entities.Role;
import com.sivalabs.jblogger.entities.User;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
package com.sivalabs.jblogger.security;
class AuthenticatedUserTest {
@Test
void hasNoAuthorities() {
User user = new User();
user.setEmail("[email protected]");
user.setPassword("pwd");
final AuthenticatedUser authenticatedUser = new AuthenticatedUser(user);
assertThat(authenticatedUser.getUsername()).isEqualTo("[email protected]");
assertThat(authenticatedUser.getPassword()).isEqualTo("pwd");
assertThat(authenticatedUser.getAuthorities()).hasSize(0);
}
@Test
void hasAuthorities() {
User user = new User();
user.setEmail("[email protected]");
user.setPassword("pwd"); | List<Role> roles = new ArrayList<>(); |
sivaprasadreddy/jblogger | src/main/java/com/sivalabs/jblogger/security/AuthenticatedUser.java | // Path: src/main/java/com/sivalabs/jblogger/entities/Role.java
// @Entity
// @Table(name="roles")
// @Data
// public class Role implements Serializable
// {
// private static final long serialVersionUID = 1L;
//
// @Id
// @SequenceGenerator(name="role_id_generator", sequenceName="role_id_seq", initialValue = 100, allocationSize=1)
// @GeneratedValue(generator = "role_id_generator")
// private Long id;
//
// @Column(nullable=false, unique=true)
// @NotEmpty
// private String name;
//
// @ManyToMany(mappedBy="roles")
// private List<User> users;
//
// }
//
// Path: src/main/java/com/sivalabs/jblogger/entities/User.java
// @Entity
// @Table(name="users")
// @Data
// public class User implements Serializable
// {
// private static final long serialVersionUID = 1L;
//
// @Id
// @SequenceGenerator(name="user_id_generator", sequenceName="user_id_seq", initialValue = 100, allocationSize=1)
// @GeneratedValue(generator = "user_id_generator")
// private Long id;
//
// @Column(nullable=false)
// @NotEmpty()
// private String name;
//
// @Column(nullable=false, unique=true)
// @NotEmpty
// @Email(message="{errors.invalid_email}")
// private String email;
//
// @Column(nullable=false)
// @NotEmpty
// @Size(min=4)
// private String password;
//
// @ManyToMany(cascade=CascadeType.MERGE)
// @JoinTable(
// name="user_role",
// joinColumns={@JoinColumn(name="USER_ID", referencedColumnName="ID")},
// inverseJoinColumns={@JoinColumn(name="ROLE_ID", referencedColumnName="ID")})
// private List<Role> roles = new ArrayList<>();
//
// }
| import com.sivalabs.jblogger.entities.Role;
import com.sivalabs.jblogger.entities.User;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import java.util.Collection;
import java.util.List; | package com.sivalabs.jblogger.security;
public class AuthenticatedUser extends org.springframework.security.core.userdetails.User
{
private static final long serialVersionUID = 1L;
private User user;
public AuthenticatedUser(User user)
{
super(user.getEmail(), user.getPassword(), getAuthorities(user));
this.user = user;
}
public User getUser()
{
return user;
}
private static Collection<? extends GrantedAuthority> getAuthorities(User user)
{ | // Path: src/main/java/com/sivalabs/jblogger/entities/Role.java
// @Entity
// @Table(name="roles")
// @Data
// public class Role implements Serializable
// {
// private static final long serialVersionUID = 1L;
//
// @Id
// @SequenceGenerator(name="role_id_generator", sequenceName="role_id_seq", initialValue = 100, allocationSize=1)
// @GeneratedValue(generator = "role_id_generator")
// private Long id;
//
// @Column(nullable=false, unique=true)
// @NotEmpty
// private String name;
//
// @ManyToMany(mappedBy="roles")
// private List<User> users;
//
// }
//
// Path: src/main/java/com/sivalabs/jblogger/entities/User.java
// @Entity
// @Table(name="users")
// @Data
// public class User implements Serializable
// {
// private static final long serialVersionUID = 1L;
//
// @Id
// @SequenceGenerator(name="user_id_generator", sequenceName="user_id_seq", initialValue = 100, allocationSize=1)
// @GeneratedValue(generator = "user_id_generator")
// private Long id;
//
// @Column(nullable=false)
// @NotEmpty()
// private String name;
//
// @Column(nullable=false, unique=true)
// @NotEmpty
// @Email(message="{errors.invalid_email}")
// private String email;
//
// @Column(nullable=false)
// @NotEmpty
// @Size(min=4)
// private String password;
//
// @ManyToMany(cascade=CascadeType.MERGE)
// @JoinTable(
// name="user_role",
// joinColumns={@JoinColumn(name="USER_ID", referencedColumnName="ID")},
// inverseJoinColumns={@JoinColumn(name="ROLE_ID", referencedColumnName="ID")})
// private List<Role> roles = new ArrayList<>();
//
// }
// Path: src/main/java/com/sivalabs/jblogger/security/AuthenticatedUser.java
import com.sivalabs.jblogger.entities.Role;
import com.sivalabs.jblogger.entities.User;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import java.util.Collection;
import java.util.List;
package com.sivalabs.jblogger.security;
public class AuthenticatedUser extends org.springframework.security.core.userdetails.User
{
private static final long serialVersionUID = 1L;
private User user;
public AuthenticatedUser(User user)
{
super(user.getEmail(), user.getPassword(), getAuthorities(user));
this.user = user;
}
public User getUser()
{
return user;
}
private static Collection<? extends GrantedAuthority> getAuthorities(User user)
{ | List<Role> roles = user.getRoles(); |
sivaprasadreddy/jblogger | src/main/java/com/sivalabs/jblogger/web/WebUtils.java | // Path: src/main/java/com/sivalabs/jblogger/config/ApplicationProperties.java
// @ConfigurationProperties(prefix="application")
// @ConstructorBinding
// @AllArgsConstructor
// @Getter
// public class ApplicationProperties
// {
// private int postsPerPage;
// private String supportEmail;
// private String twitterShareUrl;
// private String facebookShareUrl;
// private String linkedinShareUrl;
//
// }
//
// Path: src/main/java/com/sivalabs/jblogger/domain/PostDTO.java
// @Data
// @Builder
// public class PostDTO {
// private Long id;
// private String title;
// private String url;
// private String content;
// private String shortDescription;
// private String createdByUserName;
// private LocalDateTime createdOn;
// private LocalDateTime updatedOn;
// private Long viewCount;
// private List<String> tags;
// private List<CommentDTO> comments;
//
// private String twitterShareLink;
// private String facebookShareLink;
// private String linkedInShareLink;
// }
| import com.sivalabs.jblogger.config.ApplicationProperties;
import com.sivalabs.jblogger.domain.PostDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder; | package com.sivalabs.jblogger.web;
@Component
@Slf4j
public class WebUtils
{ | // Path: src/main/java/com/sivalabs/jblogger/config/ApplicationProperties.java
// @ConfigurationProperties(prefix="application")
// @ConstructorBinding
// @AllArgsConstructor
// @Getter
// public class ApplicationProperties
// {
// private int postsPerPage;
// private String supportEmail;
// private String twitterShareUrl;
// private String facebookShareUrl;
// private String linkedinShareUrl;
//
// }
//
// Path: src/main/java/com/sivalabs/jblogger/domain/PostDTO.java
// @Data
// @Builder
// public class PostDTO {
// private Long id;
// private String title;
// private String url;
// private String content;
// private String shortDescription;
// private String createdByUserName;
// private LocalDateTime createdOn;
// private LocalDateTime updatedOn;
// private Long viewCount;
// private List<String> tags;
// private List<CommentDTO> comments;
//
// private String twitterShareLink;
// private String facebookShareLink;
// private String linkedInShareLink;
// }
// Path: src/main/java/com/sivalabs/jblogger/web/WebUtils.java
import com.sivalabs.jblogger.config.ApplicationProperties;
import com.sivalabs.jblogger.domain.PostDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
package com.sivalabs.jblogger.web;
@Component
@Slf4j
public class WebUtils
{ | private static ApplicationProperties applicationProperties; |
sivaprasadreddy/jblogger | src/main/java/com/sivalabs/jblogger/web/WebUtils.java | // Path: src/main/java/com/sivalabs/jblogger/config/ApplicationProperties.java
// @ConfigurationProperties(prefix="application")
// @ConstructorBinding
// @AllArgsConstructor
// @Getter
// public class ApplicationProperties
// {
// private int postsPerPage;
// private String supportEmail;
// private String twitterShareUrl;
// private String facebookShareUrl;
// private String linkedinShareUrl;
//
// }
//
// Path: src/main/java/com/sivalabs/jblogger/domain/PostDTO.java
// @Data
// @Builder
// public class PostDTO {
// private Long id;
// private String title;
// private String url;
// private String content;
// private String shortDescription;
// private String createdByUserName;
// private LocalDateTime createdOn;
// private LocalDateTime updatedOn;
// private Long viewCount;
// private List<String> tags;
// private List<CommentDTO> comments;
//
// private String twitterShareLink;
// private String facebookShareLink;
// private String linkedInShareLink;
// }
| import com.sivalabs.jblogger.config.ApplicationProperties;
import com.sivalabs.jblogger.domain.PostDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder; | package com.sivalabs.jblogger.web;
@Component
@Slf4j
public class WebUtils
{
private static ApplicationProperties applicationProperties;
@Autowired
WebUtils(ApplicationProperties config) {
WebUtils.applicationProperties = config;
}
| // Path: src/main/java/com/sivalabs/jblogger/config/ApplicationProperties.java
// @ConfigurationProperties(prefix="application")
// @ConstructorBinding
// @AllArgsConstructor
// @Getter
// public class ApplicationProperties
// {
// private int postsPerPage;
// private String supportEmail;
// private String twitterShareUrl;
// private String facebookShareUrl;
// private String linkedinShareUrl;
//
// }
//
// Path: src/main/java/com/sivalabs/jblogger/domain/PostDTO.java
// @Data
// @Builder
// public class PostDTO {
// private Long id;
// private String title;
// private String url;
// private String content;
// private String shortDescription;
// private String createdByUserName;
// private LocalDateTime createdOn;
// private LocalDateTime updatedOn;
// private Long viewCount;
// private List<String> tags;
// private List<CommentDTO> comments;
//
// private String twitterShareLink;
// private String facebookShareLink;
// private String linkedInShareLink;
// }
// Path: src/main/java/com/sivalabs/jblogger/web/WebUtils.java
import com.sivalabs.jblogger.config.ApplicationProperties;
import com.sivalabs.jblogger.domain.PostDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
package com.sivalabs.jblogger.web;
@Component
@Slf4j
public class WebUtils
{
private static ApplicationProperties applicationProperties;
@Autowired
WebUtils(ApplicationProperties config) {
WebUtils.applicationProperties = config;
}
| public static String getTwitterShareLink(PostDTO post) |
sivaprasadreddy/jblogger | src/main/java/com/sivalabs/jblogger/services/EmailService.java | // Path: src/main/java/com/sivalabs/jblogger/config/ApplicationProperties.java
// @ConfigurationProperties(prefix="application")
// @ConstructorBinding
// @AllArgsConstructor
// @Getter
// public class ApplicationProperties
// {
// private int postsPerPage;
// private String supportEmail;
// private String twitterShareUrl;
// private String facebookShareUrl;
// private String linkedinShareUrl;
//
// }
| import com.sivalabs.jblogger.config.ApplicationProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import java.util.concurrent.CompletableFuture; | package com.sivalabs.jblogger.services;
@Component
@Slf4j
public class EmailService
{ | // Path: src/main/java/com/sivalabs/jblogger/config/ApplicationProperties.java
// @ConfigurationProperties(prefix="application")
// @ConstructorBinding
// @AllArgsConstructor
// @Getter
// public class ApplicationProperties
// {
// private int postsPerPage;
// private String supportEmail;
// private String twitterShareUrl;
// private String facebookShareUrl;
// private String linkedinShareUrl;
//
// }
// Path: src/main/java/com/sivalabs/jblogger/services/EmailService.java
import com.sivalabs.jblogger.config.ApplicationProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import java.util.concurrent.CompletableFuture;
package com.sivalabs.jblogger.services;
@Component
@Slf4j
public class EmailService
{ | private final ApplicationProperties applicationProperties; |
sivaprasadreddy/jblogger | src/test/java/com/sivalabs/jblogger/domain/BlogOverviewTest.java | // Path: src/main/java/com/sivalabs/jblogger/entities/PageView.java
// @Entity
// @Table(name="pageviews")
// @Data
// public class PageView implements Serializable
// {
// private static final long serialVersionUID = 1L;
//
// @Id
// @SequenceGenerator(name="pageview_id_generator", sequenceName="pageview_id_seq", initialValue = 100, allocationSize=1)
// @GeneratedValue(generator = "pageview_id_generator")
// private Long id;
//
// private String url;
//
// private String referrer;
//
// @Column(name="visit_time")
// private LocalDateTime visitTime = LocalDateTime.now();
//
// @ManyToOne
// @JoinColumn(name="post_id")
// private Post post;
//
// }
//
// Path: src/main/java/com/sivalabs/jblogger/entities/Post.java
// @Entity
// @Table(name = "POSTS")
// @Data
// public class Post implements Serializable
// {
// private static final long serialVersionUID = 1L;
//
// @Id
// @SequenceGenerator(name="post_id_generator", sequenceName="post_id_seq", initialValue = 100, allocationSize=1)
// @GeneratedValue(generator = "post_id_generator")
// private Long id;
//
// @Column(name = "title", nullable = false, length = 150)
// @NotEmpty
// private String title;
//
// @Column(name = "url", length = 255)
// private String url;
//
// @Lob
// @Type(type = "org.hibernate.type.TextType")
// @Column(name = "content", nullable = false)
// @NotEmpty
// private String content;
//
// @Column(name = "short_desc", length=500)
// @NotEmpty
// private String shortDescription;
//
// @ManyToOne
// @JoinColumn(name = "created_by", nullable = false)
// private User createdBy;
//
// @Column(name = "created_on")
// private LocalDateTime createdOn = LocalDateTime.now();
//
// @Column(name = "updated_on")
// private LocalDateTime updatedOn;
//
// @Column(name = "view_count", columnDefinition="bigint default 0")
// private Long viewCount = 0L;
//
// @ManyToMany(cascade=CascadeType.MERGE)
// @JoinTable(
// name="post_tag",
// joinColumns={@JoinColumn(name="POST_ID", referencedColumnName="ID")},
// inverseJoinColumns={@JoinColumn(name="TAG_ID", referencedColumnName="ID")})
// private Set<Tag> tags;
//
// @OneToMany(mappedBy = "post", cascade = CascadeType.REMOVE)
// private List<Comment> comments = new ArrayList<>();
//
// public String getTagIdsAsString()
// {
// if(tags == null || tags.isEmpty()) return "";
//
// StringBuilder sb = new StringBuilder();
// for (Tag tag : tags) {
// sb.append(","+tag.getId());
// }
// return sb.substring(1);
// }
//
// public String getTagsAsString()
// {
// if(tags == null || tags.isEmpty()) return "";
//
// StringBuilder sb = new StringBuilder();
// for (Tag tag : tags) {
// sb.append(","+tag.getLabel());
// }
// return sb.substring(1);
// }
//
// public String[] getTagsAsStringArray()
// {
// if(tags == null || tags.isEmpty()) return new String[]{};
//
// String[] arr = new String[tags.size()];
// int i = 0;
// for (Tag tag : tags)
// {
// arr[i++] = tag.getLabel();
// }
//
// return arr;
// }
//
// public String[] getTagIdsAsStringArray()
// {
// if(tags == null || tags.isEmpty()) return new String[]{};
//
// String[] arr = new String[tags.size()];
// int i = 0;
// for (Tag tag : tags)
// {
// arr[i++] = ""+tag.getId();
// }
//
// return arr;
// }
//
// }
| import com.sivalabs.jblogger.entities.PageView;
import com.sivalabs.jblogger.entities.Post;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue; | package com.sivalabs.jblogger.domain;
class BlogOverviewTest {
@Test
void getPostViewCountMapShouldReturnEmptyMapWhenNoPageViews() throws Exception {
BlogOverview overview = new BlogOverview(); | // Path: src/main/java/com/sivalabs/jblogger/entities/PageView.java
// @Entity
// @Table(name="pageviews")
// @Data
// public class PageView implements Serializable
// {
// private static final long serialVersionUID = 1L;
//
// @Id
// @SequenceGenerator(name="pageview_id_generator", sequenceName="pageview_id_seq", initialValue = 100, allocationSize=1)
// @GeneratedValue(generator = "pageview_id_generator")
// private Long id;
//
// private String url;
//
// private String referrer;
//
// @Column(name="visit_time")
// private LocalDateTime visitTime = LocalDateTime.now();
//
// @ManyToOne
// @JoinColumn(name="post_id")
// private Post post;
//
// }
//
// Path: src/main/java/com/sivalabs/jblogger/entities/Post.java
// @Entity
// @Table(name = "POSTS")
// @Data
// public class Post implements Serializable
// {
// private static final long serialVersionUID = 1L;
//
// @Id
// @SequenceGenerator(name="post_id_generator", sequenceName="post_id_seq", initialValue = 100, allocationSize=1)
// @GeneratedValue(generator = "post_id_generator")
// private Long id;
//
// @Column(name = "title", nullable = false, length = 150)
// @NotEmpty
// private String title;
//
// @Column(name = "url", length = 255)
// private String url;
//
// @Lob
// @Type(type = "org.hibernate.type.TextType")
// @Column(name = "content", nullable = false)
// @NotEmpty
// private String content;
//
// @Column(name = "short_desc", length=500)
// @NotEmpty
// private String shortDescription;
//
// @ManyToOne
// @JoinColumn(name = "created_by", nullable = false)
// private User createdBy;
//
// @Column(name = "created_on")
// private LocalDateTime createdOn = LocalDateTime.now();
//
// @Column(name = "updated_on")
// private LocalDateTime updatedOn;
//
// @Column(name = "view_count", columnDefinition="bigint default 0")
// private Long viewCount = 0L;
//
// @ManyToMany(cascade=CascadeType.MERGE)
// @JoinTable(
// name="post_tag",
// joinColumns={@JoinColumn(name="POST_ID", referencedColumnName="ID")},
// inverseJoinColumns={@JoinColumn(name="TAG_ID", referencedColumnName="ID")})
// private Set<Tag> tags;
//
// @OneToMany(mappedBy = "post", cascade = CascadeType.REMOVE)
// private List<Comment> comments = new ArrayList<>();
//
// public String getTagIdsAsString()
// {
// if(tags == null || tags.isEmpty()) return "";
//
// StringBuilder sb = new StringBuilder();
// for (Tag tag : tags) {
// sb.append(","+tag.getId());
// }
// return sb.substring(1);
// }
//
// public String getTagsAsString()
// {
// if(tags == null || tags.isEmpty()) return "";
//
// StringBuilder sb = new StringBuilder();
// for (Tag tag : tags) {
// sb.append(","+tag.getLabel());
// }
// return sb.substring(1);
// }
//
// public String[] getTagsAsStringArray()
// {
// if(tags == null || tags.isEmpty()) return new String[]{};
//
// String[] arr = new String[tags.size()];
// int i = 0;
// for (Tag tag : tags)
// {
// arr[i++] = tag.getLabel();
// }
//
// return arr;
// }
//
// public String[] getTagIdsAsStringArray()
// {
// if(tags == null || tags.isEmpty()) return new String[]{};
//
// String[] arr = new String[tags.size()];
// int i = 0;
// for (Tag tag : tags)
// {
// arr[i++] = ""+tag.getId();
// }
//
// return arr;
// }
//
// }
// Path: src/test/java/com/sivalabs/jblogger/domain/BlogOverviewTest.java
import com.sivalabs.jblogger.entities.PageView;
import com.sivalabs.jblogger.entities.Post;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
package com.sivalabs.jblogger.domain;
class BlogOverviewTest {
@Test
void getPostViewCountMapShouldReturnEmptyMapWhenNoPageViews() throws Exception {
BlogOverview overview = new BlogOverview(); | final Map<Post, Long> viewCountMap = overview.getPostViewCountMap(); |
sivaprasadreddy/jblogger | src/test/java/com/sivalabs/jblogger/domain/BlogOverviewTest.java | // Path: src/main/java/com/sivalabs/jblogger/entities/PageView.java
// @Entity
// @Table(name="pageviews")
// @Data
// public class PageView implements Serializable
// {
// private static final long serialVersionUID = 1L;
//
// @Id
// @SequenceGenerator(name="pageview_id_generator", sequenceName="pageview_id_seq", initialValue = 100, allocationSize=1)
// @GeneratedValue(generator = "pageview_id_generator")
// private Long id;
//
// private String url;
//
// private String referrer;
//
// @Column(name="visit_time")
// private LocalDateTime visitTime = LocalDateTime.now();
//
// @ManyToOne
// @JoinColumn(name="post_id")
// private Post post;
//
// }
//
// Path: src/main/java/com/sivalabs/jblogger/entities/Post.java
// @Entity
// @Table(name = "POSTS")
// @Data
// public class Post implements Serializable
// {
// private static final long serialVersionUID = 1L;
//
// @Id
// @SequenceGenerator(name="post_id_generator", sequenceName="post_id_seq", initialValue = 100, allocationSize=1)
// @GeneratedValue(generator = "post_id_generator")
// private Long id;
//
// @Column(name = "title", nullable = false, length = 150)
// @NotEmpty
// private String title;
//
// @Column(name = "url", length = 255)
// private String url;
//
// @Lob
// @Type(type = "org.hibernate.type.TextType")
// @Column(name = "content", nullable = false)
// @NotEmpty
// private String content;
//
// @Column(name = "short_desc", length=500)
// @NotEmpty
// private String shortDescription;
//
// @ManyToOne
// @JoinColumn(name = "created_by", nullable = false)
// private User createdBy;
//
// @Column(name = "created_on")
// private LocalDateTime createdOn = LocalDateTime.now();
//
// @Column(name = "updated_on")
// private LocalDateTime updatedOn;
//
// @Column(name = "view_count", columnDefinition="bigint default 0")
// private Long viewCount = 0L;
//
// @ManyToMany(cascade=CascadeType.MERGE)
// @JoinTable(
// name="post_tag",
// joinColumns={@JoinColumn(name="POST_ID", referencedColumnName="ID")},
// inverseJoinColumns={@JoinColumn(name="TAG_ID", referencedColumnName="ID")})
// private Set<Tag> tags;
//
// @OneToMany(mappedBy = "post", cascade = CascadeType.REMOVE)
// private List<Comment> comments = new ArrayList<>();
//
// public String getTagIdsAsString()
// {
// if(tags == null || tags.isEmpty()) return "";
//
// StringBuilder sb = new StringBuilder();
// for (Tag tag : tags) {
// sb.append(","+tag.getId());
// }
// return sb.substring(1);
// }
//
// public String getTagsAsString()
// {
// if(tags == null || tags.isEmpty()) return "";
//
// StringBuilder sb = new StringBuilder();
// for (Tag tag : tags) {
// sb.append(","+tag.getLabel());
// }
// return sb.substring(1);
// }
//
// public String[] getTagsAsStringArray()
// {
// if(tags == null || tags.isEmpty()) return new String[]{};
//
// String[] arr = new String[tags.size()];
// int i = 0;
// for (Tag tag : tags)
// {
// arr[i++] = tag.getLabel();
// }
//
// return arr;
// }
//
// public String[] getTagIdsAsStringArray()
// {
// if(tags == null || tags.isEmpty()) return new String[]{};
//
// String[] arr = new String[tags.size()];
// int i = 0;
// for (Tag tag : tags)
// {
// arr[i++] = ""+tag.getId();
// }
//
// return arr;
// }
//
// }
| import com.sivalabs.jblogger.entities.PageView;
import com.sivalabs.jblogger.entities.Post;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue; | package com.sivalabs.jblogger.domain;
class BlogOverviewTest {
@Test
void getPostViewCountMapShouldReturnEmptyMapWhenNoPageViews() throws Exception {
BlogOverview overview = new BlogOverview();
final Map<Post, Long> viewCountMap = overview.getPostViewCountMap();
assertTrue(viewCountMap.isEmpty());
}
@Test
void getPostViewCountMap() throws Exception {
BlogOverview overview = new BlogOverview(); | // Path: src/main/java/com/sivalabs/jblogger/entities/PageView.java
// @Entity
// @Table(name="pageviews")
// @Data
// public class PageView implements Serializable
// {
// private static final long serialVersionUID = 1L;
//
// @Id
// @SequenceGenerator(name="pageview_id_generator", sequenceName="pageview_id_seq", initialValue = 100, allocationSize=1)
// @GeneratedValue(generator = "pageview_id_generator")
// private Long id;
//
// private String url;
//
// private String referrer;
//
// @Column(name="visit_time")
// private LocalDateTime visitTime = LocalDateTime.now();
//
// @ManyToOne
// @JoinColumn(name="post_id")
// private Post post;
//
// }
//
// Path: src/main/java/com/sivalabs/jblogger/entities/Post.java
// @Entity
// @Table(name = "POSTS")
// @Data
// public class Post implements Serializable
// {
// private static final long serialVersionUID = 1L;
//
// @Id
// @SequenceGenerator(name="post_id_generator", sequenceName="post_id_seq", initialValue = 100, allocationSize=1)
// @GeneratedValue(generator = "post_id_generator")
// private Long id;
//
// @Column(name = "title", nullable = false, length = 150)
// @NotEmpty
// private String title;
//
// @Column(name = "url", length = 255)
// private String url;
//
// @Lob
// @Type(type = "org.hibernate.type.TextType")
// @Column(name = "content", nullable = false)
// @NotEmpty
// private String content;
//
// @Column(name = "short_desc", length=500)
// @NotEmpty
// private String shortDescription;
//
// @ManyToOne
// @JoinColumn(name = "created_by", nullable = false)
// private User createdBy;
//
// @Column(name = "created_on")
// private LocalDateTime createdOn = LocalDateTime.now();
//
// @Column(name = "updated_on")
// private LocalDateTime updatedOn;
//
// @Column(name = "view_count", columnDefinition="bigint default 0")
// private Long viewCount = 0L;
//
// @ManyToMany(cascade=CascadeType.MERGE)
// @JoinTable(
// name="post_tag",
// joinColumns={@JoinColumn(name="POST_ID", referencedColumnName="ID")},
// inverseJoinColumns={@JoinColumn(name="TAG_ID", referencedColumnName="ID")})
// private Set<Tag> tags;
//
// @OneToMany(mappedBy = "post", cascade = CascadeType.REMOVE)
// private List<Comment> comments = new ArrayList<>();
//
// public String getTagIdsAsString()
// {
// if(tags == null || tags.isEmpty()) return "";
//
// StringBuilder sb = new StringBuilder();
// for (Tag tag : tags) {
// sb.append(","+tag.getId());
// }
// return sb.substring(1);
// }
//
// public String getTagsAsString()
// {
// if(tags == null || tags.isEmpty()) return "";
//
// StringBuilder sb = new StringBuilder();
// for (Tag tag : tags) {
// sb.append(","+tag.getLabel());
// }
// return sb.substring(1);
// }
//
// public String[] getTagsAsStringArray()
// {
// if(tags == null || tags.isEmpty()) return new String[]{};
//
// String[] arr = new String[tags.size()];
// int i = 0;
// for (Tag tag : tags)
// {
// arr[i++] = tag.getLabel();
// }
//
// return arr;
// }
//
// public String[] getTagIdsAsStringArray()
// {
// if(tags == null || tags.isEmpty()) return new String[]{};
//
// String[] arr = new String[tags.size()];
// int i = 0;
// for (Tag tag : tags)
// {
// arr[i++] = ""+tag.getId();
// }
//
// return arr;
// }
//
// }
// Path: src/test/java/com/sivalabs/jblogger/domain/BlogOverviewTest.java
import com.sivalabs.jblogger.entities.PageView;
import com.sivalabs.jblogger.entities.Post;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
package com.sivalabs.jblogger.domain;
class BlogOverviewTest {
@Test
void getPostViewCountMapShouldReturnEmptyMapWhenNoPageViews() throws Exception {
BlogOverview overview = new BlogOverview();
final Map<Post, Long> viewCountMap = overview.getPostViewCountMap();
assertTrue(viewCountMap.isEmpty());
}
@Test
void getPostViewCountMap() throws Exception {
BlogOverview overview = new BlogOverview(); | List<PageView> pageViews = new ArrayList<>(); |
qala-io/datagen | examples/src/test/java/io/qala/datagen/examples/_25_TestOracleTest.java | // Path: datagen/src/main/java/io/qala/datagen/RandomShortApi.java
// public static int integer(int max) {
// return between(0, max).integer();
// }
| import org.junit.Test;
import static io.qala.datagen.RandomShortApi.integer;
import static org.junit.Assert.assertEquals; | package io.qala.datagen.examples;
public class _25_TestOracleTest {
@Test public void nOfCombinations_matchesSimpleImplementation() { | // Path: datagen/src/main/java/io/qala/datagen/RandomShortApi.java
// public static int integer(int max) {
// return between(0, max).integer();
// }
// Path: examples/src/test/java/io/qala/datagen/examples/_25_TestOracleTest.java
import org.junit.Test;
import static io.qala.datagen.RandomShortApi.integer;
import static org.junit.Assert.assertEquals;
package io.qala.datagen.examples;
public class _25_TestOracleTest {
@Test public void nOfCombinations_matchesSimpleImplementation() { | int n = integer(1, 1000), k = integer(1, n); |
qala-io/datagen | examples/src/test/java/io/qala/datagen/examples/_05_MaxBoundaryValidationTest.java | // Path: datagen/src/main/java/io/qala/datagen/RandomShortApi.java
// public static String unicode(int exactLength) {
// return length(exactLength).unicode();
// }
| import org.junit.Test;
import static io.qala.datagen.RandomShortApi.unicode; | package io.qala.datagen.examples;
public class _05_MaxBoundaryValidationTest {
private Db db = new Db();
@Test public void usernameValidation_passesForMaxBoundary_inTraditionalApproach() {
db.save(new Person("ABCDEFGHIJАБВГДИЙКЛм"));
}
@Test(expected = IllegalStateException.class)
public void usernameValidation_failsForMaxBoundary_ifRandomized() {//will fail once in a million cases | // Path: datagen/src/main/java/io/qala/datagen/RandomShortApi.java
// public static String unicode(int exactLength) {
// return length(exactLength).unicode();
// }
// Path: examples/src/test/java/io/qala/datagen/examples/_05_MaxBoundaryValidationTest.java
import org.junit.Test;
import static io.qala.datagen.RandomShortApi.unicode;
package io.qala.datagen.examples;
public class _05_MaxBoundaryValidationTest {
private Db db = new Db();
@Test public void usernameValidation_passesForMaxBoundary_inTraditionalApproach() {
db.save(new Person("ABCDEFGHIJАБВГДИЙКЛм"));
}
@Test(expected = IllegalStateException.class)
public void usernameValidation_failsForMaxBoundary_ifRandomized() {//will fail once in a million cases | db.save(new Person(unicode(20))); |
qala-io/datagen | junit5/src/main/java/io/qala/datagen/junit/jupiter/BlankStringProvider.java | // Path: datagen/src/main/java/io/qala/datagen/RandomShortApi.java
// public static String nullOrBlank() {
// return sample("", between(1, 100).string(' '), null);
// }
| import java.util.stream.Stream;
import static io.qala.datagen.RandomShortApi.nullOrBlank; | package io.qala.datagen.junit.jupiter;
public class BlankStringProvider extends RandomizedArgumentProvider<BlankString> {
private BlankString annotation;
@Override
public void accept(BlankString annotation) {
this.annotation = annotation;
}
@Override Stream<Object[]> getValueWithDescription() {
return Stream.of(annotation)
.map(BlankStringProvider::generateParams);
}
@Override Stream<Object> getValue() {
return Stream.of(generateParam());
}
static String generateParam() { | // Path: datagen/src/main/java/io/qala/datagen/RandomShortApi.java
// public static String nullOrBlank() {
// return sample("", between(1, 100).string(' '), null);
// }
// Path: junit5/src/main/java/io/qala/datagen/junit/jupiter/BlankStringProvider.java
import java.util.stream.Stream;
import static io.qala.datagen.RandomShortApi.nullOrBlank;
package io.qala.datagen.junit.jupiter;
public class BlankStringProvider extends RandomizedArgumentProvider<BlankString> {
private BlankString annotation;
@Override
public void accept(BlankString annotation) {
this.annotation = annotation;
}
@Override Stream<Object[]> getValueWithDescription() {
return Stream.of(annotation)
.map(BlankStringProvider::generateParams);
}
@Override Stream<Object> getValue() {
return Stream.of(generateParam());
}
static String generateParam() { | return nullOrBlank(); |
qala-io/datagen | junit5/src/main/java/io/qala/datagen/junit/jupiter/AlphanumericArgumentProvider.java | // Path: datagen/src/main/java/io/qala/datagen/RandomShortApi.java
// public static String alphanumeric(int exactLength) {
// return length(exactLength).alphanumeric();
// }
| import java.util.stream.Stream;
import static io.qala.datagen.RandomShortApi.alphanumeric; | package io.qala.datagen.junit.jupiter;
class AlphanumericArgumentProvider extends RandomizedArgumentProvider<Alphanumeric> {
private Alphanumeric annotation;
@Override
public void accept(Alphanumeric annotation) {
this.annotation = annotation;
}
@Override Stream<Object[]> getValueWithDescription() {
return Stream.of(annotation).map(AlphanumericArgumentProvider::generateParams);
}
@Override Stream<Object> getValue() {
return Stream.of(annotation).map(AlphanumericArgumentProvider::generateParam);
}
static String generateParam(Alphanumeric annotation) { | // Path: datagen/src/main/java/io/qala/datagen/RandomShortApi.java
// public static String alphanumeric(int exactLength) {
// return length(exactLength).alphanumeric();
// }
// Path: junit5/src/main/java/io/qala/datagen/junit/jupiter/AlphanumericArgumentProvider.java
import java.util.stream.Stream;
import static io.qala.datagen.RandomShortApi.alphanumeric;
package io.qala.datagen.junit.jupiter;
class AlphanumericArgumentProvider extends RandomizedArgumentProvider<Alphanumeric> {
private Alphanumeric annotation;
@Override
public void accept(Alphanumeric annotation) {
this.annotation = annotation;
}
@Override Stream<Object[]> getValueWithDescription() {
return Stream.of(annotation).map(AlphanumericArgumentProvider::generateParams);
}
@Override Stream<Object> getValue() {
return Stream.of(annotation).map(AlphanumericArgumentProvider::generateParam);
}
static String generateParam(Alphanumeric annotation) { | if (annotation.length() > 0) return alphanumeric(annotation.length()); |
qala-io/datagen | examples/src/test/java/io/qala/datagen/examples/_30_PropertyBasedTest.java | // Path: datagen/src/main/java/io/qala/datagen/RandomShortApi.java
// public static int integer(int max) {
// return between(0, max).integer();
// }
| import org.junit.Test;
import static io.qala.datagen.RandomShortApi.integer;
import static org.junit.Assert.*; | package io.qala.datagen.examples;
/**
* Source: <a href="http://fsharpforfunandprofit.com/posts/property-based-testing/">click</a>
*/
public class _30_PropertyBasedTest {
@Test public void orderDoesNotMatter() { | // Path: datagen/src/main/java/io/qala/datagen/RandomShortApi.java
// public static int integer(int max) {
// return between(0, max).integer();
// }
// Path: examples/src/test/java/io/qala/datagen/examples/_30_PropertyBasedTest.java
import org.junit.Test;
import static io.qala.datagen.RandomShortApi.integer;
import static org.junit.Assert.*;
package io.qala.datagen.examples;
/**
* Source: <a href="http://fsharpforfunandprofit.com/posts/property-based-testing/">click</a>
*/
public class _30_PropertyBasedTest {
@Test public void orderDoesNotMatter() { | int a = integer(), b = integer(); |
qala-io/datagen | examples/src/main/java/io/qala/datagen/examples/Account.java | // Path: java8types/src/main/java/io/qala/datagen/RandomDate.java
// public static RandomDate beforeNow() {
// return before(Instant.now());
// }
//
// Path: datagen/src/main/java/io/qala/datagen/RandomShortApi.java
// public static double Double() {
// return CommonsMath4.nextUniform(RANDOM, Long.MIN_VALUE, Long.MAX_VALUE, true);
// }
//
// Path: datagen/src/main/java/io/qala/datagen/RandomShortApi.java
// public static String numeric(int exactLength) {
// return length(exactLength).numeric();
// }
| import java.time.ZonedDateTime;
import static io.qala.datagen.RandomDate.beforeNow;
import static io.qala.datagen.RandomShortApi.Double;
import static io.qala.datagen.RandomShortApi.numeric; | package io.qala.datagen.examples;
@SuppressWarnings("WeakerAccess")
class Account {
private Person primaryOwner;
private Person secondaryOwner;
private String number;
private Country openedIn;
private double interestRate;
private ZonedDateTime createdTime;
static Account random() {
Account account = new Account(); | // Path: java8types/src/main/java/io/qala/datagen/RandomDate.java
// public static RandomDate beforeNow() {
// return before(Instant.now());
// }
//
// Path: datagen/src/main/java/io/qala/datagen/RandomShortApi.java
// public static double Double() {
// return CommonsMath4.nextUniform(RANDOM, Long.MIN_VALUE, Long.MAX_VALUE, true);
// }
//
// Path: datagen/src/main/java/io/qala/datagen/RandomShortApi.java
// public static String numeric(int exactLength) {
// return length(exactLength).numeric();
// }
// Path: examples/src/main/java/io/qala/datagen/examples/Account.java
import java.time.ZonedDateTime;
import static io.qala.datagen.RandomDate.beforeNow;
import static io.qala.datagen.RandomShortApi.Double;
import static io.qala.datagen.RandomShortApi.numeric;
package io.qala.datagen.examples;
@SuppressWarnings("WeakerAccess")
class Account {
private Person primaryOwner;
private Person secondaryOwner;
private String number;
private Country openedIn;
private double interestRate;
private ZonedDateTime createdTime;
static Account random() {
Account account = new Account(); | account.setCreatedTime(beforeNow().zonedDateTime()); |
qala-io/datagen | examples/src/main/java/io/qala/datagen/examples/Account.java | // Path: java8types/src/main/java/io/qala/datagen/RandomDate.java
// public static RandomDate beforeNow() {
// return before(Instant.now());
// }
//
// Path: datagen/src/main/java/io/qala/datagen/RandomShortApi.java
// public static double Double() {
// return CommonsMath4.nextUniform(RANDOM, Long.MIN_VALUE, Long.MAX_VALUE, true);
// }
//
// Path: datagen/src/main/java/io/qala/datagen/RandomShortApi.java
// public static String numeric(int exactLength) {
// return length(exactLength).numeric();
// }
| import java.time.ZonedDateTime;
import static io.qala.datagen.RandomDate.beforeNow;
import static io.qala.datagen.RandomShortApi.Double;
import static io.qala.datagen.RandomShortApi.numeric; | package io.qala.datagen.examples;
@SuppressWarnings("WeakerAccess")
class Account {
private Person primaryOwner;
private Person secondaryOwner;
private String number;
private Country openedIn;
private double interestRate;
private ZonedDateTime createdTime;
static Account random() {
Account account = new Account();
account.setCreatedTime(beforeNow().zonedDateTime()); | // Path: java8types/src/main/java/io/qala/datagen/RandomDate.java
// public static RandomDate beforeNow() {
// return before(Instant.now());
// }
//
// Path: datagen/src/main/java/io/qala/datagen/RandomShortApi.java
// public static double Double() {
// return CommonsMath4.nextUniform(RANDOM, Long.MIN_VALUE, Long.MAX_VALUE, true);
// }
//
// Path: datagen/src/main/java/io/qala/datagen/RandomShortApi.java
// public static String numeric(int exactLength) {
// return length(exactLength).numeric();
// }
// Path: examples/src/main/java/io/qala/datagen/examples/Account.java
import java.time.ZonedDateTime;
import static io.qala.datagen.RandomDate.beforeNow;
import static io.qala.datagen.RandomShortApi.Double;
import static io.qala.datagen.RandomShortApi.numeric;
package io.qala.datagen.examples;
@SuppressWarnings("WeakerAccess")
class Account {
private Person primaryOwner;
private Person secondaryOwner;
private String number;
private Country openedIn;
private double interestRate;
private ZonedDateTime createdTime;
static Account random() {
Account account = new Account();
account.setCreatedTime(beforeNow().zonedDateTime()); | account.setInterestRate(Double(.0, 1.0)); |
qala-io/datagen | examples/src/main/java/io/qala/datagen/examples/Account.java | // Path: java8types/src/main/java/io/qala/datagen/RandomDate.java
// public static RandomDate beforeNow() {
// return before(Instant.now());
// }
//
// Path: datagen/src/main/java/io/qala/datagen/RandomShortApi.java
// public static double Double() {
// return CommonsMath4.nextUniform(RANDOM, Long.MIN_VALUE, Long.MAX_VALUE, true);
// }
//
// Path: datagen/src/main/java/io/qala/datagen/RandomShortApi.java
// public static String numeric(int exactLength) {
// return length(exactLength).numeric();
// }
| import java.time.ZonedDateTime;
import static io.qala.datagen.RandomDate.beforeNow;
import static io.qala.datagen.RandomShortApi.Double;
import static io.qala.datagen.RandomShortApi.numeric; | package io.qala.datagen.examples;
@SuppressWarnings("WeakerAccess")
class Account {
private Person primaryOwner;
private Person secondaryOwner;
private String number;
private Country openedIn;
private double interestRate;
private ZonedDateTime createdTime;
static Account random() {
Account account = new Account();
account.setCreatedTime(beforeNow().zonedDateTime());
account.setInterestRate(Double(.0, 1.0));
account.setOpenedIn(Country.random()); | // Path: java8types/src/main/java/io/qala/datagen/RandomDate.java
// public static RandomDate beforeNow() {
// return before(Instant.now());
// }
//
// Path: datagen/src/main/java/io/qala/datagen/RandomShortApi.java
// public static double Double() {
// return CommonsMath4.nextUniform(RANDOM, Long.MIN_VALUE, Long.MAX_VALUE, true);
// }
//
// Path: datagen/src/main/java/io/qala/datagen/RandomShortApi.java
// public static String numeric(int exactLength) {
// return length(exactLength).numeric();
// }
// Path: examples/src/main/java/io/qala/datagen/examples/Account.java
import java.time.ZonedDateTime;
import static io.qala.datagen.RandomDate.beforeNow;
import static io.qala.datagen.RandomShortApi.Double;
import static io.qala.datagen.RandomShortApi.numeric;
package io.qala.datagen.examples;
@SuppressWarnings("WeakerAccess")
class Account {
private Person primaryOwner;
private Person secondaryOwner;
private String number;
private Country openedIn;
private double interestRate;
private ZonedDateTime createdTime;
static Account random() {
Account account = new Account();
account.setCreatedTime(beforeNow().zonedDateTime());
account.setInterestRate(Double(.0, 1.0));
account.setOpenedIn(Country.random()); | account.setNumber(numeric(10)); |
qala-io/datagen | junit5/src/main/java/io/qala/datagen/junit/jupiter/RandomIntArgumentProvider.java | // Path: datagen/src/main/java/io/qala/datagen/RandomShortApi.java
// public static int integer(int max) {
// return between(0, max).integer();
// }
| import java.util.stream.Stream;
import static io.qala.datagen.RandomShortApi.integer; | package io.qala.datagen.junit.jupiter;
class RandomIntArgumentProvider extends RandomizedArgumentProvider<RandomInt> {
private RandomInt annotation;
@Override
public void accept(RandomInt annotation) {
this.annotation = annotation;
}
@Override Stream<Object[]> getValueWithDescription() {
return Stream.of(annotation).map(RandomIntArgumentProvider::generateParams);
}
@Override Stream<Object> getValue() {
return Stream.of(annotation).map(RandomIntArgumentProvider::generateParam);
}
static int generateParam(RandomInt annotation) { | // Path: datagen/src/main/java/io/qala/datagen/RandomShortApi.java
// public static int integer(int max) {
// return between(0, max).integer();
// }
// Path: junit5/src/main/java/io/qala/datagen/junit/jupiter/RandomIntArgumentProvider.java
import java.util.stream.Stream;
import static io.qala.datagen.RandomShortApi.integer;
package io.qala.datagen.junit.jupiter;
class RandomIntArgumentProvider extends RandomizedArgumentProvider<RandomInt> {
private RandomInt annotation;
@Override
public void accept(RandomInt annotation) {
this.annotation = annotation;
}
@Override Stream<Object[]> getValueWithDescription() {
return Stream.of(annotation).map(RandomIntArgumentProvider::generateParams);
}
@Override Stream<Object> getValue() {
return Stream.of(annotation).map(RandomIntArgumentProvider::generateParam);
}
static int generateParam(RandomInt annotation) { | return integer(annotation.min(), annotation.max()); |
qala-io/datagen | junit5/src/main/java/io/qala/datagen/junit/jupiter/NumericArgumentProvider.java | // Path: datagen/src/main/java/io/qala/datagen/RandomShortApi.java
// public static String numeric(int exactLength) {
// return length(exactLength).numeric();
// }
| import java.util.stream.Stream;
import static io.qala.datagen.RandomShortApi.numeric; | package io.qala.datagen.junit.jupiter;
class NumericArgumentProvider extends RandomizedArgumentProvider<Numeric> {
private Numeric annotation;
@Override
public void accept(Numeric annotation) {
this.annotation = annotation;
}
@Override Stream<Object[]> getValueWithDescription() {
return Stream.of(annotation).map(NumericArgumentProvider::generateParams);
}
@Override Stream<Object> getValue() {
return Stream.of(annotation).map(NumericArgumentProvider::generateParam);
}
static String generateParam(Numeric annotation) { | // Path: datagen/src/main/java/io/qala/datagen/RandomShortApi.java
// public static String numeric(int exactLength) {
// return length(exactLength).numeric();
// }
// Path: junit5/src/main/java/io/qala/datagen/junit/jupiter/NumericArgumentProvider.java
import java.util.stream.Stream;
import static io.qala.datagen.RandomShortApi.numeric;
package io.qala.datagen.junit.jupiter;
class NumericArgumentProvider extends RandomizedArgumentProvider<Numeric> {
private Numeric annotation;
@Override
public void accept(Numeric annotation) {
this.annotation = annotation;
}
@Override Stream<Object[]> getValueWithDescription() {
return Stream.of(annotation).map(NumericArgumentProvider::generateParams);
}
@Override Stream<Object> getValue() {
return Stream.of(annotation).map(NumericArgumentProvider::generateParam);
}
static String generateParam(Numeric annotation) { | if (annotation.length() > 0) return numeric(annotation.length()); |
qala-io/datagen | junit5/src/main/java/io/qala/datagen/junit/jupiter/DatagenUtils.java | // Path: datagen/src/main/java/io/qala/datagen/adaptors/DatagenRandom.java
// @SuppressWarnings("AnonymousHasLambdaAlternative"/*this is compiled for Java5*/)
// public class DatagenRandom extends Random {
// //Public Morozov. Need this to be available for classes in this package.
// @Override public int next(int bits) {
// long oldseed = getCurrentSeed(), nextseed;
// do {
// nextseed = (oldseed * multiplier + addend) & mask;
// } while (oldseed == nextseed);
//
// super.setSeed(nextseed);
// overrideSeed(nextseed);
// return (int)(nextseed >>> (48 - bits));
// }
//
// @SuppressWarnings("WeakerAccess")
// public static void overrideSeed(long seed) { SEEDS.set(seed) ;}
// @SuppressWarnings("WeakerAccess")
// public static long getCurrentSeed() { return SEEDS.get();}
//
// private static final long multiplier = 0x5DEECE66DL;
// private static final long addend = 0xBL;
// private static final long mask = (1L << 48) - 1;
// private static final ThreadLocal<Long> SEEDS = new ThreadLocal<Long>() {
// @Override protected Long initialValue() {
// return System.nanoTime();
// }
// };
// }
| import io.qala.datagen.adaptors.DatagenRandom;
import io.qala.datagen.Seed;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.api.extension.ExtensionContext.Namespace;
import org.junit.jupiter.api.extension.ExtensionContext.Store;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.Method;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Optional; | package io.qala.datagen.junit.jupiter;
public class DatagenUtils {
private static final Logger LOG = LoggerFactory.getLogger(DatagenUtils.class);
static boolean passCaseNameToTestMethod(ExtensionContext context) {
Optional<Method> testMethod = context.getTestMethod();
return testMethod.filter(method -> method.getParameterCount() == 2).isPresent();
}
public static void setCurrentSeedIfNotSetYet(ExtensionContext context) {
if(getCurrentLevelSeedFromStore(context) != null) return;
Optional<Method> testMethod = context.getTestMethod();
Optional<Class<?>> testClass = context.getTestClass();
if(testMethod.isPresent()) {
Seed annotation = testMethod.get().getAnnotation(Seed.class); | // Path: datagen/src/main/java/io/qala/datagen/adaptors/DatagenRandom.java
// @SuppressWarnings("AnonymousHasLambdaAlternative"/*this is compiled for Java5*/)
// public class DatagenRandom extends Random {
// //Public Morozov. Need this to be available for classes in this package.
// @Override public int next(int bits) {
// long oldseed = getCurrentSeed(), nextseed;
// do {
// nextseed = (oldseed * multiplier + addend) & mask;
// } while (oldseed == nextseed);
//
// super.setSeed(nextseed);
// overrideSeed(nextseed);
// return (int)(nextseed >>> (48 - bits));
// }
//
// @SuppressWarnings("WeakerAccess")
// public static void overrideSeed(long seed) { SEEDS.set(seed) ;}
// @SuppressWarnings("WeakerAccess")
// public static long getCurrentSeed() { return SEEDS.get();}
//
// private static final long multiplier = 0x5DEECE66DL;
// private static final long addend = 0xBL;
// private static final long mask = (1L << 48) - 1;
// private static final ThreadLocal<Long> SEEDS = new ThreadLocal<Long>() {
// @Override protected Long initialValue() {
// return System.nanoTime();
// }
// };
// }
// Path: junit5/src/main/java/io/qala/datagen/junit/jupiter/DatagenUtils.java
import io.qala.datagen.adaptors.DatagenRandom;
import io.qala.datagen.Seed;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.api.extension.ExtensionContext.Namespace;
import org.junit.jupiter.api.extension.ExtensionContext.Store;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.Method;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Optional;
package io.qala.datagen.junit.jupiter;
public class DatagenUtils {
private static final Logger LOG = LoggerFactory.getLogger(DatagenUtils.class);
static boolean passCaseNameToTestMethod(ExtensionContext context) {
Optional<Method> testMethod = context.getTestMethod();
return testMethod.filter(method -> method.getParameterCount() == 2).isPresent();
}
public static void setCurrentSeedIfNotSetYet(ExtensionContext context) {
if(getCurrentLevelSeedFromStore(context) != null) return;
Optional<Method> testMethod = context.getTestMethod();
Optional<Class<?>> testClass = context.getTestClass();
if(testMethod.isPresent()) {
Seed annotation = testMethod.get().getAnnotation(Seed.class); | if (annotation != null) DatagenRandom.overrideSeed(annotation.value()); |
qala-io/datagen | datagen/src/main/java/io/qala/datagen/Repeater.java | // Path: datagen/src/main/java/io/qala/datagen/RandomShortApi.java
// public static int integer(int max) {
// return between(0, max).integer();
// }
| import java.util.ArrayList;
import java.util.List;
import static io.qala.datagen.RandomShortApi.integer; | package io.qala.datagen;
/**
* If the resulting string should have repeats, this class can do this. Note, that often there are separators between
* the repeats which should be trimmed at the end - and this trimming is the default behaviour. To switch it off
* use {@link #includeLastSymbol()}.
*/
@SuppressWarnings("WeakerAccess")
public class Repeater {
private final List<Object> toRepeat = new ArrayList<Object>();
private int nOfLastSymbolsToRemove = 1;
public static Repeater repeat(String toRepeat) {
return new Repeater().string(toRepeat);
}
public static Repeater repeat(RandomValue randomValue, RandomString.Type type) {
return new Repeater().random(randomValue, type);
}
public Repeater random(RandomValue randomValue, RandomString.Type type) {
toRepeat.add(new RandomValueRecorder(randomValue, type));
return this;
}
public Repeater string(String notRandomString) {
toRepeat.add(notRandomString);
return this;
}
public Repeater removeLastSymbols(int nOfSymbolsToRemoveFromTheEnd) {
this.nOfLastSymbolsToRemove = nOfSymbolsToRemoveFromTheEnd;
return this;
}
public Repeater includeLastSymbol() {
this.nOfLastSymbolsToRemove = 0;
return this;
}
public String times(int min, int max) {
if(min < 0) throw new IllegalArgumentException("I cannot repeat string negative number of times"); | // Path: datagen/src/main/java/io/qala/datagen/RandomShortApi.java
// public static int integer(int max) {
// return between(0, max).integer();
// }
// Path: datagen/src/main/java/io/qala/datagen/Repeater.java
import java.util.ArrayList;
import java.util.List;
import static io.qala.datagen.RandomShortApi.integer;
package io.qala.datagen;
/**
* If the resulting string should have repeats, this class can do this. Note, that often there are separators between
* the repeats which should be trimmed at the end - and this trimming is the default behaviour. To switch it off
* use {@link #includeLastSymbol()}.
*/
@SuppressWarnings("WeakerAccess")
public class Repeater {
private final List<Object> toRepeat = new ArrayList<Object>();
private int nOfLastSymbolsToRemove = 1;
public static Repeater repeat(String toRepeat) {
return new Repeater().string(toRepeat);
}
public static Repeater repeat(RandomValue randomValue, RandomString.Type type) {
return new Repeater().random(randomValue, type);
}
public Repeater random(RandomValue randomValue, RandomString.Type type) {
toRepeat.add(new RandomValueRecorder(randomValue, type));
return this;
}
public Repeater string(String notRandomString) {
toRepeat.add(notRandomString);
return this;
}
public Repeater removeLastSymbols(int nOfSymbolsToRemoveFromTheEnd) {
this.nOfLastSymbolsToRemove = nOfSymbolsToRemoveFromTheEnd;
return this;
}
public Repeater includeLastSymbol() {
this.nOfLastSymbolsToRemove = 0;
return this;
}
public String times(int min, int max) {
if(min < 0) throw new IllegalArgumentException("I cannot repeat string negative number of times"); | return times(integer(min, max)); |
qala-io/datagen | examples/src/test/java/io/qala/datagen/examples/_45_ModelBasedTest.java | // Path: datagen/src/main/java/io/qala/datagen/RandomShortApi.java
// public static <T> T sample(Collection<T> toSampleFrom) {
// return from(toSampleFrom).sample();
// }
| import org.junit.Test;
import java.util.List;
import static io.qala.datagen.RandomShortApi.sample; | package io.qala.datagen.examples;
@SuppressWarnings("unchecked")
public class _45_ModelBasedTest {
@Test public void addingMaterials() {
OrderingTestModel model = new OrderingTestModel();
model.createExperiment();
goOverModel(model.allActions(), 10000);
}
private static void goOverModel(List<Runnable> actions, int nTimes) { | // Path: datagen/src/main/java/io/qala/datagen/RandomShortApi.java
// public static <T> T sample(Collection<T> toSampleFrom) {
// return from(toSampleFrom).sample();
// }
// Path: examples/src/test/java/io/qala/datagen/examples/_45_ModelBasedTest.java
import org.junit.Test;
import java.util.List;
import static io.qala.datagen.RandomShortApi.sample;
package io.qala.datagen.examples;
@SuppressWarnings("unchecked")
public class _45_ModelBasedTest {
@Test public void addingMaterials() {
OrderingTestModel model = new OrderingTestModel();
model.createExperiment();
goOverModel(model.allActions(), 10000);
}
private static void goOverModel(List<Runnable> actions, int nTimes) { | for (int i = 0; i < nTimes; i++) sample(actions).run(); |
qala-io/datagen | examples/src/main/java/io/qala/datagen/examples/Person.java | // Path: datagen/src/main/java/io/qala/datagen/RandomShortApi.java
// public static String blankOr(String string) {
// return sample(nullOrBlank(), string);
// }
//
// Path: datagen/src/main/java/io/qala/datagen/RandomShortApi.java
// public static String english(int exactLength) {
// return length(exactLength).english();
// }
| import org.apache.commons.lang3.StringUtils;
import static io.qala.datagen.RandomShortApi.blankOr;
import static io.qala.datagen.RandomShortApi.english; | return firstName;
}
Person lastName(String lastName) {
this.lastName = lastName;
return this;
}
String lastName() {
return lastName;
}
String username() { return username; }
Person country(Country country) {//String - not Country
this.country = country;
return this;
}
Country country() {
return country;
}
private static final int USERNAME_MAX_LENGTH = 20;
void validate() throws IllegalStateException {
if (StringUtils.isBlank(username()))
throw new IllegalStateException("Java Constraints violation: username is mandatory! Passed: [" + username() + "]");
if (username().length() > USERNAME_MAX_LENGTH)
throw new IllegalStateException("Java Constraints violation: username [" + username() + "] cannot be more than " + USERNAME_MAX_LENGTH + "!");
}
static Person random() { | // Path: datagen/src/main/java/io/qala/datagen/RandomShortApi.java
// public static String blankOr(String string) {
// return sample(nullOrBlank(), string);
// }
//
// Path: datagen/src/main/java/io/qala/datagen/RandomShortApi.java
// public static String english(int exactLength) {
// return length(exactLength).english();
// }
// Path: examples/src/main/java/io/qala/datagen/examples/Person.java
import org.apache.commons.lang3.StringUtils;
import static io.qala.datagen.RandomShortApi.blankOr;
import static io.qala.datagen.RandomShortApi.english;
return firstName;
}
Person lastName(String lastName) {
this.lastName = lastName;
return this;
}
String lastName() {
return lastName;
}
String username() { return username; }
Person country(Country country) {//String - not Country
this.country = country;
return this;
}
Country country() {
return country;
}
private static final int USERNAME_MAX_LENGTH = 20;
void validate() throws IllegalStateException {
if (StringUtils.isBlank(username()))
throw new IllegalStateException("Java Constraints violation: username is mandatory! Passed: [" + username() + "]");
if (username().length() > USERNAME_MAX_LENGTH)
throw new IllegalStateException("Java Constraints violation: username [" + username() + "] cannot be more than " + USERNAME_MAX_LENGTH + "!");
}
static Person random() { | return new Person(english(1, 20)).country(Country.random()) |
qala-io/datagen | examples/src/main/java/io/qala/datagen/examples/Person.java | // Path: datagen/src/main/java/io/qala/datagen/RandomShortApi.java
// public static String blankOr(String string) {
// return sample(nullOrBlank(), string);
// }
//
// Path: datagen/src/main/java/io/qala/datagen/RandomShortApi.java
// public static String english(int exactLength) {
// return length(exactLength).english();
// }
| import org.apache.commons.lang3.StringUtils;
import static io.qala.datagen.RandomShortApi.blankOr;
import static io.qala.datagen.RandomShortApi.english; | }
Person lastName(String lastName) {
this.lastName = lastName;
return this;
}
String lastName() {
return lastName;
}
String username() { return username; }
Person country(Country country) {//String - not Country
this.country = country;
return this;
}
Country country() {
return country;
}
private static final int USERNAME_MAX_LENGTH = 20;
void validate() throws IllegalStateException {
if (StringUtils.isBlank(username()))
throw new IllegalStateException("Java Constraints violation: username is mandatory! Passed: [" + username() + "]");
if (username().length() > USERNAME_MAX_LENGTH)
throw new IllegalStateException("Java Constraints violation: username [" + username() + "] cannot be more than " + USERNAME_MAX_LENGTH + "!");
}
static Person random() {
return new Person(english(1, 20)).country(Country.random()) | // Path: datagen/src/main/java/io/qala/datagen/RandomShortApi.java
// public static String blankOr(String string) {
// return sample(nullOrBlank(), string);
// }
//
// Path: datagen/src/main/java/io/qala/datagen/RandomShortApi.java
// public static String english(int exactLength) {
// return length(exactLength).english();
// }
// Path: examples/src/main/java/io/qala/datagen/examples/Person.java
import org.apache.commons.lang3.StringUtils;
import static io.qala.datagen.RandomShortApi.blankOr;
import static io.qala.datagen.RandomShortApi.english;
}
Person lastName(String lastName) {
this.lastName = lastName;
return this;
}
String lastName() {
return lastName;
}
String username() { return username; }
Person country(Country country) {//String - not Country
this.country = country;
return this;
}
Country country() {
return country;
}
private static final int USERNAME_MAX_LENGTH = 20;
void validate() throws IllegalStateException {
if (StringUtils.isBlank(username()))
throw new IllegalStateException("Java Constraints violation: username is mandatory! Passed: [" + username() + "]");
if (username().length() > USERNAME_MAX_LENGTH)
throw new IllegalStateException("Java Constraints violation: username [" + username() + "] cannot be more than " + USERNAME_MAX_LENGTH + "!");
}
static Person random() {
return new Person(english(1, 20)).country(Country.random()) | .firstName(blankOr(english(1, 20))).lastName(blankOr(english(1, 20))); |
qala-io/datagen | junit5/src/main/java/io/qala/datagen/junit/jupiter/EnglishArgumentProvider.java | // Path: datagen/src/main/java/io/qala/datagen/RandomShortApi.java
// public static String english(int exactLength) {
// return length(exactLength).english();
// }
| import java.util.stream.Stream;
import static io.qala.datagen.RandomShortApi.english; | package io.qala.datagen.junit.jupiter;
class EnglishArgumentProvider extends RandomizedArgumentProvider<English> {
private English annotation;
@Override
public void accept(English annotation) {
this.annotation = annotation;
}
@Override Stream<Object[]> getValueWithDescription() {
return Stream.of(annotation).map(EnglishArgumentProvider::generateParams);
}
@Override Stream<Object> getValue() {
return Stream.of(annotation).map(EnglishArgumentProvider::generateParam);
}
static String generateParam(English annotation) { | // Path: datagen/src/main/java/io/qala/datagen/RandomShortApi.java
// public static String english(int exactLength) {
// return length(exactLength).english();
// }
// Path: junit5/src/main/java/io/qala/datagen/junit/jupiter/EnglishArgumentProvider.java
import java.util.stream.Stream;
import static io.qala.datagen.RandomShortApi.english;
package io.qala.datagen.junit.jupiter;
class EnglishArgumentProvider extends RandomizedArgumentProvider<English> {
private English annotation;
@Override
public void accept(English annotation) {
this.annotation = annotation;
}
@Override Stream<Object[]> getValueWithDescription() {
return Stream.of(annotation).map(EnglishArgumentProvider::generateParams);
}
@Override Stream<Object> getValue() {
return Stream.of(annotation).map(EnglishArgumentProvider::generateParam);
}
static String generateParam(English annotation) { | if (annotation.length() > 0) return english(annotation.length()); |
qala-io/datagen | datagen/src/main/java/io/qala/datagen/RandomElements.java | // Path: datagen/src/main/java/io/qala/datagen/RandomShortApi.java
// public static int integer(int max) {
// return between(0, max).integer();
// }
| import java.util.*;
import static io.qala.datagen.RandomShortApi.integer; | package io.qala.datagen;
@SuppressWarnings({"Convert2Diamond", "WeakerAccess"})
public class RandomElements<T> {
private final List<T> elements;
private RandomElements(T[] elements) {
this(Arrays.asList(elements));
}
private RandomElements(Collection<T> elements) {
this.elements = new ArrayList<T>(elements);
}
/**
* In case you have a collection and then couple of other elements you want to sample from too, but you don't want
* to create a collection that includes all of them combined.
*
* @param elements the collection
* @param others other elements you'd like to include into population to sample from
* @return a random element from all the listed elements/other elements
*/
@SafeVarargs public static <T> RandomElements<T> from(Collection<T> elements, T... others) {
Collection<T> coll = new ArrayList<T>(elements);
coll.addAll(Arrays.asList(others));
return new RandomElements<T>(coll);
}
@SafeVarargs public static <T> RandomElements<T> from(T... elements) {
return new RandomElements<T>(elements);
}
/**
* Returns random element from the collection.
*
* @return a random element from the collection
*/
public T sample() {
assertCollectionIsNotEmpty(); | // Path: datagen/src/main/java/io/qala/datagen/RandomShortApi.java
// public static int integer(int max) {
// return between(0, max).integer();
// }
// Path: datagen/src/main/java/io/qala/datagen/RandomElements.java
import java.util.*;
import static io.qala.datagen.RandomShortApi.integer;
package io.qala.datagen;
@SuppressWarnings({"Convert2Diamond", "WeakerAccess"})
public class RandomElements<T> {
private final List<T> elements;
private RandomElements(T[] elements) {
this(Arrays.asList(elements));
}
private RandomElements(Collection<T> elements) {
this.elements = new ArrayList<T>(elements);
}
/**
* In case you have a collection and then couple of other elements you want to sample from too, but you don't want
* to create a collection that includes all of them combined.
*
* @param elements the collection
* @param others other elements you'd like to include into population to sample from
* @return a random element from all the listed elements/other elements
*/
@SafeVarargs public static <T> RandomElements<T> from(Collection<T> elements, T... others) {
Collection<T> coll = new ArrayList<T>(elements);
coll.addAll(Arrays.asList(others));
return new RandomElements<T>(coll);
}
@SafeVarargs public static <T> RandomElements<T> from(T... elements) {
return new RandomElements<T>(elements);
}
/**
* Returns random element from the collection.
*
* @return a random element from the collection
*/
public T sample() {
assertCollectionIsNotEmpty(); | int index = integer(size() - 1); |
qala-io/datagen | junit5/src/main/java/io/qala/datagen/junit/jupiter/UnicodeArgumentProvider.java | // Path: datagen/src/main/java/io/qala/datagen/RandomShortApi.java
// public static String unicode(int exactLength) {
// return length(exactLength).unicode();
// }
| import java.util.stream.Stream;
import static io.qala.datagen.RandomShortApi.unicode; | package io.qala.datagen.junit.jupiter;
class UnicodeArgumentProvider extends RandomizedArgumentProvider<Unicode> {
private Unicode annotation;
@Override
public void accept(Unicode annotation) {
this.annotation = annotation;
}
@Override Stream<Object[]> getValueWithDescription() {
return Stream.of(annotation).map(UnicodeArgumentProvider::generateParams);
}
@Override Stream<Object> getValue() {
return Stream.of(annotation).map(UnicodeArgumentProvider::generateParam);
}
static String generateParam(Unicode annotation) { | // Path: datagen/src/main/java/io/qala/datagen/RandomShortApi.java
// public static String unicode(int exactLength) {
// return length(exactLength).unicode();
// }
// Path: junit5/src/main/java/io/qala/datagen/junit/jupiter/UnicodeArgumentProvider.java
import java.util.stream.Stream;
import static io.qala.datagen.RandomShortApi.unicode;
package io.qala.datagen.junit.jupiter;
class UnicodeArgumentProvider extends RandomizedArgumentProvider<Unicode> {
private Unicode annotation;
@Override
public void accept(Unicode annotation) {
this.annotation = annotation;
}
@Override Stream<Object[]> getValueWithDescription() {
return Stream.of(annotation).map(UnicodeArgumentProvider::generateParams);
}
@Override Stream<Object> getValue() {
return Stream.of(annotation).map(UnicodeArgumentProvider::generateParam);
}
static String generateParam(Unicode annotation) { | if (annotation.length() > 0) return unicode(annotation.length()); |
qala-io/datagen | java8types/src/main/java/io/qala/datagen/RandomDate.java | // Path: datagen/src/main/java/io/qala/datagen/RandomShortApi.java
// public static <T> T sample(Collection<T> toSampleFrom) {
// return from(toSampleFrom).sample();
// }
| import java.time.*;
import java.time.chrono.ChronoLocalDateTime;
import java.time.chrono.ChronoZonedDateTime;
import java.util.ArrayList;
import java.util.List;
import static io.qala.datagen.RandomShortApi.sample;
import static java.time.temporal.ChronoUnit.HOURS;
import static java.time.temporal.ChronoUnit.SECONDS; |
public static RandomDate plusMinus100Years() {
return between(yearsAgo(100), inYears(100));
}
public Instant instant() {
int MAX_NANO = 999_999_999;
long minSecond = from.getEpochSecond();
long maxSecond = to.getEpochSecond();
long randomSeconds = RandomValue.between(minSecond, maxSecond).Long();
int fromNano = from.getNano();
int toNano = to.getNano();
long nano = 0;
if (minSecond == maxSecond) nano = RandomValue.between(fromNano, toNano).Long();
else if (randomSeconds == maxSecond) nano = RandomValue.between(0, toNano).Long();
else if (randomSeconds == minSecond) nano = RandomValue.between(fromNano, MAX_NANO).Long();
return Instant.ofEpochSecond(randomSeconds, nano);
}
public List<Instant> instants(int n) {
return multiply(n, this::instant);
}
public LocalDateTime localDateTime() {
return LocalDateTime.ofInstant(instant(), ZoneId.systemDefault());
}
public List<LocalDateTime> localDateTimes(int nOfTimes) {
return multiply(nOfTimes, this::localDateTime);
}
public ZonedDateTime zonedDateTime() { | // Path: datagen/src/main/java/io/qala/datagen/RandomShortApi.java
// public static <T> T sample(Collection<T> toSampleFrom) {
// return from(toSampleFrom).sample();
// }
// Path: java8types/src/main/java/io/qala/datagen/RandomDate.java
import java.time.*;
import java.time.chrono.ChronoLocalDateTime;
import java.time.chrono.ChronoZonedDateTime;
import java.util.ArrayList;
import java.util.List;
import static io.qala.datagen.RandomShortApi.sample;
import static java.time.temporal.ChronoUnit.HOURS;
import static java.time.temporal.ChronoUnit.SECONDS;
public static RandomDate plusMinus100Years() {
return between(yearsAgo(100), inYears(100));
}
public Instant instant() {
int MAX_NANO = 999_999_999;
long minSecond = from.getEpochSecond();
long maxSecond = to.getEpochSecond();
long randomSeconds = RandomValue.between(minSecond, maxSecond).Long();
int fromNano = from.getNano();
int toNano = to.getNano();
long nano = 0;
if (minSecond == maxSecond) nano = RandomValue.between(fromNano, toNano).Long();
else if (randomSeconds == maxSecond) nano = RandomValue.between(0, toNano).Long();
else if (randomSeconds == minSecond) nano = RandomValue.between(fromNano, MAX_NANO).Long();
return Instant.ofEpochSecond(randomSeconds, nano);
}
public List<Instant> instants(int n) {
return multiply(n, this::instant);
}
public LocalDateTime localDateTime() {
return LocalDateTime.ofInstant(instant(), ZoneId.systemDefault());
}
public List<LocalDateTime> localDateTimes(int nOfTimes) {
return multiply(nOfTimes, this::localDateTime);
}
public ZonedDateTime zonedDateTime() { | return ZonedDateTime.ofInstant(instant(), ZoneId.of(sample(ZoneId.getAvailableZoneIds()))); |
qala-io/datagen | junit5/src/main/java/io/qala/datagen/junit/jupiter/RandomLongArgumentProvider.java | // Path: datagen/src/main/java/io/qala/datagen/RandomShortApi.java
// public static long Long() {
// return between(Long.MIN_VALUE, Long.MAX_VALUE).Long();
// }
| import java.util.stream.Stream;
import static io.qala.datagen.RandomShortApi.Long; | package io.qala.datagen.junit.jupiter;
class RandomLongArgumentProvider extends RandomizedArgumentProvider<RandomLong> {
private RandomLong annotation;
@Override
public void accept(RandomLong annotation) {
this.annotation = annotation;
}
@Override Stream<Object[]> getValueWithDescription() {
return Stream.of(annotation).map(RandomLongArgumentProvider::generateParams);
}
@Override Stream<Object> getValue() {
return Stream.of(annotation).map(RandomLongArgumentProvider::generateParam);
}
static long generateParam(RandomLong annotation) { | // Path: datagen/src/main/java/io/qala/datagen/RandomShortApi.java
// public static long Long() {
// return between(Long.MIN_VALUE, Long.MAX_VALUE).Long();
// }
// Path: junit5/src/main/java/io/qala/datagen/junit/jupiter/RandomLongArgumentProvider.java
import java.util.stream.Stream;
import static io.qala.datagen.RandomShortApi.Long;
package io.qala.datagen.junit.jupiter;
class RandomLongArgumentProvider extends RandomizedArgumentProvider<RandomLong> {
private RandomLong annotation;
@Override
public void accept(RandomLong annotation) {
this.annotation = annotation;
}
@Override Stream<Object[]> getValueWithDescription() {
return Stream.of(annotation).map(RandomLongArgumentProvider::generateParams);
}
@Override Stream<Object> getValue() {
return Stream.of(annotation).map(RandomLongArgumentProvider::generateParam);
}
static long generateParam(RandomLong annotation) { | return Long(annotation.min(), annotation.max()); |
qala-io/datagen | examples/src/test/java/io/qala/datagen/examples/_20_BigClassTest.java | // Path: datagen/src/main/java/io/qala/datagen/RandomShortApi.java
// public static String numeric(int exactLength) {
// return length(exactLength).numeric();
// }
| import org.junit.Test;
import java.time.ZonedDateTime;
import java.time.temporal.ChronoUnit;
import static io.qala.datagen.RandomShortApi.numeric; | package io.qala.datagen.examples;
public class _20_BigClassTest {
@Test public void accountNumberValidation_passesForHappyPath() {
Account account = new Account();
account.setCreatedTime(ZonedDateTime.now().minus(100, ChronoUnit.DAYS));
account.setInterestRate(.2);
account.setOpenedIn(Country.US);
account.setPrimaryOwner(new Person("username").country(Country.AD));
account.setSecondaryOwner(new Person("username2").country(Country.AE));
account.setNumber("0123456789");
account.validate();
}
@Test public void accountNumberValidation_passesForHappyPath_randomization() {
Account account = Account.random(); | // Path: datagen/src/main/java/io/qala/datagen/RandomShortApi.java
// public static String numeric(int exactLength) {
// return length(exactLength).numeric();
// }
// Path: examples/src/test/java/io/qala/datagen/examples/_20_BigClassTest.java
import org.junit.Test;
import java.time.ZonedDateTime;
import java.time.temporal.ChronoUnit;
import static io.qala.datagen.RandomShortApi.numeric;
package io.qala.datagen.examples;
public class _20_BigClassTest {
@Test public void accountNumberValidation_passesForHappyPath() {
Account account = new Account();
account.setCreatedTime(ZonedDateTime.now().minus(100, ChronoUnit.DAYS));
account.setInterestRate(.2);
account.setOpenedIn(Country.US);
account.setPrimaryOwner(new Person("username").country(Country.AD));
account.setSecondaryOwner(new Person("username2").country(Country.AE));
account.setNumber("0123456789");
account.validate();
}
@Test public void accountNumberValidation_passesForHappyPath_randomization() {
Account account = Account.random(); | account.setNumber(numeric(10)); |
qala-io/datagen | junit5/src/main/java/io/qala/datagen/junit/jupiter/seed/DatagenSeedExtension.java | // Path: junit5/src/main/java/io/qala/datagen/junit/jupiter/DatagenUtils.java
// public class DatagenUtils {
// private static final Logger LOG = LoggerFactory.getLogger(DatagenUtils.class);
//
// static boolean passCaseNameToTestMethod(ExtensionContext context) {
// Optional<Method> testMethod = context.getTestMethod();
// return testMethod.filter(method -> method.getParameterCount() == 2).isPresent();
// }
//
// public static void setCurrentSeedIfNotSetYet(ExtensionContext context) {
// if(getCurrentLevelSeedFromStore(context) != null) return;
//
// Optional<Method> testMethod = context.getTestMethod();
// Optional<Class<?>> testClass = context.getTestClass();
// if(testMethod.isPresent()) {
// Seed annotation = testMethod.get().getAnnotation(Seed.class);
// if (annotation != null) DatagenRandom.overrideSeed(annotation.value());
// } else if(testClass.isPresent()) {
// Seed annotation = testClass.get().getAnnotation(Seed.class);
// if (annotation != null) DatagenRandom.overrideSeed(annotation.value());
// }
// putSeedToStoreIfAbsent(context, DatagenRandom.getCurrentSeed());
// }
//
// public static void logCurrentSeeds(ExtensionContext context) {
// LinkedHashMap<String, Long> seedStrings = new LinkedHashMap<>();
// while(context != null) {
// Long seed = getCurrentLevelSeedFromStore(context);
// Optional<Method> testMethod = context.getTestMethod();
// Optional<Class<?>> testClass = context.getTestClass();
// if(testMethod.isPresent()) seedStrings.putIfAbsent(testMethod.get().getName(), seed);
// else testClass.ifPresent((c)->seedStrings.put(c.getSimpleName(), seed));
//
// context = context.getParent().isPresent() ? context.getParent().get() : null;
// }
// StringBuilder logLine = new StringBuilder();
// for(Map.Entry<String, Long> seed: seedStrings.entrySet()) {
// logLine.append(" ").append(seed.getKey()).append("[").append(seed.getValue()).append("]");
// }
// if(logLine.length() != 0) LOG.info("Random Seeds: {}", logLine);
// }
//
// private static void putSeedToStoreIfAbsent(ExtensionContext context, Long seed) {
// Store store = getStore(context);
// if(store != null) store.put("seed", seed);
// }
// private static Long getCurrentLevelSeedFromStore(ExtensionContext context) {
// Store store = getStore(context);
// Object seed = null;
// if(store != null) seed = store.get("seed");
// return seed != null ? (Long) seed : null;
// }
// private static Store getStore(ExtensionContext context) {
// Store store = getMethodStore(context);
// if(store == null) store = getClassStore(context);
// return store;
// }
//
// private static Store getMethodStore(ExtensionContext context) {
// Optional<Method> m = context.getTestMethod();
// if (m.isPresent()) return context.getStore(Namespace.create(DatagenUtils.class, m.get()));
// return null;
// }
//
// private static Store getClassStore(ExtensionContext context) {
// Optional<Class<?>> c = context.getTestClass();
// if (c.isPresent()) return context.getStore(Namespace.create(DatagenUtils.class, c.get()));
// return null;
// }
// }
| import io.qala.datagen.junit.jupiter.DatagenUtils;
import org.junit.jupiter.api.extension.*; | package io.qala.datagen.junit.jupiter.seed;
/**
* Logs the seeds of the failed methods so that it's possible to re-run tests with the same data generated.
* Unfortunately right now
* <a href="https://github.com/junit-team/junit5/issues/618">JUnit5 doesn't have means to know which test failed</a>
* and which passed, so currently the seed is printed for each test method that threw exception.
*
* @see io.qala.datagen.Seed
*/
public class DatagenSeedExtension implements BeforeTestExecutionCallback, BeforeAllCallback, TestExecutionExceptionHandler {
@Override
public void handleTestExecutionException(ExtensionContext context, Throwable throwable) throws Throwable { | // Path: junit5/src/main/java/io/qala/datagen/junit/jupiter/DatagenUtils.java
// public class DatagenUtils {
// private static final Logger LOG = LoggerFactory.getLogger(DatagenUtils.class);
//
// static boolean passCaseNameToTestMethod(ExtensionContext context) {
// Optional<Method> testMethod = context.getTestMethod();
// return testMethod.filter(method -> method.getParameterCount() == 2).isPresent();
// }
//
// public static void setCurrentSeedIfNotSetYet(ExtensionContext context) {
// if(getCurrentLevelSeedFromStore(context) != null) return;
//
// Optional<Method> testMethod = context.getTestMethod();
// Optional<Class<?>> testClass = context.getTestClass();
// if(testMethod.isPresent()) {
// Seed annotation = testMethod.get().getAnnotation(Seed.class);
// if (annotation != null) DatagenRandom.overrideSeed(annotation.value());
// } else if(testClass.isPresent()) {
// Seed annotation = testClass.get().getAnnotation(Seed.class);
// if (annotation != null) DatagenRandom.overrideSeed(annotation.value());
// }
// putSeedToStoreIfAbsent(context, DatagenRandom.getCurrentSeed());
// }
//
// public static void logCurrentSeeds(ExtensionContext context) {
// LinkedHashMap<String, Long> seedStrings = new LinkedHashMap<>();
// while(context != null) {
// Long seed = getCurrentLevelSeedFromStore(context);
// Optional<Method> testMethod = context.getTestMethod();
// Optional<Class<?>> testClass = context.getTestClass();
// if(testMethod.isPresent()) seedStrings.putIfAbsent(testMethod.get().getName(), seed);
// else testClass.ifPresent((c)->seedStrings.put(c.getSimpleName(), seed));
//
// context = context.getParent().isPresent() ? context.getParent().get() : null;
// }
// StringBuilder logLine = new StringBuilder();
// for(Map.Entry<String, Long> seed: seedStrings.entrySet()) {
// logLine.append(" ").append(seed.getKey()).append("[").append(seed.getValue()).append("]");
// }
// if(logLine.length() != 0) LOG.info("Random Seeds: {}", logLine);
// }
//
// private static void putSeedToStoreIfAbsent(ExtensionContext context, Long seed) {
// Store store = getStore(context);
// if(store != null) store.put("seed", seed);
// }
// private static Long getCurrentLevelSeedFromStore(ExtensionContext context) {
// Store store = getStore(context);
// Object seed = null;
// if(store != null) seed = store.get("seed");
// return seed != null ? (Long) seed : null;
// }
// private static Store getStore(ExtensionContext context) {
// Store store = getMethodStore(context);
// if(store == null) store = getClassStore(context);
// return store;
// }
//
// private static Store getMethodStore(ExtensionContext context) {
// Optional<Method> m = context.getTestMethod();
// if (m.isPresent()) return context.getStore(Namespace.create(DatagenUtils.class, m.get()));
// return null;
// }
//
// private static Store getClassStore(ExtensionContext context) {
// Optional<Class<?>> c = context.getTestClass();
// if (c.isPresent()) return context.getStore(Namespace.create(DatagenUtils.class, c.get()));
// return null;
// }
// }
// Path: junit5/src/main/java/io/qala/datagen/junit/jupiter/seed/DatagenSeedExtension.java
import io.qala.datagen.junit.jupiter.DatagenUtils;
import org.junit.jupiter.api.extension.*;
package io.qala.datagen.junit.jupiter.seed;
/**
* Logs the seeds of the failed methods so that it's possible to re-run tests with the same data generated.
* Unfortunately right now
* <a href="https://github.com/junit-team/junit5/issues/618">JUnit5 doesn't have means to know which test failed</a>
* and which passed, so currently the seed is printed for each test method that threw exception.
*
* @see io.qala.datagen.Seed
*/
public class DatagenSeedExtension implements BeforeTestExecutionCallback, BeforeAllCallback, TestExecutionExceptionHandler {
@Override
public void handleTestExecutionException(ExtensionContext context, Throwable throwable) throws Throwable { | context.getTestMethod().ifPresent((m) -> DatagenUtils.logCurrentSeeds(context)); |
qala-io/datagen | examples/src/main/java/io/qala/datagen/examples/Country.java | // Path: datagen/src/main/java/io/qala/datagen/RandomShortApi.java
// public static <T> T sample(Collection<T> toSampleFrom) {
// return from(toSampleFrom).sample();
// }
| import static io.qala.datagen.RandomShortApi.sample; | KE("Kenya"), KG("Kyrgyzstan"), KH("Cambodia"), KI("Kiribati"), KM("Comoros"), KN("Saint Kitts and Nevis"),
KP("Korea, North"), KR("Korea, South"), KW("Kuwait"), KY("Cayman Islands"), KZ("Kazakhstan"), LA("Laos"),
LB("Lebanon"), LC("Saint Lucia"), LI("Liechtenstein"), LK("Sri Lanka"), LR("Liberia"), LS("Lesotho"),
LT("Lithuania"), LU("Luxembourg"), LV("Latvia"), LY("Libya"), MA("Morocco"), MC("Monaco"), MD("Moldova"),
ME("Montenegro"), MF("Saint Martin"), MG("Madagascar"), MH("Marshall Islands"), MK("Macedonia"), ML("Mali"),
MM("Burma"), MN("Mongolia"), MO("Macau"), MP("Northern Mariana Islands"), MQ("Martinique"), MR("Mauritania"),
MS("Montserrat"), MT("Malta"), MU("Mauritius"), MV("Maldives"), MW("Malawi"), MX("Mexico"), MY("Malaysia"),
MZ("Mozambique"), NA("Namibia"), NC("New Caledonia"), NE("Niger"), NF("Norfolk Island"), NG("Nigeria"),
NI("Nicaragua"), NL("Netherlands"), NO("Norway"), NP("Nepal"), NR("Nauru"), NU("Niue"), NZ("New Zealand"),
OM("Oman"), PA("Panama"), PE("Peru"), PF("French Polynesia"), PG("Papua New Guinea"), PH("Philippines"),
PK("Pakistan"), PL("Poland"), PM("Saint Pierre and Miquelon"), PN("Pitcairn Islands"), PR("Puerto Rico"),
PS("West Bank"), PT("Portugal"), PW("Palau"), PY("Paraguay"), QA("Qatar"), RE("Reunion"), RO("Romania"),
RS("Serbia"), RU("Russia"), RW("Rwanda"), SA("Saudi Arabia"), SB("Solomon Islands"), SC("Seychelles"), SD("Sudan"),
SE("Sweden"), SG("Singapore"), SH("Saint Helena, Ascension, and Tristan da Cunha"), SI("Slovenia"), SJ("Svalbard"),
SK("Slovakia"), SL("Sierra Leone"), SM("San Marino"), SN("Senegal"), SO("Somalia"), SR("Suriname"),
SS("South Sudan"), ST("Sao Tome and Principe"), SV("El Salvador"), SX("Sint Maarten"), SY("Syria"), SZ("Swaziland"),
TC("Turks and Caicos Islands"), TD("Chad"), TF("French Southern and Antarctic Lands"), TG("Togo"), TH("Thailand"),
TJ("Tajikistan"), TK("Tokelau"), TL("Timor-Leste"), TM("Turkmenistan"), TN("Tunisia"), TO("Tonga"), TR("Turkey"),
TT("Trinidad and Tobago"), TV("Tuvalu"), TW("Taiwan"), TZ("Tanzania"), UA("Ukraine"), UG("Uganda"),
UM("United States Minor Outlying Islands"), US("United States"), UY("Uruguay"), UZ("Uzbekistan"),
VA("Holy See (Vatican City)"), VC("Saint Vincent and the Grenadines"), VE("Venezuela"), VG("British Virgin Islands"),
VI("Virgin Islands"), VN("Vietnam"), VU("Vanuatu"), WF("Wallis and Futuna"), WS("Samoa"), XK("Kosovo"), YE("Yemen"),
YT("Mayotte"), ZA("South Africa"), ZM("Zambia"), ZW("Zimbabwe");
String name;
Country(String name) {
this.name = name;
}
public static Country random() { | // Path: datagen/src/main/java/io/qala/datagen/RandomShortApi.java
// public static <T> T sample(Collection<T> toSampleFrom) {
// return from(toSampleFrom).sample();
// }
// Path: examples/src/main/java/io/qala/datagen/examples/Country.java
import static io.qala.datagen.RandomShortApi.sample;
KE("Kenya"), KG("Kyrgyzstan"), KH("Cambodia"), KI("Kiribati"), KM("Comoros"), KN("Saint Kitts and Nevis"),
KP("Korea, North"), KR("Korea, South"), KW("Kuwait"), KY("Cayman Islands"), KZ("Kazakhstan"), LA("Laos"),
LB("Lebanon"), LC("Saint Lucia"), LI("Liechtenstein"), LK("Sri Lanka"), LR("Liberia"), LS("Lesotho"),
LT("Lithuania"), LU("Luxembourg"), LV("Latvia"), LY("Libya"), MA("Morocco"), MC("Monaco"), MD("Moldova"),
ME("Montenegro"), MF("Saint Martin"), MG("Madagascar"), MH("Marshall Islands"), MK("Macedonia"), ML("Mali"),
MM("Burma"), MN("Mongolia"), MO("Macau"), MP("Northern Mariana Islands"), MQ("Martinique"), MR("Mauritania"),
MS("Montserrat"), MT("Malta"), MU("Mauritius"), MV("Maldives"), MW("Malawi"), MX("Mexico"), MY("Malaysia"),
MZ("Mozambique"), NA("Namibia"), NC("New Caledonia"), NE("Niger"), NF("Norfolk Island"), NG("Nigeria"),
NI("Nicaragua"), NL("Netherlands"), NO("Norway"), NP("Nepal"), NR("Nauru"), NU("Niue"), NZ("New Zealand"),
OM("Oman"), PA("Panama"), PE("Peru"), PF("French Polynesia"), PG("Papua New Guinea"), PH("Philippines"),
PK("Pakistan"), PL("Poland"), PM("Saint Pierre and Miquelon"), PN("Pitcairn Islands"), PR("Puerto Rico"),
PS("West Bank"), PT("Portugal"), PW("Palau"), PY("Paraguay"), QA("Qatar"), RE("Reunion"), RO("Romania"),
RS("Serbia"), RU("Russia"), RW("Rwanda"), SA("Saudi Arabia"), SB("Solomon Islands"), SC("Seychelles"), SD("Sudan"),
SE("Sweden"), SG("Singapore"), SH("Saint Helena, Ascension, and Tristan da Cunha"), SI("Slovenia"), SJ("Svalbard"),
SK("Slovakia"), SL("Sierra Leone"), SM("San Marino"), SN("Senegal"), SO("Somalia"), SR("Suriname"),
SS("South Sudan"), ST("Sao Tome and Principe"), SV("El Salvador"), SX("Sint Maarten"), SY("Syria"), SZ("Swaziland"),
TC("Turks and Caicos Islands"), TD("Chad"), TF("French Southern and Antarctic Lands"), TG("Togo"), TH("Thailand"),
TJ("Tajikistan"), TK("Tokelau"), TL("Timor-Leste"), TM("Turkmenistan"), TN("Tunisia"), TO("Tonga"), TR("Turkey"),
TT("Trinidad and Tobago"), TV("Tuvalu"), TW("Taiwan"), TZ("Tanzania"), UA("Ukraine"), UG("Uganda"),
UM("United States Minor Outlying Islands"), US("United States"), UY("Uruguay"), UZ("Uzbekistan"),
VA("Holy See (Vatican City)"), VC("Saint Vincent and the Grenadines"), VE("Venezuela"), VG("British Virgin Islands"),
VI("Virgin Islands"), VN("Vietnam"), VU("Vanuatu"), WF("Wallis and Futuna"), WS("Samoa"), XK("Kosovo"), YE("Yemen"),
YT("Mayotte"), ZA("South Africa"), ZM("Zambia"), ZW("Zimbabwe");
String name;
Country(String name) {
this.name = name;
}
public static Country random() { | return sample(values()); |
qala-io/datagen | examples/src/test/java/io/qala/datagen/examples/_35_HomeMadePropertyBasedTest.java | // Path: examples/src/test/java/io/qala/datagen/NotReleasedFeatures.java
// public static double greaterDouble(double from) {
// return RandomShortApi.greaterDouble(from);
// }
//
// Path: datagen/src/main/java/io/qala/datagen/RandomShortApi.java
// public static double positiveDouble() {
// return Double(Long.MAX_VALUE);
// }
//
// Path: examples/src/main/java/io/qala/datagen/examples/OverageCalculation.java
// static double overage(double theoreticalAmount, double actualAmount) {
// return actualAmount / theoreticalAmount - 1;
// }
| import org.junit.Test;
import static io.qala.datagen.NotReleasedFeatures.greaterDouble;
import static io.qala.datagen.RandomShortApi.positiveDouble;
import static io.qala.datagen.examples.OverageCalculation.overage;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue; | package io.qala.datagen.examples;
public class _35_HomeMadePropertyBasedTest {
@Test public void overageExamples() { | // Path: examples/src/test/java/io/qala/datagen/NotReleasedFeatures.java
// public static double greaterDouble(double from) {
// return RandomShortApi.greaterDouble(from);
// }
//
// Path: datagen/src/main/java/io/qala/datagen/RandomShortApi.java
// public static double positiveDouble() {
// return Double(Long.MAX_VALUE);
// }
//
// Path: examples/src/main/java/io/qala/datagen/examples/OverageCalculation.java
// static double overage(double theoreticalAmount, double actualAmount) {
// return actualAmount / theoreticalAmount - 1;
// }
// Path: examples/src/test/java/io/qala/datagen/examples/_35_HomeMadePropertyBasedTest.java
import org.junit.Test;
import static io.qala.datagen.NotReleasedFeatures.greaterDouble;
import static io.qala.datagen.RandomShortApi.positiveDouble;
import static io.qala.datagen.examples.OverageCalculation.overage;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
package io.qala.datagen.examples;
public class _35_HomeMadePropertyBasedTest {
@Test public void overageExamples() { | assertEquals(.3333, overage(9, 12), .0001); |
qala-io/datagen | examples/src/test/java/io/qala/datagen/examples/_35_HomeMadePropertyBasedTest.java | // Path: examples/src/test/java/io/qala/datagen/NotReleasedFeatures.java
// public static double greaterDouble(double from) {
// return RandomShortApi.greaterDouble(from);
// }
//
// Path: datagen/src/main/java/io/qala/datagen/RandomShortApi.java
// public static double positiveDouble() {
// return Double(Long.MAX_VALUE);
// }
//
// Path: examples/src/main/java/io/qala/datagen/examples/OverageCalculation.java
// static double overage(double theoreticalAmount, double actualAmount) {
// return actualAmount / theoreticalAmount - 1;
// }
| import org.junit.Test;
import static io.qala.datagen.NotReleasedFeatures.greaterDouble;
import static io.qala.datagen.RandomShortApi.positiveDouble;
import static io.qala.datagen.examples.OverageCalculation.overage;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue; | package io.qala.datagen.examples;
public class _35_HomeMadePropertyBasedTest {
@Test public void overageExamples() {
assertEquals(.3333, overage(9, 12), .0001);
assertEquals(-.25, overage(12, 9), .0001);
}
@Test public void overageIsPositive_ifWeGotMoreThanAsked() { | // Path: examples/src/test/java/io/qala/datagen/NotReleasedFeatures.java
// public static double greaterDouble(double from) {
// return RandomShortApi.greaterDouble(from);
// }
//
// Path: datagen/src/main/java/io/qala/datagen/RandomShortApi.java
// public static double positiveDouble() {
// return Double(Long.MAX_VALUE);
// }
//
// Path: examples/src/main/java/io/qala/datagen/examples/OverageCalculation.java
// static double overage(double theoreticalAmount, double actualAmount) {
// return actualAmount / theoreticalAmount - 1;
// }
// Path: examples/src/test/java/io/qala/datagen/examples/_35_HomeMadePropertyBasedTest.java
import org.junit.Test;
import static io.qala.datagen.NotReleasedFeatures.greaterDouble;
import static io.qala.datagen.RandomShortApi.positiveDouble;
import static io.qala.datagen.examples.OverageCalculation.overage;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
package io.qala.datagen.examples;
public class _35_HomeMadePropertyBasedTest {
@Test public void overageExamples() {
assertEquals(.3333, overage(9, 12), .0001);
assertEquals(-.25, overage(12, 9), .0001);
}
@Test public void overageIsPositive_ifWeGotMoreThanAsked() { | double wanted = positiveDouble(); |
qala-io/datagen | examples/src/test/java/io/qala/datagen/examples/_35_HomeMadePropertyBasedTest.java | // Path: examples/src/test/java/io/qala/datagen/NotReleasedFeatures.java
// public static double greaterDouble(double from) {
// return RandomShortApi.greaterDouble(from);
// }
//
// Path: datagen/src/main/java/io/qala/datagen/RandomShortApi.java
// public static double positiveDouble() {
// return Double(Long.MAX_VALUE);
// }
//
// Path: examples/src/main/java/io/qala/datagen/examples/OverageCalculation.java
// static double overage(double theoreticalAmount, double actualAmount) {
// return actualAmount / theoreticalAmount - 1;
// }
| import org.junit.Test;
import static io.qala.datagen.NotReleasedFeatures.greaterDouble;
import static io.qala.datagen.RandomShortApi.positiveDouble;
import static io.qala.datagen.examples.OverageCalculation.overage;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue; | package io.qala.datagen.examples;
public class _35_HomeMadePropertyBasedTest {
@Test public void overageExamples() {
assertEquals(.3333, overage(9, 12), .0001);
assertEquals(-.25, overage(12, 9), .0001);
}
@Test public void overageIsPositive_ifWeGotMoreThanAsked() {
double wanted = positiveDouble(); | // Path: examples/src/test/java/io/qala/datagen/NotReleasedFeatures.java
// public static double greaterDouble(double from) {
// return RandomShortApi.greaterDouble(from);
// }
//
// Path: datagen/src/main/java/io/qala/datagen/RandomShortApi.java
// public static double positiveDouble() {
// return Double(Long.MAX_VALUE);
// }
//
// Path: examples/src/main/java/io/qala/datagen/examples/OverageCalculation.java
// static double overage(double theoreticalAmount, double actualAmount) {
// return actualAmount / theoreticalAmount - 1;
// }
// Path: examples/src/test/java/io/qala/datagen/examples/_35_HomeMadePropertyBasedTest.java
import org.junit.Test;
import static io.qala.datagen.NotReleasedFeatures.greaterDouble;
import static io.qala.datagen.RandomShortApi.positiveDouble;
import static io.qala.datagen.examples.OverageCalculation.overage;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
package io.qala.datagen.examples;
public class _35_HomeMadePropertyBasedTest {
@Test public void overageExamples() {
assertEquals(.3333, overage(9, 12), .0001);
assertEquals(-.25, overage(12, 9), .0001);
}
@Test public void overageIsPositive_ifWeGotMoreThanAsked() {
double wanted = positiveDouble(); | double got = greaterDouble(wanted); |
qala-io/datagen | junit5/src/main/java/io/qala/datagen/junit/jupiter/RandomDoubleArgumentProvider.java | // Path: datagen/src/main/java/io/qala/datagen/RandomShortApi.java
// public static double Double() {
// return CommonsMath4.nextUniform(RANDOM, Long.MIN_VALUE, Long.MAX_VALUE, true);
// }
| import java.util.stream.Stream;
import static io.qala.datagen.RandomShortApi.Double; | package io.qala.datagen.junit.jupiter;
class RandomDoubleArgumentProvider extends RandomizedArgumentProvider<RandomDouble> {
private RandomDouble annotation;
@Override
public void accept(RandomDouble annotation) {
this.annotation = annotation;
}
@Override Stream<Object[]> getValueWithDescription() {
return Stream.of(annotation).map(RandomDoubleArgumentProvider::generateParams);
}
@Override Stream<Object> getValue() {
return Stream.of(annotation).map(RandomDoubleArgumentProvider::generateParam);
}
| // Path: datagen/src/main/java/io/qala/datagen/RandomShortApi.java
// public static double Double() {
// return CommonsMath4.nextUniform(RANDOM, Long.MIN_VALUE, Long.MAX_VALUE, true);
// }
// Path: junit5/src/main/java/io/qala/datagen/junit/jupiter/RandomDoubleArgumentProvider.java
import java.util.stream.Stream;
import static io.qala.datagen.RandomShortApi.Double;
package io.qala.datagen.junit.jupiter;
class RandomDoubleArgumentProvider extends RandomizedArgumentProvider<RandomDouble> {
private RandomDouble annotation;
@Override
public void accept(RandomDouble annotation) {
this.annotation = annotation;
}
@Override Stream<Object[]> getValueWithDescription() {
return Stream.of(annotation).map(RandomDoubleArgumentProvider::generateParams);
}
@Override Stream<Object> getValue() {
return Stream.of(annotation).map(RandomDoubleArgumentProvider::generateParam);
}
| static Double generateParam(RandomDouble annotation) { |
qala-io/datagen | examples/src/test/java/io/qala/datagen/examples/_00_WhichOneToPickTest.java | // Path: datagen/src/main/java/io/qala/datagen/RandomShortApi.java
// public static String english(int exactLength) {
// return length(exactLength).english();
// }
| import org.junit.Test;
import static io.qala.datagen.RandomShortApi.english; | package io.qala.datagen.examples;
public class _00_WhichOneToPickTest {
@Test public void usernameValidation_passesHappyPath_traditional() {
new Person("John").validate();
}
@Test public void usernameValidation_passesHappyPath_randomization() { | // Path: datagen/src/main/java/io/qala/datagen/RandomShortApi.java
// public static String english(int exactLength) {
// return length(exactLength).english();
// }
// Path: examples/src/test/java/io/qala/datagen/examples/_00_WhichOneToPickTest.java
import org.junit.Test;
import static io.qala.datagen.RandomShortApi.english;
package io.qala.datagen.examples;
public class _00_WhichOneToPickTest {
@Test public void usernameValidation_passesHappyPath_traditional() {
new Person("John").validate();
}
@Test public void usernameValidation_passesHappyPath_randomization() { | new Person(english(1, 20)).validate(); |
SoyaLeaf/CalendarII | app/src/main/java/top/soyask/calendarii/global/Setting.java | // Path: app/src/main/java/top/soyask/calendarii/entity/Symbol.java
// public enum Symbol {
// RECT("rect", 1),
// CIRCLE("circle", 2),
// TRIANGLE("triangle", 3),
// STAR("star", 4),
// HEART("heart", 5),
// ;
//
// public final String KEY;
// public final int VALUE;
//
// Symbol(String key, int value) {
// this.KEY = key;
// this.VALUE = value;
// }
//
// }
| import android.content.Context;
import android.content.SharedPreferences;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import top.soyask.calendarii.entity.Symbol; |
public static int day_size;
public static float day_number_text_size;
public static float day_lunar_text_size;
public static float day_week_text_size;
public static float day_holiday_text_size;
public static Map<String, String> symbol_comment = new HashMap<>();
public static int default_event_type;
private static boolean isLoaded = false;
public static void loadSetting(Context context) {
if (isLoaded) {
return;
}
SharedPreferences setting = context.getSharedPreferences(SETTING, Context.MODE_PRIVATE);
Setting.theme = setting.getInt(Global.SETTING_THEME, 0);
Setting.date_offset = setting.getInt(Global.SETTING_DATE_OFFSET, 0);
Setting.white_widget_pic = setting.getString(Global.SETTING_WHITE_WIDGET_PIC, null);
Setting.density_dpi = setting.getInt(Global.SETTING_DENSITY_DPI, -1);
Setting.day_size = setting.getInt(Global.SETTING_DAY_SIZE, -1);
Setting.day_number_text_size = setting.getInt(Global.SETTING_DAY_NUMBER_TEXT_SIZE, -1);
Setting.day_lunar_text_size = setting.getInt(Global.SETTING_DAY_LUNAR_TEXT_SIZE, -1);
Setting.day_week_text_size = setting.getInt(Global.SETTING_DAY_WEEK_TEXT_SIZE, -1);
Setting.day_holiday_text_size = setting.getInt(Global.SETTING_DAY_HOLIDAY_TEXT_SIZE, -1);
Setting.replenish = setting.getBoolean(Global.SETTING_REPLENISH, true);
Setting.select_anim = setting.getBoolean(Global.SETTING_SELECT_ANIM, true);
Setting.default_event_type = setting.getInt(Global.DEFAULT_EVENT_TYPE, 0); | // Path: app/src/main/java/top/soyask/calendarii/entity/Symbol.java
// public enum Symbol {
// RECT("rect", 1),
// CIRCLE("circle", 2),
// TRIANGLE("triangle", 3),
// STAR("star", 4),
// HEART("heart", 5),
// ;
//
// public final String KEY;
// public final int VALUE;
//
// Symbol(String key, int value) {
// this.KEY = key;
// this.VALUE = value;
// }
//
// }
// Path: app/src/main/java/top/soyask/calendarii/global/Setting.java
import android.content.Context;
import android.content.SharedPreferences;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import top.soyask.calendarii.entity.Symbol;
public static int day_size;
public static float day_number_text_size;
public static float day_lunar_text_size;
public static float day_week_text_size;
public static float day_holiday_text_size;
public static Map<String, String> symbol_comment = new HashMap<>();
public static int default_event_type;
private static boolean isLoaded = false;
public static void loadSetting(Context context) {
if (isLoaded) {
return;
}
SharedPreferences setting = context.getSharedPreferences(SETTING, Context.MODE_PRIVATE);
Setting.theme = setting.getInt(Global.SETTING_THEME, 0);
Setting.date_offset = setting.getInt(Global.SETTING_DATE_OFFSET, 0);
Setting.white_widget_pic = setting.getString(Global.SETTING_WHITE_WIDGET_PIC, null);
Setting.density_dpi = setting.getInt(Global.SETTING_DENSITY_DPI, -1);
Setting.day_size = setting.getInt(Global.SETTING_DAY_SIZE, -1);
Setting.day_number_text_size = setting.getInt(Global.SETTING_DAY_NUMBER_TEXT_SIZE, -1);
Setting.day_lunar_text_size = setting.getInt(Global.SETTING_DAY_LUNAR_TEXT_SIZE, -1);
Setting.day_week_text_size = setting.getInt(Global.SETTING_DAY_WEEK_TEXT_SIZE, -1);
Setting.day_holiday_text_size = setting.getInt(Global.SETTING_DAY_HOLIDAY_TEXT_SIZE, -1);
Setting.replenish = setting.getBoolean(Global.SETTING_REPLENISH, true);
Setting.select_anim = setting.getBoolean(Global.SETTING_SELECT_ANIM, true);
Setting.default_event_type = setting.getInt(Global.DEFAULT_EVENT_TYPE, 0); | putEventType(setting, Symbol.STAR.KEY, "默认"); |
SoyaLeaf/CalendarII | app/src/main/java/top/soyask/calendarii/utils/EraUtils.java | // Path: app/src/main/java/top/soyask/calendarii/global/Global.java
// public class Global {
// public static final int YEAR_START = 1900; //计算的起点
// public static final int YEAR_START_REAL = 1910; //日历上显示的最小年份
// public static final int YEAR_END = 2100;
// public static final int MONTH_COUNT = 12;
//
// public static final String SETTING_THEME = "theme";
// public static final String SETTING_DATE_OFFSET = "date_offset";
// public static final String SETTING_REPLENISH = "setting_replenish";
// public static final String SETTING_SELECT_ANIM = "select_anim";
// public static final String SETTING_WIDGET_ALPHA = "widget_alpha";
// public static final String SETTING_WHITE_WIDGET_PIC = "white_widget_pic";
// public static final String SETTING_DENSITY_DPI = "setting_density_dpi";
//
// public static final String SETTING_TRANS_WIDGET_ALPHA = SETTING_WIDGET_ALPHA; //为了同之前的版本保持兼容性
// public static final String SETTING_TRANS_WIDGET_THEME_COLOR = "setting_trans_widget_theme_color";
// public static final String SETTING_TRANS_WIDGET_WEEK_FONT_SIZE = "trans_widget_week_font_size";
// public static final String SETTING_TRANS_WIDGET_NUMBER_FONT_SIZE = "trans_widget_number_font_size";
// public static final String SETTING_TRANS_WIDGET_LUNAR_FONT_SIZE = "trans_widget_lunar_font_size";
// public static final String SETTING_TRANS_WIDGET_LINE_HEIGHT = "trans_widget_line_height";
// public static final String SETTING_TRANS_WIDGET_LUNAR_MONTH_TEXT_SIZE = "trans_widget_lunar_month_text_size";
// public static final String SETTING_TRANS_WIDGET_MONTH_TEXT_SIZE = "trans_widget_month_text_size ";
// public static final String SETTING_TRANS_WIDGET_YEAR_TEXT_SIZE = "trans_widget_year_text_size ";
//
// public static final String SETTING_DAY_SIZE = "day_size";
// public static final String SETTING_DAY_NUMBER_TEXT_SIZE = "day_number_text_size";
// public static final String SETTING_DAY_LUNAR_TEXT_SIZE = "day_lunar_text_size";
// public static final String SETTING_DAY_WEEK_TEXT_SIZE = "day_week_text_size";
// public static final String SETTING_DAY_HOLIDAY_TEXT_SIZE = "day_holiday_text_size";
//
// public static final String SETTING_HOLIDAY = "holiday";
// public static final String SETTING_WORKDAY = "workday";
//
// public static final int VIEW_WEEK = 0; //显示星期
// public static final int VIEW_DAY = 1; //显示日子
// public static final int VIEW_TODAY = 4;
// public static final int VIEW_EVENT = 5;
// public static final String DEFAULT_EVENT_TYPE = "default_event_type";
// }
| import top.soyask.calendarii.R;
import top.soyask.calendarii.global.Global; | package top.soyask.calendarii.utils;
/**
* Created by mxf on 2017/8/10.
*/
public class EraUtils {
public static final String[] HEAVENLY_STEMS = {"甲", "乙", "丙", "丁", "戊", "己", "庚", "辛", "壬", "癸"};
public static final String[] EARTHLY_BRANCHES = {"子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥"};
public static final String[] TWELVE_ZODIAC = {"鼠", "牛", "虎", "兔", "龙", "蛇", "马", "羊", "猴", "鸡", "狗", "猪"};
public static final int[] TWELVE_IMG = {
R.drawable.shu,R.drawable.niu,R.drawable.hu,R.drawable.tu,
R.drawable.lon,R.drawable.she,R.drawable.ma,R.drawable.yang,
R.drawable.hou,R.drawable.ji,R.drawable.gou,R.drawable.zhu,
};
public static String getYearForHeavenlyStems(int year) { | // Path: app/src/main/java/top/soyask/calendarii/global/Global.java
// public class Global {
// public static final int YEAR_START = 1900; //计算的起点
// public static final int YEAR_START_REAL = 1910; //日历上显示的最小年份
// public static final int YEAR_END = 2100;
// public static final int MONTH_COUNT = 12;
//
// public static final String SETTING_THEME = "theme";
// public static final String SETTING_DATE_OFFSET = "date_offset";
// public static final String SETTING_REPLENISH = "setting_replenish";
// public static final String SETTING_SELECT_ANIM = "select_anim";
// public static final String SETTING_WIDGET_ALPHA = "widget_alpha";
// public static final String SETTING_WHITE_WIDGET_PIC = "white_widget_pic";
// public static final String SETTING_DENSITY_DPI = "setting_density_dpi";
//
// public static final String SETTING_TRANS_WIDGET_ALPHA = SETTING_WIDGET_ALPHA; //为了同之前的版本保持兼容性
// public static final String SETTING_TRANS_WIDGET_THEME_COLOR = "setting_trans_widget_theme_color";
// public static final String SETTING_TRANS_WIDGET_WEEK_FONT_SIZE = "trans_widget_week_font_size";
// public static final String SETTING_TRANS_WIDGET_NUMBER_FONT_SIZE = "trans_widget_number_font_size";
// public static final String SETTING_TRANS_WIDGET_LUNAR_FONT_SIZE = "trans_widget_lunar_font_size";
// public static final String SETTING_TRANS_WIDGET_LINE_HEIGHT = "trans_widget_line_height";
// public static final String SETTING_TRANS_WIDGET_LUNAR_MONTH_TEXT_SIZE = "trans_widget_lunar_month_text_size";
// public static final String SETTING_TRANS_WIDGET_MONTH_TEXT_SIZE = "trans_widget_month_text_size ";
// public static final String SETTING_TRANS_WIDGET_YEAR_TEXT_SIZE = "trans_widget_year_text_size ";
//
// public static final String SETTING_DAY_SIZE = "day_size";
// public static final String SETTING_DAY_NUMBER_TEXT_SIZE = "day_number_text_size";
// public static final String SETTING_DAY_LUNAR_TEXT_SIZE = "day_lunar_text_size";
// public static final String SETTING_DAY_WEEK_TEXT_SIZE = "day_week_text_size";
// public static final String SETTING_DAY_HOLIDAY_TEXT_SIZE = "day_holiday_text_size";
//
// public static final String SETTING_HOLIDAY = "holiday";
// public static final String SETTING_WORKDAY = "workday";
//
// public static final int VIEW_WEEK = 0; //显示星期
// public static final int VIEW_DAY = 1; //显示日子
// public static final int VIEW_TODAY = 4;
// public static final int VIEW_EVENT = 5;
// public static final String DEFAULT_EVENT_TYPE = "default_event_type";
// }
// Path: app/src/main/java/top/soyask/calendarii/utils/EraUtils.java
import top.soyask.calendarii.R;
import top.soyask.calendarii.global.Global;
package top.soyask.calendarii.utils;
/**
* Created by mxf on 2017/8/10.
*/
public class EraUtils {
public static final String[] HEAVENLY_STEMS = {"甲", "乙", "丙", "丁", "戊", "己", "庚", "辛", "壬", "癸"};
public static final String[] EARTHLY_BRANCHES = {"子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥"};
public static final String[] TWELVE_ZODIAC = {"鼠", "牛", "虎", "兔", "龙", "蛇", "马", "羊", "猴", "鸡", "狗", "猪"};
public static final int[] TWELVE_IMG = {
R.drawable.shu,R.drawable.niu,R.drawable.hu,R.drawable.tu,
R.drawable.lon,R.drawable.she,R.drawable.ma,R.drawable.yang,
R.drawable.hou,R.drawable.ji,R.drawable.gou,R.drawable.zhu,
};
public static String getYearForHeavenlyStems(int year) { | int position = (year - Global.YEAR_START) % 10; |
SoyaLeaf/CalendarII | app/src/main/java/top/soyask/calendarii/ui/widget/WidgetManager.java | // Path: app/src/main/java/top/soyask/calendarii/ui/widget/transparent/MonthWidget.java
// public class MonthWidget extends AppWidgetProvider {
//
// private static final String TAG = "MonthWidget";
//
// public static void updateAppWidget(Context context, AppWidgetManager appWidgetManager,
// int appWidgetId) {
// Setting.loadSetting(context);
// Calendar calendar = Calendar.getInstance(Locale.CHINA);
// RemoteViews views = setupRemoteViews(context, calendar);
// appWidgetManager.notifyAppWidgetViewDataChanged(appWidgetId, R.id.gv_month);
// appWidgetManager.updateAppWidget(appWidgetId, views);
// }
//
// @NonNull
// private static RemoteViews setupRemoteViews(Context context, Calendar calendar) {
// // 应该更改theme来达到目的,然而Android似乎并没有为View提供setTheme这样的功能 w(゚Д゚)w
// int layout = Setting.TransparentWidget.trans_widget_theme_color == 0 ? R.layout.month_widget : R.layout.month_widget_light;
// RemoteViews views = new RemoteViews(context.getPackageName(), layout);
// LunarDay lunarDay = LunarUtils.getLunar(calendar);
//
// Intent intent = new Intent(context, MonthService.class);
//
// int month = calendar.get(Calendar.MONTH) + 1;
// PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, new Intent(context, MainActivity.class), 0);
//
// views.setOnClickPendingIntent(R.id.iv_launch, pendingIntent);
// int themeColor = Setting.TransparentWidget.trans_widget_theme_color;
// views.setInt(R.id.widget, "setBackgroundColor", Color.argb(Setting.TransparentWidget.trans_widget_alpha, themeColor, themeColor, themeColor));
//
// views.setRemoteAdapter(R.id.gv_month, intent);
// views.setTextViewText(R.id.tv_lunar, lunarDay.getLunarDate());
// views.setTextViewTextSize(R.id.tv_lunar, TypedValue.COMPLEX_UNIT_SP, Setting.TransparentWidget.trans_widget_lunar_month_text_size);
// views.setTextViewTextSize(R.id.tv_year, TypedValue.COMPLEX_UNIT_SP, Setting.TransparentWidget.trans_widget_year_text_size);
// views.setTextViewTextSize(R.id.tv_date, TypedValue.COMPLEX_UNIT_SP, Setting.TransparentWidget.trans_widget_month_text_size);
// views.setTextViewText(R.id.tv_year, String.valueOf(calendar.get(Calendar.YEAR)));
// views.setTextViewText(R.id.tv_date, String.format(Locale.CHINA, "%02d月", month));
// return views;
// }
//
// @Override
// public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
// for (int appWidgetId : appWidgetIds) {
// updateAppWidget(context, appWidgetManager, appWidgetId);
// }
// }
//
// @Override
// public void onDeleted(Context context, int[] appWidgetIds) {
// super.onDeleted(context, appWidgetIds);
// }
//
// @Override
// public void onEnabled(Context context) {
//
// }
//
// @Override
// public void onDisabled(Context context) {
// }
//
// }
//
// Path: app/src/main/java/top/soyask/calendarii/ui/widget/white/WhiteWidget.java
// public class WhiteWidget extends AppWidgetProvider {
//
// public static void updateAppWidget(Context context, AppWidgetManager appWidgetManager,
// int appWidgetId) {
// RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.white_widget);
// Intent intent = new Intent(context, WhiteWidgetService.class);
// Setting.loadSetting(context);
// Calendar calendar = Calendar.getInstance(Locale.CHINA);
// views.setTextViewText(R.id.tv_year, String.valueOf(calendar.get(Calendar.YEAR)));
// views.setTextViewText(R.id.tv_month, String.valueOf(calendar.get(Calendar.MONTH) + 1) + "月");
// views.setRemoteAdapter(R.id.gv_month, intent);
// if (Setting.white_widget_pic != null) {
// Bitmap bitmap = BitmapFactory.decodeFile(Setting.white_widget_pic);
// views.setBitmap(R.id.iv, "setImageBitmap", bitmap);
// } else {
// Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), R.mipmap.miku);
// views.setBitmap(R.id.iv, "setImageBitmap", bitmap);
// }
// PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, new Intent(context, MainActivity.class), 0);
// views.setOnClickPendingIntent(R.id.iv, pendingIntent);
// appWidgetManager.notifyAppWidgetViewDataChanged(appWidgetId, R.id.gv_month);
// appWidgetManager.updateAppWidget(appWidgetId, views);
// }
//
// @Override
// public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
// for (int appWidgetId : appWidgetIds) {
// updateAppWidget(context, appWidgetManager, appWidgetId);
// }
// }
//
// @Override
// public void onEnabled(Context context) {
// }
//
// @Override
// public void onDisabled(Context context) {
// // Enter relevant functionality for when the last widget is disabled
// }
// }
| import android.support.annotation.Nullable;
import android.appwidget.AppWidgetManager;
import android.content.ComponentName;
import android.content.Context;
import top.soyask.calendarii.ui.widget.transparent.MonthWidget;
import top.soyask.calendarii.ui.widget.white.WhiteWidget; | package top.soyask.calendarii.ui.widget;
/**
* Created by mxf on 2017/11/19.
*/
public class WidgetManager {
public static void updateAllWidget(Context context) {
AppWidgetManager appWidgetManager =
(AppWidgetManager) context.getSystemService(Context.APPWIDGET_SERVICE);
updateMonthWidget(context, appWidgetManager);
updateWhiteWidget(context, appWidgetManager);
}
public static void updateWhiteWidget(Context context,@Nullable AppWidgetManager appWidgetManager) {
if(appWidgetManager != null){ | // Path: app/src/main/java/top/soyask/calendarii/ui/widget/transparent/MonthWidget.java
// public class MonthWidget extends AppWidgetProvider {
//
// private static final String TAG = "MonthWidget";
//
// public static void updateAppWidget(Context context, AppWidgetManager appWidgetManager,
// int appWidgetId) {
// Setting.loadSetting(context);
// Calendar calendar = Calendar.getInstance(Locale.CHINA);
// RemoteViews views = setupRemoteViews(context, calendar);
// appWidgetManager.notifyAppWidgetViewDataChanged(appWidgetId, R.id.gv_month);
// appWidgetManager.updateAppWidget(appWidgetId, views);
// }
//
// @NonNull
// private static RemoteViews setupRemoteViews(Context context, Calendar calendar) {
// // 应该更改theme来达到目的,然而Android似乎并没有为View提供setTheme这样的功能 w(゚Д゚)w
// int layout = Setting.TransparentWidget.trans_widget_theme_color == 0 ? R.layout.month_widget : R.layout.month_widget_light;
// RemoteViews views = new RemoteViews(context.getPackageName(), layout);
// LunarDay lunarDay = LunarUtils.getLunar(calendar);
//
// Intent intent = new Intent(context, MonthService.class);
//
// int month = calendar.get(Calendar.MONTH) + 1;
// PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, new Intent(context, MainActivity.class), 0);
//
// views.setOnClickPendingIntent(R.id.iv_launch, pendingIntent);
// int themeColor = Setting.TransparentWidget.trans_widget_theme_color;
// views.setInt(R.id.widget, "setBackgroundColor", Color.argb(Setting.TransparentWidget.trans_widget_alpha, themeColor, themeColor, themeColor));
//
// views.setRemoteAdapter(R.id.gv_month, intent);
// views.setTextViewText(R.id.tv_lunar, lunarDay.getLunarDate());
// views.setTextViewTextSize(R.id.tv_lunar, TypedValue.COMPLEX_UNIT_SP, Setting.TransparentWidget.trans_widget_lunar_month_text_size);
// views.setTextViewTextSize(R.id.tv_year, TypedValue.COMPLEX_UNIT_SP, Setting.TransparentWidget.trans_widget_year_text_size);
// views.setTextViewTextSize(R.id.tv_date, TypedValue.COMPLEX_UNIT_SP, Setting.TransparentWidget.trans_widget_month_text_size);
// views.setTextViewText(R.id.tv_year, String.valueOf(calendar.get(Calendar.YEAR)));
// views.setTextViewText(R.id.tv_date, String.format(Locale.CHINA, "%02d月", month));
// return views;
// }
//
// @Override
// public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
// for (int appWidgetId : appWidgetIds) {
// updateAppWidget(context, appWidgetManager, appWidgetId);
// }
// }
//
// @Override
// public void onDeleted(Context context, int[] appWidgetIds) {
// super.onDeleted(context, appWidgetIds);
// }
//
// @Override
// public void onEnabled(Context context) {
//
// }
//
// @Override
// public void onDisabled(Context context) {
// }
//
// }
//
// Path: app/src/main/java/top/soyask/calendarii/ui/widget/white/WhiteWidget.java
// public class WhiteWidget extends AppWidgetProvider {
//
// public static void updateAppWidget(Context context, AppWidgetManager appWidgetManager,
// int appWidgetId) {
// RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.white_widget);
// Intent intent = new Intent(context, WhiteWidgetService.class);
// Setting.loadSetting(context);
// Calendar calendar = Calendar.getInstance(Locale.CHINA);
// views.setTextViewText(R.id.tv_year, String.valueOf(calendar.get(Calendar.YEAR)));
// views.setTextViewText(R.id.tv_month, String.valueOf(calendar.get(Calendar.MONTH) + 1) + "月");
// views.setRemoteAdapter(R.id.gv_month, intent);
// if (Setting.white_widget_pic != null) {
// Bitmap bitmap = BitmapFactory.decodeFile(Setting.white_widget_pic);
// views.setBitmap(R.id.iv, "setImageBitmap", bitmap);
// } else {
// Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), R.mipmap.miku);
// views.setBitmap(R.id.iv, "setImageBitmap", bitmap);
// }
// PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, new Intent(context, MainActivity.class), 0);
// views.setOnClickPendingIntent(R.id.iv, pendingIntent);
// appWidgetManager.notifyAppWidgetViewDataChanged(appWidgetId, R.id.gv_month);
// appWidgetManager.updateAppWidget(appWidgetId, views);
// }
//
// @Override
// public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
// for (int appWidgetId : appWidgetIds) {
// updateAppWidget(context, appWidgetManager, appWidgetId);
// }
// }
//
// @Override
// public void onEnabled(Context context) {
// }
//
// @Override
// public void onDisabled(Context context) {
// // Enter relevant functionality for when the last widget is disabled
// }
// }
// Path: app/src/main/java/top/soyask/calendarii/ui/widget/WidgetManager.java
import android.support.annotation.Nullable;
import android.appwidget.AppWidgetManager;
import android.content.ComponentName;
import android.content.Context;
import top.soyask.calendarii.ui.widget.transparent.MonthWidget;
import top.soyask.calendarii.ui.widget.white.WhiteWidget;
package top.soyask.calendarii.ui.widget;
/**
* Created by mxf on 2017/11/19.
*/
public class WidgetManager {
public static void updateAllWidget(Context context) {
AppWidgetManager appWidgetManager =
(AppWidgetManager) context.getSystemService(Context.APPWIDGET_SERVICE);
updateMonthWidget(context, appWidgetManager);
updateWhiteWidget(context, appWidgetManager);
}
public static void updateWhiteWidget(Context context,@Nullable AppWidgetManager appWidgetManager) {
if(appWidgetManager != null){ | int[] appWidgetIds = appWidgetManager.getAppWidgetIds(new ComponentName(context, WhiteWidget.class)); |
SoyaLeaf/CalendarII | app/src/main/java/top/soyask/calendarii/database/dao/BirthdayDao.java | // Path: app/src/main/java/top/soyask/calendarii/database/DBUtils.java
// public class DBUtils extends SQLiteOpenHelper {
//
//
// private static DBUtils dbUtils;
// private static final String EVENT_SQL;
// private static final String BIRTH_SQL;
//
// static {
// EVENT_SQL = "create table " +
// EventDao.EVENT +
// "(" +
// "id Integer primary key autoincrement," +
// "title varchar(255)," +
// "detail text," +
// "isDelete boolean," +
// "isComplete boolean," +
// "type int" +
// ");";
//
// BIRTH_SQL = "create table " +
// BirthdayDao.BIRTHDAY +
// "(" +
// "id Integer primary key autoincrement," +
// "who varchar(255)," +
// "when_ varchar(255)," +
// "isLunar boolean" +
// ");";
// }
//
// private DBUtils(Context context) {
// super(context, "db", null, 3);
// }
//
//
// public static DBUtils getInstance(Context context) {
// if (dbUtils == null) {
// dbUtils = new DBUtils(context);
// }
// return dbUtils;
// }
//
// @Override
// public void onCreate(SQLiteDatabase db) {
// db.execSQL(EVENT_SQL);
// db.execSQL(BIRTH_SQL);
// }
//
// @Override
// public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// switch (oldVersion) {
// case 1:
// db.execSQL(BIRTH_SQL);
// case 2:
// db.execSQL("alter table "+EventDao.EVENT+" add column type int");
// break;
// }
// }
//
// }
//
// Path: app/src/main/java/top/soyask/calendarii/entity/Birthday.java
// public class Birthday implements Serializable {
//
// private int id;
// private String who;
// private String when;
// private boolean isLunar;
//
//
// public void setId(int id) {
// this.id = id;
// }
//
// public int getId() {
// return id;
// }
//
// public String getWho() {
// return who;
// }
//
// public void setWho(String who) {
// this.who = who;
// }
//
// public String getWhen() {
// return when;
// }
//
// public void setWhen(String when) {
// this.when = when;
// }
//
// public boolean isLunar() {
// return isLunar;
// }
//
// public void setLunar(boolean lunar) {
// isLunar = lunar;
// }
//
// @Override
// public String toString() {
// return "Birthday{" +
// "id=" + id +
// ", who='" + who + '\'' +
// ", when='" + when + '\'' +
// ", isLunar=" + isLunar +
// '}';
// }
// }
| import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import java.util.ArrayList;
import java.util.List;
import top.soyask.calendarii.database.DBUtils;
import top.soyask.calendarii.entity.Birthday; | package top.soyask.calendarii.database.dao;
/**
* Created by mxf on 2017/10/30.
*/
public class BirthdayDao {
public static final String BIRTHDAY = "BIRTHDAY";
| // Path: app/src/main/java/top/soyask/calendarii/database/DBUtils.java
// public class DBUtils extends SQLiteOpenHelper {
//
//
// private static DBUtils dbUtils;
// private static final String EVENT_SQL;
// private static final String BIRTH_SQL;
//
// static {
// EVENT_SQL = "create table " +
// EventDao.EVENT +
// "(" +
// "id Integer primary key autoincrement," +
// "title varchar(255)," +
// "detail text," +
// "isDelete boolean," +
// "isComplete boolean," +
// "type int" +
// ");";
//
// BIRTH_SQL = "create table " +
// BirthdayDao.BIRTHDAY +
// "(" +
// "id Integer primary key autoincrement," +
// "who varchar(255)," +
// "when_ varchar(255)," +
// "isLunar boolean" +
// ");";
// }
//
// private DBUtils(Context context) {
// super(context, "db", null, 3);
// }
//
//
// public static DBUtils getInstance(Context context) {
// if (dbUtils == null) {
// dbUtils = new DBUtils(context);
// }
// return dbUtils;
// }
//
// @Override
// public void onCreate(SQLiteDatabase db) {
// db.execSQL(EVENT_SQL);
// db.execSQL(BIRTH_SQL);
// }
//
// @Override
// public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// switch (oldVersion) {
// case 1:
// db.execSQL(BIRTH_SQL);
// case 2:
// db.execSQL("alter table "+EventDao.EVENT+" add column type int");
// break;
// }
// }
//
// }
//
// Path: app/src/main/java/top/soyask/calendarii/entity/Birthday.java
// public class Birthday implements Serializable {
//
// private int id;
// private String who;
// private String when;
// private boolean isLunar;
//
//
// public void setId(int id) {
// this.id = id;
// }
//
// public int getId() {
// return id;
// }
//
// public String getWho() {
// return who;
// }
//
// public void setWho(String who) {
// this.who = who;
// }
//
// public String getWhen() {
// return when;
// }
//
// public void setWhen(String when) {
// this.when = when;
// }
//
// public boolean isLunar() {
// return isLunar;
// }
//
// public void setLunar(boolean lunar) {
// isLunar = lunar;
// }
//
// @Override
// public String toString() {
// return "Birthday{" +
// "id=" + id +
// ", who='" + who + '\'' +
// ", when='" + when + '\'' +
// ", isLunar=" + isLunar +
// '}';
// }
// }
// Path: app/src/main/java/top/soyask/calendarii/database/dao/BirthdayDao.java
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import java.util.ArrayList;
import java.util.List;
import top.soyask.calendarii.database.DBUtils;
import top.soyask.calendarii.entity.Birthday;
package top.soyask.calendarii.database.dao;
/**
* Created by mxf on 2017/10/30.
*/
public class BirthdayDao {
public static final String BIRTHDAY = "BIRTHDAY";
| private DBUtils mDBUtils; |
SoyaLeaf/CalendarII | app/src/main/java/top/soyask/calendarii/database/dao/BirthdayDao.java | // Path: app/src/main/java/top/soyask/calendarii/database/DBUtils.java
// public class DBUtils extends SQLiteOpenHelper {
//
//
// private static DBUtils dbUtils;
// private static final String EVENT_SQL;
// private static final String BIRTH_SQL;
//
// static {
// EVENT_SQL = "create table " +
// EventDao.EVENT +
// "(" +
// "id Integer primary key autoincrement," +
// "title varchar(255)," +
// "detail text," +
// "isDelete boolean," +
// "isComplete boolean," +
// "type int" +
// ");";
//
// BIRTH_SQL = "create table " +
// BirthdayDao.BIRTHDAY +
// "(" +
// "id Integer primary key autoincrement," +
// "who varchar(255)," +
// "when_ varchar(255)," +
// "isLunar boolean" +
// ");";
// }
//
// private DBUtils(Context context) {
// super(context, "db", null, 3);
// }
//
//
// public static DBUtils getInstance(Context context) {
// if (dbUtils == null) {
// dbUtils = new DBUtils(context);
// }
// return dbUtils;
// }
//
// @Override
// public void onCreate(SQLiteDatabase db) {
// db.execSQL(EVENT_SQL);
// db.execSQL(BIRTH_SQL);
// }
//
// @Override
// public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// switch (oldVersion) {
// case 1:
// db.execSQL(BIRTH_SQL);
// case 2:
// db.execSQL("alter table "+EventDao.EVENT+" add column type int");
// break;
// }
// }
//
// }
//
// Path: app/src/main/java/top/soyask/calendarii/entity/Birthday.java
// public class Birthday implements Serializable {
//
// private int id;
// private String who;
// private String when;
// private boolean isLunar;
//
//
// public void setId(int id) {
// this.id = id;
// }
//
// public int getId() {
// return id;
// }
//
// public String getWho() {
// return who;
// }
//
// public void setWho(String who) {
// this.who = who;
// }
//
// public String getWhen() {
// return when;
// }
//
// public void setWhen(String when) {
// this.when = when;
// }
//
// public boolean isLunar() {
// return isLunar;
// }
//
// public void setLunar(boolean lunar) {
// isLunar = lunar;
// }
//
// @Override
// public String toString() {
// return "Birthday{" +
// "id=" + id +
// ", who='" + who + '\'' +
// ", when='" + when + '\'' +
// ", isLunar=" + isLunar +
// '}';
// }
// }
| import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import java.util.ArrayList;
import java.util.List;
import top.soyask.calendarii.database.DBUtils;
import top.soyask.calendarii.entity.Birthday; | package top.soyask.calendarii.database.dao;
/**
* Created by mxf on 2017/10/30.
*/
public class BirthdayDao {
public static final String BIRTHDAY = "BIRTHDAY";
private DBUtils mDBUtils;
private static BirthdayDao mBirthdayDao;
private BirthdayDao(DBUtils dBUtils) {
this.mDBUtils = dBUtils;
}
public static BirthdayDao getInstance(Context context) {
if (mBirthdayDao == null) {
DBUtils dbUtils = DBUtils.getInstance(context);
mBirthdayDao = new BirthdayDao(dbUtils);
}
return mBirthdayDao;
}
| // Path: app/src/main/java/top/soyask/calendarii/database/DBUtils.java
// public class DBUtils extends SQLiteOpenHelper {
//
//
// private static DBUtils dbUtils;
// private static final String EVENT_SQL;
// private static final String BIRTH_SQL;
//
// static {
// EVENT_SQL = "create table " +
// EventDao.EVENT +
// "(" +
// "id Integer primary key autoincrement," +
// "title varchar(255)," +
// "detail text," +
// "isDelete boolean," +
// "isComplete boolean," +
// "type int" +
// ");";
//
// BIRTH_SQL = "create table " +
// BirthdayDao.BIRTHDAY +
// "(" +
// "id Integer primary key autoincrement," +
// "who varchar(255)," +
// "when_ varchar(255)," +
// "isLunar boolean" +
// ");";
// }
//
// private DBUtils(Context context) {
// super(context, "db", null, 3);
// }
//
//
// public static DBUtils getInstance(Context context) {
// if (dbUtils == null) {
// dbUtils = new DBUtils(context);
// }
// return dbUtils;
// }
//
// @Override
// public void onCreate(SQLiteDatabase db) {
// db.execSQL(EVENT_SQL);
// db.execSQL(BIRTH_SQL);
// }
//
// @Override
// public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// switch (oldVersion) {
// case 1:
// db.execSQL(BIRTH_SQL);
// case 2:
// db.execSQL("alter table "+EventDao.EVENT+" add column type int");
// break;
// }
// }
//
// }
//
// Path: app/src/main/java/top/soyask/calendarii/entity/Birthday.java
// public class Birthday implements Serializable {
//
// private int id;
// private String who;
// private String when;
// private boolean isLunar;
//
//
// public void setId(int id) {
// this.id = id;
// }
//
// public int getId() {
// return id;
// }
//
// public String getWho() {
// return who;
// }
//
// public void setWho(String who) {
// this.who = who;
// }
//
// public String getWhen() {
// return when;
// }
//
// public void setWhen(String when) {
// this.when = when;
// }
//
// public boolean isLunar() {
// return isLunar;
// }
//
// public void setLunar(boolean lunar) {
// isLunar = lunar;
// }
//
// @Override
// public String toString() {
// return "Birthday{" +
// "id=" + id +
// ", who='" + who + '\'' +
// ", when='" + when + '\'' +
// ", isLunar=" + isLunar +
// '}';
// }
// }
// Path: app/src/main/java/top/soyask/calendarii/database/dao/BirthdayDao.java
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import java.util.ArrayList;
import java.util.List;
import top.soyask.calendarii.database.DBUtils;
import top.soyask.calendarii.entity.Birthday;
package top.soyask.calendarii.database.dao;
/**
* Created by mxf on 2017/10/30.
*/
public class BirthdayDao {
public static final String BIRTHDAY = "BIRTHDAY";
private DBUtils mDBUtils;
private static BirthdayDao mBirthdayDao;
private BirthdayDao(DBUtils dBUtils) {
this.mDBUtils = dBUtils;
}
public static BirthdayDao getInstance(Context context) {
if (mBirthdayDao == null) {
DBUtils dbUtils = DBUtils.getInstance(context);
mBirthdayDao = new BirthdayDao(dbUtils);
}
return mBirthdayDao;
}
| public void add(Birthday birthday) { |
SoyaLeaf/CalendarII | app/src/main/java/top/soyask/calendarii/ui/floatwindow/FloatWindowService.java | // Path: app/src/main/java/top/soyask/calendarii/utils/PermissionUtils.java
// public class PermissionUtils {
//
// public static boolean checkSelfPermission(Activity activity, String permission, int requestCode) {
// boolean had = true;
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
// if (activity.checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
// activity.requestPermissions(new String[]{ permission }, requestCode);
// had = false;
// }
// }
// return had;
// }
//
// public static boolean checkSelfPermission(Fragment fragment, String permission, int requestCode) {
// boolean had = true;
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
// FragmentActivity activity = fragment.getActivity();
// if(activity == null) return false;
// if (activity.checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
// fragment.requestPermissions(new String[]{permission}, requestCode);
// had = false;
// }
// }
// return had;
// }
//
// public static boolean handleResults(String[] permissions, int[] grantResults) {
// for (int i = 0; i < permissions.length; i++) {
// if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
// return false;
// }
// }
// return true;
// }
//
// public static void manual(Activity activity) {
// new AlertDialog.Builder(activity)
// .setMessage("你拒绝授予权限,该功能将无法正常使用...")
// .setPositiveButton("手动授权", (dialog, which) -> {
// toSettings(activity);
// })
// .setNegativeButton("不使用该功能", null)
// .show();
// }
//
// public static void toSettings(Context context) {
// Uri uri = Uri.fromParts("package", context.getPackageName(), null);
// Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, uri);
// intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// context.startActivity(intent);
// }
// }
| import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.Toast;
import top.soyask.calendarii.R;
import top.soyask.calendarii.utils.PermissionUtils; | package top.soyask.calendarii.ui.floatwindow;
public class FloatWindowService extends Service {
private FloatWindowManager mFloatWindow;
public FloatWindowService() {
}
@Override
public IBinder onBind(Intent intent) {
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public void onCreate() {
super.onCreate();
mFloatWindow = FloatWindowManager.getInstance();
try {
mFloatWindow.show(this);
} catch (WindowManager.BadTokenException e) {
e.printStackTrace();
Toast.makeText(this, "请在设置里开启悬浮窗权限", Toast.LENGTH_SHORT).show(); | // Path: app/src/main/java/top/soyask/calendarii/utils/PermissionUtils.java
// public class PermissionUtils {
//
// public static boolean checkSelfPermission(Activity activity, String permission, int requestCode) {
// boolean had = true;
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
// if (activity.checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
// activity.requestPermissions(new String[]{ permission }, requestCode);
// had = false;
// }
// }
// return had;
// }
//
// public static boolean checkSelfPermission(Fragment fragment, String permission, int requestCode) {
// boolean had = true;
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
// FragmentActivity activity = fragment.getActivity();
// if(activity == null) return false;
// if (activity.checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
// fragment.requestPermissions(new String[]{permission}, requestCode);
// had = false;
// }
// }
// return had;
// }
//
// public static boolean handleResults(String[] permissions, int[] grantResults) {
// for (int i = 0; i < permissions.length; i++) {
// if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
// return false;
// }
// }
// return true;
// }
//
// public static void manual(Activity activity) {
// new AlertDialog.Builder(activity)
// .setMessage("你拒绝授予权限,该功能将无法正常使用...")
// .setPositiveButton("手动授权", (dialog, which) -> {
// toSettings(activity);
// })
// .setNegativeButton("不使用该功能", null)
// .show();
// }
//
// public static void toSettings(Context context) {
// Uri uri = Uri.fromParts("package", context.getPackageName(), null);
// Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, uri);
// intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// context.startActivity(intent);
// }
// }
// Path: app/src/main/java/top/soyask/calendarii/ui/floatwindow/FloatWindowService.java
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.Toast;
import top.soyask.calendarii.R;
import top.soyask.calendarii.utils.PermissionUtils;
package top.soyask.calendarii.ui.floatwindow;
public class FloatWindowService extends Service {
private FloatWindowManager mFloatWindow;
public FloatWindowService() {
}
@Override
public IBinder onBind(Intent intent) {
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public void onCreate() {
super.onCreate();
mFloatWindow = FloatWindowManager.getInstance();
try {
mFloatWindow.show(this);
} catch (WindowManager.BadTokenException e) {
e.printStackTrace();
Toast.makeText(this, "请在设置里开启悬浮窗权限", Toast.LENGTH_SHORT).show(); | PermissionUtils.toSettings(this); |
SoyaLeaf/CalendarII | app/src/main/java/top/soyask/calendarii/ui/fragment/dialog/DateSelectDialog.java | // Path: app/src/main/java/top/soyask/calendarii/utils/DayUtils.java
// public class DayUtils {
// /**
// * @param month 传入实际的月份
// * @param year
// * @return
// */
// public static int getMonthDayCount(int month, int year) {
// month = month - 1;
// switch (month) {
// case Calendar.JANUARY:
// case Calendar.MARCH:
// case Calendar.MAY:
// case Calendar.JULY:
// case Calendar.AUGUST:
// case Calendar.OCTOBER:
// case Calendar.DECEMBER:
// return 31;
// case Calendar.APRIL:
// case Calendar.JUNE:
// case Calendar.SEPTEMBER:
// case Calendar.NOVEMBER:
// return 30;
// case Calendar.FEBRUARY:
// return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0) ? 29 : 28;
// default:
// throw new IllegalArgumentException("Didn't find this month(未找到该月份):" + month);
// }
//
// }
//
// public static int getPrevMonthDayCount(int month, int year) {
// if (month > 1) {
// month--;
// } else {
// year--;
// }
// return getMonthDayCount(month, year);
// }
//
//
// public static int getDayForWeek(Calendar calendar) {
// int date = calendar.get(Calendar.DAY_OF_MONTH);
// if (date < 1 || date > 31) {
// return 1;
// }
// return calendar.get(Calendar.DAY_OF_WEEK) - 1;
// }
//
// public static int getWeekForMonth(Calendar calendar) {
// int date = calendar.get(Calendar.DAY_OF_MONTH);
// if (date < 1 || date > 31) {
// return 1;
// }
// return calendar.get(Calendar.WEEK_OF_MONTH);
// }
// }
| import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.BottomSheetDialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.NumberPicker;
import java.lang.reflect.Method;
import top.soyask.calendarii.R;
import top.soyask.calendarii.utils.DayUtils; | }
public void setDateSelectCallback(DateSelectCallback dateSelectCallback) {
this.mDateSelectCallback = dateSelectCallback;
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_confirm:
mDateSelectCallback.onSelectConfirm(mNpYear.getValue(), mNpMonth.getValue(), mNpDay.getValue());
dismiss();
break;
case R.id.btn_cancel:
mDateSelectCallback.onSelectCancel();
mDateSelectCallback.onValueChange(mYear, mMonth, mDay);
dismiss();
break;
}
}
@Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
int year = mNpYear.getValue();
int month = mNpMonth.getValue();
mDateSelectCallback.onValueChange(year, month, mNpDay.getValue());
updateDayCount(year, month);
}
private void updateDayCount(int year, int month) { | // Path: app/src/main/java/top/soyask/calendarii/utils/DayUtils.java
// public class DayUtils {
// /**
// * @param month 传入实际的月份
// * @param year
// * @return
// */
// public static int getMonthDayCount(int month, int year) {
// month = month - 1;
// switch (month) {
// case Calendar.JANUARY:
// case Calendar.MARCH:
// case Calendar.MAY:
// case Calendar.JULY:
// case Calendar.AUGUST:
// case Calendar.OCTOBER:
// case Calendar.DECEMBER:
// return 31;
// case Calendar.APRIL:
// case Calendar.JUNE:
// case Calendar.SEPTEMBER:
// case Calendar.NOVEMBER:
// return 30;
// case Calendar.FEBRUARY:
// return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0) ? 29 : 28;
// default:
// throw new IllegalArgumentException("Didn't find this month(未找到该月份):" + month);
// }
//
// }
//
// public static int getPrevMonthDayCount(int month, int year) {
// if (month > 1) {
// month--;
// } else {
// year--;
// }
// return getMonthDayCount(month, year);
// }
//
//
// public static int getDayForWeek(Calendar calendar) {
// int date = calendar.get(Calendar.DAY_OF_MONTH);
// if (date < 1 || date > 31) {
// return 1;
// }
// return calendar.get(Calendar.DAY_OF_WEEK) - 1;
// }
//
// public static int getWeekForMonth(Calendar calendar) {
// int date = calendar.get(Calendar.DAY_OF_MONTH);
// if (date < 1 || date > 31) {
// return 1;
// }
// return calendar.get(Calendar.WEEK_OF_MONTH);
// }
// }
// Path: app/src/main/java/top/soyask/calendarii/ui/fragment/dialog/DateSelectDialog.java
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.BottomSheetDialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.NumberPicker;
import java.lang.reflect.Method;
import top.soyask.calendarii.R;
import top.soyask.calendarii.utils.DayUtils;
}
public void setDateSelectCallback(DateSelectCallback dateSelectCallback) {
this.mDateSelectCallback = dateSelectCallback;
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_confirm:
mDateSelectCallback.onSelectConfirm(mNpYear.getValue(), mNpMonth.getValue(), mNpDay.getValue());
dismiss();
break;
case R.id.btn_cancel:
mDateSelectCallback.onSelectCancel();
mDateSelectCallback.onValueChange(mYear, mMonth, mDay);
dismiss();
break;
}
}
@Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
int year = mNpYear.getValue();
int month = mNpMonth.getValue();
mDateSelectCallback.onValueChange(year, month, mNpDay.getValue());
updateDayCount(year, month);
}
private void updateDayCount(int year, int month) { | int dayCount = DayUtils.getMonthDayCount(month, year); |
SoyaLeaf/CalendarII | app/src/main/java/top/soyask/calendarii/ui/view/CalendarView.java | // Path: app/src/main/java/top/soyask/calendarii/entity/Symbol.java
// public enum Symbol {
// RECT("rect", 1),
// CIRCLE("circle", 2),
// TRIANGLE("triangle", 3),
// STAR("star", 4),
// HEART("heart", 5),
// ;
//
// public final String KEY;
// public final int VALUE;
//
// Symbol(String key, int value) {
// this.KEY = key;
// this.VALUE = value;
// }
//
// }
//
// Path: app/src/main/java/top/soyask/calendarii/utils/DayUtils.java
// public class DayUtils {
// /**
// * @param month 传入实际的月份
// * @param year
// * @return
// */
// public static int getMonthDayCount(int month, int year) {
// month = month - 1;
// switch (month) {
// case Calendar.JANUARY:
// case Calendar.MARCH:
// case Calendar.MAY:
// case Calendar.JULY:
// case Calendar.AUGUST:
// case Calendar.OCTOBER:
// case Calendar.DECEMBER:
// return 31;
// case Calendar.APRIL:
// case Calendar.JUNE:
// case Calendar.SEPTEMBER:
// case Calendar.NOVEMBER:
// return 30;
// case Calendar.FEBRUARY:
// return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0) ? 29 : 28;
// default:
// throw new IllegalArgumentException("Didn't find this month(未找到该月份):" + month);
// }
//
// }
//
// public static int getPrevMonthDayCount(int month, int year) {
// if (month > 1) {
// month--;
// } else {
// year--;
// }
// return getMonthDayCount(month, year);
// }
//
//
// public static int getDayForWeek(Calendar calendar) {
// int date = calendar.get(Calendar.DAY_OF_MONTH);
// if (date < 1 || date > 31) {
// return 1;
// }
// return calendar.get(Calendar.DAY_OF_WEEK) - 1;
// }
//
// public static int getWeekForMonth(Calendar calendar) {
// int date = calendar.get(Calendar.DAY_OF_MONTH);
// if (date < 1 || date > 31) {
// return 1;
// }
// return calendar.get(Calendar.WEEK_OF_MONTH);
// }
// }
| import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Point;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.animation.Animation;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;
import top.soyask.calendarii.R;
import top.soyask.calendarii.entity.Symbol;
import top.soyask.calendarii.utils.DayUtils; | typedArray.recycle();
mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
}
public void setData(int currentYear, int currentMonth, List<? extends IDay> days) {
mDays = days;
mFirstDayOfWeek = (mDays.get(0).getDayOfWeek() + 6 - mFirstDayOffset) % 7;
initWeekViews();
initPrevMonth(currentYear, currentMonth);
initCurrentMonth(days);
initNextMonth(days);
initialized = true;
if (!mPendingList.isEmpty()) {
for (Runnable runnable : mPendingList) {
runnable.run();
}
}
mPendingList.clear();
postInvalidate();
}
private void initWeekViews() {
mDateWidth = mDisplayWidth / 7;
for (int i = 0; i < mWeekViews.length; i++) {
mWeekViews[i] = new WeekView(i, mDisplayWidth / 7);
}
}
private void initPrevMonth(int currentYear, int currentMonth) { | // Path: app/src/main/java/top/soyask/calendarii/entity/Symbol.java
// public enum Symbol {
// RECT("rect", 1),
// CIRCLE("circle", 2),
// TRIANGLE("triangle", 3),
// STAR("star", 4),
// HEART("heart", 5),
// ;
//
// public final String KEY;
// public final int VALUE;
//
// Symbol(String key, int value) {
// this.KEY = key;
// this.VALUE = value;
// }
//
// }
//
// Path: app/src/main/java/top/soyask/calendarii/utils/DayUtils.java
// public class DayUtils {
// /**
// * @param month 传入实际的月份
// * @param year
// * @return
// */
// public static int getMonthDayCount(int month, int year) {
// month = month - 1;
// switch (month) {
// case Calendar.JANUARY:
// case Calendar.MARCH:
// case Calendar.MAY:
// case Calendar.JULY:
// case Calendar.AUGUST:
// case Calendar.OCTOBER:
// case Calendar.DECEMBER:
// return 31;
// case Calendar.APRIL:
// case Calendar.JUNE:
// case Calendar.SEPTEMBER:
// case Calendar.NOVEMBER:
// return 30;
// case Calendar.FEBRUARY:
// return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0) ? 29 : 28;
// default:
// throw new IllegalArgumentException("Didn't find this month(未找到该月份):" + month);
// }
//
// }
//
// public static int getPrevMonthDayCount(int month, int year) {
// if (month > 1) {
// month--;
// } else {
// year--;
// }
// return getMonthDayCount(month, year);
// }
//
//
// public static int getDayForWeek(Calendar calendar) {
// int date = calendar.get(Calendar.DAY_OF_MONTH);
// if (date < 1 || date > 31) {
// return 1;
// }
// return calendar.get(Calendar.DAY_OF_WEEK) - 1;
// }
//
// public static int getWeekForMonth(Calendar calendar) {
// int date = calendar.get(Calendar.DAY_OF_MONTH);
// if (date < 1 || date > 31) {
// return 1;
// }
// return calendar.get(Calendar.WEEK_OF_MONTH);
// }
// }
// Path: app/src/main/java/top/soyask/calendarii/ui/view/CalendarView.java
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Point;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.animation.Animation;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;
import top.soyask.calendarii.R;
import top.soyask.calendarii.entity.Symbol;
import top.soyask.calendarii.utils.DayUtils;
typedArray.recycle();
mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
}
public void setData(int currentYear, int currentMonth, List<? extends IDay> days) {
mDays = days;
mFirstDayOfWeek = (mDays.get(0).getDayOfWeek() + 6 - mFirstDayOffset) % 7;
initWeekViews();
initPrevMonth(currentYear, currentMonth);
initCurrentMonth(days);
initNextMonth(days);
initialized = true;
if (!mPendingList.isEmpty()) {
for (Runnable runnable : mPendingList) {
runnable.run();
}
}
mPendingList.clear();
postInvalidate();
}
private void initWeekViews() {
mDateWidth = mDisplayWidth / 7;
for (int i = 0; i < mWeekViews.length; i++) {
mWeekViews[i] = new WeekView(i, mDisplayWidth / 7);
}
}
private void initPrevMonth(int currentYear, int currentMonth) { | int prevMonthDayCount = DayUtils.getPrevMonthDayCount(currentMonth, currentYear); |
SoyaLeaf/CalendarII | app/src/main/java/top/soyask/calendarii/ui/view/CalendarView.java | // Path: app/src/main/java/top/soyask/calendarii/entity/Symbol.java
// public enum Symbol {
// RECT("rect", 1),
// CIRCLE("circle", 2),
// TRIANGLE("triangle", 3),
// STAR("star", 4),
// HEART("heart", 5),
// ;
//
// public final String KEY;
// public final int VALUE;
//
// Symbol(String key, int value) {
// this.KEY = key;
// this.VALUE = value;
// }
//
// }
//
// Path: app/src/main/java/top/soyask/calendarii/utils/DayUtils.java
// public class DayUtils {
// /**
// * @param month 传入实际的月份
// * @param year
// * @return
// */
// public static int getMonthDayCount(int month, int year) {
// month = month - 1;
// switch (month) {
// case Calendar.JANUARY:
// case Calendar.MARCH:
// case Calendar.MAY:
// case Calendar.JULY:
// case Calendar.AUGUST:
// case Calendar.OCTOBER:
// case Calendar.DECEMBER:
// return 31;
// case Calendar.APRIL:
// case Calendar.JUNE:
// case Calendar.SEPTEMBER:
// case Calendar.NOVEMBER:
// return 30;
// case Calendar.FEBRUARY:
// return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0) ? 29 : 28;
// default:
// throw new IllegalArgumentException("Didn't find this month(未找到该月份):" + month);
// }
//
// }
//
// public static int getPrevMonthDayCount(int month, int year) {
// if (month > 1) {
// month--;
// } else {
// year--;
// }
// return getMonthDayCount(month, year);
// }
//
//
// public static int getDayForWeek(Calendar calendar) {
// int date = calendar.get(Calendar.DAY_OF_MONTH);
// if (date < 1 || date > 31) {
// return 1;
// }
// return calendar.get(Calendar.DAY_OF_WEEK) - 1;
// }
//
// public static int getWeekForMonth(Calendar calendar) {
// int date = calendar.get(Calendar.DAY_OF_MONTH);
// if (date < 1 || date > 31) {
// return 1;
// }
// return calendar.get(Calendar.WEEK_OF_MONTH);
// }
// }
| import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Point;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.animation.Animation;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;
import top.soyask.calendarii.R;
import top.soyask.calendarii.entity.Symbol;
import top.soyask.calendarii.utils.DayUtils; | drawBottomText(canvas);
if (day.hasEvent()) {
drawEventSymbol(canvas);
}
if (day.isHoliday()) {
drawHoliday(canvas, holidayTextColor, holidayBgColor);
}
if (day.isWorkday()) {
drawWorkday(canvas);
}
if (day.hasBirthday()) {
drawBirthday(canvas);
}
}
private void drawNumber(Canvas canvas, int color) {
paint.setColor(color);
paint.setStyle(Paint.Style.FILL);
canvas.drawText(String.valueOf(day.getDayOfMonth()), rect.centerX(), rect.centerY(), paint);
}
private void drawBottomText(Canvas canvas) {
paint.setTextSize(mDateBottomTextSize);
float bottomTextY = rect.centerY() + rect.height() / 4 + mDateBottomTextSize / 2; //将底部文居中在在3/4处
canvas.drawText(day.getBottomText(), rect.centerX(), bottomTextY, paint);
}
private void drawEventSymbol(Canvas canvas) {
float symbolCenterX = rect.centerX() + rect.width() / 6;
float symbolCenterY = rect.centerY() + mEventRectSize / 2; | // Path: app/src/main/java/top/soyask/calendarii/entity/Symbol.java
// public enum Symbol {
// RECT("rect", 1),
// CIRCLE("circle", 2),
// TRIANGLE("triangle", 3),
// STAR("star", 4),
// HEART("heart", 5),
// ;
//
// public final String KEY;
// public final int VALUE;
//
// Symbol(String key, int value) {
// this.KEY = key;
// this.VALUE = value;
// }
//
// }
//
// Path: app/src/main/java/top/soyask/calendarii/utils/DayUtils.java
// public class DayUtils {
// /**
// * @param month 传入实际的月份
// * @param year
// * @return
// */
// public static int getMonthDayCount(int month, int year) {
// month = month - 1;
// switch (month) {
// case Calendar.JANUARY:
// case Calendar.MARCH:
// case Calendar.MAY:
// case Calendar.JULY:
// case Calendar.AUGUST:
// case Calendar.OCTOBER:
// case Calendar.DECEMBER:
// return 31;
// case Calendar.APRIL:
// case Calendar.JUNE:
// case Calendar.SEPTEMBER:
// case Calendar.NOVEMBER:
// return 30;
// case Calendar.FEBRUARY:
// return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0) ? 29 : 28;
// default:
// throw new IllegalArgumentException("Didn't find this month(未找到该月份):" + month);
// }
//
// }
//
// public static int getPrevMonthDayCount(int month, int year) {
// if (month > 1) {
// month--;
// } else {
// year--;
// }
// return getMonthDayCount(month, year);
// }
//
//
// public static int getDayForWeek(Calendar calendar) {
// int date = calendar.get(Calendar.DAY_OF_MONTH);
// if (date < 1 || date > 31) {
// return 1;
// }
// return calendar.get(Calendar.DAY_OF_WEEK) - 1;
// }
//
// public static int getWeekForMonth(Calendar calendar) {
// int date = calendar.get(Calendar.DAY_OF_MONTH);
// if (date < 1 || date > 31) {
// return 1;
// }
// return calendar.get(Calendar.WEEK_OF_MONTH);
// }
// }
// Path: app/src/main/java/top/soyask/calendarii/ui/view/CalendarView.java
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Point;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.animation.Animation;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;
import top.soyask.calendarii.R;
import top.soyask.calendarii.entity.Symbol;
import top.soyask.calendarii.utils.DayUtils;
drawBottomText(canvas);
if (day.hasEvent()) {
drawEventSymbol(canvas);
}
if (day.isHoliday()) {
drawHoliday(canvas, holidayTextColor, holidayBgColor);
}
if (day.isWorkday()) {
drawWorkday(canvas);
}
if (day.hasBirthday()) {
drawBirthday(canvas);
}
}
private void drawNumber(Canvas canvas, int color) {
paint.setColor(color);
paint.setStyle(Paint.Style.FILL);
canvas.drawText(String.valueOf(day.getDayOfMonth()), rect.centerX(), rect.centerY(), paint);
}
private void drawBottomText(Canvas canvas) {
paint.setTextSize(mDateBottomTextSize);
float bottomTextY = rect.centerY() + rect.height() / 4 + mDateBottomTextSize / 2; //将底部文居中在在3/4处
canvas.drawText(day.getBottomText(), rect.centerX(), bottomTextY, paint);
}
private void drawEventSymbol(Canvas canvas) {
float symbolCenterX = rect.centerX() + rect.width() / 6;
float symbolCenterY = rect.centerY() + mEventRectSize / 2; | Symbol symbol = day.getSymbol(); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.