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
uPhyca/robota
robota/src/main/java/com/uphyca/robota/service/PostTextService.java
// Path: robota/src/main/java/com/uphyca/robota/InjectionUtils.java // public abstract class InjectionUtils { // // private InjectionUtils() { // } // // public static ObjectGraph getObjectGraph(Context context) { // return RobotaApplication.class.cast(context.getApplicationContext()) // .getObjectGraph(); // } // }
import android.app.IntentService; import android.content.Context; import android.content.Intent; import android.net.Uri; import com.uphyca.idobata.Idobata; import com.uphyca.idobata.IdobataError; import com.uphyca.robota.InjectionUtils; import javax.inject.Inject;
/* * Copyright (C) 2014 uPhyca Inc. * * 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.uphyca.robota.service; /** * @author Sosuke Masui (masui@uphyca.com) */ public class PostTextService extends IntentService { private static final String EXTRA_ROOM_URI = "room_uri"; private static final String EXTRA_SOURCE = "source"; public static void postText(Context context, Uri roomUri, String source) { Intent intent = new Intent(context, PostTextService.class).putExtra(EXTRA_SOURCE, source) .putExtra(EXTRA_ROOM_URI, roomUri); context.startService(intent); } @Inject Idobata mIdobata; public PostTextService() { super("PostTextService"); } @Override public void onCreate() { super.onCreate();
// Path: robota/src/main/java/com/uphyca/robota/InjectionUtils.java // public abstract class InjectionUtils { // // private InjectionUtils() { // } // // public static ObjectGraph getObjectGraph(Context context) { // return RobotaApplication.class.cast(context.getApplicationContext()) // .getObjectGraph(); // } // } // Path: robota/src/main/java/com/uphyca/robota/service/PostTextService.java import android.app.IntentService; import android.content.Context; import android.content.Intent; import android.net.Uri; import com.uphyca.idobata.Idobata; import com.uphyca.idobata.IdobataError; import com.uphyca.robota.InjectionUtils; import javax.inject.Inject; /* * Copyright (C) 2014 uPhyca Inc. * * 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.uphyca.robota.service; /** * @author Sosuke Masui (masui@uphyca.com) */ public class PostTextService extends IntentService { private static final String EXTRA_ROOM_URI = "room_uri"; private static final String EXTRA_SOURCE = "source"; public static void postText(Context context, Uri roomUri, String source) { Intent intent = new Intent(context, PostTextService.class).putExtra(EXTRA_SOURCE, source) .putExtra(EXTRA_ROOM_URI, roomUri); context.startService(intent); } @Inject Idobata mIdobata; public PostTextService() { super("PostTextService"); } @Override public void onCreate() { super.onCreate();
InjectionUtils.getObjectGraph(this)
uPhyca/robota
robota/src/main/java/com/uphyca/robota/ui/InstalledEnginesActivity.java
// Path: robota/src/main/java/com/uphyca/robota/InjectionUtils.java // public abstract class InjectionUtils { // // private InjectionUtils() { // } // // public static ObjectGraph getObjectGraph(Context context) { // return RobotaApplication.class.cast(context.getApplicationContext()) // .getObjectGraph(); // } // } // // Path: robota/src/main/java/com/uphyca/robota/Robota.java // public class Robota { // // private static final String INTENT = "com.uphyca.robota"; // private static final String ACTION = INTENT + ".action"; // private static final String EXTRA = INTENT + ".extra"; // private static final String PERMISSION = INTENT + ".permission"; // // // Message created event // // public static final String ACTION_MESSAGE_CREATED = ACTION + ".MESSAGE_CREATED"; // // public static final String PERMISSION_RECEIVE_MESSAGE_CREATED = PERMISSION + ".RECEIVE_MESSAGE_CREATED"; // // public static final String EXTRA_ID = EXTRA + ".ID"; // public static final String EXTRA_BODY = EXTRA + ".BODY"; // public static final String EXTRA_BODY_PLAIN = EXTRA + ".BODY_PLAIN"; // public static final String EXTRA_IMAGE_URLS = EXTRA + ".IMAGE_URLS"; // public static final String EXTRA_MULTILINE = EXTRA + ".MULTILINE"; // public static final String EXTRA_MENTIONS = EXTRA + ".MENTIONS"; // public static final String EXTRA_CREATED_AT = EXTRA + ".CREATED_AT"; // public static final String EXTRA_ROOM_ID = EXTRA + ".ROOM_ID"; // public static final String EXTRA_ROOM_NAME = EXTRA + ".ROOM_NAME"; // public static final String EXTRA_ORGANIZATION_SLUG = EXTRA + ".ORGANIZATION_SLUG"; // public static final String EXTRA_SENDER_TYPE = EXTRA + ".SENDER_TYPE"; // public static final String EXTRA_SENDER_ID = EXTRA + ".SENDER_ID"; // public static final String EXTRA_SENDER_NAME = EXTRA + ".SENDER_NAME"; // public static final String EXTRA_SENDER_ICON_URL = EXTRA + ".SENDER_ICON_URL"; // // public static final String EXTRA_BOT_ID = EXTRA + ".BOT_ID"; // public static final String EXTRA_BOT_NAME = EXTRA + ".BOT_NAME"; // public static final String EXTRA_BOT_API_TOKEN = EXTRA + ".BOT_API_TOKEN"; // public static final String EXTRA_BOT_ICON_URL = EXTRA + ".BOT_ICON_URL"; // }
import android.app.Activity; import android.app.ListFragment; import android.content.Context; import android.content.Intent; import android.content.pm.ActivityInfo; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.os.Bundle; import android.view.View; import android.widget.ListView; import android.widget.SimpleAdapter; import com.uphyca.idobata.Idobata; import com.uphyca.idobata.IdobataError; import com.uphyca.idobata.model.Seed; import com.uphyca.robota.InjectionUtils; import com.uphyca.robota.R; import com.uphyca.robota.Robota; import com.uphyca.robota.data.api.Main; import com.uphyca.robota.data.api.Networking; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.concurrent.Executor; import javax.inject.Inject;
/* * Copyright (C) 2014 uPhyca Inc. * * 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.uphyca.robota.ui; /** * @author Sosuke Masui (masui@uphyca.com) */ public class InstalledEnginesActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_installed_engines); } public static class InstalledEnginesListFragment extends ListFragment { @Inject Idobata mIdobata; @Inject @Networking Executor mExecutor; @Inject @Main Executor mDispatcher; @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState);
// Path: robota/src/main/java/com/uphyca/robota/InjectionUtils.java // public abstract class InjectionUtils { // // private InjectionUtils() { // } // // public static ObjectGraph getObjectGraph(Context context) { // return RobotaApplication.class.cast(context.getApplicationContext()) // .getObjectGraph(); // } // } // // Path: robota/src/main/java/com/uphyca/robota/Robota.java // public class Robota { // // private static final String INTENT = "com.uphyca.robota"; // private static final String ACTION = INTENT + ".action"; // private static final String EXTRA = INTENT + ".extra"; // private static final String PERMISSION = INTENT + ".permission"; // // // Message created event // // public static final String ACTION_MESSAGE_CREATED = ACTION + ".MESSAGE_CREATED"; // // public static final String PERMISSION_RECEIVE_MESSAGE_CREATED = PERMISSION + ".RECEIVE_MESSAGE_CREATED"; // // public static final String EXTRA_ID = EXTRA + ".ID"; // public static final String EXTRA_BODY = EXTRA + ".BODY"; // public static final String EXTRA_BODY_PLAIN = EXTRA + ".BODY_PLAIN"; // public static final String EXTRA_IMAGE_URLS = EXTRA + ".IMAGE_URLS"; // public static final String EXTRA_MULTILINE = EXTRA + ".MULTILINE"; // public static final String EXTRA_MENTIONS = EXTRA + ".MENTIONS"; // public static final String EXTRA_CREATED_AT = EXTRA + ".CREATED_AT"; // public static final String EXTRA_ROOM_ID = EXTRA + ".ROOM_ID"; // public static final String EXTRA_ROOM_NAME = EXTRA + ".ROOM_NAME"; // public static final String EXTRA_ORGANIZATION_SLUG = EXTRA + ".ORGANIZATION_SLUG"; // public static final String EXTRA_SENDER_TYPE = EXTRA + ".SENDER_TYPE"; // public static final String EXTRA_SENDER_ID = EXTRA + ".SENDER_ID"; // public static final String EXTRA_SENDER_NAME = EXTRA + ".SENDER_NAME"; // public static final String EXTRA_SENDER_ICON_URL = EXTRA + ".SENDER_ICON_URL"; // // public static final String EXTRA_BOT_ID = EXTRA + ".BOT_ID"; // public static final String EXTRA_BOT_NAME = EXTRA + ".BOT_NAME"; // public static final String EXTRA_BOT_API_TOKEN = EXTRA + ".BOT_API_TOKEN"; // public static final String EXTRA_BOT_ICON_URL = EXTRA + ".BOT_ICON_URL"; // } // Path: robota/src/main/java/com/uphyca/robota/ui/InstalledEnginesActivity.java import android.app.Activity; import android.app.ListFragment; import android.content.Context; import android.content.Intent; import android.content.pm.ActivityInfo; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.os.Bundle; import android.view.View; import android.widget.ListView; import android.widget.SimpleAdapter; import com.uphyca.idobata.Idobata; import com.uphyca.idobata.IdobataError; import com.uphyca.idobata.model.Seed; import com.uphyca.robota.InjectionUtils; import com.uphyca.robota.R; import com.uphyca.robota.Robota; import com.uphyca.robota.data.api.Main; import com.uphyca.robota.data.api.Networking; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.concurrent.Executor; import javax.inject.Inject; /* * Copyright (C) 2014 uPhyca Inc. * * 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.uphyca.robota.ui; /** * @author Sosuke Masui (masui@uphyca.com) */ public class InstalledEnginesActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_installed_engines); } public static class InstalledEnginesListFragment extends ListFragment { @Inject Idobata mIdobata; @Inject @Networking Executor mExecutor; @Inject @Main Executor mDispatcher; @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState);
InjectionUtils.getObjectGraph(getActivity())
uPhyca/robota
robota/src/main/java/com/uphyca/robota/ui/InstalledEnginesActivity.java
// Path: robota/src/main/java/com/uphyca/robota/InjectionUtils.java // public abstract class InjectionUtils { // // private InjectionUtils() { // } // // public static ObjectGraph getObjectGraph(Context context) { // return RobotaApplication.class.cast(context.getApplicationContext()) // .getObjectGraph(); // } // } // // Path: robota/src/main/java/com/uphyca/robota/Robota.java // public class Robota { // // private static final String INTENT = "com.uphyca.robota"; // private static final String ACTION = INTENT + ".action"; // private static final String EXTRA = INTENT + ".extra"; // private static final String PERMISSION = INTENT + ".permission"; // // // Message created event // // public static final String ACTION_MESSAGE_CREATED = ACTION + ".MESSAGE_CREATED"; // // public static final String PERMISSION_RECEIVE_MESSAGE_CREATED = PERMISSION + ".RECEIVE_MESSAGE_CREATED"; // // public static final String EXTRA_ID = EXTRA + ".ID"; // public static final String EXTRA_BODY = EXTRA + ".BODY"; // public static final String EXTRA_BODY_PLAIN = EXTRA + ".BODY_PLAIN"; // public static final String EXTRA_IMAGE_URLS = EXTRA + ".IMAGE_URLS"; // public static final String EXTRA_MULTILINE = EXTRA + ".MULTILINE"; // public static final String EXTRA_MENTIONS = EXTRA + ".MENTIONS"; // public static final String EXTRA_CREATED_AT = EXTRA + ".CREATED_AT"; // public static final String EXTRA_ROOM_ID = EXTRA + ".ROOM_ID"; // public static final String EXTRA_ROOM_NAME = EXTRA + ".ROOM_NAME"; // public static final String EXTRA_ORGANIZATION_SLUG = EXTRA + ".ORGANIZATION_SLUG"; // public static final String EXTRA_SENDER_TYPE = EXTRA + ".SENDER_TYPE"; // public static final String EXTRA_SENDER_ID = EXTRA + ".SENDER_ID"; // public static final String EXTRA_SENDER_NAME = EXTRA + ".SENDER_NAME"; // public static final String EXTRA_SENDER_ICON_URL = EXTRA + ".SENDER_ICON_URL"; // // public static final String EXTRA_BOT_ID = EXTRA + ".BOT_ID"; // public static final String EXTRA_BOT_NAME = EXTRA + ".BOT_NAME"; // public static final String EXTRA_BOT_API_TOKEN = EXTRA + ".BOT_API_TOKEN"; // public static final String EXTRA_BOT_ICON_URL = EXTRA + ".BOT_ICON_URL"; // }
import android.app.Activity; import android.app.ListFragment; import android.content.Context; import android.content.Intent; import android.content.pm.ActivityInfo; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.os.Bundle; import android.view.View; import android.widget.ListView; import android.widget.SimpleAdapter; import com.uphyca.idobata.Idobata; import com.uphyca.idobata.IdobataError; import com.uphyca.idobata.model.Seed; import com.uphyca.robota.InjectionUtils; import com.uphyca.robota.R; import com.uphyca.robota.Robota; import com.uphyca.robota.data.api.Main; import com.uphyca.robota.data.api.Networking; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.concurrent.Executor; import javax.inject.Inject;
Executor mDispatcher; @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); InjectionUtils.getObjectGraph(getActivity()) .inject(this); mExecutor.execute(new Runnable() { @Override public void run() { String botName; try { Seed seed = mIdobata.getSeed(); botName = seed.getRecords() .getBot() .getName(); } catch (IdobataError idobataError) { idobataError.printStackTrace(); botName = "robota"; } List<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>(); String[] from = { "text1", "text2" }; int[] to = { android.R.id.text1, android.R.id.text2 }; PackageManager pm = getActivity().getPackageManager();
// Path: robota/src/main/java/com/uphyca/robota/InjectionUtils.java // public abstract class InjectionUtils { // // private InjectionUtils() { // } // // public static ObjectGraph getObjectGraph(Context context) { // return RobotaApplication.class.cast(context.getApplicationContext()) // .getObjectGraph(); // } // } // // Path: robota/src/main/java/com/uphyca/robota/Robota.java // public class Robota { // // private static final String INTENT = "com.uphyca.robota"; // private static final String ACTION = INTENT + ".action"; // private static final String EXTRA = INTENT + ".extra"; // private static final String PERMISSION = INTENT + ".permission"; // // // Message created event // // public static final String ACTION_MESSAGE_CREATED = ACTION + ".MESSAGE_CREATED"; // // public static final String PERMISSION_RECEIVE_MESSAGE_CREATED = PERMISSION + ".RECEIVE_MESSAGE_CREATED"; // // public static final String EXTRA_ID = EXTRA + ".ID"; // public static final String EXTRA_BODY = EXTRA + ".BODY"; // public static final String EXTRA_BODY_PLAIN = EXTRA + ".BODY_PLAIN"; // public static final String EXTRA_IMAGE_URLS = EXTRA + ".IMAGE_URLS"; // public static final String EXTRA_MULTILINE = EXTRA + ".MULTILINE"; // public static final String EXTRA_MENTIONS = EXTRA + ".MENTIONS"; // public static final String EXTRA_CREATED_AT = EXTRA + ".CREATED_AT"; // public static final String EXTRA_ROOM_ID = EXTRA + ".ROOM_ID"; // public static final String EXTRA_ROOM_NAME = EXTRA + ".ROOM_NAME"; // public static final String EXTRA_ORGANIZATION_SLUG = EXTRA + ".ORGANIZATION_SLUG"; // public static final String EXTRA_SENDER_TYPE = EXTRA + ".SENDER_TYPE"; // public static final String EXTRA_SENDER_ID = EXTRA + ".SENDER_ID"; // public static final String EXTRA_SENDER_NAME = EXTRA + ".SENDER_NAME"; // public static final String EXTRA_SENDER_ICON_URL = EXTRA + ".SENDER_ICON_URL"; // // public static final String EXTRA_BOT_ID = EXTRA + ".BOT_ID"; // public static final String EXTRA_BOT_NAME = EXTRA + ".BOT_NAME"; // public static final String EXTRA_BOT_API_TOKEN = EXTRA + ".BOT_API_TOKEN"; // public static final String EXTRA_BOT_ICON_URL = EXTRA + ".BOT_ICON_URL"; // } // Path: robota/src/main/java/com/uphyca/robota/ui/InstalledEnginesActivity.java import android.app.Activity; import android.app.ListFragment; import android.content.Context; import android.content.Intent; import android.content.pm.ActivityInfo; import android.content.pm.PackageManager; import android.content.pm.ResolveInfo; import android.os.Bundle; import android.view.View; import android.widget.ListView; import android.widget.SimpleAdapter; import com.uphyca.idobata.Idobata; import com.uphyca.idobata.IdobataError; import com.uphyca.idobata.model.Seed; import com.uphyca.robota.InjectionUtils; import com.uphyca.robota.R; import com.uphyca.robota.Robota; import com.uphyca.robota.data.api.Main; import com.uphyca.robota.data.api.Networking; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.concurrent.Executor; import javax.inject.Inject; Executor mDispatcher; @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); InjectionUtils.getObjectGraph(getActivity()) .inject(this); mExecutor.execute(new Runnable() { @Override public void run() { String botName; try { Seed seed = mIdobata.getSeed(); botName = seed.getRecords() .getBot() .getName(); } catch (IdobataError idobataError) { idobataError.printStackTrace(); botName = "robota"; } List<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>(); String[] from = { "text1", "text2" }; int[] to = { android.R.id.text1, android.R.id.text2 }; PackageManager pm = getActivity().getPackageManager();
List<ResolveInfo> resolveInfos = pm.queryBroadcastReceivers(new Intent(Robota.ACTION_MESSAGE_CREATED), 0);
uPhyca/robota
robota/src/main/java/com/uphyca/robota/ui/OssLicensesActivity.java
// Path: robota/src/main/java/com/uphyca/robota/InjectionUtils.java // public abstract class InjectionUtils { // // private InjectionUtils() { // } // // public static ObjectGraph getObjectGraph(Context context) { // return RobotaApplication.class.cast(context.getApplicationContext()) // .getObjectGraph(); // } // }
import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.DialogFragment; import android.app.FragmentManager; import android.app.ListFragment; import android.content.res.Resources; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import com.uphyca.robota.InjectionUtils; import com.uphyca.robota.R; import com.uphyca.robota.data.api.Main; import com.uphyca.robota.data.api.Networking; import java.io.ByteArrayOutputStream; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.util.concurrent.Executor; import javax.inject.Inject; import butterknife.ButterKnife;
private static final String ARGS_TITLE = "title"; private static final String ARGS_FILE_NAME = "file_name"; public static LicenseDialogFragment newInstance(String title, String fileName) { LicenseDialogFragment f = new LicenseDialogFragment(); Bundle args = new Bundle(); args.putString(ARGS_TITLE, title); args.putString(ARGS_FILE_NAME, fileName); f.setArguments(args); return f; } @Inject @Networking Executor mExecutor; @Inject @Main Executor mDispatcher; private String mTitle; private String mFileName; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle args = getArguments(); mTitle = args.getString(ARGS_TITLE); mFileName = args.getString(ARGS_FILE_NAME);
// Path: robota/src/main/java/com/uphyca/robota/InjectionUtils.java // public abstract class InjectionUtils { // // private InjectionUtils() { // } // // public static ObjectGraph getObjectGraph(Context context) { // return RobotaApplication.class.cast(context.getApplicationContext()) // .getObjectGraph(); // } // } // Path: robota/src/main/java/com/uphyca/robota/ui/OssLicensesActivity.java import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.DialogFragment; import android.app.FragmentManager; import android.app.ListFragment; import android.content.res.Resources; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import com.uphyca.robota.InjectionUtils; import com.uphyca.robota.R; import com.uphyca.robota.data.api.Main; import com.uphyca.robota.data.api.Networking; import java.io.ByteArrayOutputStream; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.util.concurrent.Executor; import javax.inject.Inject; import butterknife.ButterKnife; private static final String ARGS_TITLE = "title"; private static final String ARGS_FILE_NAME = "file_name"; public static LicenseDialogFragment newInstance(String title, String fileName) { LicenseDialogFragment f = new LicenseDialogFragment(); Bundle args = new Bundle(); args.putString(ARGS_TITLE, title); args.putString(ARGS_FILE_NAME, fileName); f.setArguments(args); return f; } @Inject @Networking Executor mExecutor; @Inject @Main Executor mDispatcher; private String mTitle; private String mFileName; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Bundle args = getArguments(); mTitle = args.getString(ARGS_TITLE); mFileName = args.getString(ARGS_FILE_NAME);
InjectionUtils.getObjectGraph(getActivity())
uPhyca/robota
robota/src/main/java/com/uphyca/robota/data/ExponentialBackoff.java
// Path: robota/src/main/java/com/uphyca/robota/data/api/BackoffPolicy.java // public interface BackoffPolicy { // // void backoff(); // // void reset(); // // long getNextBackOffMillis(); // // boolean isFailed(); // } // // Path: robota/src/main/java/com/uphyca/robota/data/api/Environment.java // public interface Environment { // // long elapsedRealtime(); // // long currentTimeMillis(); // }
import com.uphyca.robota.data.api.BackoffPolicy; import com.uphyca.robota.data.api.Environment;
/* * Copyright (C) 2014 uPhyca Inc. * * 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.uphyca.robota.data; /** * @author Sosuke Masui (masui@uphyca.com) */ public class ExponentialBackoff implements BackoffPolicy { private static final double MULTPLIER = 2;
// Path: robota/src/main/java/com/uphyca/robota/data/api/BackoffPolicy.java // public interface BackoffPolicy { // // void backoff(); // // void reset(); // // long getNextBackOffMillis(); // // boolean isFailed(); // } // // Path: robota/src/main/java/com/uphyca/robota/data/api/Environment.java // public interface Environment { // // long elapsedRealtime(); // // long currentTimeMillis(); // } // Path: robota/src/main/java/com/uphyca/robota/data/ExponentialBackoff.java import com.uphyca.robota.data.api.BackoffPolicy; import com.uphyca.robota.data.api.Environment; /* * Copyright (C) 2014 uPhyca Inc. * * 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.uphyca.robota.data; /** * @author Sosuke Masui (masui@uphyca.com) */ public class ExponentialBackoff implements BackoffPolicy { private static final double MULTPLIER = 2;
private final Environment mEnvironment;
cocolove2/LISDemo
library-lis/src/main/java/uk/co/senab/photoview/PhotoView.java
// Path: library-lis/src/main/java/uk/co/senab/photoview/PhotoViewAttacher.java // public static interface OnMatrixChangedListener { // /** // * Callback for when the Matrix displaying the Drawable has changed. This could be because // * the View's bounds have changed, or the user has zoomed. // * // * @param rect - Rectangle displaying the Drawable's new bounds. // */ // void onMatrixChanged(RectF rect); // } // // Path: library-lis/src/main/java/uk/co/senab/photoview/PhotoViewAttacher.java // public static interface OnPhotoTapListener { // // /** // * A callback to receive where the user taps on a photo. You will only receive a callback if // * the user taps on the actual photo, tapping on 'whitespace' will be ignored. // * // * @param view - View the user tapped. // * @param x - where the user tapped from the of the Drawable, as percentage of the // * Drawable width. // * @param y - where the user tapped from the top of the Drawable, as percentage of the // * Drawable height. // */ // void onPhotoTap(View view, float x, float y); // } // // Path: library-lis/src/main/java/uk/co/senab/photoview/PhotoViewAttacher.java // public static interface OnViewTapListener { // // /** // * A callback to receive where the user taps on a ImageView. You will receive a callback if // * the user taps anywhere on the view, tapping on 'whitespace' will not be ignored. // * // * @param view - View the user tapped. // * @param x - where the user tapped from the left of the View. // * @param y - where the user tapped from the top of the View. // */ // void onViewTap(View view, float x, float y); // }
import uk.co.senab.photoview.PhotoViewAttacher.OnMatrixChangedListener; import uk.co.senab.photoview.PhotoViewAttacher.OnPhotoTapListener; import uk.co.senab.photoview.PhotoViewAttacher.OnViewTapListener; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Matrix; import android.graphics.RectF; import android.graphics.drawable.Drawable; import android.net.Uri; import android.util.AttributeSet; import android.widget.ImageView;
public void setMaximumScale(float maximumScale) { mAttacher.setMaximumScale(maximumScale); } @Override // setImageBitmap calls through to this method public void setImageDrawable(Drawable drawable) { super.setImageDrawable(drawable); if (null != mAttacher) { mAttacher.update(); } } @Override public void setImageResource(int resId) { super.setImageResource(resId); if (null != mAttacher) { mAttacher.update(); } } @Override public void setImageURI(Uri uri) { super.setImageURI(uri); if (null != mAttacher) { mAttacher.update(); } } @Override
// Path: library-lis/src/main/java/uk/co/senab/photoview/PhotoViewAttacher.java // public static interface OnMatrixChangedListener { // /** // * Callback for when the Matrix displaying the Drawable has changed. This could be because // * the View's bounds have changed, or the user has zoomed. // * // * @param rect - Rectangle displaying the Drawable's new bounds. // */ // void onMatrixChanged(RectF rect); // } // // Path: library-lis/src/main/java/uk/co/senab/photoview/PhotoViewAttacher.java // public static interface OnPhotoTapListener { // // /** // * A callback to receive where the user taps on a photo. You will only receive a callback if // * the user taps on the actual photo, tapping on 'whitespace' will be ignored. // * // * @param view - View the user tapped. // * @param x - where the user tapped from the of the Drawable, as percentage of the // * Drawable width. // * @param y - where the user tapped from the top of the Drawable, as percentage of the // * Drawable height. // */ // void onPhotoTap(View view, float x, float y); // } // // Path: library-lis/src/main/java/uk/co/senab/photoview/PhotoViewAttacher.java // public static interface OnViewTapListener { // // /** // * A callback to receive where the user taps on a ImageView. You will receive a callback if // * the user taps anywhere on the view, tapping on 'whitespace' will not be ignored. // * // * @param view - View the user tapped. // * @param x - where the user tapped from the left of the View. // * @param y - where the user tapped from the top of the View. // */ // void onViewTap(View view, float x, float y); // } // Path: library-lis/src/main/java/uk/co/senab/photoview/PhotoView.java import uk.co.senab.photoview.PhotoViewAttacher.OnMatrixChangedListener; import uk.co.senab.photoview.PhotoViewAttacher.OnPhotoTapListener; import uk.co.senab.photoview.PhotoViewAttacher.OnViewTapListener; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Matrix; import android.graphics.RectF; import android.graphics.drawable.Drawable; import android.net.Uri; import android.util.AttributeSet; import android.widget.ImageView; public void setMaximumScale(float maximumScale) { mAttacher.setMaximumScale(maximumScale); } @Override // setImageBitmap calls through to this method public void setImageDrawable(Drawable drawable) { super.setImageDrawable(drawable); if (null != mAttacher) { mAttacher.update(); } } @Override public void setImageResource(int resId) { super.setImageResource(resId); if (null != mAttacher) { mAttacher.update(); } } @Override public void setImageURI(Uri uri) { super.setImageURI(uri); if (null != mAttacher) { mAttacher.update(); } } @Override
public void setOnMatrixChangeListener(OnMatrixChangedListener listener) {
cocolove2/LISDemo
library-lis/src/main/java/uk/co/senab/photoview/PhotoView.java
// Path: library-lis/src/main/java/uk/co/senab/photoview/PhotoViewAttacher.java // public static interface OnMatrixChangedListener { // /** // * Callback for when the Matrix displaying the Drawable has changed. This could be because // * the View's bounds have changed, or the user has zoomed. // * // * @param rect - Rectangle displaying the Drawable's new bounds. // */ // void onMatrixChanged(RectF rect); // } // // Path: library-lis/src/main/java/uk/co/senab/photoview/PhotoViewAttacher.java // public static interface OnPhotoTapListener { // // /** // * A callback to receive where the user taps on a photo. You will only receive a callback if // * the user taps on the actual photo, tapping on 'whitespace' will be ignored. // * // * @param view - View the user tapped. // * @param x - where the user tapped from the of the Drawable, as percentage of the // * Drawable width. // * @param y - where the user tapped from the top of the Drawable, as percentage of the // * Drawable height. // */ // void onPhotoTap(View view, float x, float y); // } // // Path: library-lis/src/main/java/uk/co/senab/photoview/PhotoViewAttacher.java // public static interface OnViewTapListener { // // /** // * A callback to receive where the user taps on a ImageView. You will receive a callback if // * the user taps anywhere on the view, tapping on 'whitespace' will not be ignored. // * // * @param view - View the user tapped. // * @param x - where the user tapped from the left of the View. // * @param y - where the user tapped from the top of the View. // */ // void onViewTap(View view, float x, float y); // }
import uk.co.senab.photoview.PhotoViewAttacher.OnMatrixChangedListener; import uk.co.senab.photoview.PhotoViewAttacher.OnPhotoTapListener; import uk.co.senab.photoview.PhotoViewAttacher.OnViewTapListener; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Matrix; import android.graphics.RectF; import android.graphics.drawable.Drawable; import android.net.Uri; import android.util.AttributeSet; import android.widget.ImageView;
} } @Override public void setImageResource(int resId) { super.setImageResource(resId); if (null != mAttacher) { mAttacher.update(); } } @Override public void setImageURI(Uri uri) { super.setImageURI(uri); if (null != mAttacher) { mAttacher.update(); } } @Override public void setOnMatrixChangeListener(OnMatrixChangedListener listener) { mAttacher.setOnMatrixChangeListener(listener); } @Override public void setOnLongClickListener(OnLongClickListener l) { mAttacher.setOnLongClickListener(l); } @Override
// Path: library-lis/src/main/java/uk/co/senab/photoview/PhotoViewAttacher.java // public static interface OnMatrixChangedListener { // /** // * Callback for when the Matrix displaying the Drawable has changed. This could be because // * the View's bounds have changed, or the user has zoomed. // * // * @param rect - Rectangle displaying the Drawable's new bounds. // */ // void onMatrixChanged(RectF rect); // } // // Path: library-lis/src/main/java/uk/co/senab/photoview/PhotoViewAttacher.java // public static interface OnPhotoTapListener { // // /** // * A callback to receive where the user taps on a photo. You will only receive a callback if // * the user taps on the actual photo, tapping on 'whitespace' will be ignored. // * // * @param view - View the user tapped. // * @param x - where the user tapped from the of the Drawable, as percentage of the // * Drawable width. // * @param y - where the user tapped from the top of the Drawable, as percentage of the // * Drawable height. // */ // void onPhotoTap(View view, float x, float y); // } // // Path: library-lis/src/main/java/uk/co/senab/photoview/PhotoViewAttacher.java // public static interface OnViewTapListener { // // /** // * A callback to receive where the user taps on a ImageView. You will receive a callback if // * the user taps anywhere on the view, tapping on 'whitespace' will not be ignored. // * // * @param view - View the user tapped. // * @param x - where the user tapped from the left of the View. // * @param y - where the user tapped from the top of the View. // */ // void onViewTap(View view, float x, float y); // } // Path: library-lis/src/main/java/uk/co/senab/photoview/PhotoView.java import uk.co.senab.photoview.PhotoViewAttacher.OnMatrixChangedListener; import uk.co.senab.photoview.PhotoViewAttacher.OnPhotoTapListener; import uk.co.senab.photoview.PhotoViewAttacher.OnViewTapListener; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Matrix; import android.graphics.RectF; import android.graphics.drawable.Drawable; import android.net.Uri; import android.util.AttributeSet; import android.widget.ImageView; } } @Override public void setImageResource(int resId) { super.setImageResource(resId); if (null != mAttacher) { mAttacher.update(); } } @Override public void setImageURI(Uri uri) { super.setImageURI(uri); if (null != mAttacher) { mAttacher.update(); } } @Override public void setOnMatrixChangeListener(OnMatrixChangedListener listener) { mAttacher.setOnMatrixChangeListener(listener); } @Override public void setOnLongClickListener(OnLongClickListener l) { mAttacher.setOnLongClickListener(l); } @Override
public void setOnPhotoTapListener(OnPhotoTapListener listener) {
cocolove2/LISDemo
library-lis/src/main/java/uk/co/senab/photoview/PhotoView.java
// Path: library-lis/src/main/java/uk/co/senab/photoview/PhotoViewAttacher.java // public static interface OnMatrixChangedListener { // /** // * Callback for when the Matrix displaying the Drawable has changed. This could be because // * the View's bounds have changed, or the user has zoomed. // * // * @param rect - Rectangle displaying the Drawable's new bounds. // */ // void onMatrixChanged(RectF rect); // } // // Path: library-lis/src/main/java/uk/co/senab/photoview/PhotoViewAttacher.java // public static interface OnPhotoTapListener { // // /** // * A callback to receive where the user taps on a photo. You will only receive a callback if // * the user taps on the actual photo, tapping on 'whitespace' will be ignored. // * // * @param view - View the user tapped. // * @param x - where the user tapped from the of the Drawable, as percentage of the // * Drawable width. // * @param y - where the user tapped from the top of the Drawable, as percentage of the // * Drawable height. // */ // void onPhotoTap(View view, float x, float y); // } // // Path: library-lis/src/main/java/uk/co/senab/photoview/PhotoViewAttacher.java // public static interface OnViewTapListener { // // /** // * A callback to receive where the user taps on a ImageView. You will receive a callback if // * the user taps anywhere on the view, tapping on 'whitespace' will not be ignored. // * // * @param view - View the user tapped. // * @param x - where the user tapped from the left of the View. // * @param y - where the user tapped from the top of the View. // */ // void onViewTap(View view, float x, float y); // }
import uk.co.senab.photoview.PhotoViewAttacher.OnMatrixChangedListener; import uk.co.senab.photoview.PhotoViewAttacher.OnPhotoTapListener; import uk.co.senab.photoview.PhotoViewAttacher.OnViewTapListener; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Matrix; import android.graphics.RectF; import android.graphics.drawable.Drawable; import android.net.Uri; import android.util.AttributeSet; import android.widget.ImageView;
@Override public void setImageURI(Uri uri) { super.setImageURI(uri); if (null != mAttacher) { mAttacher.update(); } } @Override public void setOnMatrixChangeListener(OnMatrixChangedListener listener) { mAttacher.setOnMatrixChangeListener(listener); } @Override public void setOnLongClickListener(OnLongClickListener l) { mAttacher.setOnLongClickListener(l); } @Override public void setOnPhotoTapListener(OnPhotoTapListener listener) { mAttacher.setOnPhotoTapListener(listener); } @Override public OnPhotoTapListener getOnPhotoTapListener() { return mAttacher.getOnPhotoTapListener(); } @Override
// Path: library-lis/src/main/java/uk/co/senab/photoview/PhotoViewAttacher.java // public static interface OnMatrixChangedListener { // /** // * Callback for when the Matrix displaying the Drawable has changed. This could be because // * the View's bounds have changed, or the user has zoomed. // * // * @param rect - Rectangle displaying the Drawable's new bounds. // */ // void onMatrixChanged(RectF rect); // } // // Path: library-lis/src/main/java/uk/co/senab/photoview/PhotoViewAttacher.java // public static interface OnPhotoTapListener { // // /** // * A callback to receive where the user taps on a photo. You will only receive a callback if // * the user taps on the actual photo, tapping on 'whitespace' will be ignored. // * // * @param view - View the user tapped. // * @param x - where the user tapped from the of the Drawable, as percentage of the // * Drawable width. // * @param y - where the user tapped from the top of the Drawable, as percentage of the // * Drawable height. // */ // void onPhotoTap(View view, float x, float y); // } // // Path: library-lis/src/main/java/uk/co/senab/photoview/PhotoViewAttacher.java // public static interface OnViewTapListener { // // /** // * A callback to receive where the user taps on a ImageView. You will receive a callback if // * the user taps anywhere on the view, tapping on 'whitespace' will not be ignored. // * // * @param view - View the user tapped. // * @param x - where the user tapped from the left of the View. // * @param y - where the user tapped from the top of the View. // */ // void onViewTap(View view, float x, float y); // } // Path: library-lis/src/main/java/uk/co/senab/photoview/PhotoView.java import uk.co.senab.photoview.PhotoViewAttacher.OnMatrixChangedListener; import uk.co.senab.photoview.PhotoViewAttacher.OnPhotoTapListener; import uk.co.senab.photoview.PhotoViewAttacher.OnViewTapListener; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Matrix; import android.graphics.RectF; import android.graphics.drawable.Drawable; import android.net.Uri; import android.util.AttributeSet; import android.widget.ImageView; @Override public void setImageURI(Uri uri) { super.setImageURI(uri); if (null != mAttacher) { mAttacher.update(); } } @Override public void setOnMatrixChangeListener(OnMatrixChangedListener listener) { mAttacher.setOnMatrixChangeListener(listener); } @Override public void setOnLongClickListener(OnLongClickListener l) { mAttacher.setOnLongClickListener(l); } @Override public void setOnPhotoTapListener(OnPhotoTapListener listener) { mAttacher.setOnPhotoTapListener(listener); } @Override public OnPhotoTapListener getOnPhotoTapListener() { return mAttacher.getOnPhotoTapListener(); } @Override
public void setOnViewTapListener(OnViewTapListener listener) {
cocolove2/LISDemo
library-lis/src/main/java/com/cocolover2/lis/activity/LisSimpleListImgsActivity.java
// Path: library-lis/src/main/java/com/cocolover2/lis/LISConstant.java // public class LISConstant { // // public static final String ALL_IMG_BUCKET = "所有图片"; // public static final String ACTION_PRE = "com.cocolover2.lis.ACTION_preview"; // public static final String CATEGORY_SUFFIX = ".category.PREVIEW"; // // public static final String FLAG_PRE_SELECTED_IMGS = "pre_selected_imgs"; // //所要预览的图片的集合 // public static final String PRE_IMG_DATAS = "preview_imgs"; // //预览图片的起始位置 // public static final String PRE_IMG_START_POSITION = "preview_start_img_position"; // } // // Path: library-lis/src/main/java/com/cocolover2/lis/interf/OnSelectResultListener.java // public interface OnSelectResultListener { // void onSelectImgs(int selectedCount); // }
import android.content.Intent; import android.os.Bundle; import android.view.MotionEvent; import android.view.View; import android.widget.Button; import android.widget.ImageView; import com.cocolover2.lis.LISConstant; import com.cocolover2.lis.interf.OnSelectResultListener; import com.cocolover2.lis.R;
initPreBtn(selectedCount); } private void initPreBtn(int selectedCount) { if (selectedCount > 0) { preBtn.setText("预览(" + selectedCount + ")"); preBtn.setEnabled(true); preBtn.setTextColor(getResources().getColor(android.R.color.white)); } else { preBtn.setText("预览"); preBtn.setEnabled(false); preBtn.setTextColor(getResources().getColor(R.color.dark_gray)); } } @Override public void onBackPressed() { clearSelectedImgs(); super.onBackPressed(); } @Override public void onClick(View v) { final int id = v.getId(); if (id == R.id.lis_imglist_bottom_bucket_btn) { if (isPopShow()) hidePop(); else showPop(); } else if (id == R.id.lis_imglist_bottom_pre_btn) {
// Path: library-lis/src/main/java/com/cocolover2/lis/LISConstant.java // public class LISConstant { // // public static final String ALL_IMG_BUCKET = "所有图片"; // public static final String ACTION_PRE = "com.cocolover2.lis.ACTION_preview"; // public static final String CATEGORY_SUFFIX = ".category.PREVIEW"; // // public static final String FLAG_PRE_SELECTED_IMGS = "pre_selected_imgs"; // //所要预览的图片的集合 // public static final String PRE_IMG_DATAS = "preview_imgs"; // //预览图片的起始位置 // public static final String PRE_IMG_START_POSITION = "preview_start_img_position"; // } // // Path: library-lis/src/main/java/com/cocolover2/lis/interf/OnSelectResultListener.java // public interface OnSelectResultListener { // void onSelectImgs(int selectedCount); // } // Path: library-lis/src/main/java/com/cocolover2/lis/activity/LisSimpleListImgsActivity.java import android.content.Intent; import android.os.Bundle; import android.view.MotionEvent; import android.view.View; import android.widget.Button; import android.widget.ImageView; import com.cocolover2.lis.LISConstant; import com.cocolover2.lis.interf.OnSelectResultListener; import com.cocolover2.lis.R; initPreBtn(selectedCount); } private void initPreBtn(int selectedCount) { if (selectedCount > 0) { preBtn.setText("预览(" + selectedCount + ")"); preBtn.setEnabled(true); preBtn.setTextColor(getResources().getColor(android.R.color.white)); } else { preBtn.setText("预览"); preBtn.setEnabled(false); preBtn.setTextColor(getResources().getColor(R.color.dark_gray)); } } @Override public void onBackPressed() { clearSelectedImgs(); super.onBackPressed(); } @Override public void onClick(View v) { final int id = v.getId(); if (id == R.id.lis_imglist_bottom_bucket_btn) { if (isPopShow()) hidePop(); else showPop(); } else if (id == R.id.lis_imglist_bottom_pre_btn) {
Intent intent = new Intent(LISConstant.ACTION_PRE);
cocolove2/LISDemo
library-lis/src/main/java/com/cocolover2/lis/activity/LisBasePreviewPagerActivity.java
// Path: library-lis/src/main/java/com/cocolover2/lis/LISConstant.java // public class LISConstant { // // public static final String ALL_IMG_BUCKET = "所有图片"; // public static final String ACTION_PRE = "com.cocolover2.lis.ACTION_preview"; // public static final String CATEGORY_SUFFIX = ".category.PREVIEW"; // // public static final String FLAG_PRE_SELECTED_IMGS = "pre_selected_imgs"; // //所要预览的图片的集合 // public static final String PRE_IMG_DATAS = "preview_imgs"; // //预览图片的起始位置 // public static final String PRE_IMG_START_POSITION = "preview_start_img_position"; // } // // Path: library-lis/src/main/java/com/cocolover2/lis/interf/OnPagerUpdateListener.java // public interface OnPagerUpdateListener { // void onSelect(int position); // // void onDeleted(int position); // } // // Path: library-lis/src/main/java/com/cocolover2/lis/view/HackyViewPager.java // public class HackyViewPager extends BounceBackViewPager { // // // private static final String TAG = "HackyViewPager"; // // public HackyViewPager(Context context) { // super(context); // } // // public HackyViewPager(Context context, AttributeSet attrs) { // super(context, attrs); // } // // @Override // public boolean onInterceptTouchEvent(MotionEvent ev) { // try { // return super.onInterceptTouchEvent(ev); // } catch (IllegalArgumentException e) { // //不理会 // Log.e(TAG,"hacky viewpager error1"); // return false; // }catch(ArrayIndexOutOfBoundsException e ){ // //不理会 // Log.e(TAG,"hacky viewpager error2"); // return false; // } // } // // }
import android.os.Bundle; import android.os.Parcelable; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentStatePagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.view.LayoutInflater; import android.view.View; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.FrameLayout; import com.cocolover2.lis.LISConstant; import com.cocolover2.lis.interf.OnPagerUpdateListener; import com.cocolover2.lis.R; import com.cocolover2.lis.view.HackyViewPager; import java.util.ArrayList;
package com.cocolover2.lis.activity; public abstract class LisBasePreviewPagerActivity<T> extends AppCompatActivity { private FrameLayout topLayout, bottomLayout; private ImagePagerAdapter mAdapter; private int startPos; private ArrayList<T> mImgDatas;
// Path: library-lis/src/main/java/com/cocolover2/lis/LISConstant.java // public class LISConstant { // // public static final String ALL_IMG_BUCKET = "所有图片"; // public static final String ACTION_PRE = "com.cocolover2.lis.ACTION_preview"; // public static final String CATEGORY_SUFFIX = ".category.PREVIEW"; // // public static final String FLAG_PRE_SELECTED_IMGS = "pre_selected_imgs"; // //所要预览的图片的集合 // public static final String PRE_IMG_DATAS = "preview_imgs"; // //预览图片的起始位置 // public static final String PRE_IMG_START_POSITION = "preview_start_img_position"; // } // // Path: library-lis/src/main/java/com/cocolover2/lis/interf/OnPagerUpdateListener.java // public interface OnPagerUpdateListener { // void onSelect(int position); // // void onDeleted(int position); // } // // Path: library-lis/src/main/java/com/cocolover2/lis/view/HackyViewPager.java // public class HackyViewPager extends BounceBackViewPager { // // // private static final String TAG = "HackyViewPager"; // // public HackyViewPager(Context context) { // super(context); // } // // public HackyViewPager(Context context, AttributeSet attrs) { // super(context, attrs); // } // // @Override // public boolean onInterceptTouchEvent(MotionEvent ev) { // try { // return super.onInterceptTouchEvent(ev); // } catch (IllegalArgumentException e) { // //不理会 // Log.e(TAG,"hacky viewpager error1"); // return false; // }catch(ArrayIndexOutOfBoundsException e ){ // //不理会 // Log.e(TAG,"hacky viewpager error2"); // return false; // } // } // // } // Path: library-lis/src/main/java/com/cocolover2/lis/activity/LisBasePreviewPagerActivity.java import android.os.Bundle; import android.os.Parcelable; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentStatePagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.view.LayoutInflater; import android.view.View; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.FrameLayout; import com.cocolover2.lis.LISConstant; import com.cocolover2.lis.interf.OnPagerUpdateListener; import com.cocolover2.lis.R; import com.cocolover2.lis.view.HackyViewPager; import java.util.ArrayList; package com.cocolover2.lis.activity; public abstract class LisBasePreviewPagerActivity<T> extends AppCompatActivity { private FrameLayout topLayout, bottomLayout; private ImagePagerAdapter mAdapter; private int startPos; private ArrayList<T> mImgDatas;
private OnPagerUpdateListener pagerUpdateListener;
cocolove2/LISDemo
library-lis/src/main/java/com/cocolover2/lis/activity/LisBasePreviewPagerActivity.java
// Path: library-lis/src/main/java/com/cocolover2/lis/LISConstant.java // public class LISConstant { // // public static final String ALL_IMG_BUCKET = "所有图片"; // public static final String ACTION_PRE = "com.cocolover2.lis.ACTION_preview"; // public static final String CATEGORY_SUFFIX = ".category.PREVIEW"; // // public static final String FLAG_PRE_SELECTED_IMGS = "pre_selected_imgs"; // //所要预览的图片的集合 // public static final String PRE_IMG_DATAS = "preview_imgs"; // //预览图片的起始位置 // public static final String PRE_IMG_START_POSITION = "preview_start_img_position"; // } // // Path: library-lis/src/main/java/com/cocolover2/lis/interf/OnPagerUpdateListener.java // public interface OnPagerUpdateListener { // void onSelect(int position); // // void onDeleted(int position); // } // // Path: library-lis/src/main/java/com/cocolover2/lis/view/HackyViewPager.java // public class HackyViewPager extends BounceBackViewPager { // // // private static final String TAG = "HackyViewPager"; // // public HackyViewPager(Context context) { // super(context); // } // // public HackyViewPager(Context context, AttributeSet attrs) { // super(context, attrs); // } // // @Override // public boolean onInterceptTouchEvent(MotionEvent ev) { // try { // return super.onInterceptTouchEvent(ev); // } catch (IllegalArgumentException e) { // //不理会 // Log.e(TAG,"hacky viewpager error1"); // return false; // }catch(ArrayIndexOutOfBoundsException e ){ // //不理会 // Log.e(TAG,"hacky viewpager error2"); // return false; // } // } // // }
import android.os.Bundle; import android.os.Parcelable; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentStatePagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.view.LayoutInflater; import android.view.View; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.FrameLayout; import com.cocolover2.lis.LISConstant; import com.cocolover2.lis.interf.OnPagerUpdateListener; import com.cocolover2.lis.R; import com.cocolover2.lis.view.HackyViewPager; import java.util.ArrayList;
package com.cocolover2.lis.activity; public abstract class LisBasePreviewPagerActivity<T> extends AppCompatActivity { private FrameLayout topLayout, bottomLayout; private ImagePagerAdapter mAdapter; private int startPos; private ArrayList<T> mImgDatas; private OnPagerUpdateListener pagerUpdateListener; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_previewpager);
// Path: library-lis/src/main/java/com/cocolover2/lis/LISConstant.java // public class LISConstant { // // public static final String ALL_IMG_BUCKET = "所有图片"; // public static final String ACTION_PRE = "com.cocolover2.lis.ACTION_preview"; // public static final String CATEGORY_SUFFIX = ".category.PREVIEW"; // // public static final String FLAG_PRE_SELECTED_IMGS = "pre_selected_imgs"; // //所要预览的图片的集合 // public static final String PRE_IMG_DATAS = "preview_imgs"; // //预览图片的起始位置 // public static final String PRE_IMG_START_POSITION = "preview_start_img_position"; // } // // Path: library-lis/src/main/java/com/cocolover2/lis/interf/OnPagerUpdateListener.java // public interface OnPagerUpdateListener { // void onSelect(int position); // // void onDeleted(int position); // } // // Path: library-lis/src/main/java/com/cocolover2/lis/view/HackyViewPager.java // public class HackyViewPager extends BounceBackViewPager { // // // private static final String TAG = "HackyViewPager"; // // public HackyViewPager(Context context) { // super(context); // } // // public HackyViewPager(Context context, AttributeSet attrs) { // super(context, attrs); // } // // @Override // public boolean onInterceptTouchEvent(MotionEvent ev) { // try { // return super.onInterceptTouchEvent(ev); // } catch (IllegalArgumentException e) { // //不理会 // Log.e(TAG,"hacky viewpager error1"); // return false; // }catch(ArrayIndexOutOfBoundsException e ){ // //不理会 // Log.e(TAG,"hacky viewpager error2"); // return false; // } // } // // } // Path: library-lis/src/main/java/com/cocolover2/lis/activity/LisBasePreviewPagerActivity.java import android.os.Bundle; import android.os.Parcelable; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentStatePagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.view.LayoutInflater; import android.view.View; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.FrameLayout; import com.cocolover2.lis.LISConstant; import com.cocolover2.lis.interf.OnPagerUpdateListener; import com.cocolover2.lis.R; import com.cocolover2.lis.view.HackyViewPager; import java.util.ArrayList; package com.cocolover2.lis.activity; public abstract class LisBasePreviewPagerActivity<T> extends AppCompatActivity { private FrameLayout topLayout, bottomLayout; private ImagePagerAdapter mAdapter; private int startPos; private ArrayList<T> mImgDatas; private OnPagerUpdateListener pagerUpdateListener; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_previewpager);
mImgDatas = (ArrayList<T>) getIntent().getParcelableArrayListExtra(LISConstant.PRE_IMG_DATAS);
cocolove2/LISDemo
library-lis/src/main/java/com/cocolover2/lis/activity/LisBasePreviewPagerActivity.java
// Path: library-lis/src/main/java/com/cocolover2/lis/LISConstant.java // public class LISConstant { // // public static final String ALL_IMG_BUCKET = "所有图片"; // public static final String ACTION_PRE = "com.cocolover2.lis.ACTION_preview"; // public static final String CATEGORY_SUFFIX = ".category.PREVIEW"; // // public static final String FLAG_PRE_SELECTED_IMGS = "pre_selected_imgs"; // //所要预览的图片的集合 // public static final String PRE_IMG_DATAS = "preview_imgs"; // //预览图片的起始位置 // public static final String PRE_IMG_START_POSITION = "preview_start_img_position"; // } // // Path: library-lis/src/main/java/com/cocolover2/lis/interf/OnPagerUpdateListener.java // public interface OnPagerUpdateListener { // void onSelect(int position); // // void onDeleted(int position); // } // // Path: library-lis/src/main/java/com/cocolover2/lis/view/HackyViewPager.java // public class HackyViewPager extends BounceBackViewPager { // // // private static final String TAG = "HackyViewPager"; // // public HackyViewPager(Context context) { // super(context); // } // // public HackyViewPager(Context context, AttributeSet attrs) { // super(context, attrs); // } // // @Override // public boolean onInterceptTouchEvent(MotionEvent ev) { // try { // return super.onInterceptTouchEvent(ev); // } catch (IllegalArgumentException e) { // //不理会 // Log.e(TAG,"hacky viewpager error1"); // return false; // }catch(ArrayIndexOutOfBoundsException e ){ // //不理会 // Log.e(TAG,"hacky viewpager error2"); // return false; // } // } // // }
import android.os.Bundle; import android.os.Parcelable; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentStatePagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.view.LayoutInflater; import android.view.View; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.FrameLayout; import com.cocolover2.lis.LISConstant; import com.cocolover2.lis.interf.OnPagerUpdateListener; import com.cocolover2.lis.R; import com.cocolover2.lis.view.HackyViewPager; import java.util.ArrayList;
getSupportActionBar().hide(); } initView(); onMyCreate(savedInstanceState); } public T getItem(int position) { return mImgDatas.get(position); } protected void setOnPagerUpdateListener(OnPagerUpdateListener listener) { pagerUpdateListener = listener; } private void initView() { topLayout = (FrameLayout) findViewById(R.id.previewpager_topbar); if (getTopBarLayoutId() > 0) { final View topBar = LayoutInflater.from(this).inflate(getTopBarLayoutId(), topLayout, false); topLayout.addView(topBar, topBar.getLayoutParams()); } bottomLayout = (FrameLayout) findViewById(R.id.previewpager_bottom_layout); if (getBottomLayoutId() > 0) { final View bottomBar = LayoutInflater.from(this).inflate(getBottomLayoutId(), bottomLayout, false); bottomLayout.addView(bottomBar, bottomBar.getLayoutParams()); } initViewPager(); } private void initViewPager() {
// Path: library-lis/src/main/java/com/cocolover2/lis/LISConstant.java // public class LISConstant { // // public static final String ALL_IMG_BUCKET = "所有图片"; // public static final String ACTION_PRE = "com.cocolover2.lis.ACTION_preview"; // public static final String CATEGORY_SUFFIX = ".category.PREVIEW"; // // public static final String FLAG_PRE_SELECTED_IMGS = "pre_selected_imgs"; // //所要预览的图片的集合 // public static final String PRE_IMG_DATAS = "preview_imgs"; // //预览图片的起始位置 // public static final String PRE_IMG_START_POSITION = "preview_start_img_position"; // } // // Path: library-lis/src/main/java/com/cocolover2/lis/interf/OnPagerUpdateListener.java // public interface OnPagerUpdateListener { // void onSelect(int position); // // void onDeleted(int position); // } // // Path: library-lis/src/main/java/com/cocolover2/lis/view/HackyViewPager.java // public class HackyViewPager extends BounceBackViewPager { // // // private static final String TAG = "HackyViewPager"; // // public HackyViewPager(Context context) { // super(context); // } // // public HackyViewPager(Context context, AttributeSet attrs) { // super(context, attrs); // } // // @Override // public boolean onInterceptTouchEvent(MotionEvent ev) { // try { // return super.onInterceptTouchEvent(ev); // } catch (IllegalArgumentException e) { // //不理会 // Log.e(TAG,"hacky viewpager error1"); // return false; // }catch(ArrayIndexOutOfBoundsException e ){ // //不理会 // Log.e(TAG,"hacky viewpager error2"); // return false; // } // } // // } // Path: library-lis/src/main/java/com/cocolover2/lis/activity/LisBasePreviewPagerActivity.java import android.os.Bundle; import android.os.Parcelable; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentStatePagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.view.LayoutInflater; import android.view.View; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.FrameLayout; import com.cocolover2.lis.LISConstant; import com.cocolover2.lis.interf.OnPagerUpdateListener; import com.cocolover2.lis.R; import com.cocolover2.lis.view.HackyViewPager; import java.util.ArrayList; getSupportActionBar().hide(); } initView(); onMyCreate(savedInstanceState); } public T getItem(int position) { return mImgDatas.get(position); } protected void setOnPagerUpdateListener(OnPagerUpdateListener listener) { pagerUpdateListener = listener; } private void initView() { topLayout = (FrameLayout) findViewById(R.id.previewpager_topbar); if (getTopBarLayoutId() > 0) { final View topBar = LayoutInflater.from(this).inflate(getTopBarLayoutId(), topLayout, false); topLayout.addView(topBar, topBar.getLayoutParams()); } bottomLayout = (FrameLayout) findViewById(R.id.previewpager_bottom_layout); if (getBottomLayoutId() > 0) { final View bottomBar = LayoutInflater.from(this).inflate(getBottomLayoutId(), bottomLayout, false); bottomLayout.addView(bottomBar, bottomBar.getLayoutParams()); } initViewPager(); } private void initViewPager() {
final HackyViewPager mViewPager = (HackyViewPager) findViewById(R.id.previewpager_viewpager_pager);
cocolove2/LISDemo
app/src/main/java/com/lisdemo/MyPreActivity.java
// Path: library-lis/src/main/java/com/cocolover2/lis/interf/OnPagerUpdateListener.java // public interface OnPagerUpdateListener { // void onSelect(int position); // // void onDeleted(int position); // } // // Path: library-lis/src/main/java/com/cocolover2/lis/activity/LisSimplePreviewPagerActivity.java // public abstract class LisSimplePreviewPagerActivity<T> extends LisBasePreviewPagerActivity<T> // implements OnImageClickListener { // final long PER_MB = 1024 * 1024; // final long PER_KB = 1024; // // //针对本地图片 // protected void removeSelectItem(ImageItem item) { // AlbumHelper.removeItem(item); // item.isSelected = false; // } // // protected boolean addToSelectList(ImageItem item) { // if (AlbumHelper.getHasSelectCount() >= AlbumHelper.getMaxSize()) { // item.isSelected = false; // Toast.makeText(this, "最多选择" + AlbumHelper.getMaxSize() + "张图片", Toast.LENGTH_SHORT).show(); // return false; // } // item.isSelected = true; // return AlbumHelper.addtoSelectImgs(item); // } // // protected String getSelectImgsSize() { // int size = 0; // for (ImageItem i : AlbumHelper.getHasSelectImgs()) { // size += i.imageSize; // } // if (size < PER_KB) {//小于1KB // return size + "B"; // } // if (size < PER_MB) { // return size / PER_KB + "KB"; // } // return size / PER_MB + "MB"; // } // // //针对本地图片(其他的展示界面重写该方法) // @Override // public Fragment showContentFragment(T content) { // if (content instanceof ImageItem) { // ShowImageView fragment = ShowImageView.newInstance(((ImageItem) content).imagePath); // fragment.setOnImgClickListener(this); // return fragment; // } // return null; // } // // // // @Override // public void onImgClick() { // if (isShowTopBottom) { // hideTopAndBottomLayout(); // } else { // showTopAndBottomLayout(); // } // } // } // // Path: library-lis/src/main/java/com/cocolover2/lis/entity/ImageItem.java // public class ImageItem implements Parcelable { // public int imageId; // public String imagePath;//原图的路径 // public long imageSize; // public long createTime; // public boolean isSelected; // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(imageId); // dest.writeString(imagePath); // dest.writeLong(imageSize); // dest.writeLong(createTime); // dest.writeByte((byte) (isSelected ? 1 : 0)); // } // // public static final Parcelable.Creator<ImageItem> CREATOR = new Parcelable.Creator<ImageItem>() { // @Override // public ImageItem createFromParcel(Parcel source) { // //读取要和写入的顺序一致 // ImageItem item = new ImageItem(); // item.imageId = source.readInt(); // item.imagePath = source.readString(); // item.imageSize = source.readLong(); // item.createTime = source.readLong(); // item.isSelected = (source.readByte() != 0); // return item; // } // // @Override // public ImageItem[] newArray(int size) { // return new ImageItem[size]; // } // }; // }
import android.os.Bundle; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.cocolover2.lis.interf.OnPagerUpdateListener; import com.cocolover2.lis.activity.LisSimplePreviewPagerActivity; import com.cocolover2.lis.entity.ImageItem;
select.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (mItem.isSelected) { removeSelectItem(mItem); sizeTv.setVisibility(View.INVISIBLE); select.setImageResource(R.drawable.ic_select_no); } else { if (addToSelectList(mItem)) { select.setImageResource(R.drawable.ic_select_yes); sizeTv.setVisibility(View.VISIBLE); sizeTv.setText(getSelectImgsSize()); } } } }); setOnPagerUpdateListener(pagerSelectListener); } private void updateBottom() { if (mItem.isSelected) { sizeTv.setVisibility(View.VISIBLE); sizeTv.setText(getSelectImgsSize()); select.setImageResource(R.drawable.ic_select_yes); } else { sizeTv.setVisibility(View.INVISIBLE); select.setImageResource(R.drawable.ic_select_no); } }
// Path: library-lis/src/main/java/com/cocolover2/lis/interf/OnPagerUpdateListener.java // public interface OnPagerUpdateListener { // void onSelect(int position); // // void onDeleted(int position); // } // // Path: library-lis/src/main/java/com/cocolover2/lis/activity/LisSimplePreviewPagerActivity.java // public abstract class LisSimplePreviewPagerActivity<T> extends LisBasePreviewPagerActivity<T> // implements OnImageClickListener { // final long PER_MB = 1024 * 1024; // final long PER_KB = 1024; // // //针对本地图片 // protected void removeSelectItem(ImageItem item) { // AlbumHelper.removeItem(item); // item.isSelected = false; // } // // protected boolean addToSelectList(ImageItem item) { // if (AlbumHelper.getHasSelectCount() >= AlbumHelper.getMaxSize()) { // item.isSelected = false; // Toast.makeText(this, "最多选择" + AlbumHelper.getMaxSize() + "张图片", Toast.LENGTH_SHORT).show(); // return false; // } // item.isSelected = true; // return AlbumHelper.addtoSelectImgs(item); // } // // protected String getSelectImgsSize() { // int size = 0; // for (ImageItem i : AlbumHelper.getHasSelectImgs()) { // size += i.imageSize; // } // if (size < PER_KB) {//小于1KB // return size + "B"; // } // if (size < PER_MB) { // return size / PER_KB + "KB"; // } // return size / PER_MB + "MB"; // } // // //针对本地图片(其他的展示界面重写该方法) // @Override // public Fragment showContentFragment(T content) { // if (content instanceof ImageItem) { // ShowImageView fragment = ShowImageView.newInstance(((ImageItem) content).imagePath); // fragment.setOnImgClickListener(this); // return fragment; // } // return null; // } // // // // @Override // public void onImgClick() { // if (isShowTopBottom) { // hideTopAndBottomLayout(); // } else { // showTopAndBottomLayout(); // } // } // } // // Path: library-lis/src/main/java/com/cocolover2/lis/entity/ImageItem.java // public class ImageItem implements Parcelable { // public int imageId; // public String imagePath;//原图的路径 // public long imageSize; // public long createTime; // public boolean isSelected; // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(imageId); // dest.writeString(imagePath); // dest.writeLong(imageSize); // dest.writeLong(createTime); // dest.writeByte((byte) (isSelected ? 1 : 0)); // } // // public static final Parcelable.Creator<ImageItem> CREATOR = new Parcelable.Creator<ImageItem>() { // @Override // public ImageItem createFromParcel(Parcel source) { // //读取要和写入的顺序一致 // ImageItem item = new ImageItem(); // item.imageId = source.readInt(); // item.imagePath = source.readString(); // item.imageSize = source.readLong(); // item.createTime = source.readLong(); // item.isSelected = (source.readByte() != 0); // return item; // } // // @Override // public ImageItem[] newArray(int size) { // return new ImageItem[size]; // } // }; // } // Path: app/src/main/java/com/lisdemo/MyPreActivity.java import android.os.Bundle; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.cocolover2.lis.interf.OnPagerUpdateListener; import com.cocolover2.lis.activity.LisSimplePreviewPagerActivity; import com.cocolover2.lis.entity.ImageItem; select.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (mItem.isSelected) { removeSelectItem(mItem); sizeTv.setVisibility(View.INVISIBLE); select.setImageResource(R.drawable.ic_select_no); } else { if (addToSelectList(mItem)) { select.setImageResource(R.drawable.ic_select_yes); sizeTv.setVisibility(View.VISIBLE); sizeTv.setText(getSelectImgsSize()); } } } }); setOnPagerUpdateListener(pagerSelectListener); } private void updateBottom() { if (mItem.isSelected) { sizeTv.setVisibility(View.VISIBLE); sizeTv.setText(getSelectImgsSize()); select.setImageResource(R.drawable.ic_select_yes); } else { sizeTv.setVisibility(View.INVISIBLE); select.setImageResource(R.drawable.ic_select_no); } }
private OnPagerUpdateListener pagerSelectListener = new OnPagerUpdateListener() {
cocolove2/LISDemo
library-lis/src/main/java/com/cocolover2/lis/AlbumHelper.java
// Path: library-lis/src/main/java/com/cocolover2/lis/entity/ImageBucket.java // public class ImageBucket{ // public int count = 0; // public String bucketName;//文件夹名 // public ArrayList<ImageItem> imageList;//文件夹下所有文件的绝对路径 // public boolean isSelected = false;//文件夹是否被选中 // } // // Path: library-lis/src/main/java/com/cocolover2/lis/entity/ImageItem.java // public class ImageItem implements Parcelable { // public int imageId; // public String imagePath;//原图的路径 // public long imageSize; // public long createTime; // public boolean isSelected; // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(imageId); // dest.writeString(imagePath); // dest.writeLong(imageSize); // dest.writeLong(createTime); // dest.writeByte((byte) (isSelected ? 1 : 0)); // } // // public static final Parcelable.Creator<ImageItem> CREATOR = new Parcelable.Creator<ImageItem>() { // @Override // public ImageItem createFromParcel(Parcel source) { // //读取要和写入的顺序一致 // ImageItem item = new ImageItem(); // item.imageId = source.readInt(); // item.imagePath = source.readString(); // item.imageSize = source.readLong(); // item.createTime = source.readLong(); // item.isSelected = (source.readByte() != 0); // return item; // } // // @Override // public ImageItem[] newArray(int size) { // return new ImageItem[size]; // } // }; // }
import android.content.Context; import android.database.Cursor; import android.provider.MediaStore.Images.Media; import com.cocolover2.lis.entity.ImageBucket; import com.cocolover2.lis.entity.ImageItem; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.Map;
package com.cocolover2.lis; public final class AlbumHelper { //存储文件夹名,和文件夹内容 private HashMap<Integer, ImageBucket> bucketMap = new HashMap<>(); //所有的图片集合
// Path: library-lis/src/main/java/com/cocolover2/lis/entity/ImageBucket.java // public class ImageBucket{ // public int count = 0; // public String bucketName;//文件夹名 // public ArrayList<ImageItem> imageList;//文件夹下所有文件的绝对路径 // public boolean isSelected = false;//文件夹是否被选中 // } // // Path: library-lis/src/main/java/com/cocolover2/lis/entity/ImageItem.java // public class ImageItem implements Parcelable { // public int imageId; // public String imagePath;//原图的路径 // public long imageSize; // public long createTime; // public boolean isSelected; // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(imageId); // dest.writeString(imagePath); // dest.writeLong(imageSize); // dest.writeLong(createTime); // dest.writeByte((byte) (isSelected ? 1 : 0)); // } // // public static final Parcelable.Creator<ImageItem> CREATOR = new Parcelable.Creator<ImageItem>() { // @Override // public ImageItem createFromParcel(Parcel source) { // //读取要和写入的顺序一致 // ImageItem item = new ImageItem(); // item.imageId = source.readInt(); // item.imagePath = source.readString(); // item.imageSize = source.readLong(); // item.createTime = source.readLong(); // item.isSelected = (source.readByte() != 0); // return item; // } // // @Override // public ImageItem[] newArray(int size) { // return new ImageItem[size]; // } // }; // } // Path: library-lis/src/main/java/com/cocolover2/lis/AlbumHelper.java import android.content.Context; import android.database.Cursor; import android.provider.MediaStore.Images.Media; import com.cocolover2.lis.entity.ImageBucket; import com.cocolover2.lis.entity.ImageItem; import java.io.File; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; package com.cocolover2.lis; public final class AlbumHelper { //存储文件夹名,和文件夹内容 private HashMap<Integer, ImageBucket> bucketMap = new HashMap<>(); //所有的图片集合
private ArrayList<ImageItem> imageList = new ArrayList<>();
cocolove2/LISDemo
library-lis/src/main/java/com/cocolover2/lis/LocalImageLoader.java
// Path: library-lis/src/main/java/com/cocolover2/lis/utils/ImageCache.java // public class ImageCache { // private static LruCache<String, Bitmap> mCache; // // private ImageCache() { // } // // public static LruCache<String, Bitmap> getInstance() { // if (mCache == null) // synchronized (ImageCache.class) { // if (mCache == null) // mCache = new LruCache<String, Bitmap>((int) Runtime.getRuntime().maxMemory() / 8) { // @Override // protected int sizeOf(String key, Bitmap value) { // if (Build.VERSION.SDK_INT > 12) // return value.getByteCount(); // else // return value.getRowBytes() * value.getHeight(); // } // }; // } // return mCache; // } // } // // Path: library-lis/src/main/java/com/cocolover2/lis/utils/ImageUtils.java // public class ImageUtils { // private ImageUtils() { // throw new UnsupportedOperationException("cannot be instantiated"); // } // // /** // * 压缩图片的像素 // * // * @param path // * @param requestWidth // * @param requestHeight // * @return // */ // public static Bitmap compressImgBySize(String path, int requestWidth, int requestHeight) { // if (null == path || TextUtils.isEmpty(path) || !new File(path).exists()) // return null; // //第一次解析图片的时候将inJustDecodeBounds设置为true,来获取图片的大小 // BitmapFactory.Options options = new BitmapFactory.Options(); // options.inJustDecodeBounds = true; // BitmapFactory.decodeFile(path, options); // options.inSampleSize = calculateInSampleSize(options, requestWidth, requestHeight); // options.inJustDecodeBounds = false; // return BitmapFactory.decodeFile(path, options); // } // // private static int calculateInSampleSize(BitmapFactory.Options options, int requestWidth, int requestHeight) { // int width = options.outWidth; // int height = options.outHeight; // int inSampleSize = 1; // if (width > requestWidth || height > requestHeight) { // final int heightRatio = Math.round((float) height / (float) requestHeight); // final int widthRatio = Math.round((float) width / (float) requestWidth); // inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio; // } // return inSampleSize; // } // }
import android.graphics.Bitmap; import android.os.Handler; import android.os.HandlerThread; import android.os.Message; import android.widget.AbsListView; import android.widget.ImageView; import com.cocolover2.lis.utils.ImageCache; import com.cocolover2.lis.utils.ImageUtils; import java.util.LinkedList; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Semaphore;
* @param imageView */ public void loadImage(final String path, final ImageView imageView, int defaultImgId) { if (isScrolling) { if (defaultImgId != 0) imageView.setImageResource(defaultImgId); } if (isFling) { return; } // set tag imageView.setTag(path); // UI线程 if (mHandler == null) { mHandler = new WeakHandler(); } Bitmap bm = getBitmapFromLruCache(path); if (bm != null) { ImgBeanHolder holder = new ImgBeanHolder(); holder.bitmap = bm; holder.imageView = imageView; holder.path = path; Message message = Message.obtain(); message.obj = holder; mHandler.sendMessage(message); } else { addTask(new Runnable() { @Override public void run() {
// Path: library-lis/src/main/java/com/cocolover2/lis/utils/ImageCache.java // public class ImageCache { // private static LruCache<String, Bitmap> mCache; // // private ImageCache() { // } // // public static LruCache<String, Bitmap> getInstance() { // if (mCache == null) // synchronized (ImageCache.class) { // if (mCache == null) // mCache = new LruCache<String, Bitmap>((int) Runtime.getRuntime().maxMemory() / 8) { // @Override // protected int sizeOf(String key, Bitmap value) { // if (Build.VERSION.SDK_INT > 12) // return value.getByteCount(); // else // return value.getRowBytes() * value.getHeight(); // } // }; // } // return mCache; // } // } // // Path: library-lis/src/main/java/com/cocolover2/lis/utils/ImageUtils.java // public class ImageUtils { // private ImageUtils() { // throw new UnsupportedOperationException("cannot be instantiated"); // } // // /** // * 压缩图片的像素 // * // * @param path // * @param requestWidth // * @param requestHeight // * @return // */ // public static Bitmap compressImgBySize(String path, int requestWidth, int requestHeight) { // if (null == path || TextUtils.isEmpty(path) || !new File(path).exists()) // return null; // //第一次解析图片的时候将inJustDecodeBounds设置为true,来获取图片的大小 // BitmapFactory.Options options = new BitmapFactory.Options(); // options.inJustDecodeBounds = true; // BitmapFactory.decodeFile(path, options); // options.inSampleSize = calculateInSampleSize(options, requestWidth, requestHeight); // options.inJustDecodeBounds = false; // return BitmapFactory.decodeFile(path, options); // } // // private static int calculateInSampleSize(BitmapFactory.Options options, int requestWidth, int requestHeight) { // int width = options.outWidth; // int height = options.outHeight; // int inSampleSize = 1; // if (width > requestWidth || height > requestHeight) { // final int heightRatio = Math.round((float) height / (float) requestHeight); // final int widthRatio = Math.round((float) width / (float) requestWidth); // inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio; // } // return inSampleSize; // } // } // Path: library-lis/src/main/java/com/cocolover2/lis/LocalImageLoader.java import android.graphics.Bitmap; import android.os.Handler; import android.os.HandlerThread; import android.os.Message; import android.widget.AbsListView; import android.widget.ImageView; import com.cocolover2.lis.utils.ImageCache; import com.cocolover2.lis.utils.ImageUtils; import java.util.LinkedList; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Semaphore; * @param imageView */ public void loadImage(final String path, final ImageView imageView, int defaultImgId) { if (isScrolling) { if (defaultImgId != 0) imageView.setImageResource(defaultImgId); } if (isFling) { return; } // set tag imageView.setTag(path); // UI线程 if (mHandler == null) { mHandler = new WeakHandler(); } Bitmap bm = getBitmapFromLruCache(path); if (bm != null) { ImgBeanHolder holder = new ImgBeanHolder(); holder.bitmap = bm; holder.imageView = imageView; holder.path = path; Message message = Message.obtain(); message.obj = holder; mHandler.sendMessage(message); } else { addTask(new Runnable() { @Override public void run() {
Bitmap bm = ImageUtils.compressImgBySize(path, imgWidth,
cocolove2/LISDemo
library-lis/src/main/java/com/cocolover2/lis/LocalImageLoader.java
// Path: library-lis/src/main/java/com/cocolover2/lis/utils/ImageCache.java // public class ImageCache { // private static LruCache<String, Bitmap> mCache; // // private ImageCache() { // } // // public static LruCache<String, Bitmap> getInstance() { // if (mCache == null) // synchronized (ImageCache.class) { // if (mCache == null) // mCache = new LruCache<String, Bitmap>((int) Runtime.getRuntime().maxMemory() / 8) { // @Override // protected int sizeOf(String key, Bitmap value) { // if (Build.VERSION.SDK_INT > 12) // return value.getByteCount(); // else // return value.getRowBytes() * value.getHeight(); // } // }; // } // return mCache; // } // } // // Path: library-lis/src/main/java/com/cocolover2/lis/utils/ImageUtils.java // public class ImageUtils { // private ImageUtils() { // throw new UnsupportedOperationException("cannot be instantiated"); // } // // /** // * 压缩图片的像素 // * // * @param path // * @param requestWidth // * @param requestHeight // * @return // */ // public static Bitmap compressImgBySize(String path, int requestWidth, int requestHeight) { // if (null == path || TextUtils.isEmpty(path) || !new File(path).exists()) // return null; // //第一次解析图片的时候将inJustDecodeBounds设置为true,来获取图片的大小 // BitmapFactory.Options options = new BitmapFactory.Options(); // options.inJustDecodeBounds = true; // BitmapFactory.decodeFile(path, options); // options.inSampleSize = calculateInSampleSize(options, requestWidth, requestHeight); // options.inJustDecodeBounds = false; // return BitmapFactory.decodeFile(path, options); // } // // private static int calculateInSampleSize(BitmapFactory.Options options, int requestWidth, int requestHeight) { // int width = options.outWidth; // int height = options.outHeight; // int inSampleSize = 1; // if (width > requestWidth || height > requestHeight) { // final int heightRatio = Math.round((float) height / (float) requestHeight); // final int widthRatio = Math.round((float) width / (float) requestWidth); // inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio; // } // return inSampleSize; // } // }
import android.graphics.Bitmap; import android.os.Handler; import android.os.HandlerThread; import android.os.Message; import android.widget.AbsListView; import android.widget.ImageView; import com.cocolover2.lis.utils.ImageCache; import com.cocolover2.lis.utils.ImageUtils; import java.util.LinkedList; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Semaphore;
if (mType == Type.FIFO) { return mTasks.removeFirst(); } else if (mType == Type.LIFO) { return mTasks.removeLast(); } return null; } /** * 单例获得该实例对象 * * @return */ public static LocalImageLoader getInstance(int threadCount, Type type) { if (mInstance == null) { synchronized (LocalImageLoader.class) { if (mInstance == null) { mInstance = new LocalImageLoader(threadCount, type); } } } return mInstance; } /** * 从LruCache中获取一张图片,如果不存在就返回null。 */ private Bitmap getBitmapFromLruCache(String key) {
// Path: library-lis/src/main/java/com/cocolover2/lis/utils/ImageCache.java // public class ImageCache { // private static LruCache<String, Bitmap> mCache; // // private ImageCache() { // } // // public static LruCache<String, Bitmap> getInstance() { // if (mCache == null) // synchronized (ImageCache.class) { // if (mCache == null) // mCache = new LruCache<String, Bitmap>((int) Runtime.getRuntime().maxMemory() / 8) { // @Override // protected int sizeOf(String key, Bitmap value) { // if (Build.VERSION.SDK_INT > 12) // return value.getByteCount(); // else // return value.getRowBytes() * value.getHeight(); // } // }; // } // return mCache; // } // } // // Path: library-lis/src/main/java/com/cocolover2/lis/utils/ImageUtils.java // public class ImageUtils { // private ImageUtils() { // throw new UnsupportedOperationException("cannot be instantiated"); // } // // /** // * 压缩图片的像素 // * // * @param path // * @param requestWidth // * @param requestHeight // * @return // */ // public static Bitmap compressImgBySize(String path, int requestWidth, int requestHeight) { // if (null == path || TextUtils.isEmpty(path) || !new File(path).exists()) // return null; // //第一次解析图片的时候将inJustDecodeBounds设置为true,来获取图片的大小 // BitmapFactory.Options options = new BitmapFactory.Options(); // options.inJustDecodeBounds = true; // BitmapFactory.decodeFile(path, options); // options.inSampleSize = calculateInSampleSize(options, requestWidth, requestHeight); // options.inJustDecodeBounds = false; // return BitmapFactory.decodeFile(path, options); // } // // private static int calculateInSampleSize(BitmapFactory.Options options, int requestWidth, int requestHeight) { // int width = options.outWidth; // int height = options.outHeight; // int inSampleSize = 1; // if (width > requestWidth || height > requestHeight) { // final int heightRatio = Math.round((float) height / (float) requestHeight); // final int widthRatio = Math.round((float) width / (float) requestWidth); // inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio; // } // return inSampleSize; // } // } // Path: library-lis/src/main/java/com/cocolover2/lis/LocalImageLoader.java import android.graphics.Bitmap; import android.os.Handler; import android.os.HandlerThread; import android.os.Message; import android.widget.AbsListView; import android.widget.ImageView; import com.cocolover2.lis.utils.ImageCache; import com.cocolover2.lis.utils.ImageUtils; import java.util.LinkedList; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Semaphore; if (mType == Type.FIFO) { return mTasks.removeFirst(); } else if (mType == Type.LIFO) { return mTasks.removeLast(); } return null; } /** * 单例获得该实例对象 * * @return */ public static LocalImageLoader getInstance(int threadCount, Type type) { if (mInstance == null) { synchronized (LocalImageLoader.class) { if (mInstance == null) { mInstance = new LocalImageLoader(threadCount, type); } } } return mInstance; } /** * 从LruCache中获取一张图片,如果不存在就返回null。 */ private Bitmap getBitmapFromLruCache(String key) {
return ImageCache.getInstance().get(key_prefix + key);
ripreal/V8LogScannerWeb
src/main/java/org/v8LogScanner/dbLayer/scanProfilesPersistence/ScanProfileHibService.java
// Path: src/main/java/org/v8LogScanner/dbLayer/genericRepository/DataRepository.java // public interface DataRepository<T> { // // public Serializable add(T object); // // public void remove(T object); // // public void update(T object); // // public void resetCache(); // // public List<T> query(QuerySpecification<T> specification); // // } // // Path: src/main/java/org/v8LogScanner/dbLayer/genericRepository/QuerySpecification.java // public interface QuerySpecification<T> { // // boolean specified(T object); // // public CriteriaQuery<T> toCriteria(CriteriaBuilder builder); // // } // // Path: src/main/java/org/v8LogScanner/dbLayer/genericRepository/ScanProfileService.java // public interface ScanProfileService { // // public int add(ScanProfile profile); // // public void remove(ScanProfile profile); // // public void update(ScanProfile profile); // // public void resetCache(); // // public ScanProfile find(ScanProfile profile); // // public ScanProfile find(int id); // // public ScanProfile findIfPresent(); // // public List<ScanProfile> getAll(); // // } // // Path: src/main/java/org/v8LogScanner/dbLayer/scanProfilesPersistence/Specifications/ScanProfileHibSpecByID.java // public class ScanProfileHibSpecByID implements QuerySpecification<ScanProfileHib> { // // private int id; // // public ScanProfileHibSpecByID(int id) { // this.id = id; // } // // @Override // public boolean specified(ScanProfileHib profile) { // return id == profile.getId(); // } // // public CriteriaQuery<ScanProfileHib> toCriteria(CriteriaBuilder builder) { // // CriteriaQuery<ScanProfileHib> criteria = builder.createQuery(ScanProfileHib.class); // Root<ScanProfileHib> root = criteria.from(ScanProfileHib.class); // // criteria.where(builder.equal(root.get("id"), id)); // criteria.select(root); // // return criteria; // } // } // // Path: src/main/java/org/v8LogScanner/dbLayer/scanProfilesPersistence/Specifications/ScanProfileHibSpecByName.java // public class ScanProfileHibSpecByName implements QuerySpecification<ScanProfileHib> { // // private String name; // // public ScanProfileHibSpecByName(String name) { // this.name = name; // } // // @Override // public boolean specified(ScanProfileHib profile) { // return name == profile.getName(); // } // // public CriteriaQuery<ScanProfileHib> toCriteria(CriteriaBuilder builder) { // // CriteriaQuery<ScanProfileHib> criteria = builder.createQuery(ScanProfileHib.class); // Root<ScanProfileHib> root = criteria.from(ScanProfileHib.class); // // criteria.where(builder.equal(root.get("name"), name)); // criteria.select(root); // // return criteria; // } // } // // Path: src/main/java/org/v8LogScanner/dbLayer/scanProfilesPersistence/Specifications/ScanProfileHibSpecIfPresent.java // public class ScanProfileHibSpecIfPresent implements QuerySpecification<ScanProfileHib> { // // @Override // public boolean specified(ScanProfileHib profile) { // return profile.getId() >= 0; // } // // public CriteriaQuery<ScanProfileHib> toCriteria(CriteriaBuilder builder) { // // CriteriaQuery<ScanProfileHib> criteria = builder.createQuery(ScanProfileHib.class); // // Root<ScanProfileHib> root = criteria.from(ScanProfileHib.class); // criteria.select(root).from(ScanProfileHib.class); // criteria.orderBy(builder.desc(root.get("id"))); // // return criteria; // } // }
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.v8LogScanner.dbLayer.genericRepository.DataRepository; import org.v8LogScanner.dbLayer.genericRepository.QuerySpecification; import org.v8LogScanner.dbLayer.genericRepository.ScanProfileService; import org.v8LogScanner.dbLayer.scanProfilesPersistence.Specifications.ScanProfileHibSpecByID; import org.v8LogScanner.dbLayer.scanProfilesPersistence.Specifications.ScanProfileHibSpecByName; import org.v8LogScanner.dbLayer.scanProfilesPersistence.Specifications.ScanProfileHibSpecIfPresent; import org.v8LogScanner.rgx.ScanProfile; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List;
package org.v8LogScanner.dbLayer.scanProfilesPersistence; @Service @Transactional
// Path: src/main/java/org/v8LogScanner/dbLayer/genericRepository/DataRepository.java // public interface DataRepository<T> { // // public Serializable add(T object); // // public void remove(T object); // // public void update(T object); // // public void resetCache(); // // public List<T> query(QuerySpecification<T> specification); // // } // // Path: src/main/java/org/v8LogScanner/dbLayer/genericRepository/QuerySpecification.java // public interface QuerySpecification<T> { // // boolean specified(T object); // // public CriteriaQuery<T> toCriteria(CriteriaBuilder builder); // // } // // Path: src/main/java/org/v8LogScanner/dbLayer/genericRepository/ScanProfileService.java // public interface ScanProfileService { // // public int add(ScanProfile profile); // // public void remove(ScanProfile profile); // // public void update(ScanProfile profile); // // public void resetCache(); // // public ScanProfile find(ScanProfile profile); // // public ScanProfile find(int id); // // public ScanProfile findIfPresent(); // // public List<ScanProfile> getAll(); // // } // // Path: src/main/java/org/v8LogScanner/dbLayer/scanProfilesPersistence/Specifications/ScanProfileHibSpecByID.java // public class ScanProfileHibSpecByID implements QuerySpecification<ScanProfileHib> { // // private int id; // // public ScanProfileHibSpecByID(int id) { // this.id = id; // } // // @Override // public boolean specified(ScanProfileHib profile) { // return id == profile.getId(); // } // // public CriteriaQuery<ScanProfileHib> toCriteria(CriteriaBuilder builder) { // // CriteriaQuery<ScanProfileHib> criteria = builder.createQuery(ScanProfileHib.class); // Root<ScanProfileHib> root = criteria.from(ScanProfileHib.class); // // criteria.where(builder.equal(root.get("id"), id)); // criteria.select(root); // // return criteria; // } // } // // Path: src/main/java/org/v8LogScanner/dbLayer/scanProfilesPersistence/Specifications/ScanProfileHibSpecByName.java // public class ScanProfileHibSpecByName implements QuerySpecification<ScanProfileHib> { // // private String name; // // public ScanProfileHibSpecByName(String name) { // this.name = name; // } // // @Override // public boolean specified(ScanProfileHib profile) { // return name == profile.getName(); // } // // public CriteriaQuery<ScanProfileHib> toCriteria(CriteriaBuilder builder) { // // CriteriaQuery<ScanProfileHib> criteria = builder.createQuery(ScanProfileHib.class); // Root<ScanProfileHib> root = criteria.from(ScanProfileHib.class); // // criteria.where(builder.equal(root.get("name"), name)); // criteria.select(root); // // return criteria; // } // } // // Path: src/main/java/org/v8LogScanner/dbLayer/scanProfilesPersistence/Specifications/ScanProfileHibSpecIfPresent.java // public class ScanProfileHibSpecIfPresent implements QuerySpecification<ScanProfileHib> { // // @Override // public boolean specified(ScanProfileHib profile) { // return profile.getId() >= 0; // } // // public CriteriaQuery<ScanProfileHib> toCriteria(CriteriaBuilder builder) { // // CriteriaQuery<ScanProfileHib> criteria = builder.createQuery(ScanProfileHib.class); // // Root<ScanProfileHib> root = criteria.from(ScanProfileHib.class); // criteria.select(root).from(ScanProfileHib.class); // criteria.orderBy(builder.desc(root.get("id"))); // // return criteria; // } // } // Path: src/main/java/org/v8LogScanner/dbLayer/scanProfilesPersistence/ScanProfileHibService.java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.v8LogScanner.dbLayer.genericRepository.DataRepository; import org.v8LogScanner.dbLayer.genericRepository.QuerySpecification; import org.v8LogScanner.dbLayer.genericRepository.ScanProfileService; import org.v8LogScanner.dbLayer.scanProfilesPersistence.Specifications.ScanProfileHibSpecByID; import org.v8LogScanner.dbLayer.scanProfilesPersistence.Specifications.ScanProfileHibSpecByName; import org.v8LogScanner.dbLayer.scanProfilesPersistence.Specifications.ScanProfileHibSpecIfPresent; import org.v8LogScanner.rgx.ScanProfile; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; package org.v8LogScanner.dbLayer.scanProfilesPersistence; @Service @Transactional
public class ScanProfileHibService implements ScanProfileService {
ripreal/V8LogScannerWeb
src/main/java/org/v8LogScanner/dbLayer/scanProfilesPersistence/ScanProfileHibService.java
// Path: src/main/java/org/v8LogScanner/dbLayer/genericRepository/DataRepository.java // public interface DataRepository<T> { // // public Serializable add(T object); // // public void remove(T object); // // public void update(T object); // // public void resetCache(); // // public List<T> query(QuerySpecification<T> specification); // // } // // Path: src/main/java/org/v8LogScanner/dbLayer/genericRepository/QuerySpecification.java // public interface QuerySpecification<T> { // // boolean specified(T object); // // public CriteriaQuery<T> toCriteria(CriteriaBuilder builder); // // } // // Path: src/main/java/org/v8LogScanner/dbLayer/genericRepository/ScanProfileService.java // public interface ScanProfileService { // // public int add(ScanProfile profile); // // public void remove(ScanProfile profile); // // public void update(ScanProfile profile); // // public void resetCache(); // // public ScanProfile find(ScanProfile profile); // // public ScanProfile find(int id); // // public ScanProfile findIfPresent(); // // public List<ScanProfile> getAll(); // // } // // Path: src/main/java/org/v8LogScanner/dbLayer/scanProfilesPersistence/Specifications/ScanProfileHibSpecByID.java // public class ScanProfileHibSpecByID implements QuerySpecification<ScanProfileHib> { // // private int id; // // public ScanProfileHibSpecByID(int id) { // this.id = id; // } // // @Override // public boolean specified(ScanProfileHib profile) { // return id == profile.getId(); // } // // public CriteriaQuery<ScanProfileHib> toCriteria(CriteriaBuilder builder) { // // CriteriaQuery<ScanProfileHib> criteria = builder.createQuery(ScanProfileHib.class); // Root<ScanProfileHib> root = criteria.from(ScanProfileHib.class); // // criteria.where(builder.equal(root.get("id"), id)); // criteria.select(root); // // return criteria; // } // } // // Path: src/main/java/org/v8LogScanner/dbLayer/scanProfilesPersistence/Specifications/ScanProfileHibSpecByName.java // public class ScanProfileHibSpecByName implements QuerySpecification<ScanProfileHib> { // // private String name; // // public ScanProfileHibSpecByName(String name) { // this.name = name; // } // // @Override // public boolean specified(ScanProfileHib profile) { // return name == profile.getName(); // } // // public CriteriaQuery<ScanProfileHib> toCriteria(CriteriaBuilder builder) { // // CriteriaQuery<ScanProfileHib> criteria = builder.createQuery(ScanProfileHib.class); // Root<ScanProfileHib> root = criteria.from(ScanProfileHib.class); // // criteria.where(builder.equal(root.get("name"), name)); // criteria.select(root); // // return criteria; // } // } // // Path: src/main/java/org/v8LogScanner/dbLayer/scanProfilesPersistence/Specifications/ScanProfileHibSpecIfPresent.java // public class ScanProfileHibSpecIfPresent implements QuerySpecification<ScanProfileHib> { // // @Override // public boolean specified(ScanProfileHib profile) { // return profile.getId() >= 0; // } // // public CriteriaQuery<ScanProfileHib> toCriteria(CriteriaBuilder builder) { // // CriteriaQuery<ScanProfileHib> criteria = builder.createQuery(ScanProfileHib.class); // // Root<ScanProfileHib> root = criteria.from(ScanProfileHib.class); // criteria.select(root).from(ScanProfileHib.class); // criteria.orderBy(builder.desc(root.get("id"))); // // return criteria; // } // }
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.v8LogScanner.dbLayer.genericRepository.DataRepository; import org.v8LogScanner.dbLayer.genericRepository.QuerySpecification; import org.v8LogScanner.dbLayer.genericRepository.ScanProfileService; import org.v8LogScanner.dbLayer.scanProfilesPersistence.Specifications.ScanProfileHibSpecByID; import org.v8LogScanner.dbLayer.scanProfilesPersistence.Specifications.ScanProfileHibSpecByName; import org.v8LogScanner.dbLayer.scanProfilesPersistence.Specifications.ScanProfileHibSpecIfPresent; import org.v8LogScanner.rgx.ScanProfile; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List;
package org.v8LogScanner.dbLayer.scanProfilesPersistence; @Service @Transactional public class ScanProfileHibService implements ScanProfileService { @Autowired
// Path: src/main/java/org/v8LogScanner/dbLayer/genericRepository/DataRepository.java // public interface DataRepository<T> { // // public Serializable add(T object); // // public void remove(T object); // // public void update(T object); // // public void resetCache(); // // public List<T> query(QuerySpecification<T> specification); // // } // // Path: src/main/java/org/v8LogScanner/dbLayer/genericRepository/QuerySpecification.java // public interface QuerySpecification<T> { // // boolean specified(T object); // // public CriteriaQuery<T> toCriteria(CriteriaBuilder builder); // // } // // Path: src/main/java/org/v8LogScanner/dbLayer/genericRepository/ScanProfileService.java // public interface ScanProfileService { // // public int add(ScanProfile profile); // // public void remove(ScanProfile profile); // // public void update(ScanProfile profile); // // public void resetCache(); // // public ScanProfile find(ScanProfile profile); // // public ScanProfile find(int id); // // public ScanProfile findIfPresent(); // // public List<ScanProfile> getAll(); // // } // // Path: src/main/java/org/v8LogScanner/dbLayer/scanProfilesPersistence/Specifications/ScanProfileHibSpecByID.java // public class ScanProfileHibSpecByID implements QuerySpecification<ScanProfileHib> { // // private int id; // // public ScanProfileHibSpecByID(int id) { // this.id = id; // } // // @Override // public boolean specified(ScanProfileHib profile) { // return id == profile.getId(); // } // // public CriteriaQuery<ScanProfileHib> toCriteria(CriteriaBuilder builder) { // // CriteriaQuery<ScanProfileHib> criteria = builder.createQuery(ScanProfileHib.class); // Root<ScanProfileHib> root = criteria.from(ScanProfileHib.class); // // criteria.where(builder.equal(root.get("id"), id)); // criteria.select(root); // // return criteria; // } // } // // Path: src/main/java/org/v8LogScanner/dbLayer/scanProfilesPersistence/Specifications/ScanProfileHibSpecByName.java // public class ScanProfileHibSpecByName implements QuerySpecification<ScanProfileHib> { // // private String name; // // public ScanProfileHibSpecByName(String name) { // this.name = name; // } // // @Override // public boolean specified(ScanProfileHib profile) { // return name == profile.getName(); // } // // public CriteriaQuery<ScanProfileHib> toCriteria(CriteriaBuilder builder) { // // CriteriaQuery<ScanProfileHib> criteria = builder.createQuery(ScanProfileHib.class); // Root<ScanProfileHib> root = criteria.from(ScanProfileHib.class); // // criteria.where(builder.equal(root.get("name"), name)); // criteria.select(root); // // return criteria; // } // } // // Path: src/main/java/org/v8LogScanner/dbLayer/scanProfilesPersistence/Specifications/ScanProfileHibSpecIfPresent.java // public class ScanProfileHibSpecIfPresent implements QuerySpecification<ScanProfileHib> { // // @Override // public boolean specified(ScanProfileHib profile) { // return profile.getId() >= 0; // } // // public CriteriaQuery<ScanProfileHib> toCriteria(CriteriaBuilder builder) { // // CriteriaQuery<ScanProfileHib> criteria = builder.createQuery(ScanProfileHib.class); // // Root<ScanProfileHib> root = criteria.from(ScanProfileHib.class); // criteria.select(root).from(ScanProfileHib.class); // criteria.orderBy(builder.desc(root.get("id"))); // // return criteria; // } // } // Path: src/main/java/org/v8LogScanner/dbLayer/scanProfilesPersistence/ScanProfileHibService.java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.v8LogScanner.dbLayer.genericRepository.DataRepository; import org.v8LogScanner.dbLayer.genericRepository.QuerySpecification; import org.v8LogScanner.dbLayer.genericRepository.ScanProfileService; import org.v8LogScanner.dbLayer.scanProfilesPersistence.Specifications.ScanProfileHibSpecByID; import org.v8LogScanner.dbLayer.scanProfilesPersistence.Specifications.ScanProfileHibSpecByName; import org.v8LogScanner.dbLayer.scanProfilesPersistence.Specifications.ScanProfileHibSpecIfPresent; import org.v8LogScanner.rgx.ScanProfile; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; package org.v8LogScanner.dbLayer.scanProfilesPersistence; @Service @Transactional public class ScanProfileHibService implements ScanProfileService { @Autowired
private DataRepository<ScanProfileHib> repository;
ripreal/V8LogScannerWeb
src/main/java/org/v8LogScanner/dbLayer/scanProfilesPersistence/ScanProfileHibService.java
// Path: src/main/java/org/v8LogScanner/dbLayer/genericRepository/DataRepository.java // public interface DataRepository<T> { // // public Serializable add(T object); // // public void remove(T object); // // public void update(T object); // // public void resetCache(); // // public List<T> query(QuerySpecification<T> specification); // // } // // Path: src/main/java/org/v8LogScanner/dbLayer/genericRepository/QuerySpecification.java // public interface QuerySpecification<T> { // // boolean specified(T object); // // public CriteriaQuery<T> toCriteria(CriteriaBuilder builder); // // } // // Path: src/main/java/org/v8LogScanner/dbLayer/genericRepository/ScanProfileService.java // public interface ScanProfileService { // // public int add(ScanProfile profile); // // public void remove(ScanProfile profile); // // public void update(ScanProfile profile); // // public void resetCache(); // // public ScanProfile find(ScanProfile profile); // // public ScanProfile find(int id); // // public ScanProfile findIfPresent(); // // public List<ScanProfile> getAll(); // // } // // Path: src/main/java/org/v8LogScanner/dbLayer/scanProfilesPersistence/Specifications/ScanProfileHibSpecByID.java // public class ScanProfileHibSpecByID implements QuerySpecification<ScanProfileHib> { // // private int id; // // public ScanProfileHibSpecByID(int id) { // this.id = id; // } // // @Override // public boolean specified(ScanProfileHib profile) { // return id == profile.getId(); // } // // public CriteriaQuery<ScanProfileHib> toCriteria(CriteriaBuilder builder) { // // CriteriaQuery<ScanProfileHib> criteria = builder.createQuery(ScanProfileHib.class); // Root<ScanProfileHib> root = criteria.from(ScanProfileHib.class); // // criteria.where(builder.equal(root.get("id"), id)); // criteria.select(root); // // return criteria; // } // } // // Path: src/main/java/org/v8LogScanner/dbLayer/scanProfilesPersistence/Specifications/ScanProfileHibSpecByName.java // public class ScanProfileHibSpecByName implements QuerySpecification<ScanProfileHib> { // // private String name; // // public ScanProfileHibSpecByName(String name) { // this.name = name; // } // // @Override // public boolean specified(ScanProfileHib profile) { // return name == profile.getName(); // } // // public CriteriaQuery<ScanProfileHib> toCriteria(CriteriaBuilder builder) { // // CriteriaQuery<ScanProfileHib> criteria = builder.createQuery(ScanProfileHib.class); // Root<ScanProfileHib> root = criteria.from(ScanProfileHib.class); // // criteria.where(builder.equal(root.get("name"), name)); // criteria.select(root); // // return criteria; // } // } // // Path: src/main/java/org/v8LogScanner/dbLayer/scanProfilesPersistence/Specifications/ScanProfileHibSpecIfPresent.java // public class ScanProfileHibSpecIfPresent implements QuerySpecification<ScanProfileHib> { // // @Override // public boolean specified(ScanProfileHib profile) { // return profile.getId() >= 0; // } // // public CriteriaQuery<ScanProfileHib> toCriteria(CriteriaBuilder builder) { // // CriteriaQuery<ScanProfileHib> criteria = builder.createQuery(ScanProfileHib.class); // // Root<ScanProfileHib> root = criteria.from(ScanProfileHib.class); // criteria.select(root).from(ScanProfileHib.class); // criteria.orderBy(builder.desc(root.get("id"))); // // return criteria; // } // }
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.v8LogScanner.dbLayer.genericRepository.DataRepository; import org.v8LogScanner.dbLayer.genericRepository.QuerySpecification; import org.v8LogScanner.dbLayer.genericRepository.ScanProfileService; import org.v8LogScanner.dbLayer.scanProfilesPersistence.Specifications.ScanProfileHibSpecByID; import org.v8LogScanner.dbLayer.scanProfilesPersistence.Specifications.ScanProfileHibSpecByName; import org.v8LogScanner.dbLayer.scanProfilesPersistence.Specifications.ScanProfileHibSpecIfPresent; import org.v8LogScanner.rgx.ScanProfile; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List;
package org.v8LogScanner.dbLayer.scanProfilesPersistence; @Service @Transactional public class ScanProfileHibService implements ScanProfileService { @Autowired private DataRepository<ScanProfileHib> repository; public ScanProfileHibService(DataRepository<ScanProfileHib> repository) { this.repository = repository; } @Override public int add(ScanProfile profile) { return (int) repository.add((ScanProfileHib) profile); } @Override public void remove(ScanProfile profile) { repository.remove((ScanProfileHib) profile); } @Override public void update(ScanProfile profile) { repository.update((ScanProfileHib) profile); } @Override public ScanProfile find(ScanProfile profile) {
// Path: src/main/java/org/v8LogScanner/dbLayer/genericRepository/DataRepository.java // public interface DataRepository<T> { // // public Serializable add(T object); // // public void remove(T object); // // public void update(T object); // // public void resetCache(); // // public List<T> query(QuerySpecification<T> specification); // // } // // Path: src/main/java/org/v8LogScanner/dbLayer/genericRepository/QuerySpecification.java // public interface QuerySpecification<T> { // // boolean specified(T object); // // public CriteriaQuery<T> toCriteria(CriteriaBuilder builder); // // } // // Path: src/main/java/org/v8LogScanner/dbLayer/genericRepository/ScanProfileService.java // public interface ScanProfileService { // // public int add(ScanProfile profile); // // public void remove(ScanProfile profile); // // public void update(ScanProfile profile); // // public void resetCache(); // // public ScanProfile find(ScanProfile profile); // // public ScanProfile find(int id); // // public ScanProfile findIfPresent(); // // public List<ScanProfile> getAll(); // // } // // Path: src/main/java/org/v8LogScanner/dbLayer/scanProfilesPersistence/Specifications/ScanProfileHibSpecByID.java // public class ScanProfileHibSpecByID implements QuerySpecification<ScanProfileHib> { // // private int id; // // public ScanProfileHibSpecByID(int id) { // this.id = id; // } // // @Override // public boolean specified(ScanProfileHib profile) { // return id == profile.getId(); // } // // public CriteriaQuery<ScanProfileHib> toCriteria(CriteriaBuilder builder) { // // CriteriaQuery<ScanProfileHib> criteria = builder.createQuery(ScanProfileHib.class); // Root<ScanProfileHib> root = criteria.from(ScanProfileHib.class); // // criteria.where(builder.equal(root.get("id"), id)); // criteria.select(root); // // return criteria; // } // } // // Path: src/main/java/org/v8LogScanner/dbLayer/scanProfilesPersistence/Specifications/ScanProfileHibSpecByName.java // public class ScanProfileHibSpecByName implements QuerySpecification<ScanProfileHib> { // // private String name; // // public ScanProfileHibSpecByName(String name) { // this.name = name; // } // // @Override // public boolean specified(ScanProfileHib profile) { // return name == profile.getName(); // } // // public CriteriaQuery<ScanProfileHib> toCriteria(CriteriaBuilder builder) { // // CriteriaQuery<ScanProfileHib> criteria = builder.createQuery(ScanProfileHib.class); // Root<ScanProfileHib> root = criteria.from(ScanProfileHib.class); // // criteria.where(builder.equal(root.get("name"), name)); // criteria.select(root); // // return criteria; // } // } // // Path: src/main/java/org/v8LogScanner/dbLayer/scanProfilesPersistence/Specifications/ScanProfileHibSpecIfPresent.java // public class ScanProfileHibSpecIfPresent implements QuerySpecification<ScanProfileHib> { // // @Override // public boolean specified(ScanProfileHib profile) { // return profile.getId() >= 0; // } // // public CriteriaQuery<ScanProfileHib> toCriteria(CriteriaBuilder builder) { // // CriteriaQuery<ScanProfileHib> criteria = builder.createQuery(ScanProfileHib.class); // // Root<ScanProfileHib> root = criteria.from(ScanProfileHib.class); // criteria.select(root).from(ScanProfileHib.class); // criteria.orderBy(builder.desc(root.get("id"))); // // return criteria; // } // } // Path: src/main/java/org/v8LogScanner/dbLayer/scanProfilesPersistence/ScanProfileHibService.java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.v8LogScanner.dbLayer.genericRepository.DataRepository; import org.v8LogScanner.dbLayer.genericRepository.QuerySpecification; import org.v8LogScanner.dbLayer.genericRepository.ScanProfileService; import org.v8LogScanner.dbLayer.scanProfilesPersistence.Specifications.ScanProfileHibSpecByID; import org.v8LogScanner.dbLayer.scanProfilesPersistence.Specifications.ScanProfileHibSpecByName; import org.v8LogScanner.dbLayer.scanProfilesPersistence.Specifications.ScanProfileHibSpecIfPresent; import org.v8LogScanner.rgx.ScanProfile; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; package org.v8LogScanner.dbLayer.scanProfilesPersistence; @Service @Transactional public class ScanProfileHibService implements ScanProfileService { @Autowired private DataRepository<ScanProfileHib> repository; public ScanProfileHibService(DataRepository<ScanProfileHib> repository) { this.repository = repository; } @Override public int add(ScanProfile profile) { return (int) repository.add((ScanProfileHib) profile); } @Override public void remove(ScanProfile profile) { repository.remove((ScanProfileHib) profile); } @Override public void update(ScanProfile profile) { repository.update((ScanProfileHib) profile); } @Override public ScanProfile find(ScanProfile profile) {
QuerySpecification<ScanProfileHib> spec = new ScanProfileHibSpecByName(profile.getName());
ripreal/V8LogScannerWeb
src/main/java/org/v8LogScanner/dbLayer/scanProfilesPersistence/ScanProfileHibService.java
// Path: src/main/java/org/v8LogScanner/dbLayer/genericRepository/DataRepository.java // public interface DataRepository<T> { // // public Serializable add(T object); // // public void remove(T object); // // public void update(T object); // // public void resetCache(); // // public List<T> query(QuerySpecification<T> specification); // // } // // Path: src/main/java/org/v8LogScanner/dbLayer/genericRepository/QuerySpecification.java // public interface QuerySpecification<T> { // // boolean specified(T object); // // public CriteriaQuery<T> toCriteria(CriteriaBuilder builder); // // } // // Path: src/main/java/org/v8LogScanner/dbLayer/genericRepository/ScanProfileService.java // public interface ScanProfileService { // // public int add(ScanProfile profile); // // public void remove(ScanProfile profile); // // public void update(ScanProfile profile); // // public void resetCache(); // // public ScanProfile find(ScanProfile profile); // // public ScanProfile find(int id); // // public ScanProfile findIfPresent(); // // public List<ScanProfile> getAll(); // // } // // Path: src/main/java/org/v8LogScanner/dbLayer/scanProfilesPersistence/Specifications/ScanProfileHibSpecByID.java // public class ScanProfileHibSpecByID implements QuerySpecification<ScanProfileHib> { // // private int id; // // public ScanProfileHibSpecByID(int id) { // this.id = id; // } // // @Override // public boolean specified(ScanProfileHib profile) { // return id == profile.getId(); // } // // public CriteriaQuery<ScanProfileHib> toCriteria(CriteriaBuilder builder) { // // CriteriaQuery<ScanProfileHib> criteria = builder.createQuery(ScanProfileHib.class); // Root<ScanProfileHib> root = criteria.from(ScanProfileHib.class); // // criteria.where(builder.equal(root.get("id"), id)); // criteria.select(root); // // return criteria; // } // } // // Path: src/main/java/org/v8LogScanner/dbLayer/scanProfilesPersistence/Specifications/ScanProfileHibSpecByName.java // public class ScanProfileHibSpecByName implements QuerySpecification<ScanProfileHib> { // // private String name; // // public ScanProfileHibSpecByName(String name) { // this.name = name; // } // // @Override // public boolean specified(ScanProfileHib profile) { // return name == profile.getName(); // } // // public CriteriaQuery<ScanProfileHib> toCriteria(CriteriaBuilder builder) { // // CriteriaQuery<ScanProfileHib> criteria = builder.createQuery(ScanProfileHib.class); // Root<ScanProfileHib> root = criteria.from(ScanProfileHib.class); // // criteria.where(builder.equal(root.get("name"), name)); // criteria.select(root); // // return criteria; // } // } // // Path: src/main/java/org/v8LogScanner/dbLayer/scanProfilesPersistence/Specifications/ScanProfileHibSpecIfPresent.java // public class ScanProfileHibSpecIfPresent implements QuerySpecification<ScanProfileHib> { // // @Override // public boolean specified(ScanProfileHib profile) { // return profile.getId() >= 0; // } // // public CriteriaQuery<ScanProfileHib> toCriteria(CriteriaBuilder builder) { // // CriteriaQuery<ScanProfileHib> criteria = builder.createQuery(ScanProfileHib.class); // // Root<ScanProfileHib> root = criteria.from(ScanProfileHib.class); // criteria.select(root).from(ScanProfileHib.class); // criteria.orderBy(builder.desc(root.get("id"))); // // return criteria; // } // }
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.v8LogScanner.dbLayer.genericRepository.DataRepository; import org.v8LogScanner.dbLayer.genericRepository.QuerySpecification; import org.v8LogScanner.dbLayer.genericRepository.ScanProfileService; import org.v8LogScanner.dbLayer.scanProfilesPersistence.Specifications.ScanProfileHibSpecByID; import org.v8LogScanner.dbLayer.scanProfilesPersistence.Specifications.ScanProfileHibSpecByName; import org.v8LogScanner.dbLayer.scanProfilesPersistence.Specifications.ScanProfileHibSpecIfPresent; import org.v8LogScanner.rgx.ScanProfile; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List;
package org.v8LogScanner.dbLayer.scanProfilesPersistence; @Service @Transactional public class ScanProfileHibService implements ScanProfileService { @Autowired private DataRepository<ScanProfileHib> repository; public ScanProfileHibService(DataRepository<ScanProfileHib> repository) { this.repository = repository; } @Override public int add(ScanProfile profile) { return (int) repository.add((ScanProfileHib) profile); } @Override public void remove(ScanProfile profile) { repository.remove((ScanProfileHib) profile); } @Override public void update(ScanProfile profile) { repository.update((ScanProfileHib) profile); } @Override public ScanProfile find(ScanProfile profile) {
// Path: src/main/java/org/v8LogScanner/dbLayer/genericRepository/DataRepository.java // public interface DataRepository<T> { // // public Serializable add(T object); // // public void remove(T object); // // public void update(T object); // // public void resetCache(); // // public List<T> query(QuerySpecification<T> specification); // // } // // Path: src/main/java/org/v8LogScanner/dbLayer/genericRepository/QuerySpecification.java // public interface QuerySpecification<T> { // // boolean specified(T object); // // public CriteriaQuery<T> toCriteria(CriteriaBuilder builder); // // } // // Path: src/main/java/org/v8LogScanner/dbLayer/genericRepository/ScanProfileService.java // public interface ScanProfileService { // // public int add(ScanProfile profile); // // public void remove(ScanProfile profile); // // public void update(ScanProfile profile); // // public void resetCache(); // // public ScanProfile find(ScanProfile profile); // // public ScanProfile find(int id); // // public ScanProfile findIfPresent(); // // public List<ScanProfile> getAll(); // // } // // Path: src/main/java/org/v8LogScanner/dbLayer/scanProfilesPersistence/Specifications/ScanProfileHibSpecByID.java // public class ScanProfileHibSpecByID implements QuerySpecification<ScanProfileHib> { // // private int id; // // public ScanProfileHibSpecByID(int id) { // this.id = id; // } // // @Override // public boolean specified(ScanProfileHib profile) { // return id == profile.getId(); // } // // public CriteriaQuery<ScanProfileHib> toCriteria(CriteriaBuilder builder) { // // CriteriaQuery<ScanProfileHib> criteria = builder.createQuery(ScanProfileHib.class); // Root<ScanProfileHib> root = criteria.from(ScanProfileHib.class); // // criteria.where(builder.equal(root.get("id"), id)); // criteria.select(root); // // return criteria; // } // } // // Path: src/main/java/org/v8LogScanner/dbLayer/scanProfilesPersistence/Specifications/ScanProfileHibSpecByName.java // public class ScanProfileHibSpecByName implements QuerySpecification<ScanProfileHib> { // // private String name; // // public ScanProfileHibSpecByName(String name) { // this.name = name; // } // // @Override // public boolean specified(ScanProfileHib profile) { // return name == profile.getName(); // } // // public CriteriaQuery<ScanProfileHib> toCriteria(CriteriaBuilder builder) { // // CriteriaQuery<ScanProfileHib> criteria = builder.createQuery(ScanProfileHib.class); // Root<ScanProfileHib> root = criteria.from(ScanProfileHib.class); // // criteria.where(builder.equal(root.get("name"), name)); // criteria.select(root); // // return criteria; // } // } // // Path: src/main/java/org/v8LogScanner/dbLayer/scanProfilesPersistence/Specifications/ScanProfileHibSpecIfPresent.java // public class ScanProfileHibSpecIfPresent implements QuerySpecification<ScanProfileHib> { // // @Override // public boolean specified(ScanProfileHib profile) { // return profile.getId() >= 0; // } // // public CriteriaQuery<ScanProfileHib> toCriteria(CriteriaBuilder builder) { // // CriteriaQuery<ScanProfileHib> criteria = builder.createQuery(ScanProfileHib.class); // // Root<ScanProfileHib> root = criteria.from(ScanProfileHib.class); // criteria.select(root).from(ScanProfileHib.class); // criteria.orderBy(builder.desc(root.get("id"))); // // return criteria; // } // } // Path: src/main/java/org/v8LogScanner/dbLayer/scanProfilesPersistence/ScanProfileHibService.java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.v8LogScanner.dbLayer.genericRepository.DataRepository; import org.v8LogScanner.dbLayer.genericRepository.QuerySpecification; import org.v8LogScanner.dbLayer.genericRepository.ScanProfileService; import org.v8LogScanner.dbLayer.scanProfilesPersistence.Specifications.ScanProfileHibSpecByID; import org.v8LogScanner.dbLayer.scanProfilesPersistence.Specifications.ScanProfileHibSpecByName; import org.v8LogScanner.dbLayer.scanProfilesPersistence.Specifications.ScanProfileHibSpecIfPresent; import org.v8LogScanner.rgx.ScanProfile; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; package org.v8LogScanner.dbLayer.scanProfilesPersistence; @Service @Transactional public class ScanProfileHibService implements ScanProfileService { @Autowired private DataRepository<ScanProfileHib> repository; public ScanProfileHibService(DataRepository<ScanProfileHib> repository) { this.repository = repository; } @Override public int add(ScanProfile profile) { return (int) repository.add((ScanProfileHib) profile); } @Override public void remove(ScanProfile profile) { repository.remove((ScanProfileHib) profile); } @Override public void update(ScanProfile profile) { repository.update((ScanProfileHib) profile); } @Override public ScanProfile find(ScanProfile profile) {
QuerySpecification<ScanProfileHib> spec = new ScanProfileHibSpecByName(profile.getName());
ripreal/V8LogScannerWeb
src/main/java/org/v8LogScanner/dbLayer/scanProfilesPersistence/ScanProfileHibService.java
// Path: src/main/java/org/v8LogScanner/dbLayer/genericRepository/DataRepository.java // public interface DataRepository<T> { // // public Serializable add(T object); // // public void remove(T object); // // public void update(T object); // // public void resetCache(); // // public List<T> query(QuerySpecification<T> specification); // // } // // Path: src/main/java/org/v8LogScanner/dbLayer/genericRepository/QuerySpecification.java // public interface QuerySpecification<T> { // // boolean specified(T object); // // public CriteriaQuery<T> toCriteria(CriteriaBuilder builder); // // } // // Path: src/main/java/org/v8LogScanner/dbLayer/genericRepository/ScanProfileService.java // public interface ScanProfileService { // // public int add(ScanProfile profile); // // public void remove(ScanProfile profile); // // public void update(ScanProfile profile); // // public void resetCache(); // // public ScanProfile find(ScanProfile profile); // // public ScanProfile find(int id); // // public ScanProfile findIfPresent(); // // public List<ScanProfile> getAll(); // // } // // Path: src/main/java/org/v8LogScanner/dbLayer/scanProfilesPersistence/Specifications/ScanProfileHibSpecByID.java // public class ScanProfileHibSpecByID implements QuerySpecification<ScanProfileHib> { // // private int id; // // public ScanProfileHibSpecByID(int id) { // this.id = id; // } // // @Override // public boolean specified(ScanProfileHib profile) { // return id == profile.getId(); // } // // public CriteriaQuery<ScanProfileHib> toCriteria(CriteriaBuilder builder) { // // CriteriaQuery<ScanProfileHib> criteria = builder.createQuery(ScanProfileHib.class); // Root<ScanProfileHib> root = criteria.from(ScanProfileHib.class); // // criteria.where(builder.equal(root.get("id"), id)); // criteria.select(root); // // return criteria; // } // } // // Path: src/main/java/org/v8LogScanner/dbLayer/scanProfilesPersistence/Specifications/ScanProfileHibSpecByName.java // public class ScanProfileHibSpecByName implements QuerySpecification<ScanProfileHib> { // // private String name; // // public ScanProfileHibSpecByName(String name) { // this.name = name; // } // // @Override // public boolean specified(ScanProfileHib profile) { // return name == profile.getName(); // } // // public CriteriaQuery<ScanProfileHib> toCriteria(CriteriaBuilder builder) { // // CriteriaQuery<ScanProfileHib> criteria = builder.createQuery(ScanProfileHib.class); // Root<ScanProfileHib> root = criteria.from(ScanProfileHib.class); // // criteria.where(builder.equal(root.get("name"), name)); // criteria.select(root); // // return criteria; // } // } // // Path: src/main/java/org/v8LogScanner/dbLayer/scanProfilesPersistence/Specifications/ScanProfileHibSpecIfPresent.java // public class ScanProfileHibSpecIfPresent implements QuerySpecification<ScanProfileHib> { // // @Override // public boolean specified(ScanProfileHib profile) { // return profile.getId() >= 0; // } // // public CriteriaQuery<ScanProfileHib> toCriteria(CriteriaBuilder builder) { // // CriteriaQuery<ScanProfileHib> criteria = builder.createQuery(ScanProfileHib.class); // // Root<ScanProfileHib> root = criteria.from(ScanProfileHib.class); // criteria.select(root).from(ScanProfileHib.class); // criteria.orderBy(builder.desc(root.get("id"))); // // return criteria; // } // }
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.v8LogScanner.dbLayer.genericRepository.DataRepository; import org.v8LogScanner.dbLayer.genericRepository.QuerySpecification; import org.v8LogScanner.dbLayer.genericRepository.ScanProfileService; import org.v8LogScanner.dbLayer.scanProfilesPersistence.Specifications.ScanProfileHibSpecByID; import org.v8LogScanner.dbLayer.scanProfilesPersistence.Specifications.ScanProfileHibSpecByName; import org.v8LogScanner.dbLayer.scanProfilesPersistence.Specifications.ScanProfileHibSpecIfPresent; import org.v8LogScanner.rgx.ScanProfile; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List;
@Override public int add(ScanProfile profile) { return (int) repository.add((ScanProfileHib) profile); } @Override public void remove(ScanProfile profile) { repository.remove((ScanProfileHib) profile); } @Override public void update(ScanProfile profile) { repository.update((ScanProfileHib) profile); } @Override public ScanProfile find(ScanProfile profile) { QuerySpecification<ScanProfileHib> spec = new ScanProfileHibSpecByName(profile.getName()); List<ScanProfileHib> profiles = repository.query(spec); if (profiles.size() > 0) { ScanProfile prof = profiles.get(0); return prof; } else return null; } @Override public ScanProfile find(int id) {
// Path: src/main/java/org/v8LogScanner/dbLayer/genericRepository/DataRepository.java // public interface DataRepository<T> { // // public Serializable add(T object); // // public void remove(T object); // // public void update(T object); // // public void resetCache(); // // public List<T> query(QuerySpecification<T> specification); // // } // // Path: src/main/java/org/v8LogScanner/dbLayer/genericRepository/QuerySpecification.java // public interface QuerySpecification<T> { // // boolean specified(T object); // // public CriteriaQuery<T> toCriteria(CriteriaBuilder builder); // // } // // Path: src/main/java/org/v8LogScanner/dbLayer/genericRepository/ScanProfileService.java // public interface ScanProfileService { // // public int add(ScanProfile profile); // // public void remove(ScanProfile profile); // // public void update(ScanProfile profile); // // public void resetCache(); // // public ScanProfile find(ScanProfile profile); // // public ScanProfile find(int id); // // public ScanProfile findIfPresent(); // // public List<ScanProfile> getAll(); // // } // // Path: src/main/java/org/v8LogScanner/dbLayer/scanProfilesPersistence/Specifications/ScanProfileHibSpecByID.java // public class ScanProfileHibSpecByID implements QuerySpecification<ScanProfileHib> { // // private int id; // // public ScanProfileHibSpecByID(int id) { // this.id = id; // } // // @Override // public boolean specified(ScanProfileHib profile) { // return id == profile.getId(); // } // // public CriteriaQuery<ScanProfileHib> toCriteria(CriteriaBuilder builder) { // // CriteriaQuery<ScanProfileHib> criteria = builder.createQuery(ScanProfileHib.class); // Root<ScanProfileHib> root = criteria.from(ScanProfileHib.class); // // criteria.where(builder.equal(root.get("id"), id)); // criteria.select(root); // // return criteria; // } // } // // Path: src/main/java/org/v8LogScanner/dbLayer/scanProfilesPersistence/Specifications/ScanProfileHibSpecByName.java // public class ScanProfileHibSpecByName implements QuerySpecification<ScanProfileHib> { // // private String name; // // public ScanProfileHibSpecByName(String name) { // this.name = name; // } // // @Override // public boolean specified(ScanProfileHib profile) { // return name == profile.getName(); // } // // public CriteriaQuery<ScanProfileHib> toCriteria(CriteriaBuilder builder) { // // CriteriaQuery<ScanProfileHib> criteria = builder.createQuery(ScanProfileHib.class); // Root<ScanProfileHib> root = criteria.from(ScanProfileHib.class); // // criteria.where(builder.equal(root.get("name"), name)); // criteria.select(root); // // return criteria; // } // } // // Path: src/main/java/org/v8LogScanner/dbLayer/scanProfilesPersistence/Specifications/ScanProfileHibSpecIfPresent.java // public class ScanProfileHibSpecIfPresent implements QuerySpecification<ScanProfileHib> { // // @Override // public boolean specified(ScanProfileHib profile) { // return profile.getId() >= 0; // } // // public CriteriaQuery<ScanProfileHib> toCriteria(CriteriaBuilder builder) { // // CriteriaQuery<ScanProfileHib> criteria = builder.createQuery(ScanProfileHib.class); // // Root<ScanProfileHib> root = criteria.from(ScanProfileHib.class); // criteria.select(root).from(ScanProfileHib.class); // criteria.orderBy(builder.desc(root.get("id"))); // // return criteria; // } // } // Path: src/main/java/org/v8LogScanner/dbLayer/scanProfilesPersistence/ScanProfileHibService.java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.v8LogScanner.dbLayer.genericRepository.DataRepository; import org.v8LogScanner.dbLayer.genericRepository.QuerySpecification; import org.v8LogScanner.dbLayer.genericRepository.ScanProfileService; import org.v8LogScanner.dbLayer.scanProfilesPersistence.Specifications.ScanProfileHibSpecByID; import org.v8LogScanner.dbLayer.scanProfilesPersistence.Specifications.ScanProfileHibSpecByName; import org.v8LogScanner.dbLayer.scanProfilesPersistence.Specifications.ScanProfileHibSpecIfPresent; import org.v8LogScanner.rgx.ScanProfile; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; @Override public int add(ScanProfile profile) { return (int) repository.add((ScanProfileHib) profile); } @Override public void remove(ScanProfile profile) { repository.remove((ScanProfileHib) profile); } @Override public void update(ScanProfile profile) { repository.update((ScanProfileHib) profile); } @Override public ScanProfile find(ScanProfile profile) { QuerySpecification<ScanProfileHib> spec = new ScanProfileHibSpecByName(profile.getName()); List<ScanProfileHib> profiles = repository.query(spec); if (profiles.size() > 0) { ScanProfile prof = profiles.get(0); return prof; } else return null; } @Override public ScanProfile find(int id) {
QuerySpecification<ScanProfileHib> spec = new ScanProfileHibSpecByID(id);
ripreal/V8LogScannerWeb
src/main/java/org/v8LogScanner/dbLayer/scanProfilesPersistence/ScanProfileHibService.java
// Path: src/main/java/org/v8LogScanner/dbLayer/genericRepository/DataRepository.java // public interface DataRepository<T> { // // public Serializable add(T object); // // public void remove(T object); // // public void update(T object); // // public void resetCache(); // // public List<T> query(QuerySpecification<T> specification); // // } // // Path: src/main/java/org/v8LogScanner/dbLayer/genericRepository/QuerySpecification.java // public interface QuerySpecification<T> { // // boolean specified(T object); // // public CriteriaQuery<T> toCriteria(CriteriaBuilder builder); // // } // // Path: src/main/java/org/v8LogScanner/dbLayer/genericRepository/ScanProfileService.java // public interface ScanProfileService { // // public int add(ScanProfile profile); // // public void remove(ScanProfile profile); // // public void update(ScanProfile profile); // // public void resetCache(); // // public ScanProfile find(ScanProfile profile); // // public ScanProfile find(int id); // // public ScanProfile findIfPresent(); // // public List<ScanProfile> getAll(); // // } // // Path: src/main/java/org/v8LogScanner/dbLayer/scanProfilesPersistence/Specifications/ScanProfileHibSpecByID.java // public class ScanProfileHibSpecByID implements QuerySpecification<ScanProfileHib> { // // private int id; // // public ScanProfileHibSpecByID(int id) { // this.id = id; // } // // @Override // public boolean specified(ScanProfileHib profile) { // return id == profile.getId(); // } // // public CriteriaQuery<ScanProfileHib> toCriteria(CriteriaBuilder builder) { // // CriteriaQuery<ScanProfileHib> criteria = builder.createQuery(ScanProfileHib.class); // Root<ScanProfileHib> root = criteria.from(ScanProfileHib.class); // // criteria.where(builder.equal(root.get("id"), id)); // criteria.select(root); // // return criteria; // } // } // // Path: src/main/java/org/v8LogScanner/dbLayer/scanProfilesPersistence/Specifications/ScanProfileHibSpecByName.java // public class ScanProfileHibSpecByName implements QuerySpecification<ScanProfileHib> { // // private String name; // // public ScanProfileHibSpecByName(String name) { // this.name = name; // } // // @Override // public boolean specified(ScanProfileHib profile) { // return name == profile.getName(); // } // // public CriteriaQuery<ScanProfileHib> toCriteria(CriteriaBuilder builder) { // // CriteriaQuery<ScanProfileHib> criteria = builder.createQuery(ScanProfileHib.class); // Root<ScanProfileHib> root = criteria.from(ScanProfileHib.class); // // criteria.where(builder.equal(root.get("name"), name)); // criteria.select(root); // // return criteria; // } // } // // Path: src/main/java/org/v8LogScanner/dbLayer/scanProfilesPersistence/Specifications/ScanProfileHibSpecIfPresent.java // public class ScanProfileHibSpecIfPresent implements QuerySpecification<ScanProfileHib> { // // @Override // public boolean specified(ScanProfileHib profile) { // return profile.getId() >= 0; // } // // public CriteriaQuery<ScanProfileHib> toCriteria(CriteriaBuilder builder) { // // CriteriaQuery<ScanProfileHib> criteria = builder.createQuery(ScanProfileHib.class); // // Root<ScanProfileHib> root = criteria.from(ScanProfileHib.class); // criteria.select(root).from(ScanProfileHib.class); // criteria.orderBy(builder.desc(root.get("id"))); // // return criteria; // } // }
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.v8LogScanner.dbLayer.genericRepository.DataRepository; import org.v8LogScanner.dbLayer.genericRepository.QuerySpecification; import org.v8LogScanner.dbLayer.genericRepository.ScanProfileService; import org.v8LogScanner.dbLayer.scanProfilesPersistence.Specifications.ScanProfileHibSpecByID; import org.v8LogScanner.dbLayer.scanProfilesPersistence.Specifications.ScanProfileHibSpecByName; import org.v8LogScanner.dbLayer.scanProfilesPersistence.Specifications.ScanProfileHibSpecIfPresent; import org.v8LogScanner.rgx.ScanProfile; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List;
} @Override public ScanProfile find(ScanProfile profile) { QuerySpecification<ScanProfileHib> spec = new ScanProfileHibSpecByName(profile.getName()); List<ScanProfileHib> profiles = repository.query(spec); if (profiles.size() > 0) { ScanProfile prof = profiles.get(0); return prof; } else return null; } @Override public ScanProfile find(int id) { QuerySpecification<ScanProfileHib> spec = new ScanProfileHibSpecByID(id); List<ScanProfileHib> profiles = repository.query(spec); if (profiles.size() > 0) return (ScanProfile) profiles.get(0); else return null; } @Override public ScanProfile findIfPresent() { ScanProfile profile = null;
// Path: src/main/java/org/v8LogScanner/dbLayer/genericRepository/DataRepository.java // public interface DataRepository<T> { // // public Serializable add(T object); // // public void remove(T object); // // public void update(T object); // // public void resetCache(); // // public List<T> query(QuerySpecification<T> specification); // // } // // Path: src/main/java/org/v8LogScanner/dbLayer/genericRepository/QuerySpecification.java // public interface QuerySpecification<T> { // // boolean specified(T object); // // public CriteriaQuery<T> toCriteria(CriteriaBuilder builder); // // } // // Path: src/main/java/org/v8LogScanner/dbLayer/genericRepository/ScanProfileService.java // public interface ScanProfileService { // // public int add(ScanProfile profile); // // public void remove(ScanProfile profile); // // public void update(ScanProfile profile); // // public void resetCache(); // // public ScanProfile find(ScanProfile profile); // // public ScanProfile find(int id); // // public ScanProfile findIfPresent(); // // public List<ScanProfile> getAll(); // // } // // Path: src/main/java/org/v8LogScanner/dbLayer/scanProfilesPersistence/Specifications/ScanProfileHibSpecByID.java // public class ScanProfileHibSpecByID implements QuerySpecification<ScanProfileHib> { // // private int id; // // public ScanProfileHibSpecByID(int id) { // this.id = id; // } // // @Override // public boolean specified(ScanProfileHib profile) { // return id == profile.getId(); // } // // public CriteriaQuery<ScanProfileHib> toCriteria(CriteriaBuilder builder) { // // CriteriaQuery<ScanProfileHib> criteria = builder.createQuery(ScanProfileHib.class); // Root<ScanProfileHib> root = criteria.from(ScanProfileHib.class); // // criteria.where(builder.equal(root.get("id"), id)); // criteria.select(root); // // return criteria; // } // } // // Path: src/main/java/org/v8LogScanner/dbLayer/scanProfilesPersistence/Specifications/ScanProfileHibSpecByName.java // public class ScanProfileHibSpecByName implements QuerySpecification<ScanProfileHib> { // // private String name; // // public ScanProfileHibSpecByName(String name) { // this.name = name; // } // // @Override // public boolean specified(ScanProfileHib profile) { // return name == profile.getName(); // } // // public CriteriaQuery<ScanProfileHib> toCriteria(CriteriaBuilder builder) { // // CriteriaQuery<ScanProfileHib> criteria = builder.createQuery(ScanProfileHib.class); // Root<ScanProfileHib> root = criteria.from(ScanProfileHib.class); // // criteria.where(builder.equal(root.get("name"), name)); // criteria.select(root); // // return criteria; // } // } // // Path: src/main/java/org/v8LogScanner/dbLayer/scanProfilesPersistence/Specifications/ScanProfileHibSpecIfPresent.java // public class ScanProfileHibSpecIfPresent implements QuerySpecification<ScanProfileHib> { // // @Override // public boolean specified(ScanProfileHib profile) { // return profile.getId() >= 0; // } // // public CriteriaQuery<ScanProfileHib> toCriteria(CriteriaBuilder builder) { // // CriteriaQuery<ScanProfileHib> criteria = builder.createQuery(ScanProfileHib.class); // // Root<ScanProfileHib> root = criteria.from(ScanProfileHib.class); // criteria.select(root).from(ScanProfileHib.class); // criteria.orderBy(builder.desc(root.get("id"))); // // return criteria; // } // } // Path: src/main/java/org/v8LogScanner/dbLayer/scanProfilesPersistence/ScanProfileHibService.java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.v8LogScanner.dbLayer.genericRepository.DataRepository; import org.v8LogScanner.dbLayer.genericRepository.QuerySpecification; import org.v8LogScanner.dbLayer.genericRepository.ScanProfileService; import org.v8LogScanner.dbLayer.scanProfilesPersistence.Specifications.ScanProfileHibSpecByID; import org.v8LogScanner.dbLayer.scanProfilesPersistence.Specifications.ScanProfileHibSpecByName; import org.v8LogScanner.dbLayer.scanProfilesPersistence.Specifications.ScanProfileHibSpecIfPresent; import org.v8LogScanner.rgx.ScanProfile; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; } @Override public ScanProfile find(ScanProfile profile) { QuerySpecification<ScanProfileHib> spec = new ScanProfileHibSpecByName(profile.getName()); List<ScanProfileHib> profiles = repository.query(spec); if (profiles.size() > 0) { ScanProfile prof = profiles.get(0); return prof; } else return null; } @Override public ScanProfile find(int id) { QuerySpecification<ScanProfileHib> spec = new ScanProfileHibSpecByID(id); List<ScanProfileHib> profiles = repository.query(spec); if (profiles.size() > 0) return (ScanProfile) profiles.get(0); else return null; } @Override public ScanProfile findIfPresent() { ScanProfile profile = null;
QuerySpecification<ScanProfileHib> spec = new ScanProfileHibSpecIfPresent();
christ66/cobertura
cobertura/src/main/java/net/sourceforge/cobertura/instrument/CoberturaFile.java
// Path: cobertura/src/main/java/net/sourceforge/cobertura/util/ArchiveUtil.java // public abstract class ArchiveUtil { // // /** // * Return true if the given name ends with .jar, .zip, // * .war, .ear, or .sar (case insensitive). // * // * @param name The file name. // * // * @return true if the name is an archive. // */ // public static boolean isArchive(String name) { // name = name.toLowerCase(); // return name.endsWith(".jar") || name.endsWith(".zip") // || name.endsWith(".war") || name.endsWith(".ear") // || name.endsWith(".sar"); // } // // /** // * Check to see if the given file name is a signature file // * (meta-inf/*.rsa or meta-inf/*.sf). // * // * @param name The file name. Commonly a ZipEntry name. // * // * @return true if the name is a signature file. // */ // public static boolean isSignatureFile(String name) { // name = name.toLowerCase(); // return (name.startsWith("meta-inf/") && (name.endsWith(".rsa") || name // .endsWith(".sf"))); // } // // }
import net.sourceforge.cobertura.util.ArchiveUtil; import java.io.File;
/* * Cobertura - http://cobertura.sourceforge.net/ * * Copyright (C) 2006 John Lewis * * Note: This file is dual licensed under the GPL and the Apache * Source License (so that it can be used from both the main * Cobertura classes and the ant tasks). * * Cobertura 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 2 of the License, * or (at your option) any later version. * * Cobertura 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 Cobertura; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA */ package net.sourceforge.cobertura.instrument; /** * This represents a regular File, but unlike java.io.File, the baseDir and * relative pathname used to create it are saved for later use. * * @author John Lewis */ class CoberturaFile extends File { private static final long serialVersionUID = 0L; private String baseDir; private String pathname; CoberturaFile(String baseDir, String pathname) { super(baseDir, pathname); this.baseDir = baseDir; this.pathname = pathname; } public String getBaseDir() { return baseDir; } public String getPathname() { return pathname; } /** * @return True if file has an extension that matches one of the * standard java archives, false otherwise. */ boolean isArchive() { if (!isFile()) { return false; }
// Path: cobertura/src/main/java/net/sourceforge/cobertura/util/ArchiveUtil.java // public abstract class ArchiveUtil { // // /** // * Return true if the given name ends with .jar, .zip, // * .war, .ear, or .sar (case insensitive). // * // * @param name The file name. // * // * @return true if the name is an archive. // */ // public static boolean isArchive(String name) { // name = name.toLowerCase(); // return name.endsWith(".jar") || name.endsWith(".zip") // || name.endsWith(".war") || name.endsWith(".ear") // || name.endsWith(".sar"); // } // // /** // * Check to see if the given file name is a signature file // * (meta-inf/*.rsa or meta-inf/*.sf). // * // * @param name The file name. Commonly a ZipEntry name. // * // * @return true if the name is a signature file. // */ // public static boolean isSignatureFile(String name) { // name = name.toLowerCase(); // return (name.startsWith("meta-inf/") && (name.endsWith(".rsa") || name // .endsWith(".sf"))); // } // // } // Path: cobertura/src/main/java/net/sourceforge/cobertura/instrument/CoberturaFile.java import net.sourceforge.cobertura.util.ArchiveUtil; import java.io.File; /* * Cobertura - http://cobertura.sourceforge.net/ * * Copyright (C) 2006 John Lewis * * Note: This file is dual licensed under the GPL and the Apache * Source License (so that it can be used from both the main * Cobertura classes and the ant tasks). * * Cobertura 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 2 of the License, * or (at your option) any later version. * * Cobertura 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 Cobertura; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA */ package net.sourceforge.cobertura.instrument; /** * This represents a regular File, but unlike java.io.File, the baseDir and * relative pathname used to create it are saved for later use. * * @author John Lewis */ class CoberturaFile extends File { private static final long serialVersionUID = 0L; private String baseDir; private String pathname; CoberturaFile(String baseDir, String pathname) { super(baseDir, pathname); this.baseDir = baseDir; this.pathname = pathname; } public String getBaseDir() { return baseDir; } public String getPathname() { return pathname; } /** * @return True if file has an extension that matches one of the * standard java archives, false otherwise. */ boolean isArchive() { if (!isFile()) { return false; }
return ArchiveUtil.isArchive(pathname);
christ66/cobertura
cobertura/src/main/java/net/sourceforge/cobertura/instrument/pass3/TestUnitCodeProvider.java
// Path: cobertura/src/main/java/net/sourceforge/cobertura/Cobertura.java // public class Cobertura { // public static String TestClassAndMethodNamesMerged = ""; // } // // Path: cobertura/src/main/java/net/sourceforge/cobertura/coveragedata/TestUnitInformationHolder.java // public class TestUnitInformationHolder { // private List<String> testNames; // // public TestUnitInformationHolder() { // testNames = new ArrayList<String>(); // } // // public void appendTestUnit(String nameOfTestUnit) { // testNames.add(nameOfTestUnit); // } // // public int getNumOfExecutions() { // return testNames.size(); // } // // public List<String> getAndReset() { // List<String> returnArray = testNames; // testNames = new ArrayList<String>(); // return returnArray; // } // // public List<String> getTestUnitList() { // return testNames; // } // }
import net.sourceforge.cobertura.Cobertura; import net.sourceforge.cobertura.coveragedata.TestUnitInformationHolder; import org.objectweb.asm.*;
/* * Cobertura - http://cobertura.sourceforge.net/ * * Copyright (C) 2013 Steven Christou * * Note: This file is dual licensed under the GPL and the Apache * Source License (so that it can be used from both the main * Cobertura classes and the ant tasks). * * Cobertura 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 2 of the License, * or (at your option) any later version. * * Cobertura 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 Cobertura; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA */ package net.sourceforge.cobertura.instrument.pass3; /** * * For every single line of code we add the following: * * Before instrumentation: * 1: public int foo() { * 2: int x = 0; * 3: x++; * 4: return x; * 5: } * * After instrumentation: * public int foo() { * __cobertura_counters * .get(2) * .append(", " + net.sourceforge.cobertura.Cobertura.TestClassAndMethodNamesMerged); * int x = 0; * __cobertura_counters * .get(3) * .append(", " + net.sourceforge.cobertura.Cobertura.TestClassAndMethodNamesMerged); * x++; * __cobertura_counters * .get(4) * .append(", " + net.sourceforge.cobertura.Cobertura.TestClassAndMethodNamesMerged); * return x; * } * * In future versions it might be best to switch from the ConcurrentHashMap to a more static approach. * * @author christ66 */ public class TestUnitCodeProvider extends AbstractCodeProvider implements CodeProvider, Opcodes { /** * Type of the generated field, that is used to store counters */ static final String COBERTURA_COUNTERS_FIELD_TYPE = "[Lnet/sourceforge/cobertura/coveragedata/TestUnitInformationHolder;"; /** * Generates: * */ public void generateCodeThatIncrementsCoberturaCounterFromInternalVariable( MethodVisitor nextMethodVisitor, int lastJumpIdVariableIndex, String className) { nextMethodVisitor.visitVarInsn(Opcodes.ALOAD, 0); nextMethodVisitor.visitFieldInsn(Opcodes.GETFIELD, className, COBERTURA_COUNTERS_FIELD_NAME, COBERTURA_COUNTERS_FIELD_TYPE); nextMethodVisitor.visitVarInsn(Opcodes.ILOAD, lastJumpIdVariableIndex); nextMethodVisitor.visitInsn(Opcodes.DUP2); nextMethodVisitor.visitInsn(Opcodes.IALOAD); nextMethodVisitor.visitFieldInsn(Opcodes.GETSTATIC, Type
// Path: cobertura/src/main/java/net/sourceforge/cobertura/Cobertura.java // public class Cobertura { // public static String TestClassAndMethodNamesMerged = ""; // } // // Path: cobertura/src/main/java/net/sourceforge/cobertura/coveragedata/TestUnitInformationHolder.java // public class TestUnitInformationHolder { // private List<String> testNames; // // public TestUnitInformationHolder() { // testNames = new ArrayList<String>(); // } // // public void appendTestUnit(String nameOfTestUnit) { // testNames.add(nameOfTestUnit); // } // // public int getNumOfExecutions() { // return testNames.size(); // } // // public List<String> getAndReset() { // List<String> returnArray = testNames; // testNames = new ArrayList<String>(); // return returnArray; // } // // public List<String> getTestUnitList() { // return testNames; // } // } // Path: cobertura/src/main/java/net/sourceforge/cobertura/instrument/pass3/TestUnitCodeProvider.java import net.sourceforge.cobertura.Cobertura; import net.sourceforge.cobertura.coveragedata.TestUnitInformationHolder; import org.objectweb.asm.*; /* * Cobertura - http://cobertura.sourceforge.net/ * * Copyright (C) 2013 Steven Christou * * Note: This file is dual licensed under the GPL and the Apache * Source License (so that it can be used from both the main * Cobertura classes and the ant tasks). * * Cobertura 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 2 of the License, * or (at your option) any later version. * * Cobertura 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 Cobertura; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA */ package net.sourceforge.cobertura.instrument.pass3; /** * * For every single line of code we add the following: * * Before instrumentation: * 1: public int foo() { * 2: int x = 0; * 3: x++; * 4: return x; * 5: } * * After instrumentation: * public int foo() { * __cobertura_counters * .get(2) * .append(", " + net.sourceforge.cobertura.Cobertura.TestClassAndMethodNamesMerged); * int x = 0; * __cobertura_counters * .get(3) * .append(", " + net.sourceforge.cobertura.Cobertura.TestClassAndMethodNamesMerged); * x++; * __cobertura_counters * .get(4) * .append(", " + net.sourceforge.cobertura.Cobertura.TestClassAndMethodNamesMerged); * return x; * } * * In future versions it might be best to switch from the ConcurrentHashMap to a more static approach. * * @author christ66 */ public class TestUnitCodeProvider extends AbstractCodeProvider implements CodeProvider, Opcodes { /** * Type of the generated field, that is used to store counters */ static final String COBERTURA_COUNTERS_FIELD_TYPE = "[Lnet/sourceforge/cobertura/coveragedata/TestUnitInformationHolder;"; /** * Generates: * */ public void generateCodeThatIncrementsCoberturaCounterFromInternalVariable( MethodVisitor nextMethodVisitor, int lastJumpIdVariableIndex, String className) { nextMethodVisitor.visitVarInsn(Opcodes.ALOAD, 0); nextMethodVisitor.visitFieldInsn(Opcodes.GETFIELD, className, COBERTURA_COUNTERS_FIELD_NAME, COBERTURA_COUNTERS_FIELD_TYPE); nextMethodVisitor.visitVarInsn(Opcodes.ILOAD, lastJumpIdVariableIndex); nextMethodVisitor.visitInsn(Opcodes.DUP2); nextMethodVisitor.visitInsn(Opcodes.IALOAD); nextMethodVisitor.visitFieldInsn(Opcodes.GETSTATIC, Type
.getInternalName(Cobertura.class),
christ66/cobertura
cobertura/src/main/java/net/sourceforge/cobertura/instrument/pass3/TestUnitCodeProvider.java
// Path: cobertura/src/main/java/net/sourceforge/cobertura/Cobertura.java // public class Cobertura { // public static String TestClassAndMethodNamesMerged = ""; // } // // Path: cobertura/src/main/java/net/sourceforge/cobertura/coveragedata/TestUnitInformationHolder.java // public class TestUnitInformationHolder { // private List<String> testNames; // // public TestUnitInformationHolder() { // testNames = new ArrayList<String>(); // } // // public void appendTestUnit(String nameOfTestUnit) { // testNames.add(nameOfTestUnit); // } // // public int getNumOfExecutions() { // return testNames.size(); // } // // public List<String> getAndReset() { // List<String> returnArray = testNames; // testNames = new ArrayList<String>(); // return returnArray; // } // // public List<String> getTestUnitList() { // return testNames; // } // }
import net.sourceforge.cobertura.Cobertura; import net.sourceforge.cobertura.coveragedata.TestUnitInformationHolder; import org.objectweb.asm.*;
/* * Cobertura - http://cobertura.sourceforge.net/ * * Copyright (C) 2013 Steven Christou * * Note: This file is dual licensed under the GPL and the Apache * Source License (so that it can be used from both the main * Cobertura classes and the ant tasks). * * Cobertura 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 2 of the License, * or (at your option) any later version. * * Cobertura 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 Cobertura; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA */ package net.sourceforge.cobertura.instrument.pass3; /** * * For every single line of code we add the following: * * Before instrumentation: * 1: public int foo() { * 2: int x = 0; * 3: x++; * 4: return x; * 5: } * * After instrumentation: * public int foo() { * __cobertura_counters * .get(2) * .append(", " + net.sourceforge.cobertura.Cobertura.TestClassAndMethodNamesMerged); * int x = 0; * __cobertura_counters * .get(3) * .append(", " + net.sourceforge.cobertura.Cobertura.TestClassAndMethodNamesMerged); * x++; * __cobertura_counters * .get(4) * .append(", " + net.sourceforge.cobertura.Cobertura.TestClassAndMethodNamesMerged); * return x; * } * * In future versions it might be best to switch from the ConcurrentHashMap to a more static approach. * * @author christ66 */ public class TestUnitCodeProvider extends AbstractCodeProvider implements CodeProvider, Opcodes { /** * Type of the generated field, that is used to store counters */ static final String COBERTURA_COUNTERS_FIELD_TYPE = "[Lnet/sourceforge/cobertura/coveragedata/TestUnitInformationHolder;"; /** * Generates: * */ public void generateCodeThatIncrementsCoberturaCounterFromInternalVariable( MethodVisitor nextMethodVisitor, int lastJumpIdVariableIndex, String className) { nextMethodVisitor.visitVarInsn(Opcodes.ALOAD, 0); nextMethodVisitor.visitFieldInsn(Opcodes.GETFIELD, className, COBERTURA_COUNTERS_FIELD_NAME, COBERTURA_COUNTERS_FIELD_TYPE); nextMethodVisitor.visitVarInsn(Opcodes.ILOAD, lastJumpIdVariableIndex); nextMethodVisitor.visitInsn(Opcodes.DUP2); nextMethodVisitor.visitInsn(Opcodes.IALOAD); nextMethodVisitor.visitFieldInsn(Opcodes.GETSTATIC, Type .getInternalName(Cobertura.class), "TestClassAndMethodNamesMerged", "Ljava/lang/String;"); nextMethodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, Type
// Path: cobertura/src/main/java/net/sourceforge/cobertura/Cobertura.java // public class Cobertura { // public static String TestClassAndMethodNamesMerged = ""; // } // // Path: cobertura/src/main/java/net/sourceforge/cobertura/coveragedata/TestUnitInformationHolder.java // public class TestUnitInformationHolder { // private List<String> testNames; // // public TestUnitInformationHolder() { // testNames = new ArrayList<String>(); // } // // public void appendTestUnit(String nameOfTestUnit) { // testNames.add(nameOfTestUnit); // } // // public int getNumOfExecutions() { // return testNames.size(); // } // // public List<String> getAndReset() { // List<String> returnArray = testNames; // testNames = new ArrayList<String>(); // return returnArray; // } // // public List<String> getTestUnitList() { // return testNames; // } // } // Path: cobertura/src/main/java/net/sourceforge/cobertura/instrument/pass3/TestUnitCodeProvider.java import net.sourceforge.cobertura.Cobertura; import net.sourceforge.cobertura.coveragedata.TestUnitInformationHolder; import org.objectweb.asm.*; /* * Cobertura - http://cobertura.sourceforge.net/ * * Copyright (C) 2013 Steven Christou * * Note: This file is dual licensed under the GPL and the Apache * Source License (so that it can be used from both the main * Cobertura classes and the ant tasks). * * Cobertura 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 2 of the License, * or (at your option) any later version. * * Cobertura 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 Cobertura; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA */ package net.sourceforge.cobertura.instrument.pass3; /** * * For every single line of code we add the following: * * Before instrumentation: * 1: public int foo() { * 2: int x = 0; * 3: x++; * 4: return x; * 5: } * * After instrumentation: * public int foo() { * __cobertura_counters * .get(2) * .append(", " + net.sourceforge.cobertura.Cobertura.TestClassAndMethodNamesMerged); * int x = 0; * __cobertura_counters * .get(3) * .append(", " + net.sourceforge.cobertura.Cobertura.TestClassAndMethodNamesMerged); * x++; * __cobertura_counters * .get(4) * .append(", " + net.sourceforge.cobertura.Cobertura.TestClassAndMethodNamesMerged); * return x; * } * * In future versions it might be best to switch from the ConcurrentHashMap to a more static approach. * * @author christ66 */ public class TestUnitCodeProvider extends AbstractCodeProvider implements CodeProvider, Opcodes { /** * Type of the generated field, that is used to store counters */ static final String COBERTURA_COUNTERS_FIELD_TYPE = "[Lnet/sourceforge/cobertura/coveragedata/TestUnitInformationHolder;"; /** * Generates: * */ public void generateCodeThatIncrementsCoberturaCounterFromInternalVariable( MethodVisitor nextMethodVisitor, int lastJumpIdVariableIndex, String className) { nextMethodVisitor.visitVarInsn(Opcodes.ALOAD, 0); nextMethodVisitor.visitFieldInsn(Opcodes.GETFIELD, className, COBERTURA_COUNTERS_FIELD_NAME, COBERTURA_COUNTERS_FIELD_TYPE); nextMethodVisitor.visitVarInsn(Opcodes.ILOAD, lastJumpIdVariableIndex); nextMethodVisitor.visitInsn(Opcodes.DUP2); nextMethodVisitor.visitInsn(Opcodes.IALOAD); nextMethodVisitor.visitFieldInsn(Opcodes.GETSTATIC, Type .getInternalName(Cobertura.class), "TestClassAndMethodNamesMerged", "Ljava/lang/String;"); nextMethodVisitor.visitMethodInsn(Opcodes.INVOKEVIRTUAL, Type
.getInternalName(TestUnitInformationHolder.class),
christ66/cobertura
cobertura/src/main/java/net/sourceforge/cobertura/instrument/FindTouchPointsMethodAdapter.java
// Path: cobertura/src/main/java/net/sourceforge/cobertura/util/RegexUtil.java // public abstract class RegexUtil { // // private static final Logger logger = Logger.getLogger(RegexUtil.class); // // /** // * <p> // * Check to see if one of the regular expressions in a collection match // * an input string. // * </p> // * // * @param regexs The collection of regular expressions. // * @param str The string to check for a match. // * // * @return True if a match is found. // */ // public static boolean matches(Collection regexs, String str) { // Iterator iter = regexs.iterator(); // while (iter.hasNext()) { // Pattern regex = (Pattern) iter.next(); // Matcher m = regex.matcher(str); // if (m.matches()) { // return true; // } // } // // return false; // } // // public static void addRegex(Collection list, String regex) { // try { // Pattern pattern = Pattern.compile(regex); // list.add(pattern); // } catch (PatternSyntaxException pse) { // logger.warn("The regular expression " + regex + " is invalid: " // + pse.getLocalizedMessage()); // } // } // // }
import org.objectweb.asm.tree.InsnNode; import org.objectweb.asm.tree.MethodInsnNode; import org.objectweb.asm.tree.VarInsnNode; import java.util.*; import java.util.concurrent.atomic.AtomicInteger; import java.util.regex.Pattern; import net.sourceforge.cobertura.util.RegexUtil; import org.objectweb.asm.Label; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import org.objectweb.asm.tree.AbstractInsnNode;
public void visitLabel(Label label) { int eventId = getEventId(); touchPointListener.beforeLabel(eventId, label, currentLine, mv); super.visitLabel(label); touchPointListener.afterLabel(eventId, label, currentLine, mv); } @Override public void visitJumpInsn(int opcode, Label label) { /* Ignore any jump instructions in the "class init" method. When initializing static variables, the JVM first checks that the variable is null before attempting to set it. This check contains an IFNONNULL jump instruction which would confuse people if it showed up in the reports.*/ if ((opcode != Opcodes.GOTO) && (opcode != Opcodes.JSR) && (currentLine != 0) && (!methodName.equals("<clinit>"))) { int eventId = getEventId(); touchPointListener.beforeJump(eventId, label, currentLine, mv); super.visitJumpInsn(opcode, label); touchPointListener.afterJump(eventId, label, currentLine, mv); } else { super.visitJumpInsn(opcode, label); } } @Override public void visitMethodInsn(int opcode, String owner, String method, String descr) { super.visitMethodInsn(opcode, owner, method, descr); //We skip lines that contains call to methods that are specified inside ignoreRegexp
// Path: cobertura/src/main/java/net/sourceforge/cobertura/util/RegexUtil.java // public abstract class RegexUtil { // // private static final Logger logger = Logger.getLogger(RegexUtil.class); // // /** // * <p> // * Check to see if one of the regular expressions in a collection match // * an input string. // * </p> // * // * @param regexs The collection of regular expressions. // * @param str The string to check for a match. // * // * @return True if a match is found. // */ // public static boolean matches(Collection regexs, String str) { // Iterator iter = regexs.iterator(); // while (iter.hasNext()) { // Pattern regex = (Pattern) iter.next(); // Matcher m = regex.matcher(str); // if (m.matches()) { // return true; // } // } // // return false; // } // // public static void addRegex(Collection list, String regex) { // try { // Pattern pattern = Pattern.compile(regex); // list.add(pattern); // } catch (PatternSyntaxException pse) { // logger.warn("The regular expression " + regex + " is invalid: " // + pse.getLocalizedMessage()); // } // } // // } // Path: cobertura/src/main/java/net/sourceforge/cobertura/instrument/FindTouchPointsMethodAdapter.java import org.objectweb.asm.tree.InsnNode; import org.objectweb.asm.tree.MethodInsnNode; import org.objectweb.asm.tree.VarInsnNode; import java.util.*; import java.util.concurrent.atomic.AtomicInteger; import java.util.regex.Pattern; import net.sourceforge.cobertura.util.RegexUtil; import org.objectweb.asm.Label; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import org.objectweb.asm.tree.AbstractInsnNode; public void visitLabel(Label label) { int eventId = getEventId(); touchPointListener.beforeLabel(eventId, label, currentLine, mv); super.visitLabel(label); touchPointListener.afterLabel(eventId, label, currentLine, mv); } @Override public void visitJumpInsn(int opcode, Label label) { /* Ignore any jump instructions in the "class init" method. When initializing static variables, the JVM first checks that the variable is null before attempting to set it. This check contains an IFNONNULL jump instruction which would confuse people if it showed up in the reports.*/ if ((opcode != Opcodes.GOTO) && (opcode != Opcodes.JSR) && (currentLine != 0) && (!methodName.equals("<clinit>"))) { int eventId = getEventId(); touchPointListener.beforeJump(eventId, label, currentLine, mv); super.visitJumpInsn(opcode, label); touchPointListener.afterJump(eventId, label, currentLine, mv); } else { super.visitJumpInsn(opcode, label); } } @Override public void visitMethodInsn(int opcode, String owner, String method, String descr) { super.visitMethodInsn(opcode, owner, method, descr); //We skip lines that contains call to methods that are specified inside ignoreRegexp
if (RegexUtil.matches(ignoreRegexp, owner)) {
christ66/cobertura
cobertura/src/main/java/net/sourceforge/cobertura/instrument/ClassPattern.java
// Path: cobertura/src/main/java/net/sourceforge/cobertura/util/RegexUtil.java // public abstract class RegexUtil { // // private static final Logger logger = Logger.getLogger(RegexUtil.class); // // /** // * <p> // * Check to see if one of the regular expressions in a collection match // * an input string. // * </p> // * // * @param regexs The collection of regular expressions. // * @param str The string to check for a match. // * // * @return True if a match is found. // */ // public static boolean matches(Collection regexs, String str) { // Iterator iter = regexs.iterator(); // while (iter.hasNext()) { // Pattern regex = (Pattern) iter.next(); // Matcher m = regex.matcher(str); // if (m.matches()) { // return true; // } // } // // return false; // } // // public static void addRegex(Collection list, String regex) { // try { // Pattern pattern = Pattern.compile(regex); // list.add(pattern); // } catch (PatternSyntaxException pse) { // logger.warn("The regular expression " + regex + " is invalid: " // + pse.getLocalizedMessage()); // } // } // // }
import net.sourceforge.cobertura.util.RegexUtil; import java.util.HashSet; import java.util.Set;
/* * Cobertura - http://cobertura.sourceforge.net/ * * Copyright (C) 2006 John Lewis * * Note: This file is dual licensed under the GPL and the Apache * Source License (so that it can be used from both the main * Cobertura classes and the ant tasks). * * Cobertura 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 2 of the License, * or (at your option) any later version. * * Cobertura 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 Cobertura; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA */ package net.sourceforge.cobertura.instrument; /** * This class represents a collection of regular expressions that will be used to see * if a classname matches them. * <p/> * Regular expressions are specified by calling add methods. If no add methods are * called, this class will match any classname. * * @author John Lewis */ public class ClassPattern { private Set<String> includeClassesRegexes = new HashSet<String>(); private Set<String> excludeClassesRegexes = new HashSet<String>(); private static final String WEBINF_CLASSES = "WEB-INF/classes/"; /** * Returns true if any regular expressions have been specified by calling the * add methods. If none are specified, this class matches anything. * * @return true if any regular expressions have been specified */ boolean isSpecified() { return includeClassesRegexes.size() > 0; } /** * Check to see if a class matches this ClassPattern * <p/> * If a pattern has not been specified, this matches anything. * <p/> * This method also looks for "WEB-INF/classes" at the beginning of the * classname. It is removed before checking for a match. * * @param filename Either a full classname or a full class filename * * @return true if the classname matches this ClassPattern or if this ClassPattern * has not been specified. */ boolean matches(String filename) { boolean matches = true; if (isSpecified()) { matches = false; // Remove .class extension if it exists if (filename.endsWith(".class")) { filename = filename.substring(0, filename.length() - 6); } filename = filename.replace('\\', '/'); filename = removeAnyWebInfClassesString(filename); filename = filename.replace('/', '.');
// Path: cobertura/src/main/java/net/sourceforge/cobertura/util/RegexUtil.java // public abstract class RegexUtil { // // private static final Logger logger = Logger.getLogger(RegexUtil.class); // // /** // * <p> // * Check to see if one of the regular expressions in a collection match // * an input string. // * </p> // * // * @param regexs The collection of regular expressions. // * @param str The string to check for a match. // * // * @return True if a match is found. // */ // public static boolean matches(Collection regexs, String str) { // Iterator iter = regexs.iterator(); // while (iter.hasNext()) { // Pattern regex = (Pattern) iter.next(); // Matcher m = regex.matcher(str); // if (m.matches()) { // return true; // } // } // // return false; // } // // public static void addRegex(Collection list, String regex) { // try { // Pattern pattern = Pattern.compile(regex); // list.add(pattern); // } catch (PatternSyntaxException pse) { // logger.warn("The regular expression " + regex + " is invalid: " // + pse.getLocalizedMessage()); // } // } // // } // Path: cobertura/src/main/java/net/sourceforge/cobertura/instrument/ClassPattern.java import net.sourceforge.cobertura.util.RegexUtil; import java.util.HashSet; import java.util.Set; /* * Cobertura - http://cobertura.sourceforge.net/ * * Copyright (C) 2006 John Lewis * * Note: This file is dual licensed under the GPL and the Apache * Source License (so that it can be used from both the main * Cobertura classes and the ant tasks). * * Cobertura 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 2 of the License, * or (at your option) any later version. * * Cobertura 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 Cobertura; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA */ package net.sourceforge.cobertura.instrument; /** * This class represents a collection of regular expressions that will be used to see * if a classname matches them. * <p/> * Regular expressions are specified by calling add methods. If no add methods are * called, this class will match any classname. * * @author John Lewis */ public class ClassPattern { private Set<String> includeClassesRegexes = new HashSet<String>(); private Set<String> excludeClassesRegexes = new HashSet<String>(); private static final String WEBINF_CLASSES = "WEB-INF/classes/"; /** * Returns true if any regular expressions have been specified by calling the * add methods. If none are specified, this class matches anything. * * @return true if any regular expressions have been specified */ boolean isSpecified() { return includeClassesRegexes.size() > 0; } /** * Check to see if a class matches this ClassPattern * <p/> * If a pattern has not been specified, this matches anything. * <p/> * This method also looks for "WEB-INF/classes" at the beginning of the * classname. It is removed before checking for a match. * * @param filename Either a full classname or a full class filename * * @return true if the classname matches this ClassPattern or if this ClassPattern * has not been specified. */ boolean matches(String filename) { boolean matches = true; if (isSpecified()) { matches = false; // Remove .class extension if it exists if (filename.endsWith(".class")) { filename = filename.substring(0, filename.length() - 6); } filename = filename.replace('\\', '/'); filename = removeAnyWebInfClassesString(filename); filename = filename.replace('/', '.');
if (RegexUtil.matches(includeClassesRegexes, filename)) {
christ66/cobertura
cobertura/src/main/java/net/sourceforge/cobertura/coveragedata/LineData.java
// Path: cobertura/src/main/java/net/sourceforge/cobertura/util/StringUtil.java // public abstract class StringUtil { // // /** // * <p> // * Replaces all instances of "replace" with "with" from the "original" // * string. // * </p> // * <p/> // * <p> // * NOTE: it is known that a similar function is included in jdk 1.4 as replaceAll(), // * but is written here so as to allow backward compatibility to users using SDK's // * prior to 1.4 // * </p> // * // * @param original The original string to do replacement on. // * @param replace The string to replace. // * @param with The string to replace "replace" with. // * // * @return The replaced string. // */ // public static String replaceAll(String original, String replace, String with) { // if (original == null) { // return original; // } // // final int len = replace.length(); // StringBuffer sb = new StringBuffer(original.length()); // int start = 0; // int found = -1; // // while ((found = original.indexOf(replace, start)) != -1) { // sb.append(original.substring(start, found)); // sb.append(with); // start = found + len; // } // // sb.append(original.substring(start)); // return sb.toString(); // } // // /** // * Takes a double and turns it into a percent string. // * Ex. 0.5 turns into 50% // * // * @param value // * // * @return corresponding percent string // */ // public static String getPercentValue(double value) { // //moved from HTMLReport.getPercentValue() // value = Math.floor(value * 100) / 100; //to represent 199 covered lines from 200 as 99% covered, not 100 % // return NumberFormat.getPercentInstance().format(value); // } // // }
import net.sourceforge.cobertura.CoverageIgnore; import net.sourceforge.cobertura.util.StringUtil; import java.io.Serializable; import java.util.ArrayList; import java.util.List;
return this.lineNumber - ((LineData) o).lineNumber; } public boolean equals(Object obj) { if (this == obj) return true; if ((obj == null) || !(obj.getClass().equals(this.getClass()))) return false; LineData lineData = (LineData) obj; return (this.hits == lineData.hits) && ((this.jumps == lineData.jumps) || ((this.jumps != null) && (this.jumps .equals(lineData.jumps)))) && ((this.switches == lineData.switches) || ((this.switches != null) && (this.switches .equals(lineData.switches)))) && (this.lineNumber == lineData.lineNumber) && (this.methodDescriptor.equals(lineData.methodDescriptor)) && (this.methodName.equals(lineData.methodName)); } public double getBranchCoverageRate() { if (getNumberOfValidBranches() == 0) return 1d; return ((double) getNumberOfCoveredBranches()) / getNumberOfValidBranches(); } public String getConditionCoverage() { StringBuffer ret = new StringBuffer(); if (getNumberOfValidBranches() == 0) {
// Path: cobertura/src/main/java/net/sourceforge/cobertura/util/StringUtil.java // public abstract class StringUtil { // // /** // * <p> // * Replaces all instances of "replace" with "with" from the "original" // * string. // * </p> // * <p/> // * <p> // * NOTE: it is known that a similar function is included in jdk 1.4 as replaceAll(), // * but is written here so as to allow backward compatibility to users using SDK's // * prior to 1.4 // * </p> // * // * @param original The original string to do replacement on. // * @param replace The string to replace. // * @param with The string to replace "replace" with. // * // * @return The replaced string. // */ // public static String replaceAll(String original, String replace, String with) { // if (original == null) { // return original; // } // // final int len = replace.length(); // StringBuffer sb = new StringBuffer(original.length()); // int start = 0; // int found = -1; // // while ((found = original.indexOf(replace, start)) != -1) { // sb.append(original.substring(start, found)); // sb.append(with); // start = found + len; // } // // sb.append(original.substring(start)); // return sb.toString(); // } // // /** // * Takes a double and turns it into a percent string. // * Ex. 0.5 turns into 50% // * // * @param value // * // * @return corresponding percent string // */ // public static String getPercentValue(double value) { // //moved from HTMLReport.getPercentValue() // value = Math.floor(value * 100) / 100; //to represent 199 covered lines from 200 as 99% covered, not 100 % // return NumberFormat.getPercentInstance().format(value); // } // // } // Path: cobertura/src/main/java/net/sourceforge/cobertura/coveragedata/LineData.java import net.sourceforge.cobertura.CoverageIgnore; import net.sourceforge.cobertura.util.StringUtil; import java.io.Serializable; import java.util.ArrayList; import java.util.List; return this.lineNumber - ((LineData) o).lineNumber; } public boolean equals(Object obj) { if (this == obj) return true; if ((obj == null) || !(obj.getClass().equals(this.getClass()))) return false; LineData lineData = (LineData) obj; return (this.hits == lineData.hits) && ((this.jumps == lineData.jumps) || ((this.jumps != null) && (this.jumps .equals(lineData.jumps)))) && ((this.switches == lineData.switches) || ((this.switches != null) && (this.switches .equals(lineData.switches)))) && (this.lineNumber == lineData.lineNumber) && (this.methodDescriptor.equals(lineData.methodDescriptor)) && (this.methodName.equals(lineData.methodName)); } public double getBranchCoverageRate() { if (getNumberOfValidBranches() == 0) return 1d; return ((double) getNumberOfCoveredBranches()) / getNumberOfValidBranches(); } public String getConditionCoverage() { StringBuffer ret = new StringBuffer(); if (getNumberOfValidBranches() == 0) {
ret.append(StringUtil.getPercentValue(1.0));
xdtianyu/Gallery
app/src/main/java/org/xdty/gallery/contract/MainContact.java
// Path: app/src/main/java/org/xdty/gallery/model/Media.java // public interface Media<T extends Media> { // // String[] scheme(); // // String getName(); // // String getHost(); // // long getLastModified(); // // long length(); // // String getPath(); // // String getParent(); // // void setParent(T parent); // // T parent(); // // void clear(); // // boolean hasImage(); // // List<T> children(); // // int childrenSize(); // // String getUri(); // // InputStream getInputStream() throws IOException; // // boolean isFile(); // // T[] listMedia(); // // boolean isImage(); // // boolean isDirectory(); // // T fromUri(String uri); // // T auth(String domain, String directory, String username, String password); // // int getPosition(); // // void setPosition(int position); // // class MediaException extends RuntimeException { // // public MediaException(String detailMessage) { // super(detailMessage); // } // } // // class NumericComparator implements Comparator<Media> { // // public static NumericComparator factory() { // return SingletonHelper.INSTANCE; // } // // private boolean isDigit(char ch) { // return ch >= 48 && ch <= 57; // } // // /** // * Length of string is passed in for improved efficiency (only need to calculate it once) // **/ // private String getChunk(String s, int length, int marker) { // StringBuilder chunk = new StringBuilder(); // char c = s.charAt(marker); // chunk.append(c); // marker++; // if (isDigit(c)) { // while (marker < length) { // c = s.charAt(marker); // if (!isDigit(c)) { // break; // } // chunk.append(c); // marker++; // } // } else { // while (marker < length) { // c = s.charAt(marker); // if (isDigit(c)) { // break; // } // chunk.append(c); // marker++; // } // } // return chunk.toString(); // } // // @Override // public int compare(Media m1, Media m2) { // String s1 = m1.getName(); // String s2 = m2.getName(); // // return compare(s1, s2); // } // // public int compare(String s1, String s2) { // // int thisMarker = 0; // int thatMarker = 0; // int s1Length = s1.length(); // int s2Length = s2.length(); // // while (thisMarker < s1Length && thatMarker < s2Length) { // String thisChunk = getChunk(s1, s1Length, thisMarker); // thisMarker += thisChunk.length(); // // String thatChunk = getChunk(s2, s2Length, thatMarker); // thatMarker += thatChunk.length(); // // // If both chunks contain numeric characters, sort them numerically // int result = 0; // if (isDigit(thisChunk.charAt(0)) && isDigit(thatChunk.charAt(0))) { // // Simple chunk comparison by length. // int thisChunkLength = thisChunk.length(); // result = thisChunkLength - thatChunk.length(); // // If equal, the first different number counts // if (result == 0) { // for (int i = 0; i < thisChunkLength; i++) { // result = thisChunk.charAt(i) - thatChunk.charAt(i); // if (result != 0) { // return result; // } // } // } // } else { // result = thisChunk.compareTo(thatChunk); // } // // if (result != 0) { // return result; // } // } // // return s1Length - s2Length; // } // // private final static class SingletonHelper { // private final static NumericComparator INSTANCE = new NumericComparator(); // } // } // // }
import org.xdty.gallery.model.Media; import java.util.List;
package org.xdty.gallery.contract; public interface MainContact { interface View extends BaseView<Presenter> { void setTitle(String title); void scrollToPosition(int position);
// Path: app/src/main/java/org/xdty/gallery/model/Media.java // public interface Media<T extends Media> { // // String[] scheme(); // // String getName(); // // String getHost(); // // long getLastModified(); // // long length(); // // String getPath(); // // String getParent(); // // void setParent(T parent); // // T parent(); // // void clear(); // // boolean hasImage(); // // List<T> children(); // // int childrenSize(); // // String getUri(); // // InputStream getInputStream() throws IOException; // // boolean isFile(); // // T[] listMedia(); // // boolean isImage(); // // boolean isDirectory(); // // T fromUri(String uri); // // T auth(String domain, String directory, String username, String password); // // int getPosition(); // // void setPosition(int position); // // class MediaException extends RuntimeException { // // public MediaException(String detailMessage) { // super(detailMessage); // } // } // // class NumericComparator implements Comparator<Media> { // // public static NumericComparator factory() { // return SingletonHelper.INSTANCE; // } // // private boolean isDigit(char ch) { // return ch >= 48 && ch <= 57; // } // // /** // * Length of string is passed in for improved efficiency (only need to calculate it once) // **/ // private String getChunk(String s, int length, int marker) { // StringBuilder chunk = new StringBuilder(); // char c = s.charAt(marker); // chunk.append(c); // marker++; // if (isDigit(c)) { // while (marker < length) { // c = s.charAt(marker); // if (!isDigit(c)) { // break; // } // chunk.append(c); // marker++; // } // } else { // while (marker < length) { // c = s.charAt(marker); // if (isDigit(c)) { // break; // } // chunk.append(c); // marker++; // } // } // return chunk.toString(); // } // // @Override // public int compare(Media m1, Media m2) { // String s1 = m1.getName(); // String s2 = m2.getName(); // // return compare(s1, s2); // } // // public int compare(String s1, String s2) { // // int thisMarker = 0; // int thatMarker = 0; // int s1Length = s1.length(); // int s2Length = s2.length(); // // while (thisMarker < s1Length && thatMarker < s2Length) { // String thisChunk = getChunk(s1, s1Length, thisMarker); // thisMarker += thisChunk.length(); // // String thatChunk = getChunk(s2, s2Length, thatMarker); // thatMarker += thatChunk.length(); // // // If both chunks contain numeric characters, sort them numerically // int result = 0; // if (isDigit(thisChunk.charAt(0)) && isDigit(thatChunk.charAt(0))) { // // Simple chunk comparison by length. // int thisChunkLength = thisChunk.length(); // result = thisChunkLength - thatChunk.length(); // // If equal, the first different number counts // if (result == 0) { // for (int i = 0; i < thisChunkLength; i++) { // result = thisChunk.charAt(i) - thatChunk.charAt(i); // if (result != 0) { // return result; // } // } // } // } else { // result = thisChunk.compareTo(thatChunk); // } // // if (result != 0) { // return result; // } // } // // return s1Length - s2Length; // } // // private final static class SingletonHelper { // private final static NumericComparator INSTANCE = new NumericComparator(); // } // } // // } // Path: app/src/main/java/org/xdty/gallery/contract/MainContact.java import org.xdty.gallery.model.Media; import java.util.List; package org.xdty.gallery.contract; public interface MainContact { interface View extends BaseView<Presenter> { void setTitle(String title); void scrollToPosition(int position);
void replaceData(List<Media> mediaList);
xdtianyu/Gallery
app/src/debug/java/org/xdty/gallery/application/DebugApplication.java
// Path: app/src/main/java/org/xdty/gallery/utils/OkHttp.java // public class OkHttp { // private OkHttpClient.Builder mOkHttpBuilder; // // private OkHttp() { // HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(); // loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.NONE); // // Interceptor interceptor = new Interceptor() { // @Override // public Response intercept(Chain chain) throws IOException { // Request request = chain.request(); // HttpUrl url = request.url() // .newBuilder() // //.addQueryParameter("timestamp", // // Long.toString(System.currentTimeMillis() / 1000 / 60)) // .build(); // request = request.newBuilder().url(url).build(); // return chain.proceed(request); // } // }; // // mOkHttpBuilder = new OkHttpClient.Builder() // .addInterceptor(loggingInterceptor) // .addInterceptor(interceptor); // } // // public static OkHttp getInstance() { // return SingletonHelper.INSTANCE; // } // // public void addNetworkInterceptor(Interceptor interceptor) { // mOkHttpBuilder.addNetworkInterceptor(interceptor); // } // // public OkHttpClient client() { // OkHttpClient client = mOkHttpBuilder.build(); // org.xdty.http.OkHttp.getInstance().setClient(client); // return client; // } // // private static class SingletonHelper { // private final static OkHttp INSTANCE = new OkHttp(); // } // }
import android.os.StrictMode; import com.facebook.stetho.Stetho; import com.facebook.stetho.okhttp3.StethoInterceptor; import org.xdty.gallery.utils.OkHttp; import io.reactivex.Completable;
package org.xdty.gallery.application; public class DebugApplication extends Application { private final static String TAG = DebugApplication.class.getSimpleName(); @Override public void onCreate() { StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder() .detectAll() .penaltyLog() .build()); StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder() .detectLeakedSqlLiteObjects() .detectLeakedClosableObjects() .penaltyLog() //.penaltyDeath() .build()); Completable.fromRunnable(() -> Stetho.initialize(Stetho.newInitializerBuilder(DebugApplication.this) .enableDumpapp( Stetho.defaultDumperPluginsProvider(DebugApplication.this)) .enableWebKitInspector(Stetho.defaultInspectorModulesProvider( DebugApplication.this)) .build()) ).subscribe();
// Path: app/src/main/java/org/xdty/gallery/utils/OkHttp.java // public class OkHttp { // private OkHttpClient.Builder mOkHttpBuilder; // // private OkHttp() { // HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(); // loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.NONE); // // Interceptor interceptor = new Interceptor() { // @Override // public Response intercept(Chain chain) throws IOException { // Request request = chain.request(); // HttpUrl url = request.url() // .newBuilder() // //.addQueryParameter("timestamp", // // Long.toString(System.currentTimeMillis() / 1000 / 60)) // .build(); // request = request.newBuilder().url(url).build(); // return chain.proceed(request); // } // }; // // mOkHttpBuilder = new OkHttpClient.Builder() // .addInterceptor(loggingInterceptor) // .addInterceptor(interceptor); // } // // public static OkHttp getInstance() { // return SingletonHelper.INSTANCE; // } // // public void addNetworkInterceptor(Interceptor interceptor) { // mOkHttpBuilder.addNetworkInterceptor(interceptor); // } // // public OkHttpClient client() { // OkHttpClient client = mOkHttpBuilder.build(); // org.xdty.http.OkHttp.getInstance().setClient(client); // return client; // } // // private static class SingletonHelper { // private final static OkHttp INSTANCE = new OkHttp(); // } // } // Path: app/src/debug/java/org/xdty/gallery/application/DebugApplication.java import android.os.StrictMode; import com.facebook.stetho.Stetho; import com.facebook.stetho.okhttp3.StethoInterceptor; import org.xdty.gallery.utils.OkHttp; import io.reactivex.Completable; package org.xdty.gallery.application; public class DebugApplication extends Application { private final static String TAG = DebugApplication.class.getSimpleName(); @Override public void onCreate() { StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder() .detectAll() .penaltyLog() .build()); StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder() .detectLeakedSqlLiteObjects() .detectLeakedClosableObjects() .penaltyLog() //.penaltyDeath() .build()); Completable.fromRunnable(() -> Stetho.initialize(Stetho.newInitializerBuilder(DebugApplication.this) .enableDumpapp( Stetho.defaultDumperPluginsProvider(DebugApplication.this)) .enableWebKitInspector(Stetho.defaultInspectorModulesProvider( DebugApplication.this)) .build()) ).subscribe();
OkHttp.getInstance().addNetworkInterceptor(new StethoInterceptor());
xdtianyu/Gallery
app/src/main/java/org/xdty/gallery/model/database/DatabaseImpl.java
// Path: app/src/main/java/org/xdty/gallery/application/Application.java // public class Application extends android.app.Application { // // private static AppComponent sAppComponent; // // @Inject // protected Setting mSetting; // // public static AppComponent getAppComponent() { // return sAppComponent; // } // // @Override // public void onCreate() { // super.onCreate(); // // sAppComponent = DaggerAppComponent.builder().appModule(new AppModule(this)).build(); // sAppComponent.inject(this); // // if (BuildConfig.DEBUG || mSetting.isCatchCrashEnable()) { // CustomActivityOnCrash.install(this); // } // // RxJavaPlugins.setErrorHandler(Throwable::printStackTrace); // } // // }
import org.xdty.gallery.application.Application; import org.xdty.gallery.model.db.Server; import java.util.List; import javax.inject.Inject; import io.reactivex.Observable; import io.reactivex.ObservableOnSubscribe; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.CompositeDisposable; import io.reactivex.schedulers.Schedulers; import io.requery.Persistable; import io.requery.sql.EntityDataStore;
package org.xdty.gallery.model.database; public class DatabaseImpl implements Database { @Inject EntityDataStore<Persistable> mDataStore; private CompositeDisposable mSubscriptions = new CompositeDisposable(); public DatabaseImpl() {
// Path: app/src/main/java/org/xdty/gallery/application/Application.java // public class Application extends android.app.Application { // // private static AppComponent sAppComponent; // // @Inject // protected Setting mSetting; // // public static AppComponent getAppComponent() { // return sAppComponent; // } // // @Override // public void onCreate() { // super.onCreate(); // // sAppComponent = DaggerAppComponent.builder().appModule(new AppModule(this)).build(); // sAppComponent.inject(this); // // if (BuildConfig.DEBUG || mSetting.isCatchCrashEnable()) { // CustomActivityOnCrash.install(this); // } // // RxJavaPlugins.setErrorHandler(Throwable::printStackTrace); // } // // } // Path: app/src/main/java/org/xdty/gallery/model/database/DatabaseImpl.java import org.xdty.gallery.application.Application; import org.xdty.gallery.model.db.Server; import java.util.List; import javax.inject.Inject; import io.reactivex.Observable; import io.reactivex.ObservableOnSubscribe; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.CompositeDisposable; import io.reactivex.schedulers.Schedulers; import io.requery.Persistable; import io.requery.sql.EntityDataStore; package org.xdty.gallery.model.database; public class DatabaseImpl implements Database { @Inject EntityDataStore<Persistable> mDataStore; private CompositeDisposable mSubscriptions = new CompositeDisposable(); public DatabaseImpl() {
Application.getAppComponent().inject(this);
xdtianyu/Gallery
app/src/main/java/org/xdty/gallery/glide/GlideSetup.java
// Path: app/src/main/java/org/xdty/gallery/model/Media.java // public interface Media<T extends Media> { // // String[] scheme(); // // String getName(); // // String getHost(); // // long getLastModified(); // // long length(); // // String getPath(); // // String getParent(); // // void setParent(T parent); // // T parent(); // // void clear(); // // boolean hasImage(); // // List<T> children(); // // int childrenSize(); // // String getUri(); // // InputStream getInputStream() throws IOException; // // boolean isFile(); // // T[] listMedia(); // // boolean isImage(); // // boolean isDirectory(); // // T fromUri(String uri); // // T auth(String domain, String directory, String username, String password); // // int getPosition(); // // void setPosition(int position); // // class MediaException extends RuntimeException { // // public MediaException(String detailMessage) { // super(detailMessage); // } // } // // class NumericComparator implements Comparator<Media> { // // public static NumericComparator factory() { // return SingletonHelper.INSTANCE; // } // // private boolean isDigit(char ch) { // return ch >= 48 && ch <= 57; // } // // /** // * Length of string is passed in for improved efficiency (only need to calculate it once) // **/ // private String getChunk(String s, int length, int marker) { // StringBuilder chunk = new StringBuilder(); // char c = s.charAt(marker); // chunk.append(c); // marker++; // if (isDigit(c)) { // while (marker < length) { // c = s.charAt(marker); // if (!isDigit(c)) { // break; // } // chunk.append(c); // marker++; // } // } else { // while (marker < length) { // c = s.charAt(marker); // if (isDigit(c)) { // break; // } // chunk.append(c); // marker++; // } // } // return chunk.toString(); // } // // @Override // public int compare(Media m1, Media m2) { // String s1 = m1.getName(); // String s2 = m2.getName(); // // return compare(s1, s2); // } // // public int compare(String s1, String s2) { // // int thisMarker = 0; // int thatMarker = 0; // int s1Length = s1.length(); // int s2Length = s2.length(); // // while (thisMarker < s1Length && thatMarker < s2Length) { // String thisChunk = getChunk(s1, s1Length, thisMarker); // thisMarker += thisChunk.length(); // // String thatChunk = getChunk(s2, s2Length, thatMarker); // thatMarker += thatChunk.length(); // // // If both chunks contain numeric characters, sort them numerically // int result = 0; // if (isDigit(thisChunk.charAt(0)) && isDigit(thatChunk.charAt(0))) { // // Simple chunk comparison by length. // int thisChunkLength = thisChunk.length(); // result = thisChunkLength - thatChunk.length(); // // If equal, the first different number counts // if (result == 0) { // for (int i = 0; i < thisChunkLength; i++) { // result = thisChunk.charAt(i) - thatChunk.charAt(i); // if (result != 0) { // return result; // } // } // } // } else { // result = thisChunk.compareTo(thatChunk); // } // // if (result != 0) { // return result; // } // } // // return s1Length - s2Length; // } // // private final static class SingletonHelper { // private final static NumericComparator INSTANCE = new NumericComparator(); // } // } // // }
import android.content.Context; import com.bumptech.glide.Glide; import com.bumptech.glide.GlideBuilder; import com.bumptech.glide.load.DecodeFormat; import com.bumptech.glide.load.engine.cache.InternalCacheDiskCacheFactory; import com.bumptech.glide.load.engine.executor.FifoPriorityThreadPoolExecutor; import com.bumptech.glide.module.GlideModule; import org.xdty.gallery.model.Media; import java.io.InputStream;
package org.xdty.gallery.glide; public class GlideSetup implements GlideModule { @Override public void applyOptions(Context context, GlideBuilder builder) { //builder.setMemoryCache(new LruResourceCache(64 * 1024 * 1024)); //builder.setBitmapPool(new LruBitmapPool(32 * 1024 * 1024)); builder.setDecodeFormat(DecodeFormat.PREFER_ARGB_8888); builder.setDiskCache(new InternalCacheDiskCacheFactory(context, 2147483647)); builder.setResizeService(new FifoPriorityThreadPoolExecutor(2)); } @Override public void registerComponents(Context context, Glide glide) {
// Path: app/src/main/java/org/xdty/gallery/model/Media.java // public interface Media<T extends Media> { // // String[] scheme(); // // String getName(); // // String getHost(); // // long getLastModified(); // // long length(); // // String getPath(); // // String getParent(); // // void setParent(T parent); // // T parent(); // // void clear(); // // boolean hasImage(); // // List<T> children(); // // int childrenSize(); // // String getUri(); // // InputStream getInputStream() throws IOException; // // boolean isFile(); // // T[] listMedia(); // // boolean isImage(); // // boolean isDirectory(); // // T fromUri(String uri); // // T auth(String domain, String directory, String username, String password); // // int getPosition(); // // void setPosition(int position); // // class MediaException extends RuntimeException { // // public MediaException(String detailMessage) { // super(detailMessage); // } // } // // class NumericComparator implements Comparator<Media> { // // public static NumericComparator factory() { // return SingletonHelper.INSTANCE; // } // // private boolean isDigit(char ch) { // return ch >= 48 && ch <= 57; // } // // /** // * Length of string is passed in for improved efficiency (only need to calculate it once) // **/ // private String getChunk(String s, int length, int marker) { // StringBuilder chunk = new StringBuilder(); // char c = s.charAt(marker); // chunk.append(c); // marker++; // if (isDigit(c)) { // while (marker < length) { // c = s.charAt(marker); // if (!isDigit(c)) { // break; // } // chunk.append(c); // marker++; // } // } else { // while (marker < length) { // c = s.charAt(marker); // if (isDigit(c)) { // break; // } // chunk.append(c); // marker++; // } // } // return chunk.toString(); // } // // @Override // public int compare(Media m1, Media m2) { // String s1 = m1.getName(); // String s2 = m2.getName(); // // return compare(s1, s2); // } // // public int compare(String s1, String s2) { // // int thisMarker = 0; // int thatMarker = 0; // int s1Length = s1.length(); // int s2Length = s2.length(); // // while (thisMarker < s1Length && thatMarker < s2Length) { // String thisChunk = getChunk(s1, s1Length, thisMarker); // thisMarker += thisChunk.length(); // // String thatChunk = getChunk(s2, s2Length, thatMarker); // thatMarker += thatChunk.length(); // // // If both chunks contain numeric characters, sort them numerically // int result = 0; // if (isDigit(thisChunk.charAt(0)) && isDigit(thatChunk.charAt(0))) { // // Simple chunk comparison by length. // int thisChunkLength = thisChunk.length(); // result = thisChunkLength - thatChunk.length(); // // If equal, the first different number counts // if (result == 0) { // for (int i = 0; i < thisChunkLength; i++) { // result = thisChunk.charAt(i) - thatChunk.charAt(i); // if (result != 0) { // return result; // } // } // } // } else { // result = thisChunk.compareTo(thatChunk); // } // // if (result != 0) { // return result; // } // } // // return s1Length - s2Length; // } // // private final static class SingletonHelper { // private final static NumericComparator INSTANCE = new NumericComparator(); // } // } // // } // Path: app/src/main/java/org/xdty/gallery/glide/GlideSetup.java import android.content.Context; import com.bumptech.glide.Glide; import com.bumptech.glide.GlideBuilder; import com.bumptech.glide.load.DecodeFormat; import com.bumptech.glide.load.engine.cache.InternalCacheDiskCacheFactory; import com.bumptech.glide.load.engine.executor.FifoPriorityThreadPoolExecutor; import com.bumptech.glide.module.GlideModule; import org.xdty.gallery.model.Media; import java.io.InputStream; package org.xdty.gallery.glide; public class GlideSetup implements GlideModule { @Override public void applyOptions(Context context, GlideBuilder builder) { //builder.setMemoryCache(new LruResourceCache(64 * 1024 * 1024)); //builder.setBitmapPool(new LruBitmapPool(32 * 1024 * 1024)); builder.setDecodeFormat(DecodeFormat.PREFER_ARGB_8888); builder.setDiskCache(new InternalCacheDiskCacheFactory(context, 2147483647)); builder.setResizeService(new FifoPriorityThreadPoolExecutor(2)); } @Override public void registerComponents(Context context, Glide glide) {
glide.register(Media.class, InputStream.class, new MediaLoader.Factory());
xdtianyu/Gallery
photoview/src/main/java/uk/co/senab/photoview/PhotoView.java
// Path: photoview/src/main/java/uk/co/senab/photoview/PhotoViewAttacher.java // public interface OnMatrixChangedListener { // /** // * Callback for when the Matrix displaying the Drawable has changed. This could be because // * the View's bounds have changed, or the user has zoomed. // * // * @param rect - Rectangle displaying the Drawable's new bounds. // */ // void onMatrixChanged(RectF rect); // } // // Path: photoview/src/main/java/uk/co/senab/photoview/PhotoViewAttacher.java // public interface OnPhotoTapListener { // // /** // * A callback to receive where the user taps on a photo. You will only receive a callback // * if // * the user taps on the actual photo, tapping on 'whitespace' will be ignored. // * // * @param view - View the user tapped. // * @param x - where the user tapped from the of the Drawable, as percentage of the // * Drawable width. // * @param y - where the user tapped from the top of the Drawable, as percentage of the // * Drawable height. // */ // void onPhotoTap(View view, float x, float y); // // /** // * A simple callback where out of photo happened; // */ // void onOutsidePhotoTap(); // } // // Path: photoview/src/main/java/uk/co/senab/photoview/PhotoViewAttacher.java // public interface OnViewTapListener { // // /** // * A callback to receive where the user taps on a ImageView. You will receive a callback if // * the user taps anywhere on the view, tapping on 'whitespace' will not be ignored. // * // * @param view - View the user tapped. // * @param x - where the user tapped from the left of the View. // * @param y - where the user tapped from the top of the View. // */ // void onViewTap(View view, float x, float y); // }
import android.content.Context; import android.graphics.Bitmap; import android.graphics.Matrix; import android.graphics.RectF; import android.graphics.drawable.Drawable; import android.net.Uri; import android.util.AttributeSet; import android.view.GestureDetector; import android.widget.ImageView; import uk.co.senab.photoview.PhotoViewAttacher.OnMatrixChangedListener; import uk.co.senab.photoview.PhotoViewAttacher.OnPhotoTapListener; import uk.co.senab.photoview.PhotoViewAttacher.OnViewTapListener;
mAttacher.update(); } } @Override public void setImageResource(int resId) { super.setImageResource(resId); if (null != mAttacher) { mAttacher.update(); } } @Override public void setImageURI(Uri uri) { super.setImageURI(uri); if (null != mAttacher) { mAttacher.update(); } } @Override protected boolean setFrame(int l, int t, int r, int b) { boolean changed = super.setFrame(l, t, r, b); if (null != mAttacher) { mAttacher.update(); } return changed; } @Override
// Path: photoview/src/main/java/uk/co/senab/photoview/PhotoViewAttacher.java // public interface OnMatrixChangedListener { // /** // * Callback for when the Matrix displaying the Drawable has changed. This could be because // * the View's bounds have changed, or the user has zoomed. // * // * @param rect - Rectangle displaying the Drawable's new bounds. // */ // void onMatrixChanged(RectF rect); // } // // Path: photoview/src/main/java/uk/co/senab/photoview/PhotoViewAttacher.java // public interface OnPhotoTapListener { // // /** // * A callback to receive where the user taps on a photo. You will only receive a callback // * if // * the user taps on the actual photo, tapping on 'whitespace' will be ignored. // * // * @param view - View the user tapped. // * @param x - where the user tapped from the of the Drawable, as percentage of the // * Drawable width. // * @param y - where the user tapped from the top of the Drawable, as percentage of the // * Drawable height. // */ // void onPhotoTap(View view, float x, float y); // // /** // * A simple callback where out of photo happened; // */ // void onOutsidePhotoTap(); // } // // Path: photoview/src/main/java/uk/co/senab/photoview/PhotoViewAttacher.java // public interface OnViewTapListener { // // /** // * A callback to receive where the user taps on a ImageView. You will receive a callback if // * the user taps anywhere on the view, tapping on 'whitespace' will not be ignored. // * // * @param view - View the user tapped. // * @param x - where the user tapped from the left of the View. // * @param y - where the user tapped from the top of the View. // */ // void onViewTap(View view, float x, float y); // } // Path: photoview/src/main/java/uk/co/senab/photoview/PhotoView.java import android.content.Context; import android.graphics.Bitmap; import android.graphics.Matrix; import android.graphics.RectF; import android.graphics.drawable.Drawable; import android.net.Uri; import android.util.AttributeSet; import android.view.GestureDetector; import android.widget.ImageView; import uk.co.senab.photoview.PhotoViewAttacher.OnMatrixChangedListener; import uk.co.senab.photoview.PhotoViewAttacher.OnPhotoTapListener; import uk.co.senab.photoview.PhotoViewAttacher.OnViewTapListener; mAttacher.update(); } } @Override public void setImageResource(int resId) { super.setImageResource(resId); if (null != mAttacher) { mAttacher.update(); } } @Override public void setImageURI(Uri uri) { super.setImageURI(uri); if (null != mAttacher) { mAttacher.update(); } } @Override protected boolean setFrame(int l, int t, int r, int b) { boolean changed = super.setFrame(l, t, r, b); if (null != mAttacher) { mAttacher.update(); } return changed; } @Override
public void setOnMatrixChangeListener(OnMatrixChangedListener listener) {
xdtianyu/Gallery
photoview/src/main/java/uk/co/senab/photoview/PhotoView.java
// Path: photoview/src/main/java/uk/co/senab/photoview/PhotoViewAttacher.java // public interface OnMatrixChangedListener { // /** // * Callback for when the Matrix displaying the Drawable has changed. This could be because // * the View's bounds have changed, or the user has zoomed. // * // * @param rect - Rectangle displaying the Drawable's new bounds. // */ // void onMatrixChanged(RectF rect); // } // // Path: photoview/src/main/java/uk/co/senab/photoview/PhotoViewAttacher.java // public interface OnPhotoTapListener { // // /** // * A callback to receive where the user taps on a photo. You will only receive a callback // * if // * the user taps on the actual photo, tapping on 'whitespace' will be ignored. // * // * @param view - View the user tapped. // * @param x - where the user tapped from the of the Drawable, as percentage of the // * Drawable width. // * @param y - where the user tapped from the top of the Drawable, as percentage of the // * Drawable height. // */ // void onPhotoTap(View view, float x, float y); // // /** // * A simple callback where out of photo happened; // */ // void onOutsidePhotoTap(); // } // // Path: photoview/src/main/java/uk/co/senab/photoview/PhotoViewAttacher.java // public interface OnViewTapListener { // // /** // * A callback to receive where the user taps on a ImageView. You will receive a callback if // * the user taps anywhere on the view, tapping on 'whitespace' will not be ignored. // * // * @param view - View the user tapped. // * @param x - where the user tapped from the left of the View. // * @param y - where the user tapped from the top of the View. // */ // void onViewTap(View view, float x, float y); // }
import android.content.Context; import android.graphics.Bitmap; import android.graphics.Matrix; import android.graphics.RectF; import android.graphics.drawable.Drawable; import android.net.Uri; import android.util.AttributeSet; import android.view.GestureDetector; import android.widget.ImageView; import uk.co.senab.photoview.PhotoViewAttacher.OnMatrixChangedListener; import uk.co.senab.photoview.PhotoViewAttacher.OnPhotoTapListener; import uk.co.senab.photoview.PhotoViewAttacher.OnViewTapListener;
} @Override public void setImageURI(Uri uri) { super.setImageURI(uri); if (null != mAttacher) { mAttacher.update(); } } @Override protected boolean setFrame(int l, int t, int r, int b) { boolean changed = super.setFrame(l, t, r, b); if (null != mAttacher) { mAttacher.update(); } return changed; } @Override public void setOnMatrixChangeListener(OnMatrixChangedListener listener) { mAttacher.setOnMatrixChangeListener(listener); } @Override public void setOnLongClickListener(OnLongClickListener l) { mAttacher.setOnLongClickListener(l); } @Override
// Path: photoview/src/main/java/uk/co/senab/photoview/PhotoViewAttacher.java // public interface OnMatrixChangedListener { // /** // * Callback for when the Matrix displaying the Drawable has changed. This could be because // * the View's bounds have changed, or the user has zoomed. // * // * @param rect - Rectangle displaying the Drawable's new bounds. // */ // void onMatrixChanged(RectF rect); // } // // Path: photoview/src/main/java/uk/co/senab/photoview/PhotoViewAttacher.java // public interface OnPhotoTapListener { // // /** // * A callback to receive where the user taps on a photo. You will only receive a callback // * if // * the user taps on the actual photo, tapping on 'whitespace' will be ignored. // * // * @param view - View the user tapped. // * @param x - where the user tapped from the of the Drawable, as percentage of the // * Drawable width. // * @param y - where the user tapped from the top of the Drawable, as percentage of the // * Drawable height. // */ // void onPhotoTap(View view, float x, float y); // // /** // * A simple callback where out of photo happened; // */ // void onOutsidePhotoTap(); // } // // Path: photoview/src/main/java/uk/co/senab/photoview/PhotoViewAttacher.java // public interface OnViewTapListener { // // /** // * A callback to receive where the user taps on a ImageView. You will receive a callback if // * the user taps anywhere on the view, tapping on 'whitespace' will not be ignored. // * // * @param view - View the user tapped. // * @param x - where the user tapped from the left of the View. // * @param y - where the user tapped from the top of the View. // */ // void onViewTap(View view, float x, float y); // } // Path: photoview/src/main/java/uk/co/senab/photoview/PhotoView.java import android.content.Context; import android.graphics.Bitmap; import android.graphics.Matrix; import android.graphics.RectF; import android.graphics.drawable.Drawable; import android.net.Uri; import android.util.AttributeSet; import android.view.GestureDetector; import android.widget.ImageView; import uk.co.senab.photoview.PhotoViewAttacher.OnMatrixChangedListener; import uk.co.senab.photoview.PhotoViewAttacher.OnPhotoTapListener; import uk.co.senab.photoview.PhotoViewAttacher.OnViewTapListener; } @Override public void setImageURI(Uri uri) { super.setImageURI(uri); if (null != mAttacher) { mAttacher.update(); } } @Override protected boolean setFrame(int l, int t, int r, int b) { boolean changed = super.setFrame(l, t, r, b); if (null != mAttacher) { mAttacher.update(); } return changed; } @Override public void setOnMatrixChangeListener(OnMatrixChangedListener listener) { mAttacher.setOnMatrixChangeListener(listener); } @Override public void setOnLongClickListener(OnLongClickListener l) { mAttacher.setOnLongClickListener(l); } @Override
public void setOnPhotoTapListener(OnPhotoTapListener listener) {
xdtianyu/Gallery
photoview/src/main/java/uk/co/senab/photoview/PhotoView.java
// Path: photoview/src/main/java/uk/co/senab/photoview/PhotoViewAttacher.java // public interface OnMatrixChangedListener { // /** // * Callback for when the Matrix displaying the Drawable has changed. This could be because // * the View's bounds have changed, or the user has zoomed. // * // * @param rect - Rectangle displaying the Drawable's new bounds. // */ // void onMatrixChanged(RectF rect); // } // // Path: photoview/src/main/java/uk/co/senab/photoview/PhotoViewAttacher.java // public interface OnPhotoTapListener { // // /** // * A callback to receive where the user taps on a photo. You will only receive a callback // * if // * the user taps on the actual photo, tapping on 'whitespace' will be ignored. // * // * @param view - View the user tapped. // * @param x - where the user tapped from the of the Drawable, as percentage of the // * Drawable width. // * @param y - where the user tapped from the top of the Drawable, as percentage of the // * Drawable height. // */ // void onPhotoTap(View view, float x, float y); // // /** // * A simple callback where out of photo happened; // */ // void onOutsidePhotoTap(); // } // // Path: photoview/src/main/java/uk/co/senab/photoview/PhotoViewAttacher.java // public interface OnViewTapListener { // // /** // * A callback to receive where the user taps on a ImageView. You will receive a callback if // * the user taps anywhere on the view, tapping on 'whitespace' will not be ignored. // * // * @param view - View the user tapped. // * @param x - where the user tapped from the left of the View. // * @param y - where the user tapped from the top of the View. // */ // void onViewTap(View view, float x, float y); // }
import android.content.Context; import android.graphics.Bitmap; import android.graphics.Matrix; import android.graphics.RectF; import android.graphics.drawable.Drawable; import android.net.Uri; import android.util.AttributeSet; import android.view.GestureDetector; import android.widget.ImageView; import uk.co.senab.photoview.PhotoViewAttacher.OnMatrixChangedListener; import uk.co.senab.photoview.PhotoViewAttacher.OnPhotoTapListener; import uk.co.senab.photoview.PhotoViewAttacher.OnViewTapListener;
if (null != mAttacher) { mAttacher.update(); } } @Override protected boolean setFrame(int l, int t, int r, int b) { boolean changed = super.setFrame(l, t, r, b); if (null != mAttacher) { mAttacher.update(); } return changed; } @Override public void setOnMatrixChangeListener(OnMatrixChangedListener listener) { mAttacher.setOnMatrixChangeListener(listener); } @Override public void setOnLongClickListener(OnLongClickListener l) { mAttacher.setOnLongClickListener(l); } @Override public void setOnPhotoTapListener(OnPhotoTapListener listener) { mAttacher.setOnPhotoTapListener(listener); } @Override
// Path: photoview/src/main/java/uk/co/senab/photoview/PhotoViewAttacher.java // public interface OnMatrixChangedListener { // /** // * Callback for when the Matrix displaying the Drawable has changed. This could be because // * the View's bounds have changed, or the user has zoomed. // * // * @param rect - Rectangle displaying the Drawable's new bounds. // */ // void onMatrixChanged(RectF rect); // } // // Path: photoview/src/main/java/uk/co/senab/photoview/PhotoViewAttacher.java // public interface OnPhotoTapListener { // // /** // * A callback to receive where the user taps on a photo. You will only receive a callback // * if // * the user taps on the actual photo, tapping on 'whitespace' will be ignored. // * // * @param view - View the user tapped. // * @param x - where the user tapped from the of the Drawable, as percentage of the // * Drawable width. // * @param y - where the user tapped from the top of the Drawable, as percentage of the // * Drawable height. // */ // void onPhotoTap(View view, float x, float y); // // /** // * A simple callback where out of photo happened; // */ // void onOutsidePhotoTap(); // } // // Path: photoview/src/main/java/uk/co/senab/photoview/PhotoViewAttacher.java // public interface OnViewTapListener { // // /** // * A callback to receive where the user taps on a ImageView. You will receive a callback if // * the user taps anywhere on the view, tapping on 'whitespace' will not be ignored. // * // * @param view - View the user tapped. // * @param x - where the user tapped from the left of the View. // * @param y - where the user tapped from the top of the View. // */ // void onViewTap(View view, float x, float y); // } // Path: photoview/src/main/java/uk/co/senab/photoview/PhotoView.java import android.content.Context; import android.graphics.Bitmap; import android.graphics.Matrix; import android.graphics.RectF; import android.graphics.drawable.Drawable; import android.net.Uri; import android.util.AttributeSet; import android.view.GestureDetector; import android.widget.ImageView; import uk.co.senab.photoview.PhotoViewAttacher.OnMatrixChangedListener; import uk.co.senab.photoview.PhotoViewAttacher.OnPhotoTapListener; import uk.co.senab.photoview.PhotoViewAttacher.OnViewTapListener; if (null != mAttacher) { mAttacher.update(); } } @Override protected boolean setFrame(int l, int t, int r, int b) { boolean changed = super.setFrame(l, t, r, b); if (null != mAttacher) { mAttacher.update(); } return changed; } @Override public void setOnMatrixChangeListener(OnMatrixChangedListener listener) { mAttacher.setOnMatrixChangeListener(listener); } @Override public void setOnLongClickListener(OnLongClickListener l) { mAttacher.setOnLongClickListener(l); } @Override public void setOnPhotoTapListener(OnPhotoTapListener listener) { mAttacher.setOnPhotoTapListener(listener); } @Override
public void setOnViewTapListener(OnViewTapListener listener) {
xdtianyu/Gallery
app/src/main/java/org/xdty/gallery/application/Application.java
// Path: app/src/main/java/org/xdty/gallery/di/AppComponent.java // @Singleton // @Component(modules = AppModule.class) // public interface AppComponent { // void inject(Application application); // // void inject(MainPresenter mainPresenter); // // void inject(ViewerPresenter viewerPresenter); // // void inject(GalleryAdapter galleryAdapter); // // void inject(DatabaseImpl database); // } // // Path: app/src/main/java/org/xdty/gallery/di/modules/AppModule.java // @Module // public class AppModule { // // private Application mApplication; // // public AppModule(Application application) { // mApplication = application; // } // // @Singleton // @Provides // Context provideContext() { // return mApplication; // } // // @Singleton // @Provides // Application provideApplication() { // return mApplication; // } // // @Singleton // @Provides // Setting provideSetting() { // return new SettingImpl(mApplication); // } // // @Singleton // @Provides // Gson provideGson() { // return new Gson(); // } // // @Singleton // @Provides // MediaDataSource provideMediaDataSource() { // return new MediaRepository(); // } // // @Singleton // @Provides // public OkHttpClient provideOkHttpClient() { // return OkHttp.getInstance().client(); // } // // @Singleton // @Provides // public Database provideDatabase() { // return DatabaseImpl.getInstance(); // } // // @Singleton // @Provides // public EntityDataStore<Persistable> provideDatabaseSource() { // // DatabaseSource source = new DatabaseSource(mApplication, Models.DEFAULT, DB_NAME, // DB_VERSION); // source.setLoggingEnabled(BuildConfig.DEBUG); // Configuration configuration = source.getConfiguration(); // // return new EntityDataStore<>(configuration); // } // // } // // Path: app/src/main/java/org/xdty/gallery/setting/Setting.java // public interface Setting { // // boolean isCatchCrashEnable(); // // Set<String> getServers(); // // void addServer(String server); // // String getLocalPath(); // // }
import org.xdty.gallery.BuildConfig; import org.xdty.gallery.di.AppComponent; import org.xdty.gallery.di.DaggerAppComponent; import org.xdty.gallery.di.modules.AppModule; import org.xdty.gallery.setting.Setting; import javax.inject.Inject; import cat.ereza.customactivityoncrash.CustomActivityOnCrash; import io.reactivex.plugins.RxJavaPlugins;
package org.xdty.gallery.application; public class Application extends android.app.Application { private static AppComponent sAppComponent; @Inject
// Path: app/src/main/java/org/xdty/gallery/di/AppComponent.java // @Singleton // @Component(modules = AppModule.class) // public interface AppComponent { // void inject(Application application); // // void inject(MainPresenter mainPresenter); // // void inject(ViewerPresenter viewerPresenter); // // void inject(GalleryAdapter galleryAdapter); // // void inject(DatabaseImpl database); // } // // Path: app/src/main/java/org/xdty/gallery/di/modules/AppModule.java // @Module // public class AppModule { // // private Application mApplication; // // public AppModule(Application application) { // mApplication = application; // } // // @Singleton // @Provides // Context provideContext() { // return mApplication; // } // // @Singleton // @Provides // Application provideApplication() { // return mApplication; // } // // @Singleton // @Provides // Setting provideSetting() { // return new SettingImpl(mApplication); // } // // @Singleton // @Provides // Gson provideGson() { // return new Gson(); // } // // @Singleton // @Provides // MediaDataSource provideMediaDataSource() { // return new MediaRepository(); // } // // @Singleton // @Provides // public OkHttpClient provideOkHttpClient() { // return OkHttp.getInstance().client(); // } // // @Singleton // @Provides // public Database provideDatabase() { // return DatabaseImpl.getInstance(); // } // // @Singleton // @Provides // public EntityDataStore<Persistable> provideDatabaseSource() { // // DatabaseSource source = new DatabaseSource(mApplication, Models.DEFAULT, DB_NAME, // DB_VERSION); // source.setLoggingEnabled(BuildConfig.DEBUG); // Configuration configuration = source.getConfiguration(); // // return new EntityDataStore<>(configuration); // } // // } // // Path: app/src/main/java/org/xdty/gallery/setting/Setting.java // public interface Setting { // // boolean isCatchCrashEnable(); // // Set<String> getServers(); // // void addServer(String server); // // String getLocalPath(); // // } // Path: app/src/main/java/org/xdty/gallery/application/Application.java import org.xdty.gallery.BuildConfig; import org.xdty.gallery.di.AppComponent; import org.xdty.gallery.di.DaggerAppComponent; import org.xdty.gallery.di.modules.AppModule; import org.xdty.gallery.setting.Setting; import javax.inject.Inject; import cat.ereza.customactivityoncrash.CustomActivityOnCrash; import io.reactivex.plugins.RxJavaPlugins; package org.xdty.gallery.application; public class Application extends android.app.Application { private static AppComponent sAppComponent; @Inject
protected Setting mSetting;
xdtianyu/Gallery
app/src/main/java/org/xdty/gallery/application/Application.java
// Path: app/src/main/java/org/xdty/gallery/di/AppComponent.java // @Singleton // @Component(modules = AppModule.class) // public interface AppComponent { // void inject(Application application); // // void inject(MainPresenter mainPresenter); // // void inject(ViewerPresenter viewerPresenter); // // void inject(GalleryAdapter galleryAdapter); // // void inject(DatabaseImpl database); // } // // Path: app/src/main/java/org/xdty/gallery/di/modules/AppModule.java // @Module // public class AppModule { // // private Application mApplication; // // public AppModule(Application application) { // mApplication = application; // } // // @Singleton // @Provides // Context provideContext() { // return mApplication; // } // // @Singleton // @Provides // Application provideApplication() { // return mApplication; // } // // @Singleton // @Provides // Setting provideSetting() { // return new SettingImpl(mApplication); // } // // @Singleton // @Provides // Gson provideGson() { // return new Gson(); // } // // @Singleton // @Provides // MediaDataSource provideMediaDataSource() { // return new MediaRepository(); // } // // @Singleton // @Provides // public OkHttpClient provideOkHttpClient() { // return OkHttp.getInstance().client(); // } // // @Singleton // @Provides // public Database provideDatabase() { // return DatabaseImpl.getInstance(); // } // // @Singleton // @Provides // public EntityDataStore<Persistable> provideDatabaseSource() { // // DatabaseSource source = new DatabaseSource(mApplication, Models.DEFAULT, DB_NAME, // DB_VERSION); // source.setLoggingEnabled(BuildConfig.DEBUG); // Configuration configuration = source.getConfiguration(); // // return new EntityDataStore<>(configuration); // } // // } // // Path: app/src/main/java/org/xdty/gallery/setting/Setting.java // public interface Setting { // // boolean isCatchCrashEnable(); // // Set<String> getServers(); // // void addServer(String server); // // String getLocalPath(); // // }
import org.xdty.gallery.BuildConfig; import org.xdty.gallery.di.AppComponent; import org.xdty.gallery.di.DaggerAppComponent; import org.xdty.gallery.di.modules.AppModule; import org.xdty.gallery.setting.Setting; import javax.inject.Inject; import cat.ereza.customactivityoncrash.CustomActivityOnCrash; import io.reactivex.plugins.RxJavaPlugins;
package org.xdty.gallery.application; public class Application extends android.app.Application { private static AppComponent sAppComponent; @Inject protected Setting mSetting; public static AppComponent getAppComponent() { return sAppComponent; } @Override public void onCreate() { super.onCreate();
// Path: app/src/main/java/org/xdty/gallery/di/AppComponent.java // @Singleton // @Component(modules = AppModule.class) // public interface AppComponent { // void inject(Application application); // // void inject(MainPresenter mainPresenter); // // void inject(ViewerPresenter viewerPresenter); // // void inject(GalleryAdapter galleryAdapter); // // void inject(DatabaseImpl database); // } // // Path: app/src/main/java/org/xdty/gallery/di/modules/AppModule.java // @Module // public class AppModule { // // private Application mApplication; // // public AppModule(Application application) { // mApplication = application; // } // // @Singleton // @Provides // Context provideContext() { // return mApplication; // } // // @Singleton // @Provides // Application provideApplication() { // return mApplication; // } // // @Singleton // @Provides // Setting provideSetting() { // return new SettingImpl(mApplication); // } // // @Singleton // @Provides // Gson provideGson() { // return new Gson(); // } // // @Singleton // @Provides // MediaDataSource provideMediaDataSource() { // return new MediaRepository(); // } // // @Singleton // @Provides // public OkHttpClient provideOkHttpClient() { // return OkHttp.getInstance().client(); // } // // @Singleton // @Provides // public Database provideDatabase() { // return DatabaseImpl.getInstance(); // } // // @Singleton // @Provides // public EntityDataStore<Persistable> provideDatabaseSource() { // // DatabaseSource source = new DatabaseSource(mApplication, Models.DEFAULT, DB_NAME, // DB_VERSION); // source.setLoggingEnabled(BuildConfig.DEBUG); // Configuration configuration = source.getConfiguration(); // // return new EntityDataStore<>(configuration); // } // // } // // Path: app/src/main/java/org/xdty/gallery/setting/Setting.java // public interface Setting { // // boolean isCatchCrashEnable(); // // Set<String> getServers(); // // void addServer(String server); // // String getLocalPath(); // // } // Path: app/src/main/java/org/xdty/gallery/application/Application.java import org.xdty.gallery.BuildConfig; import org.xdty.gallery.di.AppComponent; import org.xdty.gallery.di.DaggerAppComponent; import org.xdty.gallery.di.modules.AppModule; import org.xdty.gallery.setting.Setting; import javax.inject.Inject; import cat.ereza.customactivityoncrash.CustomActivityOnCrash; import io.reactivex.plugins.RxJavaPlugins; package org.xdty.gallery.application; public class Application extends android.app.Application { private static AppComponent sAppComponent; @Inject protected Setting mSetting; public static AppComponent getAppComponent() { return sAppComponent; } @Override public void onCreate() { super.onCreate();
sAppComponent = DaggerAppComponent.builder().appModule(new AppModule(this)).build();
xdtianyu/Gallery
app/src/main/java/org/xdty/gallery/glide/MediaDataFetcher.java
// Path: app/src/main/java/org/xdty/gallery/model/Media.java // public interface Media<T extends Media> { // // String[] scheme(); // // String getName(); // // String getHost(); // // long getLastModified(); // // long length(); // // String getPath(); // // String getParent(); // // void setParent(T parent); // // T parent(); // // void clear(); // // boolean hasImage(); // // List<T> children(); // // int childrenSize(); // // String getUri(); // // InputStream getInputStream() throws IOException; // // boolean isFile(); // // T[] listMedia(); // // boolean isImage(); // // boolean isDirectory(); // // T fromUri(String uri); // // T auth(String domain, String directory, String username, String password); // // int getPosition(); // // void setPosition(int position); // // class MediaException extends RuntimeException { // // public MediaException(String detailMessage) { // super(detailMessage); // } // } // // class NumericComparator implements Comparator<Media> { // // public static NumericComparator factory() { // return SingletonHelper.INSTANCE; // } // // private boolean isDigit(char ch) { // return ch >= 48 && ch <= 57; // } // // /** // * Length of string is passed in for improved efficiency (only need to calculate it once) // **/ // private String getChunk(String s, int length, int marker) { // StringBuilder chunk = new StringBuilder(); // char c = s.charAt(marker); // chunk.append(c); // marker++; // if (isDigit(c)) { // while (marker < length) { // c = s.charAt(marker); // if (!isDigit(c)) { // break; // } // chunk.append(c); // marker++; // } // } else { // while (marker < length) { // c = s.charAt(marker); // if (isDigit(c)) { // break; // } // chunk.append(c); // marker++; // } // } // return chunk.toString(); // } // // @Override // public int compare(Media m1, Media m2) { // String s1 = m1.getName(); // String s2 = m2.getName(); // // return compare(s1, s2); // } // // public int compare(String s1, String s2) { // // int thisMarker = 0; // int thatMarker = 0; // int s1Length = s1.length(); // int s2Length = s2.length(); // // while (thisMarker < s1Length && thatMarker < s2Length) { // String thisChunk = getChunk(s1, s1Length, thisMarker); // thisMarker += thisChunk.length(); // // String thatChunk = getChunk(s2, s2Length, thatMarker); // thatMarker += thatChunk.length(); // // // If both chunks contain numeric characters, sort them numerically // int result = 0; // if (isDigit(thisChunk.charAt(0)) && isDigit(thatChunk.charAt(0))) { // // Simple chunk comparison by length. // int thisChunkLength = thisChunk.length(); // result = thisChunkLength - thatChunk.length(); // // If equal, the first different number counts // if (result == 0) { // for (int i = 0; i < thisChunkLength; i++) { // result = thisChunk.charAt(i) - thatChunk.charAt(i); // if (result != 0) { // return result; // } // } // } // } else { // result = thisChunk.compareTo(thatChunk); // } // // if (result != 0) { // return result; // } // } // // return s1Length - s2Length; // } // // private final static class SingletonHelper { // private final static NumericComparator INSTANCE = new NumericComparator(); // } // } // // }
import android.content.Context; import android.util.Log; import com.bumptech.glide.Priority; import com.bumptech.glide.load.data.DataFetcher; import org.xdty.gallery.model.Media; import java.io.IOException; import java.io.InputStream; import java.util.List;
package org.xdty.gallery.glide; public class MediaDataFetcher implements DataFetcher<InputStream> { private static final String TAG = MediaDataFetcher.class.getSimpleName();
// Path: app/src/main/java/org/xdty/gallery/model/Media.java // public interface Media<T extends Media> { // // String[] scheme(); // // String getName(); // // String getHost(); // // long getLastModified(); // // long length(); // // String getPath(); // // String getParent(); // // void setParent(T parent); // // T parent(); // // void clear(); // // boolean hasImage(); // // List<T> children(); // // int childrenSize(); // // String getUri(); // // InputStream getInputStream() throws IOException; // // boolean isFile(); // // T[] listMedia(); // // boolean isImage(); // // boolean isDirectory(); // // T fromUri(String uri); // // T auth(String domain, String directory, String username, String password); // // int getPosition(); // // void setPosition(int position); // // class MediaException extends RuntimeException { // // public MediaException(String detailMessage) { // super(detailMessage); // } // } // // class NumericComparator implements Comparator<Media> { // // public static NumericComparator factory() { // return SingletonHelper.INSTANCE; // } // // private boolean isDigit(char ch) { // return ch >= 48 && ch <= 57; // } // // /** // * Length of string is passed in for improved efficiency (only need to calculate it once) // **/ // private String getChunk(String s, int length, int marker) { // StringBuilder chunk = new StringBuilder(); // char c = s.charAt(marker); // chunk.append(c); // marker++; // if (isDigit(c)) { // while (marker < length) { // c = s.charAt(marker); // if (!isDigit(c)) { // break; // } // chunk.append(c); // marker++; // } // } else { // while (marker < length) { // c = s.charAt(marker); // if (isDigit(c)) { // break; // } // chunk.append(c); // marker++; // } // } // return chunk.toString(); // } // // @Override // public int compare(Media m1, Media m2) { // String s1 = m1.getName(); // String s2 = m2.getName(); // // return compare(s1, s2); // } // // public int compare(String s1, String s2) { // // int thisMarker = 0; // int thatMarker = 0; // int s1Length = s1.length(); // int s2Length = s2.length(); // // while (thisMarker < s1Length && thatMarker < s2Length) { // String thisChunk = getChunk(s1, s1Length, thisMarker); // thisMarker += thisChunk.length(); // // String thatChunk = getChunk(s2, s2Length, thatMarker); // thatMarker += thatChunk.length(); // // // If both chunks contain numeric characters, sort them numerically // int result = 0; // if (isDigit(thisChunk.charAt(0)) && isDigit(thatChunk.charAt(0))) { // // Simple chunk comparison by length. // int thisChunkLength = thisChunk.length(); // result = thisChunkLength - thatChunk.length(); // // If equal, the first different number counts // if (result == 0) { // for (int i = 0; i < thisChunkLength; i++) { // result = thisChunk.charAt(i) - thatChunk.charAt(i); // if (result != 0) { // return result; // } // } // } // } else { // result = thisChunk.compareTo(thatChunk); // } // // if (result != 0) { // return result; // } // } // // return s1Length - s2Length; // } // // private final static class SingletonHelper { // private final static NumericComparator INSTANCE = new NumericComparator(); // } // } // // } // Path: app/src/main/java/org/xdty/gallery/glide/MediaDataFetcher.java import android.content.Context; import android.util.Log; import com.bumptech.glide.Priority; import com.bumptech.glide.load.data.DataFetcher; import org.xdty.gallery.model.Media; import java.io.IOException; import java.io.InputStream; import java.util.List; package org.xdty.gallery.glide; public class MediaDataFetcher implements DataFetcher<InputStream> { private static final String TAG = MediaDataFetcher.class.getSimpleName();
private final Media mediaFile;
xdtianyu/Gallery
app/src/main/java/org/xdty/gallery/contract/ViewerContact.java
// Path: app/src/main/java/org/xdty/gallery/model/Media.java // public interface Media<T extends Media> { // // String[] scheme(); // // String getName(); // // String getHost(); // // long getLastModified(); // // long length(); // // String getPath(); // // String getParent(); // // void setParent(T parent); // // T parent(); // // void clear(); // // boolean hasImage(); // // List<T> children(); // // int childrenSize(); // // String getUri(); // // InputStream getInputStream() throws IOException; // // boolean isFile(); // // T[] listMedia(); // // boolean isImage(); // // boolean isDirectory(); // // T fromUri(String uri); // // T auth(String domain, String directory, String username, String password); // // int getPosition(); // // void setPosition(int position); // // class MediaException extends RuntimeException { // // public MediaException(String detailMessage) { // super(detailMessage); // } // } // // class NumericComparator implements Comparator<Media> { // // public static NumericComparator factory() { // return SingletonHelper.INSTANCE; // } // // private boolean isDigit(char ch) { // return ch >= 48 && ch <= 57; // } // // /** // * Length of string is passed in for improved efficiency (only need to calculate it once) // **/ // private String getChunk(String s, int length, int marker) { // StringBuilder chunk = new StringBuilder(); // char c = s.charAt(marker); // chunk.append(c); // marker++; // if (isDigit(c)) { // while (marker < length) { // c = s.charAt(marker); // if (!isDigit(c)) { // break; // } // chunk.append(c); // marker++; // } // } else { // while (marker < length) { // c = s.charAt(marker); // if (isDigit(c)) { // break; // } // chunk.append(c); // marker++; // } // } // return chunk.toString(); // } // // @Override // public int compare(Media m1, Media m2) { // String s1 = m1.getName(); // String s2 = m2.getName(); // // return compare(s1, s2); // } // // public int compare(String s1, String s2) { // // int thisMarker = 0; // int thatMarker = 0; // int s1Length = s1.length(); // int s2Length = s2.length(); // // while (thisMarker < s1Length && thatMarker < s2Length) { // String thisChunk = getChunk(s1, s1Length, thisMarker); // thisMarker += thisChunk.length(); // // String thatChunk = getChunk(s2, s2Length, thatMarker); // thatMarker += thatChunk.length(); // // // If both chunks contain numeric characters, sort them numerically // int result = 0; // if (isDigit(thisChunk.charAt(0)) && isDigit(thatChunk.charAt(0))) { // // Simple chunk comparison by length. // int thisChunkLength = thisChunk.length(); // result = thisChunkLength - thatChunk.length(); // // If equal, the first different number counts // if (result == 0) { // for (int i = 0; i < thisChunkLength; i++) { // result = thisChunk.charAt(i) - thatChunk.charAt(i); // if (result != 0) { // return result; // } // } // } // } else { // result = thisChunk.compareTo(thatChunk); // } // // if (result != 0) { // return result; // } // } // // return s1Length - s2Length; // } // // private final static class SingletonHelper { // private final static NumericComparator INSTANCE = new NumericComparator(); // } // } // // }
import org.xdty.gallery.model.Media; import java.util.List;
package org.xdty.gallery.contract; public interface ViewerContact { interface View extends BaseView<Presenter> { void updateOrientation(int width, int height); void hideSystemUIDelayed(int timeout); void cancelHideSystemUIDelayed(); boolean isSystemUIVisible(); void showSystemUI(boolean autoHide); void hideSystemUI();
// Path: app/src/main/java/org/xdty/gallery/model/Media.java // public interface Media<T extends Media> { // // String[] scheme(); // // String getName(); // // String getHost(); // // long getLastModified(); // // long length(); // // String getPath(); // // String getParent(); // // void setParent(T parent); // // T parent(); // // void clear(); // // boolean hasImage(); // // List<T> children(); // // int childrenSize(); // // String getUri(); // // InputStream getInputStream() throws IOException; // // boolean isFile(); // // T[] listMedia(); // // boolean isImage(); // // boolean isDirectory(); // // T fromUri(String uri); // // T auth(String domain, String directory, String username, String password); // // int getPosition(); // // void setPosition(int position); // // class MediaException extends RuntimeException { // // public MediaException(String detailMessage) { // super(detailMessage); // } // } // // class NumericComparator implements Comparator<Media> { // // public static NumericComparator factory() { // return SingletonHelper.INSTANCE; // } // // private boolean isDigit(char ch) { // return ch >= 48 && ch <= 57; // } // // /** // * Length of string is passed in for improved efficiency (only need to calculate it once) // **/ // private String getChunk(String s, int length, int marker) { // StringBuilder chunk = new StringBuilder(); // char c = s.charAt(marker); // chunk.append(c); // marker++; // if (isDigit(c)) { // while (marker < length) { // c = s.charAt(marker); // if (!isDigit(c)) { // break; // } // chunk.append(c); // marker++; // } // } else { // while (marker < length) { // c = s.charAt(marker); // if (isDigit(c)) { // break; // } // chunk.append(c); // marker++; // } // } // return chunk.toString(); // } // // @Override // public int compare(Media m1, Media m2) { // String s1 = m1.getName(); // String s2 = m2.getName(); // // return compare(s1, s2); // } // // public int compare(String s1, String s2) { // // int thisMarker = 0; // int thatMarker = 0; // int s1Length = s1.length(); // int s2Length = s2.length(); // // while (thisMarker < s1Length && thatMarker < s2Length) { // String thisChunk = getChunk(s1, s1Length, thisMarker); // thisMarker += thisChunk.length(); // // String thatChunk = getChunk(s2, s2Length, thatMarker); // thatMarker += thatChunk.length(); // // // If both chunks contain numeric characters, sort them numerically // int result = 0; // if (isDigit(thisChunk.charAt(0)) && isDigit(thatChunk.charAt(0))) { // // Simple chunk comparison by length. // int thisChunkLength = thisChunk.length(); // result = thisChunkLength - thatChunk.length(); // // If equal, the first different number counts // if (result == 0) { // for (int i = 0; i < thisChunkLength; i++) { // result = thisChunk.charAt(i) - thatChunk.charAt(i); // if (result != 0) { // return result; // } // } // } // } else { // result = thisChunk.compareTo(thatChunk); // } // // if (result != 0) { // return result; // } // } // // return s1Length - s2Length; // } // // private final static class SingletonHelper { // private final static NumericComparator INSTANCE = new NumericComparator(); // } // } // // } // Path: app/src/main/java/org/xdty/gallery/contract/ViewerContact.java import org.xdty.gallery.model.Media; import java.util.List; package org.xdty.gallery.contract; public interface ViewerContact { interface View extends BaseView<Presenter> { void updateOrientation(int width, int height); void hideSystemUIDelayed(int timeout); void cancelHideSystemUIDelayed(); boolean isSystemUIVisible(); void showSystemUI(boolean autoHide); void hideSystemUI();
void replaceData(List<Media> medias, int position);
xdtianyu/Gallery
app/src/main/java/org/xdty/gallery/data/MediaRepository.java
// Path: app/src/main/java/org/xdty/gallery/model/Media.java // public interface Media<T extends Media> { // // String[] scheme(); // // String getName(); // // String getHost(); // // long getLastModified(); // // long length(); // // String getPath(); // // String getParent(); // // void setParent(T parent); // // T parent(); // // void clear(); // // boolean hasImage(); // // List<T> children(); // // int childrenSize(); // // String getUri(); // // InputStream getInputStream() throws IOException; // // boolean isFile(); // // T[] listMedia(); // // boolean isImage(); // // boolean isDirectory(); // // T fromUri(String uri); // // T auth(String domain, String directory, String username, String password); // // int getPosition(); // // void setPosition(int position); // // class MediaException extends RuntimeException { // // public MediaException(String detailMessage) { // super(detailMessage); // } // } // // class NumericComparator implements Comparator<Media> { // // public static NumericComparator factory() { // return SingletonHelper.INSTANCE; // } // // private boolean isDigit(char ch) { // return ch >= 48 && ch <= 57; // } // // /** // * Length of string is passed in for improved efficiency (only need to calculate it once) // **/ // private String getChunk(String s, int length, int marker) { // StringBuilder chunk = new StringBuilder(); // char c = s.charAt(marker); // chunk.append(c); // marker++; // if (isDigit(c)) { // while (marker < length) { // c = s.charAt(marker); // if (!isDigit(c)) { // break; // } // chunk.append(c); // marker++; // } // } else { // while (marker < length) { // c = s.charAt(marker); // if (isDigit(c)) { // break; // } // chunk.append(c); // marker++; // } // } // return chunk.toString(); // } // // @Override // public int compare(Media m1, Media m2) { // String s1 = m1.getName(); // String s2 = m2.getName(); // // return compare(s1, s2); // } // // public int compare(String s1, String s2) { // // int thisMarker = 0; // int thatMarker = 0; // int s1Length = s1.length(); // int s2Length = s2.length(); // // while (thisMarker < s1Length && thatMarker < s2Length) { // String thisChunk = getChunk(s1, s1Length, thisMarker); // thisMarker += thisChunk.length(); // // String thatChunk = getChunk(s2, s2Length, thatMarker); // thatMarker += thatChunk.length(); // // // If both chunks contain numeric characters, sort them numerically // int result = 0; // if (isDigit(thisChunk.charAt(0)) && isDigit(thatChunk.charAt(0))) { // // Simple chunk comparison by length. // int thisChunkLength = thisChunk.length(); // result = thisChunkLength - thatChunk.length(); // // If equal, the first different number counts // if (result == 0) { // for (int i = 0; i < thisChunkLength; i++) { // result = thisChunk.charAt(i) - thatChunk.charAt(i); // if (result != 0) { // return result; // } // } // } // } else { // result = thisChunk.compareTo(thatChunk); // } // // if (result != 0) { // return result; // } // } // // return s1Length - s2Length; // } // // private final static class SingletonHelper { // private final static NumericComparator INSTANCE = new NumericComparator(); // } // } // // }
import org.xdty.gallery.model.Media; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import io.reactivex.Observable; import io.reactivex.ObservableOnSubscribe; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.schedulers.Schedulers;
package org.xdty.gallery.data; public class MediaRepository implements MediaDataSource { private MediaCache mMediaCache;
// Path: app/src/main/java/org/xdty/gallery/model/Media.java // public interface Media<T extends Media> { // // String[] scheme(); // // String getName(); // // String getHost(); // // long getLastModified(); // // long length(); // // String getPath(); // // String getParent(); // // void setParent(T parent); // // T parent(); // // void clear(); // // boolean hasImage(); // // List<T> children(); // // int childrenSize(); // // String getUri(); // // InputStream getInputStream() throws IOException; // // boolean isFile(); // // T[] listMedia(); // // boolean isImage(); // // boolean isDirectory(); // // T fromUri(String uri); // // T auth(String domain, String directory, String username, String password); // // int getPosition(); // // void setPosition(int position); // // class MediaException extends RuntimeException { // // public MediaException(String detailMessage) { // super(detailMessage); // } // } // // class NumericComparator implements Comparator<Media> { // // public static NumericComparator factory() { // return SingletonHelper.INSTANCE; // } // // private boolean isDigit(char ch) { // return ch >= 48 && ch <= 57; // } // // /** // * Length of string is passed in for improved efficiency (only need to calculate it once) // **/ // private String getChunk(String s, int length, int marker) { // StringBuilder chunk = new StringBuilder(); // char c = s.charAt(marker); // chunk.append(c); // marker++; // if (isDigit(c)) { // while (marker < length) { // c = s.charAt(marker); // if (!isDigit(c)) { // break; // } // chunk.append(c); // marker++; // } // } else { // while (marker < length) { // c = s.charAt(marker); // if (isDigit(c)) { // break; // } // chunk.append(c); // marker++; // } // } // return chunk.toString(); // } // // @Override // public int compare(Media m1, Media m2) { // String s1 = m1.getName(); // String s2 = m2.getName(); // // return compare(s1, s2); // } // // public int compare(String s1, String s2) { // // int thisMarker = 0; // int thatMarker = 0; // int s1Length = s1.length(); // int s2Length = s2.length(); // // while (thisMarker < s1Length && thatMarker < s2Length) { // String thisChunk = getChunk(s1, s1Length, thisMarker); // thisMarker += thisChunk.length(); // // String thatChunk = getChunk(s2, s2Length, thatMarker); // thatMarker += thatChunk.length(); // // // If both chunks contain numeric characters, sort them numerically // int result = 0; // if (isDigit(thisChunk.charAt(0)) && isDigit(thatChunk.charAt(0))) { // // Simple chunk comparison by length. // int thisChunkLength = thisChunk.length(); // result = thisChunkLength - thatChunk.length(); // // If equal, the first different number counts // if (result == 0) { // for (int i = 0; i < thisChunkLength; i++) { // result = thisChunk.charAt(i) - thatChunk.charAt(i); // if (result != 0) { // return result; // } // } // } // } else { // result = thisChunk.compareTo(thatChunk); // } // // if (result != 0) { // return result; // } // } // // return s1Length - s2Length; // } // // private final static class SingletonHelper { // private final static NumericComparator INSTANCE = new NumericComparator(); // } // } // // } // Path: app/src/main/java/org/xdty/gallery/data/MediaRepository.java import org.xdty.gallery.model.Media; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import io.reactivex.Observable; import io.reactivex.ObservableOnSubscribe; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.schedulers.Schedulers; package org.xdty.gallery.data; public class MediaRepository implements MediaDataSource { private MediaCache mMediaCache;
private ArrayList<Media> mRoots = new ArrayList<>();
xdtianyu/Gallery
app/src/main/java/org/xdty/gallery/utils/Utils.java
// Path: app/src/main/java/org/xdty/gallery/model/Config.java // public class Config { // // public final static String SAMBA_SERVER = "samba_server"; // public final static String SAMBA_FOLDER = "samba_folder"; // public final static String SAMBA_USERNAME = "samba_username"; // public final static String SAMBA_PASSWORD = "samba_password"; // public final static String ROTATE_TYPE = "rotate_type"; // public final static String VIEWPAGER_EFFECT = "viewpager_effect"; // public final static String GRID_EFFECT = "grid_effect"; // public final static String GRID_EFFECT_DURATION = "grid_effect_duration"; // public final static String LOCAL_SORT_TYPE = "local_sort_type"; // public final static String NETWORK_SORT_TYPE = "network_sort_type"; // public final static String FILE_EXPLORER_MODE = "file_explorer_mode"; // public final static String SHOW_HIDING_FILES = "show_hiding_files"; // public final static String REVERSE_LOCAL_SORT = "reverse_local_sort"; // public final static String REVERSE_NETWORK_SORT = "reverse_network_sort"; // // public final static String thumbnailDir = "thumbnails"; // public final static String ROOT_PATH = "root://"; // // public final static String SERVERS = "servers"; // // public final static int MAX_IMAGE_SIZE = 2048; // public final static int IMAGE_SIMPLE_SIZE = 2; // public final static int IMAGE_THUMBNAIL_SIMPLE_SIZE = 2; // }
import android.content.Context; import android.content.SharedPreferences; import android.content.res.Configuration; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Matrix; import android.preference.PreferenceManager; import android.util.TypedValue; import android.webkit.MimeTypeMap; import org.xdty.gallery.R; import org.xdty.gallery.model.Config; import java.io.IOException; import java.io.InputStream; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale;
} public static Bitmap getResizedBitmap(Bitmap bm, int newWidth, int newHeight) { int width = bm.getWidth(); int height = bm.getHeight(); float scaleWidth = ((float) newWidth) / width; float scaleHeight = ((float) newHeight) / height; Matrix matrix = new Matrix(); matrix.postScale(scaleWidth, scaleHeight); Bitmap resizedBitmap = Bitmap.createBitmap( bm, 0, 0, width, height, matrix, false); bm.recycle(); return resizedBitmap; } public static Bitmap decodeSampledBitmapFromStream(InputStream inputStream, int reqWidth, int reqHeight) throws IOException { // First decode with inJustDecodeBounds=true to check dimensions final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeStream(inputStream, null, options); // Calculate inSampleSize //options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); options.inSampleSize = calculateLessInSampleSize(options, reqWidth, reqHeight); //options.inSampleSize = Config.IMAGE_THUMBNAIL_SIMPLE_SIZE; // Decode bitmap with inSampleSize set options.inJustDecodeBounds = false;
// Path: app/src/main/java/org/xdty/gallery/model/Config.java // public class Config { // // public final static String SAMBA_SERVER = "samba_server"; // public final static String SAMBA_FOLDER = "samba_folder"; // public final static String SAMBA_USERNAME = "samba_username"; // public final static String SAMBA_PASSWORD = "samba_password"; // public final static String ROTATE_TYPE = "rotate_type"; // public final static String VIEWPAGER_EFFECT = "viewpager_effect"; // public final static String GRID_EFFECT = "grid_effect"; // public final static String GRID_EFFECT_DURATION = "grid_effect_duration"; // public final static String LOCAL_SORT_TYPE = "local_sort_type"; // public final static String NETWORK_SORT_TYPE = "network_sort_type"; // public final static String FILE_EXPLORER_MODE = "file_explorer_mode"; // public final static String SHOW_HIDING_FILES = "show_hiding_files"; // public final static String REVERSE_LOCAL_SORT = "reverse_local_sort"; // public final static String REVERSE_NETWORK_SORT = "reverse_network_sort"; // // public final static String thumbnailDir = "thumbnails"; // public final static String ROOT_PATH = "root://"; // // public final static String SERVERS = "servers"; // // public final static int MAX_IMAGE_SIZE = 2048; // public final static int IMAGE_SIMPLE_SIZE = 2; // public final static int IMAGE_THUMBNAIL_SIMPLE_SIZE = 2; // } // Path: app/src/main/java/org/xdty/gallery/utils/Utils.java import android.content.Context; import android.content.SharedPreferences; import android.content.res.Configuration; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Matrix; import android.preference.PreferenceManager; import android.util.TypedValue; import android.webkit.MimeTypeMap; import org.xdty.gallery.R; import org.xdty.gallery.model.Config; import java.io.IOException; import java.io.InputStream; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; } public static Bitmap getResizedBitmap(Bitmap bm, int newWidth, int newHeight) { int width = bm.getWidth(); int height = bm.getHeight(); float scaleWidth = ((float) newWidth) / width; float scaleHeight = ((float) newHeight) / height; Matrix matrix = new Matrix(); matrix.postScale(scaleWidth, scaleHeight); Bitmap resizedBitmap = Bitmap.createBitmap( bm, 0, 0, width, height, matrix, false); bm.recycle(); return resizedBitmap; } public static Bitmap decodeSampledBitmapFromStream(InputStream inputStream, int reqWidth, int reqHeight) throws IOException { // First decode with inJustDecodeBounds=true to check dimensions final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeStream(inputStream, null, options); // Calculate inSampleSize //options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); options.inSampleSize = calculateLessInSampleSize(options, reqWidth, reqHeight); //options.inSampleSize = Config.IMAGE_THUMBNAIL_SIMPLE_SIZE; // Decode bitmap with inSampleSize set options.inJustDecodeBounds = false;
options.inPreferredConfig = Bitmap.Config.RGB_565;
ulisesbocchio/spring-boot-security-saml-samples
spring-security-saml-sample/src/main/java/com/ulisesbocchio/security/saml/spring/mvc/HomeController.java
// Path: spring-security-saml-sample/src/main/java/com/ulisesbocchio/security/saml/spring/security/SAMLUserDetails.java // public class SAMLUserDetails implements UserDetails { // // private SAMLCredential samlCredential; // // public SAMLUserDetails(SAMLCredential samlCredential) { // this.samlCredential = samlCredential; // } // // @Override // public Collection<? extends GrantedAuthority> getAuthorities() { // return Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER")); // } // // @Override // public String getPassword() { // return ""; // } // // @Override // public String getUsername() { // return samlCredential.getNameID().getValue(); // } // // @Override // public boolean isAccountNonExpired() { // return true; // } // // @Override // public boolean isAccountNonLocked() { // return true; // } // // @Override // public boolean isCredentialsNonExpired() { // return true; // } // // @Override // public boolean isEnabled() { // return true; // } // // public String getAttribute(String name) { // return samlCredential.getAttributeAsString(name); // } // // public String[] getAttributeArray(String name) { // return samlCredential.getAttributeAsStringArray(name); // } // // public Map<String, String> getAttributes() { // return samlCredential.getAttributes().stream() // .collect(Collectors.toMap(Attribute::getName, this::getString)); // } // // private String getString(Attribute attribute) { // String value = getValue(attribute); // return value == null ? "" : value; // } // // public Map<String, String[]> getAttributesArrays() { // return samlCredential.getAttributes().stream() // .collect(Collectors.toMap(Attribute::getName, this::getValueArray)); // } // // private String getValue(Attribute attribute) { // return getAttribute(attribute.getName()); // } // // private String[] getValueArray(Attribute attribute) { // return getAttributeArray(attribute.getName()); // } // }
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import com.ulisesbocchio.security.saml.spring.security.SAMLUserDetails; import org.springframework.stereotype.Controller;
package com.ulisesbocchio.security.saml.spring.mvc; /** * @author Ulises Bocchio */ @Controller public class HomeController { @RequestMapping("/home")
// Path: spring-security-saml-sample/src/main/java/com/ulisesbocchio/security/saml/spring/security/SAMLUserDetails.java // public class SAMLUserDetails implements UserDetails { // // private SAMLCredential samlCredential; // // public SAMLUserDetails(SAMLCredential samlCredential) { // this.samlCredential = samlCredential; // } // // @Override // public Collection<? extends GrantedAuthority> getAuthorities() { // return Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER")); // } // // @Override // public String getPassword() { // return ""; // } // // @Override // public String getUsername() { // return samlCredential.getNameID().getValue(); // } // // @Override // public boolean isAccountNonExpired() { // return true; // } // // @Override // public boolean isAccountNonLocked() { // return true; // } // // @Override // public boolean isCredentialsNonExpired() { // return true; // } // // @Override // public boolean isEnabled() { // return true; // } // // public String getAttribute(String name) { // return samlCredential.getAttributeAsString(name); // } // // public String[] getAttributeArray(String name) { // return samlCredential.getAttributeAsStringArray(name); // } // // public Map<String, String> getAttributes() { // return samlCredential.getAttributes().stream() // .collect(Collectors.toMap(Attribute::getName, this::getString)); // } // // private String getString(Attribute attribute) { // String value = getValue(attribute); // return value == null ? "" : value; // } // // public Map<String, String[]> getAttributesArrays() { // return samlCredential.getAttributes().stream() // .collect(Collectors.toMap(Attribute::getName, this::getValueArray)); // } // // private String getValue(Attribute attribute) { // return getAttribute(attribute.getName()); // } // // private String[] getValueArray(Attribute attribute) { // return getAttributeArray(attribute.getName()); // } // } // Path: spring-security-saml-sample/src/main/java/com/ulisesbocchio/security/saml/spring/mvc/HomeController.java import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import com.ulisesbocchio.security.saml.spring.security.SAMLUserDetails; import org.springframework.stereotype.Controller; package com.ulisesbocchio.security.saml.spring.mvc; /** * @author Ulises Bocchio */ @Controller public class HomeController { @RequestMapping("/home")
public ModelAndView home(@SAMLUser SAMLUserDetails user) {
Azanor/thaumcraft-api
research/ResearchEntry.java
// Path: research/ResearchStage.java // public static class Knowledge { // public EnumKnowledgeType type; // public ResearchCategory category; // public int amount = 0; // // public Knowledge(EnumKnowledgeType type, ResearchCategory category, int num) { // super(); // this.type = type; // this.category = category; // this.amount = num; // } // // public static Knowledge parse(String text) { // String[] s = text.split(";"); // if (s.length==2) { // int num = 0; // try { // num = Integer.parseInt(s[1]); // } catch (Exception e) {} // EnumKnowledgeType t = EnumKnowledgeType.valueOf(s[0].toUpperCase()); // if (t!=null && !t.hasFields() && num>0) { // return new Knowledge(t, null, num); // } // } else if (s.length==3) { // int num = 0; // try { // num = Integer.parseInt(s[2]); // } catch (Exception e) {} // EnumKnowledgeType t = EnumKnowledgeType.valueOf(s[0].toUpperCase()); // ResearchCategory f = ResearchCategories.getResearchCategory(s[1].toUpperCase()); // if (t!=null && f!=null && num>0) { // return new Knowledge(t,f,num); // } // } // return null; // } // }
import java.util.Arrays; import net.minecraft.item.ItemStack; import net.minecraft.util.text.translation.I18n; import thaumcraft.api.research.ResearchStage.Knowledge;
package thaumcraft.api.research; public class ResearchEntry { /** * A short string used as a key for this research. Must be unique */ String key; /** * A short string used as a reference to the research category to which this must be added. */ String category; /** * A text name of the research entry. Can be a localizable string. */ String name; /** * This links to any research that needs to be completed before this research can be discovered or learnt. */ String[] parents; /** * any research linked to this that will be unlocked automatically when this research is complete */ String[] siblings; /** * the horizontal position of the research icon */ int displayColumn; /** * the vertical position of the research icon */ int displayRow; /** * the icon to be used for this research */ Object[] icons; /** * special meta-data tags that indicate how this research must be handled */ EnumResearchMeta[] meta; /** * items the player will receive on completion of this research */ ItemStack[] rewardItem; /** * knowledge the player will receive on completion of this research */
// Path: research/ResearchStage.java // public static class Knowledge { // public EnumKnowledgeType type; // public ResearchCategory category; // public int amount = 0; // // public Knowledge(EnumKnowledgeType type, ResearchCategory category, int num) { // super(); // this.type = type; // this.category = category; // this.amount = num; // } // // public static Knowledge parse(String text) { // String[] s = text.split(";"); // if (s.length==2) { // int num = 0; // try { // num = Integer.parseInt(s[1]); // } catch (Exception e) {} // EnumKnowledgeType t = EnumKnowledgeType.valueOf(s[0].toUpperCase()); // if (t!=null && !t.hasFields() && num>0) { // return new Knowledge(t, null, num); // } // } else if (s.length==3) { // int num = 0; // try { // num = Integer.parseInt(s[2]); // } catch (Exception e) {} // EnumKnowledgeType t = EnumKnowledgeType.valueOf(s[0].toUpperCase()); // ResearchCategory f = ResearchCategories.getResearchCategory(s[1].toUpperCase()); // if (t!=null && f!=null && num>0) { // return new Knowledge(t,f,num); // } // } // return null; // } // } // Path: research/ResearchEntry.java import java.util.Arrays; import net.minecraft.item.ItemStack; import net.minecraft.util.text.translation.I18n; import thaumcraft.api.research.ResearchStage.Knowledge; package thaumcraft.api.research; public class ResearchEntry { /** * A short string used as a key for this research. Must be unique */ String key; /** * A short string used as a reference to the research category to which this must be added. */ String category; /** * A text name of the research entry. Can be a localizable string. */ String name; /** * This links to any research that needs to be completed before this research can be discovered or learnt. */ String[] parents; /** * any research linked to this that will be unlocked automatically when this research is complete */ String[] siblings; /** * the horizontal position of the research icon */ int displayColumn; /** * the vertical position of the research icon */ int displayRow; /** * the icon to be used for this research */ Object[] icons; /** * special meta-data tags that indicate how this research must be handled */ EnumResearchMeta[] meta; /** * items the player will receive on completion of this research */ ItemStack[] rewardItem; /** * knowledge the player will receive on completion of this research */
Knowledge[] rewardKnow;
Azanor/thaumcraft-api
research/ScanOreDictionary.java
// Path: internal/CommonInternals.java // public class CommonInternals { // // public static HashMap<String,ResourceLocation> jsonLocs = new HashMap<>(); // public static ArrayList<ThaumcraftApi.EntityTags> scanEntities = new ArrayList<>(); // public static HashMap<ResourceLocation,IThaumcraftRecipe> craftingRecipeCatalog = new HashMap<>(); // public static HashMap<ResourceLocation,Object> craftingRecipeCatalogFake = new HashMap<>(); // public static ArrayList<SmeltBonus> smeltingBonus = new ArrayList<SmeltBonus>(); // public static ConcurrentHashMap<Integer,AspectList> objectTags = new ConcurrentHashMap<>(); // public static HashMap<Object,Integer> warpMap = new HashMap<Object,Integer>(); // public static HashMap<String,ItemStack> seedList = new HashMap<String,ItemStack>(); // // public static IThaumcraftRecipe getCatalogRecipe(ResourceLocation key) { // return craftingRecipeCatalog.get(key); // } // // public static Object getCatalogRecipeFake(ResourceLocation key) { // return craftingRecipeCatalogFake.get(key); // } // // /** // * Obviously the int generated is not truly unique, but it is unique enough for this purpose. // * @param stack // * @return // */ // public static int generateUniqueItemstackId(ItemStack stack) { // ItemStack sc = stack.copy(); // sc.setCount(1); // String ss = sc.serializeNBT().toString(); // return ss.hashCode(); // } // // /** // * Obviously the int generated is not truly unique, but it is unique enough for this purpose. // * Strips all nbt data from itemstack // * @param stack // * @return // */ // public static int generateUniqueItemstackIdStripped(ItemStack stack) { // ItemStack sc = stack.copy(); // sc.setCount(1); // sc.setTagCompound(null); // String ss = sc.serializeNBT().toString(); // return ss.hashCode(); // } // }
import java.util.concurrent.ConcurrentHashMap; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.item.EntityItem; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.util.math.BlockPos; import net.minecraftforge.oredict.OreDictionary; import thaumcraft.api.internal.CommonInternals;
package thaumcraft.api.research; public class ScanOreDictionary implements IScanThing { String research; String[] entries; public ConcurrentHashMap<Integer,Boolean> cache = new ConcurrentHashMap<>(); public ScanOreDictionary(String research, String ... entries) { this.research = research; this.entries = entries; } @Override public boolean checkThing(EntityPlayer player, Object obj) { ItemStack stack = null; if (obj!=null) { if (obj instanceof BlockPos) { IBlockState state = player.world.getBlockState((BlockPos) obj); stack = state.getBlock().getItem(player.world, (BlockPos) obj, state); } else if (obj instanceof ItemStack) stack = (ItemStack) obj; else if (obj instanceof EntityItem && ((EntityItem)obj).getItem()!=null) stack = ((EntityItem)obj).getItem(); } if (stack!=null && !stack.isEmpty()) {
// Path: internal/CommonInternals.java // public class CommonInternals { // // public static HashMap<String,ResourceLocation> jsonLocs = new HashMap<>(); // public static ArrayList<ThaumcraftApi.EntityTags> scanEntities = new ArrayList<>(); // public static HashMap<ResourceLocation,IThaumcraftRecipe> craftingRecipeCatalog = new HashMap<>(); // public static HashMap<ResourceLocation,Object> craftingRecipeCatalogFake = new HashMap<>(); // public static ArrayList<SmeltBonus> smeltingBonus = new ArrayList<SmeltBonus>(); // public static ConcurrentHashMap<Integer,AspectList> objectTags = new ConcurrentHashMap<>(); // public static HashMap<Object,Integer> warpMap = new HashMap<Object,Integer>(); // public static HashMap<String,ItemStack> seedList = new HashMap<String,ItemStack>(); // // public static IThaumcraftRecipe getCatalogRecipe(ResourceLocation key) { // return craftingRecipeCatalog.get(key); // } // // public static Object getCatalogRecipeFake(ResourceLocation key) { // return craftingRecipeCatalogFake.get(key); // } // // /** // * Obviously the int generated is not truly unique, but it is unique enough for this purpose. // * @param stack // * @return // */ // public static int generateUniqueItemstackId(ItemStack stack) { // ItemStack sc = stack.copy(); // sc.setCount(1); // String ss = sc.serializeNBT().toString(); // return ss.hashCode(); // } // // /** // * Obviously the int generated is not truly unique, but it is unique enough for this purpose. // * Strips all nbt data from itemstack // * @param stack // * @return // */ // public static int generateUniqueItemstackIdStripped(ItemStack stack) { // ItemStack sc = stack.copy(); // sc.setCount(1); // sc.setTagCompound(null); // String ss = sc.serializeNBT().toString(); // return ss.hashCode(); // } // } // Path: research/ScanOreDictionary.java import java.util.concurrent.ConcurrentHashMap; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.item.EntityItem; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.util.math.BlockPos; import net.minecraftforge.oredict.OreDictionary; import thaumcraft.api.internal.CommonInternals; package thaumcraft.api.research; public class ScanOreDictionary implements IScanThing { String research; String[] entries; public ConcurrentHashMap<Integer,Boolean> cache = new ConcurrentHashMap<>(); public ScanOreDictionary(String research, String ... entries) { this.research = research; this.entries = entries; } @Override public boolean checkThing(EntityPlayer player, Object obj) { ItemStack stack = null; if (obj!=null) { if (obj instanceof BlockPos) { IBlockState state = player.world.getBlockState((BlockPos) obj); stack = state.getBlock().getItem(player.world, (BlockPos) obj, state); } else if (obj instanceof ItemStack) stack = (ItemStack) obj; else if (obj instanceof EntityItem && ((EntityItem)obj).getItem()!=null) stack = ((EntityItem)obj).getItem(); } if (stack!=null && !stack.isEmpty()) {
int hid = CommonInternals.generateUniqueItemstackId(stack);
Azanor/thaumcraft-api
research/theorycraft/CardExperimentation.java
// Path: research/ResearchCategories.java // public class ResearchCategories { // // //Research // public static LinkedHashMap <String, ResearchCategory> researchCategories = new LinkedHashMap <String,ResearchCategory>(); // // /** // * @param key // * @return the research item linked to this key // */ // public static ResearchCategory getResearchCategory(String key) { // return researchCategories.get(key); // } // // /** // * @param key // * @return the name of the research category linked to this key. // * Must be stored as localization information in the LanguageRegistry. // */ // public static String getCategoryName(String key) { // return I18n.translateToLocal("tc.research_category."+key); // } // // /** // * @param key the research key // * @return the ResearchItem object. // */ // public static ResearchEntry getResearch(String key) { // Collection rc = researchCategories.values(); // for (Object cat:rc) { // Collection rl = ((ResearchCategory)cat).research.values(); // for (Object ri:rl) { // if ((((ResearchEntry)ri).key).equals(key)) return (ResearchEntry)ri; // } // } // return null; // } // // /** // * This should only be done at the PostInit stage // * @param key the key used for this category // * @param researchkey the research that the player needs to have completed before this category becomes visible. Set as null to always show. // * @param aspectsFormula aspects required to gain knowledge in this category // * @param icon the icon to be used for the research category tab // * @param background the resource location of the background image to use for this category // * @return the registered category // */ // public static ResearchCategory registerCategory(String key, String researchkey, AspectList formula, ResourceLocation icon, ResourceLocation background) { // if (getResearchCategory(key)==null) { // ResearchCategory rl = new ResearchCategory(key,researchkey, formula, icon, background); // researchCategories.put(key, rl); // return rl; // } // return null; // } // // /** // * This should only be done at the PostInit stage // * @param key the key used for this category // * @param researchkey the research that the player needs to have completed before this category becomes visible. Set as null to always show. // * @param icon the icon to be used for the research category tab // * @param background the resource location of the background image to use for this category // * @param background2 the resource location of the foreground image that lies between the background and icons // * @return the registered category // */ // public static ResearchCategory registerCategory(String key, String researchkey, AspectList formula, ResourceLocation icon, ResourceLocation background, ResourceLocation background2) { // if (getResearchCategory(key)==null) { // ResearchCategory rl = new ResearchCategory(key, researchkey, formula, icon, background, background2); // researchCategories.put(key, rl); // return rl; // } // return null; // } // // // // }
import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.math.MathHelper; import net.minecraft.util.text.TextComponentTranslation; import thaumcraft.api.research.ResearchCategories;
package thaumcraft.api.research.theorycraft; public class CardExperimentation extends TheorycraftCard { @Override public int getInspirationCost() { return 2; } @Override public String getLocalizedName() { return new TextComponentTranslation("card.experimentation.name").getUnformattedText(); } @Override public String getLocalizedText() { return new TextComponentTranslation("card.experimentation.text").getUnformattedText(); } @Override public boolean activate(EntityPlayer player, ResearchTableData data) { try {
// Path: research/ResearchCategories.java // public class ResearchCategories { // // //Research // public static LinkedHashMap <String, ResearchCategory> researchCategories = new LinkedHashMap <String,ResearchCategory>(); // // /** // * @param key // * @return the research item linked to this key // */ // public static ResearchCategory getResearchCategory(String key) { // return researchCategories.get(key); // } // // /** // * @param key // * @return the name of the research category linked to this key. // * Must be stored as localization information in the LanguageRegistry. // */ // public static String getCategoryName(String key) { // return I18n.translateToLocal("tc.research_category."+key); // } // // /** // * @param key the research key // * @return the ResearchItem object. // */ // public static ResearchEntry getResearch(String key) { // Collection rc = researchCategories.values(); // for (Object cat:rc) { // Collection rl = ((ResearchCategory)cat).research.values(); // for (Object ri:rl) { // if ((((ResearchEntry)ri).key).equals(key)) return (ResearchEntry)ri; // } // } // return null; // } // // /** // * This should only be done at the PostInit stage // * @param key the key used for this category // * @param researchkey the research that the player needs to have completed before this category becomes visible. Set as null to always show. // * @param aspectsFormula aspects required to gain knowledge in this category // * @param icon the icon to be used for the research category tab // * @param background the resource location of the background image to use for this category // * @return the registered category // */ // public static ResearchCategory registerCategory(String key, String researchkey, AspectList formula, ResourceLocation icon, ResourceLocation background) { // if (getResearchCategory(key)==null) { // ResearchCategory rl = new ResearchCategory(key,researchkey, formula, icon, background); // researchCategories.put(key, rl); // return rl; // } // return null; // } // // /** // * This should only be done at the PostInit stage // * @param key the key used for this category // * @param researchkey the research that the player needs to have completed before this category becomes visible. Set as null to always show. // * @param icon the icon to be used for the research category tab // * @param background the resource location of the background image to use for this category // * @param background2 the resource location of the foreground image that lies between the background and icons // * @return the registered category // */ // public static ResearchCategory registerCategory(String key, String researchkey, AspectList formula, ResourceLocation icon, ResourceLocation background, ResourceLocation background2) { // if (getResearchCategory(key)==null) { // ResearchCategory rl = new ResearchCategory(key, researchkey, formula, icon, background, background2); // researchCategories.put(key, rl); // return rl; // } // return null; // } // // // // } // Path: research/theorycraft/CardExperimentation.java import net.minecraft.entity.player.EntityPlayer; import net.minecraft.util.math.MathHelper; import net.minecraft.util.text.TextComponentTranslation; import thaumcraft.api.research.ResearchCategories; package thaumcraft.api.research.theorycraft; public class CardExperimentation extends TheorycraftCard { @Override public int getInspirationCost() { return 2; } @Override public String getLocalizedName() { return new TextComponentTranslation("card.experimentation.name").getUnformattedText(); } @Override public String getLocalizedText() { return new TextComponentTranslation("card.experimentation.text").getUnformattedText(); } @Override public boolean activate(EntityPlayer player, ResearchTableData data) { try {
String[] s = ResearchCategories.researchCategories.keySet().toArray(new String[] {});
ghedlund/jpraat
src/main/java/ca/hedlund/jpraat/binding/fon/LongSound.java
// Path: src/main/java/ca/hedlund/jpraat/binding/jna/NativeIntptr_t.java // public final class NativeIntptr_t extends IntegerType { // // private static final long serialVersionUID = 1L; // // public final static int SIZE = Native.LONG_SIZE; // // public NativeIntptr_t() { // this(0L); // } // // /** Create a NativeIntptr_t with the given value. */ // public NativeIntptr_t(long value) { // this(value, false); // } // // /** Create a NativeIntptr_t with the given value, optionally unsigned. */ // public NativeIntptr_t(long value, boolean unsigned) { // super(SIZE, value, unsigned); // } // // }
import java.util.concurrent.atomic.*; import ca.hedlund.jpraat.binding.jna.NativeIntptr_t; import com.sun.jna.*; import ca.hedlund.jpraat.binding.*; import ca.hedlund.jpraat.binding.sys.*; import ca.hedlund.jpraat.exceptions.*;
} finally { Praat.wrapperLock.unlock(); } return retVal; } public boolean haveWindow (double tmin, double tmax) throws PraatException { boolean retVal = false; try { Praat.wrapperLock.lock(); retVal = Praat.INSTANCE.LongSound_haveWindow_wrapped(this, tmin, tmax); Praat.checkAndClearLastError(); } catch (PraatException e) { throw e; } finally { Praat.wrapperLock.unlock(); } return retVal; } public void getWindowExtrema (double tmin, double tmax, long channel, AtomicReference<Double> minimum, AtomicReference<Double> maximum) throws PraatException { final Pointer pmin = new Memory(Native.getNativeSize(Double.class)*2); final Pointer pmax = pmin.getPointer(1); try { Praat.wrapperLock.lock(); Praat.INSTANCE.LongSound_getWindowExtrema_wrapped(this, tmin, tmax,
// Path: src/main/java/ca/hedlund/jpraat/binding/jna/NativeIntptr_t.java // public final class NativeIntptr_t extends IntegerType { // // private static final long serialVersionUID = 1L; // // public final static int SIZE = Native.LONG_SIZE; // // public NativeIntptr_t() { // this(0L); // } // // /** Create a NativeIntptr_t with the given value. */ // public NativeIntptr_t(long value) { // this(value, false); // } // // /** Create a NativeIntptr_t with the given value, optionally unsigned. */ // public NativeIntptr_t(long value, boolean unsigned) { // super(SIZE, value, unsigned); // } // // } // Path: src/main/java/ca/hedlund/jpraat/binding/fon/LongSound.java import java.util.concurrent.atomic.*; import ca.hedlund.jpraat.binding.jna.NativeIntptr_t; import com.sun.jna.*; import ca.hedlund.jpraat.binding.*; import ca.hedlund.jpraat.binding.sys.*; import ca.hedlund.jpraat.exceptions.*; } finally { Praat.wrapperLock.unlock(); } return retVal; } public boolean haveWindow (double tmin, double tmax) throws PraatException { boolean retVal = false; try { Praat.wrapperLock.lock(); retVal = Praat.INSTANCE.LongSound_haveWindow_wrapped(this, tmin, tmax); Praat.checkAndClearLastError(); } catch (PraatException e) { throw e; } finally { Praat.wrapperLock.unlock(); } return retVal; } public void getWindowExtrema (double tmin, double tmax, long channel, AtomicReference<Double> minimum, AtomicReference<Double> maximum) throws PraatException { final Pointer pmin = new Memory(Native.getNativeSize(Double.class)*2); final Pointer pmax = pmin.getPointer(1); try { Praat.wrapperLock.lock(); Praat.INSTANCE.LongSound_getWindowExtrema_wrapped(this, tmin, tmax,
new NativeIntptr_t(channel), pmin, pmax);
ghedlund/jpraat
src/main/java/ca/hedlund/jpraat/binding/fon/PointProcess.java
// Path: src/main/java/ca/hedlund/jpraat/binding/melder/MelderIntegerRange.java // public class MelderIntegerRange extends Structure { // // public int first, last = 0; // // public class ByValue extends MelderIntegerRange implements Structure.ByValue {}; // // public class ByReference extends MelderIntegerRange implements Structure.ByReference {}; // // }
import java.util.concurrent.atomic.*; import ca.hedlund.jpraat.binding.melder.MelderIntegerRange; import com.sun.jna.*; import ca.hedlund.jpraat.binding.*; import ca.hedlund.jpraat.binding.jna.*; import ca.hedlund.jpraat.exceptions.*;
finishingTime, density); Praat.checkAndClearLastError(); } catch (PraatException e) { throw e; } finally { Praat.wrapperLock.unlock(); } return retVal; } public void init (double startingTime, double finishingTime, long initialMaxnt) { Praat.INSTANCE.PointProcess_init(this, startingTime, finishingTime, new NativeIntptr_t(initialMaxnt)); } public long getLowIndex (double t) { return Praat.INSTANCE.PointProcess_getLowIndex(this, t).longValue(); } public long getHighIndex (double t) { return Praat.INSTANCE.PointProcess_getHighIndex(this, t).longValue(); } public long getNearestIndex (double t) { return Praat.INSTANCE.PointProcess_getNearestIndex(this, t).longValue(); } public double getValueAtIndex (long idx) { return Praat.INSTANCE.PointProcess_getValueAtIndex(this, new NativeIntptr_t(idx)); }
// Path: src/main/java/ca/hedlund/jpraat/binding/melder/MelderIntegerRange.java // public class MelderIntegerRange extends Structure { // // public int first, last = 0; // // public class ByValue extends MelderIntegerRange implements Structure.ByValue {}; // // public class ByReference extends MelderIntegerRange implements Structure.ByReference {}; // // } // Path: src/main/java/ca/hedlund/jpraat/binding/fon/PointProcess.java import java.util.concurrent.atomic.*; import ca.hedlund.jpraat.binding.melder.MelderIntegerRange; import com.sun.jna.*; import ca.hedlund.jpraat.binding.*; import ca.hedlund.jpraat.binding.jna.*; import ca.hedlund.jpraat.exceptions.*; finishingTime, density); Praat.checkAndClearLastError(); } catch (PraatException e) { throw e; } finally { Praat.wrapperLock.unlock(); } return retVal; } public void init (double startingTime, double finishingTime, long initialMaxnt) { Praat.INSTANCE.PointProcess_init(this, startingTime, finishingTime, new NativeIntptr_t(initialMaxnt)); } public long getLowIndex (double t) { return Praat.INSTANCE.PointProcess_getLowIndex(this, t).longValue(); } public long getHighIndex (double t) { return Praat.INSTANCE.PointProcess_getHighIndex(this, t).longValue(); } public long getNearestIndex (double t) { return Praat.INSTANCE.PointProcess_getNearestIndex(this, t).longValue(); } public double getValueAtIndex (long idx) { return Praat.INSTANCE.PointProcess_getValueAtIndex(this, new NativeIntptr_t(idx)); }
public MelderIntegerRange getWindowPoints (double tmin, double tmax) {
StratusLab/marketplace
server/war/src/main/java/eu/stratuslab/marketplace/server/cfg/Configuration.java
// Path: server/war/src/main/java/eu/stratuslab/marketplace/server/MarketplaceException.java // @SuppressWarnings("serial") // public class MarketplaceException extends RuntimeException { // // public MarketplaceException() { // } // // public MarketplaceException(String message) { // super(message); // } // // public MarketplaceException(String message, Throwable cause){ // super(message, cause); // } // // }
import java.util.logging.Logger; import eu.stratuslab.marketplace.server.MarketplaceException; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Properties;
private static List<File> getConfigurationFileLocations() { ArrayList<File> locations = new ArrayList<File>(); // Possible locations for the configuration file are the current working // directory, the user's home directory, or the standard system // location, in that order. File[] dirs = { new File(System.getProperty("user.dir")), new File(System.getProperty("user.home")), new File("/etc/stratuslab/") }; for (File dir : dirs) { locations.add(new File(dir, CONFIG_FILENAME)); } return Collections.unmodifiableList(locations); } private static Properties getConfigurationProperties( List<File> configFileLocations) { for (File f : configFileLocations) { if (f.canRead()) { LOGGER.info("using configuration: " + f.getAbsolutePath()); Properties properties = loadProperties(f); validateConfiguration(properties); return properties; } }
// Path: server/war/src/main/java/eu/stratuslab/marketplace/server/MarketplaceException.java // @SuppressWarnings("serial") // public class MarketplaceException extends RuntimeException { // // public MarketplaceException() { // } // // public MarketplaceException(String message) { // super(message); // } // // public MarketplaceException(String message, Throwable cause){ // super(message, cause); // } // // } // Path: server/war/src/main/java/eu/stratuslab/marketplace/server/cfg/Configuration.java import java.util.logging.Logger; import eu.stratuslab.marketplace.server.MarketplaceException; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Properties; private static List<File> getConfigurationFileLocations() { ArrayList<File> locations = new ArrayList<File>(); // Possible locations for the configuration file are the current working // directory, the user's home directory, or the standard system // location, in that order. File[] dirs = { new File(System.getProperty("user.dir")), new File(System.getProperty("user.home")), new File("/etc/stratuslab/") }; for (File dir : dirs) { locations.add(new File(dir, CONFIG_FILENAME)); } return Collections.unmodifiableList(locations); } private static Properties getConfigurationProperties( List<File> configFileLocations) { for (File f : configFileLocations) { if (f.canRead()) { LOGGER.info("using configuration: " + f.getAbsolutePath()); Properties properties = loadProperties(f); validateConfiguration(properties); return properties; } }
throw new MarketplaceException("cannot locate configuration file");
StratusLab/marketplace
server/war/src/main/java/eu/stratuslab/marketplace/server/store/rdf/sesame/SesameRdfStore.java
// Path: server/war/src/main/java/eu/stratuslab/marketplace/server/MarketplaceException.java // @SuppressWarnings("serial") // public class MarketplaceException extends RuntimeException { // // public MarketplaceException() { // } // // public MarketplaceException(String message) { // super(message); // } // // public MarketplaceException(String message, Throwable cause){ // super(message, cause); // } // // } // // Path: server/war/src/main/java/eu/stratuslab/marketplace/server/store/rdf/RdfStore.java // public abstract class RdfStore { // // public abstract void shutdown(); // public abstract void initialize(); // public abstract boolean store(String identifier, String entry); // public abstract void tag(String identifier, String tag); // public abstract void removeTag(String identifier, String tag); // public abstract List<Map<String, String>> getRdfEntriesAsMap(String query) throws MarketplaceException; // public abstract String getRdfEntriesAsXml(String query) throws MarketplaceException; // public abstract String getRdfEntriesAsJson(String query) throws MarketplaceException; // public abstract String getRdfEntry(String uri) throws MarketplaceException; // public abstract void remove(String identifier); // public abstract int size(); // }
import static eu.stratuslab.marketplace.metadata.MetadataNamespaceContext.MARKETPLACE_URI; import static eu.stratuslab.marketplace.metadata.MetadataNamespaceContext.SLTERMS_NS_URI; import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.Reader; import java.io.StringReader; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.logging.Logger; import org.openrdf.model.Value; import org.openrdf.model.ValueFactory; import org.openrdf.model.impl.LiteralImpl; import org.openrdf.query.BindingSet; import org.openrdf.query.MalformedQueryException; import org.openrdf.query.QueryEvaluationException; import org.openrdf.query.QueryLanguage; import org.openrdf.query.TupleQuery; import org.openrdf.query.TupleQueryResult; import org.openrdf.query.resultio.TupleQueryResultWriter; import org.openrdf.query.resultio.TupleQueryResultWriterFactory; import org.openrdf.query.resultio.sparqlxml.SPARQLResultsXMLWriterFactory; import org.openrdf.query.resultio.sparqljson.SPARQLResultsJSONWriterFactory; import org.openrdf.repository.Repository; import org.openrdf.repository.RepositoryConnection; import org.openrdf.repository.RepositoryException; import org.openrdf.repository.RepositoryLockedException; import org.openrdf.repository.sail.SailRepository; import org.openrdf.rio.RDFFormat; import org.openrdf.sail.LockManager; import org.openrdf.sail.SailException; import org.openrdf.sail.SailLockedException; import org.openrdf.sail.helpers.SailBase; import eu.stratuslab.marketplace.server.MarketplaceException; import eu.stratuslab.marketplace.server.store.rdf.RdfStore;
} public boolean store(String identifier, String entry) { boolean success = false; String idURI = "/" + identifier; try { RepositoryConnection con = getMetadataStore().getConnection(); ValueFactory vf = con.getValueFactory(); Reader reader = new StringReader(entry); try { con.clear(vf.createURI(idURI)); con.add(reader, MARKETPLACE_URI, RDFFormat.RDFXML, vf.createURI(idURI)); } finally { con.close(); } success = true; } catch (RepositoryException e) { LOGGER.severe("Unable to clear metadata entry: " + e.getMessage()); } catch (java.io.IOException e) { LOGGER.severe("Error storing metadata entry: " + e.getMessage()); } catch (org.openrdf.rio.RDFParseException e) { LOGGER.severe(e.getMessage()); } return success; } @Override
// Path: server/war/src/main/java/eu/stratuslab/marketplace/server/MarketplaceException.java // @SuppressWarnings("serial") // public class MarketplaceException extends RuntimeException { // // public MarketplaceException() { // } // // public MarketplaceException(String message) { // super(message); // } // // public MarketplaceException(String message, Throwable cause){ // super(message, cause); // } // // } // // Path: server/war/src/main/java/eu/stratuslab/marketplace/server/store/rdf/RdfStore.java // public abstract class RdfStore { // // public abstract void shutdown(); // public abstract void initialize(); // public abstract boolean store(String identifier, String entry); // public abstract void tag(String identifier, String tag); // public abstract void removeTag(String identifier, String tag); // public abstract List<Map<String, String>> getRdfEntriesAsMap(String query) throws MarketplaceException; // public abstract String getRdfEntriesAsXml(String query) throws MarketplaceException; // public abstract String getRdfEntriesAsJson(String query) throws MarketplaceException; // public abstract String getRdfEntry(String uri) throws MarketplaceException; // public abstract void remove(String identifier); // public abstract int size(); // } // Path: server/war/src/main/java/eu/stratuslab/marketplace/server/store/rdf/sesame/SesameRdfStore.java import static eu.stratuslab.marketplace.metadata.MetadataNamespaceContext.MARKETPLACE_URI; import static eu.stratuslab.marketplace.metadata.MetadataNamespaceContext.SLTERMS_NS_URI; import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.Reader; import java.io.StringReader; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.logging.Logger; import org.openrdf.model.Value; import org.openrdf.model.ValueFactory; import org.openrdf.model.impl.LiteralImpl; import org.openrdf.query.BindingSet; import org.openrdf.query.MalformedQueryException; import org.openrdf.query.QueryEvaluationException; import org.openrdf.query.QueryLanguage; import org.openrdf.query.TupleQuery; import org.openrdf.query.TupleQueryResult; import org.openrdf.query.resultio.TupleQueryResultWriter; import org.openrdf.query.resultio.TupleQueryResultWriterFactory; import org.openrdf.query.resultio.sparqlxml.SPARQLResultsXMLWriterFactory; import org.openrdf.query.resultio.sparqljson.SPARQLResultsJSONWriterFactory; import org.openrdf.repository.Repository; import org.openrdf.repository.RepositoryConnection; import org.openrdf.repository.RepositoryException; import org.openrdf.repository.RepositoryLockedException; import org.openrdf.repository.sail.SailRepository; import org.openrdf.rio.RDFFormat; import org.openrdf.sail.LockManager; import org.openrdf.sail.SailException; import org.openrdf.sail.SailLockedException; import org.openrdf.sail.helpers.SailBase; import eu.stratuslab.marketplace.server.MarketplaceException; import eu.stratuslab.marketplace.server.store.rdf.RdfStore; } public boolean store(String identifier, String entry) { boolean success = false; String idURI = "/" + identifier; try { RepositoryConnection con = getMetadataStore().getConnection(); ValueFactory vf = con.getValueFactory(); Reader reader = new StringReader(entry); try { con.clear(vf.createURI(idURI)); con.add(reader, MARKETPLACE_URI, RDFFormat.RDFXML, vf.createURI(idURI)); } finally { con.close(); } success = true; } catch (RepositoryException e) { LOGGER.severe("Unable to clear metadata entry: " + e.getMessage()); } catch (java.io.IOException e) { LOGGER.severe("Error storing metadata entry: " + e.getMessage()); } catch (org.openrdf.rio.RDFParseException e) { LOGGER.severe(e.getMessage()); } return success; } @Override
public String getRdfEntry(String uri) throws MarketplaceException {
StratusLab/marketplace
server/war/src/main/java/eu/stratuslab/marketplace/server/utils/MetadataFileUtils.java
// Path: server/war/src/main/java/eu/stratuslab/marketplace/server/cfg/Configuration.java // public final class Configuration { // // private static final Logger LOGGER = Logger.getLogger("org.restlet"); // // private static final String CONFIG_FILENAME = "marketplace.cfg"; // // private static final Properties PROPERTIES; // // static { // List<File> configFileLocations = getConfigurationFileLocations(); // PROPERTIES = getConfigurationProperties(configFileLocations); // } // // private Configuration() { // // } // // private static List<File> getConfigurationFileLocations() { // // ArrayList<File> locations = new ArrayList<File>(); // // // Possible locations for the configuration file are the current working // // directory, the user's home directory, or the standard system // // location, in that order. // File[] dirs = { new File(System.getProperty("user.dir")), // new File(System.getProperty("user.home")), // new File("/etc/stratuslab/") }; // // for (File dir : dirs) { // locations.add(new File(dir, CONFIG_FILENAME)); // } // // return Collections.unmodifiableList(locations); // } // // private static Properties getConfigurationProperties( // List<File> configFileLocations) { // // for (File f : configFileLocations) { // if (f.canRead()) { // LOGGER.info("using configuration: " + f.getAbsolutePath()); // Properties properties = loadProperties(f); // validateConfiguration(properties); // return properties; // } // } // throw new MarketplaceException("cannot locate configuration file"); // } // // private static Properties loadProperties(File configFile) { // // Properties properties = new Properties(); // // try { // Reader reader = new InputStreamReader( // new FileInputStream(configFile), "UTF-8"); // try { // properties.load(reader); // } catch (IOException consumed) { // // TODO: Add logging. // } finally { // try { // reader.close(); // } catch (IOException consumed) { // // TODO: Add logging. // } // } // } catch (FileNotFoundException consumed) { // // Return empty properties file. // } catch (UnsupportedEncodingException e) { // // Return empty properties file. // } // // return properties; // } // // public static String getParameterValue(Parameter parameter) { // return parameter.getProperty(PROPERTIES); // } // // public static boolean getParameterValueAsBoolean(Parameter parameter) { // return Boolean.parseBoolean(parameter.getProperty(PROPERTIES)); // } // // public static int getParameterValueAsInt(Parameter parameter) { // return Integer.parseInt(parameter.getProperty(PROPERTIES)); // } // // public static long getParameterValueAsLong(Parameter parameter) { // return Long.parseLong(parameter.getProperty(PROPERTIES)); // } // // public static File getParameterValueAsFile(Parameter parameter) { // return new File(parameter.getProperty(PROPERTIES)); // } // // private static void validateConfiguration(Properties properties) { // checkAllParametersAreValid(properties); // checkAllParametersAreKnown(properties); // } // // private static void checkAllParametersAreValid(Properties properties) { // for (Parameter p : Parameter.values()) { // String value = p.getProperty(properties); // if (value != null) { // p.validate(value); // } // } // } // // private static void checkAllParametersAreKnown(Properties properties) { // for (Object key : properties.keySet()) { // Parameter.parameterFromKey(key); // } // } // // }
import static eu.stratuslab.marketplace.server.cfg.Parameter.PENDING_DIR; import java.io.ByteArrayInputStream; import java.io.Closeable; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStreamWriter; import java.io.Reader; import java.io.UnsupportedEncodingException; import java.io.Writer; import java.nio.channels.Channels; import java.util.Scanner; import java.util.UUID; import javax.xml.parsers.DocumentBuilder; import org.restlet.data.Status; import org.restlet.representation.Representation; import org.restlet.resource.ResourceException; import org.w3c.dom.Document; import org.xml.sax.SAXException; import eu.stratuslab.marketplace.XMLUtils; import eu.stratuslab.marketplace.metadata.MetadataUtils; import eu.stratuslab.marketplace.server.cfg.Configuration;
/** * Created as part of the StratusLab project (http://stratuslab.eu), * co-funded by the European Commission under the Grant Agreement * INSFO-RI-261552. * * Copyright (c) 2011 * * 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 eu.stratuslab.marketplace.server.utils; public final class MetadataFileUtils { private static final String ENCODING = "UTF-8"; private MetadataFileUtils(){} public static File writeContentsToDisk(Representation entity) { char[] buffer = new char[4096];
// Path: server/war/src/main/java/eu/stratuslab/marketplace/server/cfg/Configuration.java // public final class Configuration { // // private static final Logger LOGGER = Logger.getLogger("org.restlet"); // // private static final String CONFIG_FILENAME = "marketplace.cfg"; // // private static final Properties PROPERTIES; // // static { // List<File> configFileLocations = getConfigurationFileLocations(); // PROPERTIES = getConfigurationProperties(configFileLocations); // } // // private Configuration() { // // } // // private static List<File> getConfigurationFileLocations() { // // ArrayList<File> locations = new ArrayList<File>(); // // // Possible locations for the configuration file are the current working // // directory, the user's home directory, or the standard system // // location, in that order. // File[] dirs = { new File(System.getProperty("user.dir")), // new File(System.getProperty("user.home")), // new File("/etc/stratuslab/") }; // // for (File dir : dirs) { // locations.add(new File(dir, CONFIG_FILENAME)); // } // // return Collections.unmodifiableList(locations); // } // // private static Properties getConfigurationProperties( // List<File> configFileLocations) { // // for (File f : configFileLocations) { // if (f.canRead()) { // LOGGER.info("using configuration: " + f.getAbsolutePath()); // Properties properties = loadProperties(f); // validateConfiguration(properties); // return properties; // } // } // throw new MarketplaceException("cannot locate configuration file"); // } // // private static Properties loadProperties(File configFile) { // // Properties properties = new Properties(); // // try { // Reader reader = new InputStreamReader( // new FileInputStream(configFile), "UTF-8"); // try { // properties.load(reader); // } catch (IOException consumed) { // // TODO: Add logging. // } finally { // try { // reader.close(); // } catch (IOException consumed) { // // TODO: Add logging. // } // } // } catch (FileNotFoundException consumed) { // // Return empty properties file. // } catch (UnsupportedEncodingException e) { // // Return empty properties file. // } // // return properties; // } // // public static String getParameterValue(Parameter parameter) { // return parameter.getProperty(PROPERTIES); // } // // public static boolean getParameterValueAsBoolean(Parameter parameter) { // return Boolean.parseBoolean(parameter.getProperty(PROPERTIES)); // } // // public static int getParameterValueAsInt(Parameter parameter) { // return Integer.parseInt(parameter.getProperty(PROPERTIES)); // } // // public static long getParameterValueAsLong(Parameter parameter) { // return Long.parseLong(parameter.getProperty(PROPERTIES)); // } // // public static File getParameterValueAsFile(Parameter parameter) { // return new File(parameter.getProperty(PROPERTIES)); // } // // private static void validateConfiguration(Properties properties) { // checkAllParametersAreValid(properties); // checkAllParametersAreKnown(properties); // } // // private static void checkAllParametersAreValid(Properties properties) { // for (Parameter p : Parameter.values()) { // String value = p.getProperty(properties); // if (value != null) { // p.validate(value); // } // } // } // // private static void checkAllParametersAreKnown(Properties properties) { // for (Object key : properties.keySet()) { // Parameter.parameterFromKey(key); // } // } // // } // Path: server/war/src/main/java/eu/stratuslab/marketplace/server/utils/MetadataFileUtils.java import static eu.stratuslab.marketplace.server.cfg.Parameter.PENDING_DIR; import java.io.ByteArrayInputStream; import java.io.Closeable; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStreamWriter; import java.io.Reader; import java.io.UnsupportedEncodingException; import java.io.Writer; import java.nio.channels.Channels; import java.util.Scanner; import java.util.UUID; import javax.xml.parsers.DocumentBuilder; import org.restlet.data.Status; import org.restlet.representation.Representation; import org.restlet.resource.ResourceException; import org.w3c.dom.Document; import org.xml.sax.SAXException; import eu.stratuslab.marketplace.XMLUtils; import eu.stratuslab.marketplace.metadata.MetadataUtils; import eu.stratuslab.marketplace.server.cfg.Configuration; /** * Created as part of the StratusLab project (http://stratuslab.eu), * co-funded by the European Commission under the Grant Agreement * INSFO-RI-261552. * * Copyright (c) 2011 * * 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 eu.stratuslab.marketplace.server.utils; public final class MetadataFileUtils { private static final String ENCODING = "UTF-8"; private MetadataFileUtils(){} public static File writeContentsToDisk(Representation entity) { char[] buffer = new char[4096];
File storeDirectory = Configuration
StratusLab/marketplace
server/war/src/main/java/eu/stratuslab/marketplace/server/resources/QueryResource.java
// Path: server/war/src/main/java/eu/stratuslab/marketplace/server/MarketplaceException.java // @SuppressWarnings("serial") // public class MarketplaceException extends RuntimeException { // // public MarketplaceException() { // } // // public MarketplaceException(String message) { // super(message); // } // // public MarketplaceException(String message, Throwable cause){ // super(message, cause); // } // // }
import static eu.stratuslab.marketplace.metadata.MetadataNamespaceContext.MARKETPLACE_URI; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.logging.Logger; import org.openrdf.query.MalformedQueryException; import org.openrdf.query.QueryLanguage; import org.openrdf.query.parser.QueryParser; import org.openrdf.query.parser.QueryParserUtil; import org.restlet.data.Form; import org.restlet.data.MediaType; import org.restlet.data.Status; import org.restlet.representation.Representation; import org.restlet.representation.StringRepresentation; import org.restlet.resource.Get; import org.restlet.resource.ResourceException; import com.hp.hpl.jena.query.Query; import com.hp.hpl.jena.sparql.lang.ParserSPARQL11; import com.hp.hpl.jena.sparql.syntax.Element; import com.hp.hpl.jena.sparql.syntax.ElementGroup; import com.hp.hpl.jena.sparql.syntax.ElementNamedGraph; import eu.stratuslab.marketplace.server.MarketplaceException;
SparqlQuery query = new SparqlQuery( getQueryFromRequest(), SparqlQuery.OUTPUT_JSON); String results = (String)executeQuery(query); if(results == null){ results = ""; } representation = new StringRepresentation(results, MediaType.APPLICATION_SPARQL_RESULTS_JSON); } catch (MalformedQueryException e) { throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, e .getMessage(), e); } return representation; } private Object executeQuery(SparqlQuery query){ //check that query is allowed. if(!query.isAllowed()){ throw new ResourceException( Status.CLIENT_ERROR_BAD_REQUEST, "query not allowed."); } Object results = null; try { results = getFormattedQueryResults(query);
// Path: server/war/src/main/java/eu/stratuslab/marketplace/server/MarketplaceException.java // @SuppressWarnings("serial") // public class MarketplaceException extends RuntimeException { // // public MarketplaceException() { // } // // public MarketplaceException(String message) { // super(message); // } // // public MarketplaceException(String message, Throwable cause){ // super(message, cause); // } // // } // Path: server/war/src/main/java/eu/stratuslab/marketplace/server/resources/QueryResource.java import static eu.stratuslab.marketplace.metadata.MetadataNamespaceContext.MARKETPLACE_URI; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.logging.Logger; import org.openrdf.query.MalformedQueryException; import org.openrdf.query.QueryLanguage; import org.openrdf.query.parser.QueryParser; import org.openrdf.query.parser.QueryParserUtil; import org.restlet.data.Form; import org.restlet.data.MediaType; import org.restlet.data.Status; import org.restlet.representation.Representation; import org.restlet.representation.StringRepresentation; import org.restlet.resource.Get; import org.restlet.resource.ResourceException; import com.hp.hpl.jena.query.Query; import com.hp.hpl.jena.sparql.lang.ParserSPARQL11; import com.hp.hpl.jena.sparql.syntax.Element; import com.hp.hpl.jena.sparql.syntax.ElementGroup; import com.hp.hpl.jena.sparql.syntax.ElementNamedGraph; import eu.stratuslab.marketplace.server.MarketplaceException; SparqlQuery query = new SparqlQuery( getQueryFromRequest(), SparqlQuery.OUTPUT_JSON); String results = (String)executeQuery(query); if(results == null){ results = ""; } representation = new StringRepresentation(results, MediaType.APPLICATION_SPARQL_RESULTS_JSON); } catch (MalformedQueryException e) { throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, e .getMessage(), e); } return representation; } private Object executeQuery(SparqlQuery query){ //check that query is allowed. if(!query.isAllowed()){ throw new ResourceException( Status.CLIENT_ERROR_BAD_REQUEST, "query not allowed."); } Object results = null; try { results = getFormattedQueryResults(query);
} catch (MarketplaceException e) {
StratusLab/marketplace
server/war/src/main/java/eu/stratuslab/marketplace/server/resources/EndorsersResource.java
// Path: server/war/src/main/java/eu/stratuslab/marketplace/server/MarketplaceException.java // @SuppressWarnings("serial") // public class MarketplaceException extends RuntimeException { // // public MarketplaceException() { // } // // public MarketplaceException(String message) { // super(message); // } // // public MarketplaceException(String message, Throwable cause){ // super(message, cause); // } // // }
import eu.emi.security.authn.x509.helpers.JavaAndBCStyle; import eu.emi.security.authn.x509.impl.X500NameUtils; import eu.stratuslab.marketplace.server.MarketplaceException; import java.util.List; import java.util.Map; import java.util.ArrayList; import org.restlet.data.MediaType; import org.restlet.data.Status; import org.restlet.representation.Representation; import org.restlet.representation.StringRepresentation; import org.restlet.resource.Get; import org.restlet.resource.ResourceException;
/** * Created as part of the StratusLab project (http://stratuslab.eu), * co-funded by the European Commission under the Grant Agreement * INSFO-RI-261552. * * Copyright (c) 2011 * * 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 eu.stratuslab.marketplace.server.resources; /** * This resource represents a list of endorsers */ public class EndorsersResource extends BaseResource { @Get("html") public Representation toHtml() { List<Map<String, String>> results = new ArrayList<Map<String, String>>(); try { results = query(getQueryBuilder().buildEndorsersQuery());
// Path: server/war/src/main/java/eu/stratuslab/marketplace/server/MarketplaceException.java // @SuppressWarnings("serial") // public class MarketplaceException extends RuntimeException { // // public MarketplaceException() { // } // // public MarketplaceException(String message) { // super(message); // } // // public MarketplaceException(String message, Throwable cause){ // super(message, cause); // } // // } // Path: server/war/src/main/java/eu/stratuslab/marketplace/server/resources/EndorsersResource.java import eu.emi.security.authn.x509.helpers.JavaAndBCStyle; import eu.emi.security.authn.x509.impl.X500NameUtils; import eu.stratuslab.marketplace.server.MarketplaceException; import java.util.List; import java.util.Map; import java.util.ArrayList; import org.restlet.data.MediaType; import org.restlet.data.Status; import org.restlet.representation.Representation; import org.restlet.representation.StringRepresentation; import org.restlet.resource.Get; import org.restlet.resource.ResourceException; /** * Created as part of the StratusLab project (http://stratuslab.eu), * co-funded by the European Commission under the Grant Agreement * INSFO-RI-261552. * * Copyright (c) 2011 * * 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 eu.stratuslab.marketplace.server.resources; /** * This resource represents a list of endorsers */ public class EndorsersResource extends BaseResource { @Get("html") public Representation toHtml() { List<Map<String, String>> results = new ArrayList<Map<String, String>>(); try { results = query(getQueryBuilder().buildEndorsersQuery());
} catch(MarketplaceException e){
StratusLab/marketplace
server/war/src/main/java/eu/stratuslab/marketplace/server/query/SparqlBuilder.java
// Path: server/war/src/main/java/eu/stratuslab/marketplace/server/utils/MarketplaceUtils.java // public final class MarketplaceUtils { // // private static final String DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss'Z'"; // // private MarketplaceUtils(){} // // public static String getCurrentDate() { // return getFormattedDate(new Date()); // } // // public static Date getFormattedDate(String timestamp) throws ParseException{ // return getDateFormat().parse(timestamp); // } // // public static String getFormattedDate(Date date){ // return getDateFormat().format(date); // } // // private static DateFormat getDateFormat() { // SimpleDateFormat format = new SimpleDateFormat(DATE_FORMAT); // format.setLenient(false); // format.setTimeZone(TimeZone.getTimeZone("UTC")); // // return format; // } // // }
import java.util.Map; import eu.stratuslab.marketplace.PatternUtils; import eu.stratuslab.marketplace.server.utils.MarketplaceUtils;
//Build the paging query String searching = buildSearchingFilter(requestQueryValues); String where = WHERE + SparqlUtils.WHERE_BLOCK; StringBuilder wherePredicate = new StringBuilder( where); wherePredicate.append(filter); if (!hasDate) { wherePredicate .append(SparqlUtils.getLatestFilter()); } setStatus(wherePredicate, status); setAccess(wherePredicate, access); wherePredicate.append(searching); wherePredicate.append(" }"); query.append(wherePredicate); query.append(SparqlUtils.GROUP_BY); } private void setStatus(StringBuilder wherePredicate, String status){ if(status.equals("expired")){ //implies validity date in the past and not deprecated wherePredicate .append(SparqlUtils.getExpiredFilter(
// Path: server/war/src/main/java/eu/stratuslab/marketplace/server/utils/MarketplaceUtils.java // public final class MarketplaceUtils { // // private static final String DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss'Z'"; // // private MarketplaceUtils(){} // // public static String getCurrentDate() { // return getFormattedDate(new Date()); // } // // public static Date getFormattedDate(String timestamp) throws ParseException{ // return getDateFormat().parse(timestamp); // } // // public static String getFormattedDate(Date date){ // return getDateFormat().format(date); // } // // private static DateFormat getDateFormat() { // SimpleDateFormat format = new SimpleDateFormat(DATE_FORMAT); // format.setLenient(false); // format.setTimeZone(TimeZone.getTimeZone("UTC")); // // return format; // } // // } // Path: server/war/src/main/java/eu/stratuslab/marketplace/server/query/SparqlBuilder.java import java.util.Map; import eu.stratuslab.marketplace.PatternUtils; import eu.stratuslab.marketplace.server.utils.MarketplaceUtils; //Build the paging query String searching = buildSearchingFilter(requestQueryValues); String where = WHERE + SparqlUtils.WHERE_BLOCK; StringBuilder wherePredicate = new StringBuilder( where); wherePredicate.append(filter); if (!hasDate) { wherePredicate .append(SparqlUtils.getLatestFilter()); } setStatus(wherePredicate, status); setAccess(wherePredicate, access); wherePredicate.append(searching); wherePredicate.append(" }"); query.append(wherePredicate); query.append(SparqlUtils.GROUP_BY); } private void setStatus(StringBuilder wherePredicate, String status){ if(status.equals("expired")){ //implies validity date in the past and not deprecated wherePredicate .append(SparqlUtils.getExpiredFilter(
MarketplaceUtils.getCurrentDate()));
StratusLab/marketplace
server/war/src/main/java/eu/stratuslab/marketplace/server/store/file/GitStore.java
// Path: server/war/src/main/java/eu/stratuslab/marketplace/server/utils/MetadataFileUtils.java // public final class MetadataFileUtils { // // private static final String ENCODING = "UTF-8"; // // private MetadataFileUtils(){} // // public static File writeContentsToDisk(Representation entity) { // // char[] buffer = new char[4096]; // // File storeDirectory = Configuration // .getParameterValueAsFile(PENDING_DIR); // // File output = new File(storeDirectory, UUID.randomUUID().toString()); // // Reader reader = null; // Writer writer = null; // // try { // reader = Channels.newReader(entity.getChannel(), ENCODING); // writer = new OutputStreamWriter( // new FileOutputStream(output), ENCODING); // // int nchars = reader.read(buffer); // while (nchars >= 0) { // writer.write(buffer, 0, nchars); // nchars = reader.read(buffer); // } // // } catch (IOException consumed) { // // } finally { // closeReliably(reader); // closeReliably(writer); // } // return output; // } // // public static String readFileAsString(String filePath) // throws IOException { // // StringBuilder text = new StringBuilder(); // String nl = System.getProperty("line.separator"); // Scanner scanner = new Scanner(new FileInputStream(filePath), // ENCODING); // try { // while (scanner.hasNextLine()){ // text.append(scanner.nextLine() + nl); // } // } // finally{ // scanner.close(); // } // // return text.toString(); // } // // public static void closeReliably(Closeable closeable) { // // if (closeable != null) { // try { // closeable.close(); // } catch (IOException consumed) { // } // } // } // // public static String stripSignature(String signedString) { // // DocumentBuilder db = XMLUtils.newDocumentBuilder(false); // Document datumDoc = null; // String rdfEntry = ""; // try { // datumDoc = db.parse(new ByteArrayInputStream(signedString // .getBytes(ENCODING))); // // // Create a deep copy of the document and strip signature elements. // Document copy = (Document) datumDoc.cloneNode(true); // MetadataUtils.stripSignatureElements(copy); // rdfEntry = XMLUtils.documentToString(copy); // } catch (SAXException e) { // throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, // "Unable to parse metadata: " + e.getMessage(), e); // } catch (IOException e) { // throw new ResourceException(e); // } // // return rdfEntry; // } // // public static Document extractXmlDocument(String rdf){ // Document datumDoc = null; // // try { // // datumDoc = extractXmlDocument(new ByteArrayInputStream( // rdf.getBytes(ENCODING))); // // } catch (UnsupportedEncodingException e) { // throw new ResourceException(e); // } // // return datumDoc; // } // // public static Document extractXmlDocument(InputStream stream) { // // DocumentBuilder db = XMLUtils.newDocumentBuilder(false); // Document datumDoc = null; // // try { // // datumDoc = db.parse(stream); // // } catch (SAXException e) { // throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, // "unable to parse metadata: " + e.getMessage(), e); // } catch (IOException e) { // throw new ResourceException(e); // } // // return datumDoc; // } // // public static boolean createIfNotExists(String path) { // // File dir = new File(path); // if (!dir.exists()) { // if (!dir.mkdirs()) { // return false; // } // } // // return true; // } // // }
import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.logging.Logger; import org.apache.commons.io.FilenameUtils; import org.w3c.dom.Document; import eu.stratuslab.marketplace.server.utils.MetadataFileUtils;
package eu.stratuslab.marketplace.server.store.file; public class GitStore extends FileStore { private FileStore fileStore; private HashMap<String, Document> localUpdates = new HashMap<String, Document>(); private GitManager manager; private static final Logger LOGGER = Logger.getLogger("org.restlet"); private FileMonitor monitor; public GitStore(String dataDir, FileStore store) { String gitDir = dataDir + File.separator + "metadata";
// Path: server/war/src/main/java/eu/stratuslab/marketplace/server/utils/MetadataFileUtils.java // public final class MetadataFileUtils { // // private static final String ENCODING = "UTF-8"; // // private MetadataFileUtils(){} // // public static File writeContentsToDisk(Representation entity) { // // char[] buffer = new char[4096]; // // File storeDirectory = Configuration // .getParameterValueAsFile(PENDING_DIR); // // File output = new File(storeDirectory, UUID.randomUUID().toString()); // // Reader reader = null; // Writer writer = null; // // try { // reader = Channels.newReader(entity.getChannel(), ENCODING); // writer = new OutputStreamWriter( // new FileOutputStream(output), ENCODING); // // int nchars = reader.read(buffer); // while (nchars >= 0) { // writer.write(buffer, 0, nchars); // nchars = reader.read(buffer); // } // // } catch (IOException consumed) { // // } finally { // closeReliably(reader); // closeReliably(writer); // } // return output; // } // // public static String readFileAsString(String filePath) // throws IOException { // // StringBuilder text = new StringBuilder(); // String nl = System.getProperty("line.separator"); // Scanner scanner = new Scanner(new FileInputStream(filePath), // ENCODING); // try { // while (scanner.hasNextLine()){ // text.append(scanner.nextLine() + nl); // } // } // finally{ // scanner.close(); // } // // return text.toString(); // } // // public static void closeReliably(Closeable closeable) { // // if (closeable != null) { // try { // closeable.close(); // } catch (IOException consumed) { // } // } // } // // public static String stripSignature(String signedString) { // // DocumentBuilder db = XMLUtils.newDocumentBuilder(false); // Document datumDoc = null; // String rdfEntry = ""; // try { // datumDoc = db.parse(new ByteArrayInputStream(signedString // .getBytes(ENCODING))); // // // Create a deep copy of the document and strip signature elements. // Document copy = (Document) datumDoc.cloneNode(true); // MetadataUtils.stripSignatureElements(copy); // rdfEntry = XMLUtils.documentToString(copy); // } catch (SAXException e) { // throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, // "Unable to parse metadata: " + e.getMessage(), e); // } catch (IOException e) { // throw new ResourceException(e); // } // // return rdfEntry; // } // // public static Document extractXmlDocument(String rdf){ // Document datumDoc = null; // // try { // // datumDoc = extractXmlDocument(new ByteArrayInputStream( // rdf.getBytes(ENCODING))); // // } catch (UnsupportedEncodingException e) { // throw new ResourceException(e); // } // // return datumDoc; // } // // public static Document extractXmlDocument(InputStream stream) { // // DocumentBuilder db = XMLUtils.newDocumentBuilder(false); // Document datumDoc = null; // // try { // // datumDoc = db.parse(stream); // // } catch (SAXException e) { // throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, // "unable to parse metadata: " + e.getMessage(), e); // } catch (IOException e) { // throw new ResourceException(e); // } // // return datumDoc; // } // // public static boolean createIfNotExists(String path) { // // File dir = new File(path); // if (!dir.exists()) { // if (!dir.mkdirs()) { // return false; // } // } // // return true; // } // // } // Path: server/war/src/main/java/eu/stratuslab/marketplace/server/store/file/GitStore.java import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.logging.Logger; import org.apache.commons.io.FilenameUtils; import org.w3c.dom.Document; import eu.stratuslab.marketplace.server.utils.MetadataFileUtils; package eu.stratuslab.marketplace.server.store.file; public class GitStore extends FileStore { private FileStore fileStore; private HashMap<String, Document> localUpdates = new HashMap<String, Document>(); private GitManager manager; private static final Logger LOGGER = Logger.getLogger("org.restlet"); private FileMonitor monitor; public GitStore(String dataDir, FileStore store) { String gitDir = dataDir + File.separator + "metadata";
MetadataFileUtils.createIfNotExists(gitDir);
StratusLab/marketplace
server/war/src/main/java/eu/stratuslab/marketplace/server/store/rdf/RdfStoreUpdater.java
// Path: server/war/src/main/java/eu/stratuslab/marketplace/server/store/file/FileStore.java // public abstract class FileStore { // // public abstract void store(String key, Document metadata); // public abstract void remove(String key); // public abstract String read(String key); // public abstract List<String> updates(int limit); // public abstract void shutdown(); // // }
import java.util.List; import java.util.logging.Logger; import eu.stratuslab.marketplace.server.store.file.FileStore;
package eu.stratuslab.marketplace.server.store.rdf; public class RdfStoreUpdater { private static final Logger LOGGER = Logger.getLogger("org.restlet"); private static final int DEFAULT_LIMIT = 1000; private int limit;
// Path: server/war/src/main/java/eu/stratuslab/marketplace/server/store/file/FileStore.java // public abstract class FileStore { // // public abstract void store(String key, Document metadata); // public abstract void remove(String key); // public abstract String read(String key); // public abstract List<String> updates(int limit); // public abstract void shutdown(); // // } // Path: server/war/src/main/java/eu/stratuslab/marketplace/server/store/rdf/RdfStoreUpdater.java import java.util.List; import java.util.logging.Logger; import eu.stratuslab.marketplace.server.store.file.FileStore; package eu.stratuslab.marketplace.server.store.rdf; public class RdfStoreUpdater { private static final Logger LOGGER = Logger.getLogger("org.restlet"); private static final int DEFAULT_LIMIT = 1000; private int limit;
private FileStore store;
StratusLab/marketplace
server/war/src/main/java/eu/stratuslab/marketplace/server/utils/Notifier.java
// Path: server/war/src/main/java/eu/stratuslab/marketplace/server/MarketplaceException.java // @SuppressWarnings("serial") // public class MarketplaceException extends RuntimeException { // // public MarketplaceException() { // } // // public MarketplaceException(String message) { // super(message); // } // // public MarketplaceException(String message, Throwable cause){ // super(message, cause); // } // // } // // Path: server/war/src/main/java/eu/stratuslab/marketplace/server/cfg/Configuration.java // public final class Configuration { // // private static final Logger LOGGER = Logger.getLogger("org.restlet"); // // private static final String CONFIG_FILENAME = "marketplace.cfg"; // // private static final Properties PROPERTIES; // // static { // List<File> configFileLocations = getConfigurationFileLocations(); // PROPERTIES = getConfigurationProperties(configFileLocations); // } // // private Configuration() { // // } // // private static List<File> getConfigurationFileLocations() { // // ArrayList<File> locations = new ArrayList<File>(); // // // Possible locations for the configuration file are the current working // // directory, the user's home directory, or the standard system // // location, in that order. // File[] dirs = { new File(System.getProperty("user.dir")), // new File(System.getProperty("user.home")), // new File("/etc/stratuslab/") }; // // for (File dir : dirs) { // locations.add(new File(dir, CONFIG_FILENAME)); // } // // return Collections.unmodifiableList(locations); // } // // private static Properties getConfigurationProperties( // List<File> configFileLocations) { // // for (File f : configFileLocations) { // if (f.canRead()) { // LOGGER.info("using configuration: " + f.getAbsolutePath()); // Properties properties = loadProperties(f); // validateConfiguration(properties); // return properties; // } // } // throw new MarketplaceException("cannot locate configuration file"); // } // // private static Properties loadProperties(File configFile) { // // Properties properties = new Properties(); // // try { // Reader reader = new InputStreamReader( // new FileInputStream(configFile), "UTF-8"); // try { // properties.load(reader); // } catch (IOException consumed) { // // TODO: Add logging. // } finally { // try { // reader.close(); // } catch (IOException consumed) { // // TODO: Add logging. // } // } // } catch (FileNotFoundException consumed) { // // Return empty properties file. // } catch (UnsupportedEncodingException e) { // // Return empty properties file. // } // // return properties; // } // // public static String getParameterValue(Parameter parameter) { // return parameter.getProperty(PROPERTIES); // } // // public static boolean getParameterValueAsBoolean(Parameter parameter) { // return Boolean.parseBoolean(parameter.getProperty(PROPERTIES)); // } // // public static int getParameterValueAsInt(Parameter parameter) { // return Integer.parseInt(parameter.getProperty(PROPERTIES)); // } // // public static long getParameterValueAsLong(Parameter parameter) { // return Long.parseLong(parameter.getProperty(PROPERTIES)); // } // // public static File getParameterValueAsFile(Parameter parameter) { // return new File(parameter.getProperty(PROPERTIES)); // } // // private static void validateConfiguration(Properties properties) { // checkAllParametersAreValid(properties); // checkAllParametersAreKnown(properties); // } // // private static void checkAllParametersAreValid(Properties properties) { // for (Parameter p : Parameter.values()) { // String value = p.getProperty(properties); // if (value != null) { // p.validate(value); // } // } // } // // private static void checkAllParametersAreKnown(Properties properties) { // for (Object key : properties.keySet()) { // Parameter.parameterFromKey(key); // } // } // // }
import static eu.stratuslab.marketplace.server.cfg.Parameter.ADMIN_EMAIL; import static eu.stratuslab.marketplace.server.cfg.Parameter.MAIL_DEBUG; import static eu.stratuslab.marketplace.server.cfg.Parameter.MAIL_HOST; import static eu.stratuslab.marketplace.server.cfg.Parameter.MAIL_PASSWORD; import static eu.stratuslab.marketplace.server.cfg.Parameter.MAIL_PORT; import static eu.stratuslab.marketplace.server.cfg.Parameter.MAIL_SSL; import static eu.stratuslab.marketplace.server.cfg.Parameter.MAIL_USER; import java.util.Date; import java.util.Properties; import java.util.logging.Logger; import javax.mail.Address; import javax.mail.AuthenticationFailedException; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import eu.stratuslab.marketplace.server.MarketplaceException; import eu.stratuslab.marketplace.server.cfg.Configuration;
/** * Created as part of the StratusLab project (http://stratuslab.eu), * co-funded by the European Commission under the Grant Agreement * INSFO-RI-261552. * * Copyright (c) 2011 * * 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 eu.stratuslab.marketplace.server.utils; public final class Notifier { private static Logger logger = Logger.getLogger("org.restlet"); private Notifier() { } public static boolean sendNotification(String message){ return sendNotification(getAdminEmail(), message); } public static boolean sendNotification(String email, String message)
// Path: server/war/src/main/java/eu/stratuslab/marketplace/server/MarketplaceException.java // @SuppressWarnings("serial") // public class MarketplaceException extends RuntimeException { // // public MarketplaceException() { // } // // public MarketplaceException(String message) { // super(message); // } // // public MarketplaceException(String message, Throwable cause){ // super(message, cause); // } // // } // // Path: server/war/src/main/java/eu/stratuslab/marketplace/server/cfg/Configuration.java // public final class Configuration { // // private static final Logger LOGGER = Logger.getLogger("org.restlet"); // // private static final String CONFIG_FILENAME = "marketplace.cfg"; // // private static final Properties PROPERTIES; // // static { // List<File> configFileLocations = getConfigurationFileLocations(); // PROPERTIES = getConfigurationProperties(configFileLocations); // } // // private Configuration() { // // } // // private static List<File> getConfigurationFileLocations() { // // ArrayList<File> locations = new ArrayList<File>(); // // // Possible locations for the configuration file are the current working // // directory, the user's home directory, or the standard system // // location, in that order. // File[] dirs = { new File(System.getProperty("user.dir")), // new File(System.getProperty("user.home")), // new File("/etc/stratuslab/") }; // // for (File dir : dirs) { // locations.add(new File(dir, CONFIG_FILENAME)); // } // // return Collections.unmodifiableList(locations); // } // // private static Properties getConfigurationProperties( // List<File> configFileLocations) { // // for (File f : configFileLocations) { // if (f.canRead()) { // LOGGER.info("using configuration: " + f.getAbsolutePath()); // Properties properties = loadProperties(f); // validateConfiguration(properties); // return properties; // } // } // throw new MarketplaceException("cannot locate configuration file"); // } // // private static Properties loadProperties(File configFile) { // // Properties properties = new Properties(); // // try { // Reader reader = new InputStreamReader( // new FileInputStream(configFile), "UTF-8"); // try { // properties.load(reader); // } catch (IOException consumed) { // // TODO: Add logging. // } finally { // try { // reader.close(); // } catch (IOException consumed) { // // TODO: Add logging. // } // } // } catch (FileNotFoundException consumed) { // // Return empty properties file. // } catch (UnsupportedEncodingException e) { // // Return empty properties file. // } // // return properties; // } // // public static String getParameterValue(Parameter parameter) { // return parameter.getProperty(PROPERTIES); // } // // public static boolean getParameterValueAsBoolean(Parameter parameter) { // return Boolean.parseBoolean(parameter.getProperty(PROPERTIES)); // } // // public static int getParameterValueAsInt(Parameter parameter) { // return Integer.parseInt(parameter.getProperty(PROPERTIES)); // } // // public static long getParameterValueAsLong(Parameter parameter) { // return Long.parseLong(parameter.getProperty(PROPERTIES)); // } // // public static File getParameterValueAsFile(Parameter parameter) { // return new File(parameter.getProperty(PROPERTIES)); // } // // private static void validateConfiguration(Properties properties) { // checkAllParametersAreValid(properties); // checkAllParametersAreKnown(properties); // } // // private static void checkAllParametersAreValid(Properties properties) { // for (Parameter p : Parameter.values()) { // String value = p.getProperty(properties); // if (value != null) { // p.validate(value); // } // } // } // // private static void checkAllParametersAreKnown(Properties properties) { // for (Object key : properties.keySet()) { // Parameter.parameterFromKey(key); // } // } // // } // Path: server/war/src/main/java/eu/stratuslab/marketplace/server/utils/Notifier.java import static eu.stratuslab.marketplace.server.cfg.Parameter.ADMIN_EMAIL; import static eu.stratuslab.marketplace.server.cfg.Parameter.MAIL_DEBUG; import static eu.stratuslab.marketplace.server.cfg.Parameter.MAIL_HOST; import static eu.stratuslab.marketplace.server.cfg.Parameter.MAIL_PASSWORD; import static eu.stratuslab.marketplace.server.cfg.Parameter.MAIL_PORT; import static eu.stratuslab.marketplace.server.cfg.Parameter.MAIL_SSL; import static eu.stratuslab.marketplace.server.cfg.Parameter.MAIL_USER; import java.util.Date; import java.util.Properties; import java.util.logging.Logger; import javax.mail.Address; import javax.mail.AuthenticationFailedException; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import eu.stratuslab.marketplace.server.MarketplaceException; import eu.stratuslab.marketplace.server.cfg.Configuration; /** * Created as part of the StratusLab project (http://stratuslab.eu), * co-funded by the European Commission under the Grant Agreement * INSFO-RI-261552. * * Copyright (c) 2011 * * 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 eu.stratuslab.marketplace.server.utils; public final class Notifier { private static Logger logger = Logger.getLogger("org.restlet"); private Notifier() { } public static boolean sendNotification(String message){ return sendNotification(getAdminEmail(), message); } public static boolean sendNotification(String email, String message)
throws MarketplaceException {
StratusLab/marketplace
server/war/src/main/java/eu/stratuslab/marketplace/server/utils/Notifier.java
// Path: server/war/src/main/java/eu/stratuslab/marketplace/server/MarketplaceException.java // @SuppressWarnings("serial") // public class MarketplaceException extends RuntimeException { // // public MarketplaceException() { // } // // public MarketplaceException(String message) { // super(message); // } // // public MarketplaceException(String message, Throwable cause){ // super(message, cause); // } // // } // // Path: server/war/src/main/java/eu/stratuslab/marketplace/server/cfg/Configuration.java // public final class Configuration { // // private static final Logger LOGGER = Logger.getLogger("org.restlet"); // // private static final String CONFIG_FILENAME = "marketplace.cfg"; // // private static final Properties PROPERTIES; // // static { // List<File> configFileLocations = getConfigurationFileLocations(); // PROPERTIES = getConfigurationProperties(configFileLocations); // } // // private Configuration() { // // } // // private static List<File> getConfigurationFileLocations() { // // ArrayList<File> locations = new ArrayList<File>(); // // // Possible locations for the configuration file are the current working // // directory, the user's home directory, or the standard system // // location, in that order. // File[] dirs = { new File(System.getProperty("user.dir")), // new File(System.getProperty("user.home")), // new File("/etc/stratuslab/") }; // // for (File dir : dirs) { // locations.add(new File(dir, CONFIG_FILENAME)); // } // // return Collections.unmodifiableList(locations); // } // // private static Properties getConfigurationProperties( // List<File> configFileLocations) { // // for (File f : configFileLocations) { // if (f.canRead()) { // LOGGER.info("using configuration: " + f.getAbsolutePath()); // Properties properties = loadProperties(f); // validateConfiguration(properties); // return properties; // } // } // throw new MarketplaceException("cannot locate configuration file"); // } // // private static Properties loadProperties(File configFile) { // // Properties properties = new Properties(); // // try { // Reader reader = new InputStreamReader( // new FileInputStream(configFile), "UTF-8"); // try { // properties.load(reader); // } catch (IOException consumed) { // // TODO: Add logging. // } finally { // try { // reader.close(); // } catch (IOException consumed) { // // TODO: Add logging. // } // } // } catch (FileNotFoundException consumed) { // // Return empty properties file. // } catch (UnsupportedEncodingException e) { // // Return empty properties file. // } // // return properties; // } // // public static String getParameterValue(Parameter parameter) { // return parameter.getProperty(PROPERTIES); // } // // public static boolean getParameterValueAsBoolean(Parameter parameter) { // return Boolean.parseBoolean(parameter.getProperty(PROPERTIES)); // } // // public static int getParameterValueAsInt(Parameter parameter) { // return Integer.parseInt(parameter.getProperty(PROPERTIES)); // } // // public static long getParameterValueAsLong(Parameter parameter) { // return Long.parseLong(parameter.getProperty(PROPERTIES)); // } // // public static File getParameterValueAsFile(Parameter parameter) { // return new File(parameter.getProperty(PROPERTIES)); // } // // private static void validateConfiguration(Properties properties) { // checkAllParametersAreValid(properties); // checkAllParametersAreKnown(properties); // } // // private static void checkAllParametersAreValid(Properties properties) { // for (Parameter p : Parameter.values()) { // String value = p.getProperty(properties); // if (value != null) { // p.validate(value); // } // } // } // // private static void checkAllParametersAreKnown(Properties properties) { // for (Object key : properties.keySet()) { // Parameter.parameterFromKey(key); // } // } // // }
import static eu.stratuslab.marketplace.server.cfg.Parameter.ADMIN_EMAIL; import static eu.stratuslab.marketplace.server.cfg.Parameter.MAIL_DEBUG; import static eu.stratuslab.marketplace.server.cfg.Parameter.MAIL_HOST; import static eu.stratuslab.marketplace.server.cfg.Parameter.MAIL_PASSWORD; import static eu.stratuslab.marketplace.server.cfg.Parameter.MAIL_PORT; import static eu.stratuslab.marketplace.server.cfg.Parameter.MAIL_SSL; import static eu.stratuslab.marketplace.server.cfg.Parameter.MAIL_USER; import java.util.Date; import java.util.Properties; import java.util.logging.Logger; import javax.mail.Address; import javax.mail.AuthenticationFailedException; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import eu.stratuslab.marketplace.server.MarketplaceException; import eu.stratuslab.marketplace.server.cfg.Configuration;
t.sendMessage(msg, msg.getAllRecipients()); logger.info("mail was successfully sent"); } catch (AuthenticationFailedException afe) { StringBuilder m = new StringBuilder(); m.append("authentication failure\n"); m.append(afe.getMessage() + "\n"); logger.severe(m.toString()); sendOk = false; } catch (MessagingException me) { StringBuilder m = new StringBuilder(); m.append("error sending message to " + email + "\n"); m.append(me.getMessage() + "\n"); logger.severe(m.toString()); sendOk = false; } } catch (MessagingException consumed) { StringBuilder m = new StringBuilder(); m.append("error sending message to " + email + "\n"); m.append(consumed.getMessage() + "\n"); sendOk = false; } return sendOk; } private static InternetAddress getAdminEmail() { try {
// Path: server/war/src/main/java/eu/stratuslab/marketplace/server/MarketplaceException.java // @SuppressWarnings("serial") // public class MarketplaceException extends RuntimeException { // // public MarketplaceException() { // } // // public MarketplaceException(String message) { // super(message); // } // // public MarketplaceException(String message, Throwable cause){ // super(message, cause); // } // // } // // Path: server/war/src/main/java/eu/stratuslab/marketplace/server/cfg/Configuration.java // public final class Configuration { // // private static final Logger LOGGER = Logger.getLogger("org.restlet"); // // private static final String CONFIG_FILENAME = "marketplace.cfg"; // // private static final Properties PROPERTIES; // // static { // List<File> configFileLocations = getConfigurationFileLocations(); // PROPERTIES = getConfigurationProperties(configFileLocations); // } // // private Configuration() { // // } // // private static List<File> getConfigurationFileLocations() { // // ArrayList<File> locations = new ArrayList<File>(); // // // Possible locations for the configuration file are the current working // // directory, the user's home directory, or the standard system // // location, in that order. // File[] dirs = { new File(System.getProperty("user.dir")), // new File(System.getProperty("user.home")), // new File("/etc/stratuslab/") }; // // for (File dir : dirs) { // locations.add(new File(dir, CONFIG_FILENAME)); // } // // return Collections.unmodifiableList(locations); // } // // private static Properties getConfigurationProperties( // List<File> configFileLocations) { // // for (File f : configFileLocations) { // if (f.canRead()) { // LOGGER.info("using configuration: " + f.getAbsolutePath()); // Properties properties = loadProperties(f); // validateConfiguration(properties); // return properties; // } // } // throw new MarketplaceException("cannot locate configuration file"); // } // // private static Properties loadProperties(File configFile) { // // Properties properties = new Properties(); // // try { // Reader reader = new InputStreamReader( // new FileInputStream(configFile), "UTF-8"); // try { // properties.load(reader); // } catch (IOException consumed) { // // TODO: Add logging. // } finally { // try { // reader.close(); // } catch (IOException consumed) { // // TODO: Add logging. // } // } // } catch (FileNotFoundException consumed) { // // Return empty properties file. // } catch (UnsupportedEncodingException e) { // // Return empty properties file. // } // // return properties; // } // // public static String getParameterValue(Parameter parameter) { // return parameter.getProperty(PROPERTIES); // } // // public static boolean getParameterValueAsBoolean(Parameter parameter) { // return Boolean.parseBoolean(parameter.getProperty(PROPERTIES)); // } // // public static int getParameterValueAsInt(Parameter parameter) { // return Integer.parseInt(parameter.getProperty(PROPERTIES)); // } // // public static long getParameterValueAsLong(Parameter parameter) { // return Long.parseLong(parameter.getProperty(PROPERTIES)); // } // // public static File getParameterValueAsFile(Parameter parameter) { // return new File(parameter.getProperty(PROPERTIES)); // } // // private static void validateConfiguration(Properties properties) { // checkAllParametersAreValid(properties); // checkAllParametersAreKnown(properties); // } // // private static void checkAllParametersAreValid(Properties properties) { // for (Parameter p : Parameter.values()) { // String value = p.getProperty(properties); // if (value != null) { // p.validate(value); // } // } // } // // private static void checkAllParametersAreKnown(Properties properties) { // for (Object key : properties.keySet()) { // Parameter.parameterFromKey(key); // } // } // // } // Path: server/war/src/main/java/eu/stratuslab/marketplace/server/utils/Notifier.java import static eu.stratuslab.marketplace.server.cfg.Parameter.ADMIN_EMAIL; import static eu.stratuslab.marketplace.server.cfg.Parameter.MAIL_DEBUG; import static eu.stratuslab.marketplace.server.cfg.Parameter.MAIL_HOST; import static eu.stratuslab.marketplace.server.cfg.Parameter.MAIL_PASSWORD; import static eu.stratuslab.marketplace.server.cfg.Parameter.MAIL_PORT; import static eu.stratuslab.marketplace.server.cfg.Parameter.MAIL_SSL; import static eu.stratuslab.marketplace.server.cfg.Parameter.MAIL_USER; import java.util.Date; import java.util.Properties; import java.util.logging.Logger; import javax.mail.Address; import javax.mail.AuthenticationFailedException; import javax.mail.Message; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.Transport; import javax.mail.internet.AddressException; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeMessage; import eu.stratuslab.marketplace.server.MarketplaceException; import eu.stratuslab.marketplace.server.cfg.Configuration; t.sendMessage(msg, msg.getAllRecipients()); logger.info("mail was successfully sent"); } catch (AuthenticationFailedException afe) { StringBuilder m = new StringBuilder(); m.append("authentication failure\n"); m.append(afe.getMessage() + "\n"); logger.severe(m.toString()); sendOk = false; } catch (MessagingException me) { StringBuilder m = new StringBuilder(); m.append("error sending message to " + email + "\n"); m.append(me.getMessage() + "\n"); logger.severe(m.toString()); sendOk = false; } } catch (MessagingException consumed) { StringBuilder m = new StringBuilder(); m.append("error sending message to " + email + "\n"); m.append(consumed.getMessage() + "\n"); sendOk = false; } return sendOk; } private static InternetAddress getAdminEmail() { try {
String adminEmail = Configuration.getParameterValue(ADMIN_EMAIL);
StratusLab/marketplace
server/war/src/main/java/eu/stratuslab/marketplace/server/routers/ActionRouter.java
// Path: server/war/src/main/java/eu/stratuslab/marketplace/server/resources/ActionResource.java // public class ActionResource extends BaseResource { // // private static final Logger LOGGER = Logger.getLogger("org.restlet"); // // private Document doc; // // private String uuid; // // private String command; // // @Override // protected void doInit() { // // Request request = getRequest(); // // Map<String, Object> attributes = request.getAttributes(); // // uuid = attributes.get("uuid").toString(); // command = attributes.get("command").toString(); // // doc = retrieveMetadata(uuid); // // } // // @Get("txt") // public Representation toText() { // return doAction(); // } // // private Representation doAction() { // // Representation representation = null; // // if ("confirm".equals(command)) { // representation = confirmEntry(); // } else if ("abort".equals(command)) { // representation = abortEntry(); // } else if ("abuse".equals(command)) { // representation = reportAbuse(); // } // // return representation; // } // // private Representation confirmEntry() { // File uploadedFile = getUploadedFile(uuid); // // String iri = commitMetadataEntry(uploadedFile, doc); // // setStatus(Status.SUCCESS_CREATED); // // Representation rep = createStatusRepresentation("Confirm", "metadata entry created\n"); // rep.setLocationRef(getRequest().getRootRef() + "/metadata" + iri); // // return rep; // // } // // private Representation abortEntry() { // File uploadedFile = getUploadedFile(uuid); // // if (!uploadedFile.delete()) { // LOGGER.severe("cannot delete file: " + uploadedFile); // } // // return createStatusRepresentation("Abort", "aborted addition of metadata entry " // + uuid + "\n"); // } // // private Representation reportAbuse() { // LOGGER.severe("abuse reported:" + uuid); // // File uploadedFile = getUploadedFile(uuid); // // String message = MessageUtils.createAbuseNotification(uploadedFile); // Notifier.sendNotification(message); // // return createStatusRepresentation("Abuse", "administrators have been notified " + // "of the problem and may contact you during the investigation\n"); // } // // private static File getUploadedFile(String uuid) { // String dir = Configuration.getParameterValue(PENDING_DIR); // return new File(dir, uuid); // } // // private static Document retrieveMetadata(String uuid) { // // InputStream stream = null; // // try { // // File file = getUploadedFile(uuid); // // stream = new FileInputStream(file); // Document doc = MetadataFileUtils.extractXmlDocument(stream); // // return doc; // // } catch (IOException e) { // throw new ResourceException(Status.CLIENT_ERROR_NOT_FOUND, e // .getMessage(), e); // } finally { // if (stream != null) { // try { // stream.close(); // } catch (IOException consumed) { // } // } // } // } // } // // Path: server/war/src/main/java/eu/stratuslab/marketplace/server/resources/InvalidActionResource.java // public class InvalidActionResource extends ServerResource { // // @Get("txt|html|xml") // public Representation toError() { // // Request request = getRequest(); // Reference resourceRef = request.getResourceRef(); // // String msg = String.format("invalid action: %s", resourceRef); // // throw new ResourceException(CLIENT_ERROR_NOT_FOUND, msg); // } // }
import org.restlet.routing.Router; import org.restlet.routing.Template; import org.restlet.routing.TemplateRoute; import eu.stratuslab.marketplace.server.resources.ActionResource; import eu.stratuslab.marketplace.server.resources.InvalidActionResource;
/** * Created as part of the StratusLab project (http://stratuslab.eu), * co-funded by the European Commission under the Grant Agreement * INSFO-RI-261552. * * Copyright (c) 2011 * * 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 eu.stratuslab.marketplace.server.routers; public class ActionRouter extends Router { public ActionRouter() { super(); // Routing is tolerant of extraneous leading and trailing slashes. // TODO: Determine a better mechanism for being tolerant of slashes. TemplateRoute route;
// Path: server/war/src/main/java/eu/stratuslab/marketplace/server/resources/ActionResource.java // public class ActionResource extends BaseResource { // // private static final Logger LOGGER = Logger.getLogger("org.restlet"); // // private Document doc; // // private String uuid; // // private String command; // // @Override // protected void doInit() { // // Request request = getRequest(); // // Map<String, Object> attributes = request.getAttributes(); // // uuid = attributes.get("uuid").toString(); // command = attributes.get("command").toString(); // // doc = retrieveMetadata(uuid); // // } // // @Get("txt") // public Representation toText() { // return doAction(); // } // // private Representation doAction() { // // Representation representation = null; // // if ("confirm".equals(command)) { // representation = confirmEntry(); // } else if ("abort".equals(command)) { // representation = abortEntry(); // } else if ("abuse".equals(command)) { // representation = reportAbuse(); // } // // return representation; // } // // private Representation confirmEntry() { // File uploadedFile = getUploadedFile(uuid); // // String iri = commitMetadataEntry(uploadedFile, doc); // // setStatus(Status.SUCCESS_CREATED); // // Representation rep = createStatusRepresentation("Confirm", "metadata entry created\n"); // rep.setLocationRef(getRequest().getRootRef() + "/metadata" + iri); // // return rep; // // } // // private Representation abortEntry() { // File uploadedFile = getUploadedFile(uuid); // // if (!uploadedFile.delete()) { // LOGGER.severe("cannot delete file: " + uploadedFile); // } // // return createStatusRepresentation("Abort", "aborted addition of metadata entry " // + uuid + "\n"); // } // // private Representation reportAbuse() { // LOGGER.severe("abuse reported:" + uuid); // // File uploadedFile = getUploadedFile(uuid); // // String message = MessageUtils.createAbuseNotification(uploadedFile); // Notifier.sendNotification(message); // // return createStatusRepresentation("Abuse", "administrators have been notified " + // "of the problem and may contact you during the investigation\n"); // } // // private static File getUploadedFile(String uuid) { // String dir = Configuration.getParameterValue(PENDING_DIR); // return new File(dir, uuid); // } // // private static Document retrieveMetadata(String uuid) { // // InputStream stream = null; // // try { // // File file = getUploadedFile(uuid); // // stream = new FileInputStream(file); // Document doc = MetadataFileUtils.extractXmlDocument(stream); // // return doc; // // } catch (IOException e) { // throw new ResourceException(Status.CLIENT_ERROR_NOT_FOUND, e // .getMessage(), e); // } finally { // if (stream != null) { // try { // stream.close(); // } catch (IOException consumed) { // } // } // } // } // } // // Path: server/war/src/main/java/eu/stratuslab/marketplace/server/resources/InvalidActionResource.java // public class InvalidActionResource extends ServerResource { // // @Get("txt|html|xml") // public Representation toError() { // // Request request = getRequest(); // Reference resourceRef = request.getResourceRef(); // // String msg = String.format("invalid action: %s", resourceRef); // // throw new ResourceException(CLIENT_ERROR_NOT_FOUND, msg); // } // } // Path: server/war/src/main/java/eu/stratuslab/marketplace/server/routers/ActionRouter.java import org.restlet.routing.Router; import org.restlet.routing.Template; import org.restlet.routing.TemplateRoute; import eu.stratuslab.marketplace.server.resources.ActionResource; import eu.stratuslab.marketplace.server.resources.InvalidActionResource; /** * Created as part of the StratusLab project (http://stratuslab.eu), * co-funded by the European Commission under the Grant Agreement * INSFO-RI-261552. * * Copyright (c) 2011 * * 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 eu.stratuslab.marketplace.server.routers; public class ActionRouter extends Router { public ActionRouter() { super(); // Routing is tolerant of extraneous leading and trailing slashes. // TODO: Determine a better mechanism for being tolerant of slashes. TemplateRoute route;
route = attach("/{uuid}/{command}/", ActionResource.class);
StratusLab/marketplace
server/war/src/main/java/eu/stratuslab/marketplace/server/routers/ActionRouter.java
// Path: server/war/src/main/java/eu/stratuslab/marketplace/server/resources/ActionResource.java // public class ActionResource extends BaseResource { // // private static final Logger LOGGER = Logger.getLogger("org.restlet"); // // private Document doc; // // private String uuid; // // private String command; // // @Override // protected void doInit() { // // Request request = getRequest(); // // Map<String, Object> attributes = request.getAttributes(); // // uuid = attributes.get("uuid").toString(); // command = attributes.get("command").toString(); // // doc = retrieveMetadata(uuid); // // } // // @Get("txt") // public Representation toText() { // return doAction(); // } // // private Representation doAction() { // // Representation representation = null; // // if ("confirm".equals(command)) { // representation = confirmEntry(); // } else if ("abort".equals(command)) { // representation = abortEntry(); // } else if ("abuse".equals(command)) { // representation = reportAbuse(); // } // // return representation; // } // // private Representation confirmEntry() { // File uploadedFile = getUploadedFile(uuid); // // String iri = commitMetadataEntry(uploadedFile, doc); // // setStatus(Status.SUCCESS_CREATED); // // Representation rep = createStatusRepresentation("Confirm", "metadata entry created\n"); // rep.setLocationRef(getRequest().getRootRef() + "/metadata" + iri); // // return rep; // // } // // private Representation abortEntry() { // File uploadedFile = getUploadedFile(uuid); // // if (!uploadedFile.delete()) { // LOGGER.severe("cannot delete file: " + uploadedFile); // } // // return createStatusRepresentation("Abort", "aborted addition of metadata entry " // + uuid + "\n"); // } // // private Representation reportAbuse() { // LOGGER.severe("abuse reported:" + uuid); // // File uploadedFile = getUploadedFile(uuid); // // String message = MessageUtils.createAbuseNotification(uploadedFile); // Notifier.sendNotification(message); // // return createStatusRepresentation("Abuse", "administrators have been notified " + // "of the problem and may contact you during the investigation\n"); // } // // private static File getUploadedFile(String uuid) { // String dir = Configuration.getParameterValue(PENDING_DIR); // return new File(dir, uuid); // } // // private static Document retrieveMetadata(String uuid) { // // InputStream stream = null; // // try { // // File file = getUploadedFile(uuid); // // stream = new FileInputStream(file); // Document doc = MetadataFileUtils.extractXmlDocument(stream); // // return doc; // // } catch (IOException e) { // throw new ResourceException(Status.CLIENT_ERROR_NOT_FOUND, e // .getMessage(), e); // } finally { // if (stream != null) { // try { // stream.close(); // } catch (IOException consumed) { // } // } // } // } // } // // Path: server/war/src/main/java/eu/stratuslab/marketplace/server/resources/InvalidActionResource.java // public class InvalidActionResource extends ServerResource { // // @Get("txt|html|xml") // public Representation toError() { // // Request request = getRequest(); // Reference resourceRef = request.getResourceRef(); // // String msg = String.format("invalid action: %s", resourceRef); // // throw new ResourceException(CLIENT_ERROR_NOT_FOUND, msg); // } // }
import org.restlet.routing.Router; import org.restlet.routing.Template; import org.restlet.routing.TemplateRoute; import eu.stratuslab.marketplace.server.resources.ActionResource; import eu.stratuslab.marketplace.server.resources.InvalidActionResource;
/** * Created as part of the StratusLab project (http://stratuslab.eu), * co-funded by the European Commission under the Grant Agreement * INSFO-RI-261552. * * Copyright (c) 2011 * * 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 eu.stratuslab.marketplace.server.routers; public class ActionRouter extends Router { public ActionRouter() { super(); // Routing is tolerant of extraneous leading and trailing slashes. // TODO: Determine a better mechanism for being tolerant of slashes. TemplateRoute route; route = attach("/{uuid}/{command}/", ActionResource.class); route.getTemplate().setMatchingMode(Template.MODE_STARTS_WITH); route = attach("/{uuid}/{command}", ActionResource.class); route.getTemplate().setMatchingMode(Template.MODE_STARTS_WITH); route = attach("{uuid}/{command}/", ActionResource.class); route.getTemplate().setMatchingMode(Template.MODE_STARTS_WITH); route = attach("{uuid}/{command}", ActionResource.class); route.getTemplate().setMatchingMode(Template.MODE_STARTS_WITH);
// Path: server/war/src/main/java/eu/stratuslab/marketplace/server/resources/ActionResource.java // public class ActionResource extends BaseResource { // // private static final Logger LOGGER = Logger.getLogger("org.restlet"); // // private Document doc; // // private String uuid; // // private String command; // // @Override // protected void doInit() { // // Request request = getRequest(); // // Map<String, Object> attributes = request.getAttributes(); // // uuid = attributes.get("uuid").toString(); // command = attributes.get("command").toString(); // // doc = retrieveMetadata(uuid); // // } // // @Get("txt") // public Representation toText() { // return doAction(); // } // // private Representation doAction() { // // Representation representation = null; // // if ("confirm".equals(command)) { // representation = confirmEntry(); // } else if ("abort".equals(command)) { // representation = abortEntry(); // } else if ("abuse".equals(command)) { // representation = reportAbuse(); // } // // return representation; // } // // private Representation confirmEntry() { // File uploadedFile = getUploadedFile(uuid); // // String iri = commitMetadataEntry(uploadedFile, doc); // // setStatus(Status.SUCCESS_CREATED); // // Representation rep = createStatusRepresentation("Confirm", "metadata entry created\n"); // rep.setLocationRef(getRequest().getRootRef() + "/metadata" + iri); // // return rep; // // } // // private Representation abortEntry() { // File uploadedFile = getUploadedFile(uuid); // // if (!uploadedFile.delete()) { // LOGGER.severe("cannot delete file: " + uploadedFile); // } // // return createStatusRepresentation("Abort", "aborted addition of metadata entry " // + uuid + "\n"); // } // // private Representation reportAbuse() { // LOGGER.severe("abuse reported:" + uuid); // // File uploadedFile = getUploadedFile(uuid); // // String message = MessageUtils.createAbuseNotification(uploadedFile); // Notifier.sendNotification(message); // // return createStatusRepresentation("Abuse", "administrators have been notified " + // "of the problem and may contact you during the investigation\n"); // } // // private static File getUploadedFile(String uuid) { // String dir = Configuration.getParameterValue(PENDING_DIR); // return new File(dir, uuid); // } // // private static Document retrieveMetadata(String uuid) { // // InputStream stream = null; // // try { // // File file = getUploadedFile(uuid); // // stream = new FileInputStream(file); // Document doc = MetadataFileUtils.extractXmlDocument(stream); // // return doc; // // } catch (IOException e) { // throw new ResourceException(Status.CLIENT_ERROR_NOT_FOUND, e // .getMessage(), e); // } finally { // if (stream != null) { // try { // stream.close(); // } catch (IOException consumed) { // } // } // } // } // } // // Path: server/war/src/main/java/eu/stratuslab/marketplace/server/resources/InvalidActionResource.java // public class InvalidActionResource extends ServerResource { // // @Get("txt|html|xml") // public Representation toError() { // // Request request = getRequest(); // Reference resourceRef = request.getResourceRef(); // // String msg = String.format("invalid action: %s", resourceRef); // // throw new ResourceException(CLIENT_ERROR_NOT_FOUND, msg); // } // } // Path: server/war/src/main/java/eu/stratuslab/marketplace/server/routers/ActionRouter.java import org.restlet.routing.Router; import org.restlet.routing.Template; import org.restlet.routing.TemplateRoute; import eu.stratuslab.marketplace.server.resources.ActionResource; import eu.stratuslab.marketplace.server.resources.InvalidActionResource; /** * Created as part of the StratusLab project (http://stratuslab.eu), * co-funded by the European Commission under the Grant Agreement * INSFO-RI-261552. * * Copyright (c) 2011 * * 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 eu.stratuslab.marketplace.server.routers; public class ActionRouter extends Router { public ActionRouter() { super(); // Routing is tolerant of extraneous leading and trailing slashes. // TODO: Determine a better mechanism for being tolerant of slashes. TemplateRoute route; route = attach("/{uuid}/{command}/", ActionResource.class); route.getTemplate().setMatchingMode(Template.MODE_STARTS_WITH); route = attach("/{uuid}/{command}", ActionResource.class); route.getTemplate().setMatchingMode(Template.MODE_STARTS_WITH); route = attach("{uuid}/{command}/", ActionResource.class); route.getTemplate().setMatchingMode(Template.MODE_STARTS_WITH); route = attach("{uuid}/{command}", ActionResource.class); route.getTemplate().setMatchingMode(Template.MODE_STARTS_WITH);
attachDefault(InvalidActionResource.class);
StratusLab/marketplace
server/war/src/main/java/eu/stratuslab/marketplace/server/store/rdf/RdfStore.java
// Path: server/war/src/main/java/eu/stratuslab/marketplace/server/MarketplaceException.java // @SuppressWarnings("serial") // public class MarketplaceException extends RuntimeException { // // public MarketplaceException() { // } // // public MarketplaceException(String message) { // super(message); // } // // public MarketplaceException(String message, Throwable cause){ // super(message, cause); // } // // }
import eu.stratuslab.marketplace.server.MarketplaceException; import java.util.List; import java.util.Map;
/** * Created as part of the StratusLab project (http://stratuslab.eu), * co-funded by the European Commission under the Grant Agreement * INSFO-RI-261552. * * Copyright (c) 2011 * * 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 eu.stratuslab.marketplace.server.store.rdf; public abstract class RdfStore { public abstract void shutdown(); public abstract void initialize(); public abstract boolean store(String identifier, String entry); public abstract void tag(String identifier, String tag); public abstract void removeTag(String identifier, String tag);
// Path: server/war/src/main/java/eu/stratuslab/marketplace/server/MarketplaceException.java // @SuppressWarnings("serial") // public class MarketplaceException extends RuntimeException { // // public MarketplaceException() { // } // // public MarketplaceException(String message) { // super(message); // } // // public MarketplaceException(String message, Throwable cause){ // super(message, cause); // } // // } // Path: server/war/src/main/java/eu/stratuslab/marketplace/server/store/rdf/RdfStore.java import eu.stratuslab.marketplace.server.MarketplaceException; import java.util.List; import java.util.Map; /** * Created as part of the StratusLab project (http://stratuslab.eu), * co-funded by the European Commission under the Grant Agreement * INSFO-RI-261552. * * Copyright (c) 2011 * * 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 eu.stratuslab.marketplace.server.store.rdf; public abstract class RdfStore { public abstract void shutdown(); public abstract void initialize(); public abstract boolean store(String identifier, String entry); public abstract void tag(String identifier, String tag); public abstract void removeTag(String identifier, String tag);
public abstract List<Map<String, String>> getRdfEntriesAsMap(String query) throws MarketplaceException;
StratusLab/marketplace
server/war/src/main/java/eu/stratuslab/marketplace/server/resources/EndorserResource.java
// Path: server/war/src/main/java/eu/stratuslab/marketplace/server/MarketplaceException.java // @SuppressWarnings("serial") // public class MarketplaceException extends RuntimeException { // // public MarketplaceException() { // } // // public MarketplaceException(String message) { // super(message); // } // // public MarketplaceException(String message, Throwable cause){ // super(message, cause); // } // // } // // Path: server/war/src/main/java/eu/stratuslab/marketplace/server/utils/MarketplaceUtils.java // public final class MarketplaceUtils { // // private static final String DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss'Z'"; // // private MarketplaceUtils(){} // // public static String getCurrentDate() { // return getFormattedDate(new Date()); // } // // public static Date getFormattedDate(String timestamp) throws ParseException{ // return getDateFormat().parse(timestamp); // } // // public static String getFormattedDate(Date date){ // return getDateFormat().format(date); // } // // private static DateFormat getDateFormat() { // SimpleDateFormat format = new SimpleDateFormat(DATE_FORMAT); // format.setLenient(false); // format.setTimeZone(TimeZone.getTimeZone("UTC")); // // return format; // } // // }
import eu.stratuslab.marketplace.server.MarketplaceException; import eu.stratuslab.marketplace.server.utils.MarketplaceUtils; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.Map; import java.util.ArrayList; import org.restlet.data.Form; import org.restlet.data.MediaType; import org.restlet.representation.Representation; import org.restlet.representation.StringRepresentation; import org.restlet.resource.Get;
/** * Created as part of the StratusLab project (http://stratuslab.eu), * co-funded by the European Commission under the Grant Agreement * INSFO-RI-261552. * * Copyright (c) 2011 * * 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 eu.stratuslab.marketplace.server.resources; /** * This resource represents a single endorser */ public class EndorserResource extends BaseResource { private static final int DEFAULT_RANGE = 30; private String query = null; private String email = null; @Override protected void doInit() { email = (String) getRequest().getAttributes().get("email"); String range = getRangeFromRequest(); query = getQueryBuilder().buildEndorserQuery(email, getHistoryRange(range)); } @Get("html") public Representation toHtml() { List<Map<String, String>> results = new ArrayList<Map<String, String>>(); try { results = query(query);
// Path: server/war/src/main/java/eu/stratuslab/marketplace/server/MarketplaceException.java // @SuppressWarnings("serial") // public class MarketplaceException extends RuntimeException { // // public MarketplaceException() { // } // // public MarketplaceException(String message) { // super(message); // } // // public MarketplaceException(String message, Throwable cause){ // super(message, cause); // } // // } // // Path: server/war/src/main/java/eu/stratuslab/marketplace/server/utils/MarketplaceUtils.java // public final class MarketplaceUtils { // // private static final String DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss'Z'"; // // private MarketplaceUtils(){} // // public static String getCurrentDate() { // return getFormattedDate(new Date()); // } // // public static Date getFormattedDate(String timestamp) throws ParseException{ // return getDateFormat().parse(timestamp); // } // // public static String getFormattedDate(Date date){ // return getDateFormat().format(date); // } // // private static DateFormat getDateFormat() { // SimpleDateFormat format = new SimpleDateFormat(DATE_FORMAT); // format.setLenient(false); // format.setTimeZone(TimeZone.getTimeZone("UTC")); // // return format; // } // // } // Path: server/war/src/main/java/eu/stratuslab/marketplace/server/resources/EndorserResource.java import eu.stratuslab.marketplace.server.MarketplaceException; import eu.stratuslab.marketplace.server.utils.MarketplaceUtils; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.Map; import java.util.ArrayList; import org.restlet.data.Form; import org.restlet.data.MediaType; import org.restlet.representation.Representation; import org.restlet.representation.StringRepresentation; import org.restlet.resource.Get; /** * Created as part of the StratusLab project (http://stratuslab.eu), * co-funded by the European Commission under the Grant Agreement * INSFO-RI-261552. * * Copyright (c) 2011 * * 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 eu.stratuslab.marketplace.server.resources; /** * This resource represents a single endorser */ public class EndorserResource extends BaseResource { private static final int DEFAULT_RANGE = 30; private String query = null; private String email = null; @Override protected void doInit() { email = (String) getRequest().getAttributes().get("email"); String range = getRangeFromRequest(); query = getQueryBuilder().buildEndorserQuery(email, getHistoryRange(range)); } @Get("html") public Representation toHtml() { List<Map<String, String>> results = new ArrayList<Map<String, String>>(); try { results = query(query);
} catch(MarketplaceException e){
StratusLab/marketplace
server/war/src/main/java/eu/stratuslab/marketplace/server/resources/EndorserResource.java
// Path: server/war/src/main/java/eu/stratuslab/marketplace/server/MarketplaceException.java // @SuppressWarnings("serial") // public class MarketplaceException extends RuntimeException { // // public MarketplaceException() { // } // // public MarketplaceException(String message) { // super(message); // } // // public MarketplaceException(String message, Throwable cause){ // super(message, cause); // } // // } // // Path: server/war/src/main/java/eu/stratuslab/marketplace/server/utils/MarketplaceUtils.java // public final class MarketplaceUtils { // // private static final String DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss'Z'"; // // private MarketplaceUtils(){} // // public static String getCurrentDate() { // return getFormattedDate(new Date()); // } // // public static Date getFormattedDate(String timestamp) throws ParseException{ // return getDateFormat().parse(timestamp); // } // // public static String getFormattedDate(Date date){ // return getDateFormat().format(date); // } // // private static DateFormat getDateFormat() { // SimpleDateFormat format = new SimpleDateFormat(DATE_FORMAT); // format.setLenient(false); // format.setTimeZone(TimeZone.getTimeZone("UTC")); // // return format; // } // // }
import eu.stratuslab.marketplace.server.MarketplaceException; import eu.stratuslab.marketplace.server.utils.MarketplaceUtils; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.Map; import java.util.ArrayList; import org.restlet.data.Form; import org.restlet.data.MediaType; import org.restlet.representation.Representation; import org.restlet.representation.StringRepresentation; import org.restlet.resource.Get;
StringRepresentation representation = new StringRepresentation(results, MediaType.APPLICATION_XML); // Returns the XML representation of this document. return representation; } private String getRangeFromRequest(){ Form form = getRequest().getResourceRef().getQueryAsForm(); String range = form.getFirstValue("range", "30"); return range; } private String getHistoryRange(String range){ Date today = new Date(); Calendar cal = Calendar.getInstance(); cal.setTime(today); int r = DEFAULT_RANGE; try { r = Integer.parseInt(range); } catch(NumberFormatException n){ LOGGER.warning("incorrect range value entered: " + range); } cal.add(Calendar.DATE, -r); Date expiration = cal.getTime();
// Path: server/war/src/main/java/eu/stratuslab/marketplace/server/MarketplaceException.java // @SuppressWarnings("serial") // public class MarketplaceException extends RuntimeException { // // public MarketplaceException() { // } // // public MarketplaceException(String message) { // super(message); // } // // public MarketplaceException(String message, Throwable cause){ // super(message, cause); // } // // } // // Path: server/war/src/main/java/eu/stratuslab/marketplace/server/utils/MarketplaceUtils.java // public final class MarketplaceUtils { // // private static final String DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss'Z'"; // // private MarketplaceUtils(){} // // public static String getCurrentDate() { // return getFormattedDate(new Date()); // } // // public static Date getFormattedDate(String timestamp) throws ParseException{ // return getDateFormat().parse(timestamp); // } // // public static String getFormattedDate(Date date){ // return getDateFormat().format(date); // } // // private static DateFormat getDateFormat() { // SimpleDateFormat format = new SimpleDateFormat(DATE_FORMAT); // format.setLenient(false); // format.setTimeZone(TimeZone.getTimeZone("UTC")); // // return format; // } // // } // Path: server/war/src/main/java/eu/stratuslab/marketplace/server/resources/EndorserResource.java import eu.stratuslab.marketplace.server.MarketplaceException; import eu.stratuslab.marketplace.server.utils.MarketplaceUtils; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.Map; import java.util.ArrayList; import org.restlet.data.Form; import org.restlet.data.MediaType; import org.restlet.representation.Representation; import org.restlet.representation.StringRepresentation; import org.restlet.resource.Get; StringRepresentation representation = new StringRepresentation(results, MediaType.APPLICATION_XML); // Returns the XML representation of this document. return representation; } private String getRangeFromRequest(){ Form form = getRequest().getResourceRef().getQueryAsForm(); String range = form.getFirstValue("range", "30"); return range; } private String getHistoryRange(String range){ Date today = new Date(); Calendar cal = Calendar.getInstance(); cal.setTime(today); int r = DEFAULT_RANGE; try { r = Integer.parseInt(range); } catch(NumberFormatException n){ LOGGER.warning("incorrect range value entered: " + range); } cal.add(Calendar.DATE, -r); Date expiration = cal.getTime();
return MarketplaceUtils.getFormattedDate(expiration);
StratusLab/marketplace
server/war/src/main/java/eu/stratuslab/marketplace/server/resources/TagsResource.java
// Path: server/war/src/main/java/eu/stratuslab/marketplace/server/MarketplaceException.java // @SuppressWarnings("serial") // public class MarketplaceException extends RuntimeException { // // public MarketplaceException() { // } // // public MarketplaceException(String message) { // super(message); // } // // public MarketplaceException(String message, Throwable cause){ // super(message, cause); // } // // }
import java.util.ArrayList; import java.util.List; import java.util.Map; import org.restlet.data.MediaType; import org.restlet.representation.Representation; import org.restlet.representation.StringRepresentation; import org.restlet.resource.Get; import eu.stratuslab.marketplace.server.MarketplaceException;
/** * Created as part of the StratusLab project (http://stratuslab.eu), * co-funded by the European Commission under the Grant Agreement * INSFO-RI-261552. * * Copyright (c) 2011 * * 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 eu.stratuslab.marketplace.server.resources; public class TagsResource extends BaseResource{ private String query = null; private String email = null; @Override protected void doInit() { email = (String) getRequest().getAttributes().get("email"); query = getQueryBuilder().buildEndorserTagsQuery(email); } @Get("html") public Representation toHtml() { List<Map<String, String>> results = new ArrayList<Map<String, String>>(); try { results = query(query);
// Path: server/war/src/main/java/eu/stratuslab/marketplace/server/MarketplaceException.java // @SuppressWarnings("serial") // public class MarketplaceException extends RuntimeException { // // public MarketplaceException() { // } // // public MarketplaceException(String message) { // super(message); // } // // public MarketplaceException(String message, Throwable cause){ // super(message, cause); // } // // } // Path: server/war/src/main/java/eu/stratuslab/marketplace/server/resources/TagsResource.java import java.util.ArrayList; import java.util.List; import java.util.Map; import org.restlet.data.MediaType; import org.restlet.representation.Representation; import org.restlet.representation.StringRepresentation; import org.restlet.resource.Get; import eu.stratuslab.marketplace.server.MarketplaceException; /** * Created as part of the StratusLab project (http://stratuslab.eu), * co-funded by the European Commission under the Grant Agreement * INSFO-RI-261552. * * Copyright (c) 2011 * * 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 eu.stratuslab.marketplace.server.resources; public class TagsResource extends BaseResource{ private String query = null; private String email = null; @Override protected void doInit() { email = (String) getRequest().getAttributes().get("email"); query = getQueryBuilder().buildEndorserTagsQuery(email); } @Get("html") public Representation toHtml() { List<Map<String, String>> results = new ArrayList<Map<String, String>>(); try { results = query(query);
} catch(MarketplaceException e){
StratusLab/marketplace
server/war/src/main/java/eu/stratuslab/marketplace/server/store/file/FlatFileStore.java
// Path: server/war/src/main/java/eu/stratuslab/marketplace/server/utils/MetadataFileUtils.java // public final class MetadataFileUtils { // // private static final String ENCODING = "UTF-8"; // // private MetadataFileUtils(){} // // public static File writeContentsToDisk(Representation entity) { // // char[] buffer = new char[4096]; // // File storeDirectory = Configuration // .getParameterValueAsFile(PENDING_DIR); // // File output = new File(storeDirectory, UUID.randomUUID().toString()); // // Reader reader = null; // Writer writer = null; // // try { // reader = Channels.newReader(entity.getChannel(), ENCODING); // writer = new OutputStreamWriter( // new FileOutputStream(output), ENCODING); // // int nchars = reader.read(buffer); // while (nchars >= 0) { // writer.write(buffer, 0, nchars); // nchars = reader.read(buffer); // } // // } catch (IOException consumed) { // // } finally { // closeReliably(reader); // closeReliably(writer); // } // return output; // } // // public static String readFileAsString(String filePath) // throws IOException { // // StringBuilder text = new StringBuilder(); // String nl = System.getProperty("line.separator"); // Scanner scanner = new Scanner(new FileInputStream(filePath), // ENCODING); // try { // while (scanner.hasNextLine()){ // text.append(scanner.nextLine() + nl); // } // } // finally{ // scanner.close(); // } // // return text.toString(); // } // // public static void closeReliably(Closeable closeable) { // // if (closeable != null) { // try { // closeable.close(); // } catch (IOException consumed) { // } // } // } // // public static String stripSignature(String signedString) { // // DocumentBuilder db = XMLUtils.newDocumentBuilder(false); // Document datumDoc = null; // String rdfEntry = ""; // try { // datumDoc = db.parse(new ByteArrayInputStream(signedString // .getBytes(ENCODING))); // // // Create a deep copy of the document and strip signature elements. // Document copy = (Document) datumDoc.cloneNode(true); // MetadataUtils.stripSignatureElements(copy); // rdfEntry = XMLUtils.documentToString(copy); // } catch (SAXException e) { // throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, // "Unable to parse metadata: " + e.getMessage(), e); // } catch (IOException e) { // throw new ResourceException(e); // } // // return rdfEntry; // } // // public static Document extractXmlDocument(String rdf){ // Document datumDoc = null; // // try { // // datumDoc = extractXmlDocument(new ByteArrayInputStream( // rdf.getBytes(ENCODING))); // // } catch (UnsupportedEncodingException e) { // throw new ResourceException(e); // } // // return datumDoc; // } // // public static Document extractXmlDocument(InputStream stream) { // // DocumentBuilder db = XMLUtils.newDocumentBuilder(false); // Document datumDoc = null; // // try { // // datumDoc = db.parse(stream); // // } catch (SAXException e) { // throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, // "unable to parse metadata: " + e.getMessage(), e); // } catch (IOException e) { // throw new ResourceException(e); // } // // return datumDoc; // } // // public static boolean createIfNotExists(String path) { // // File dir = new File(path); // if (!dir.exists()) { // if (!dir.mkdirs()) { // return false; // } // } // // return true; // } // // }
import eu.stratuslab.marketplace.server.utils.MetadataFileUtils; import java.io.File; import java.io.IOException; import java.util.List; import java.util.logging.Logger; import org.restlet.data.Status; import org.restlet.resource.ResourceException; import org.w3c.dom.Document; import eu.stratuslab.marketplace.XMLUtils; import eu.stratuslab.marketplace.metadata.MetadataUtils;
/** * Created as part of the StratusLab project (http://stratuslab.eu), * co-funded by the European Commission under the Grant Agreement * INSFO-RI-261552. * * Copyright (c) 2011 * * 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 eu.stratuslab.marketplace.server.store.file; public class FlatFileStore extends FileStore { private String dataDir; private static final Logger LOGGER = Logger.getLogger("org.restlet"); public FlatFileStore(String dataDir){ this.dataDir = dataDir + File.separator + "metadata";
// Path: server/war/src/main/java/eu/stratuslab/marketplace/server/utils/MetadataFileUtils.java // public final class MetadataFileUtils { // // private static final String ENCODING = "UTF-8"; // // private MetadataFileUtils(){} // // public static File writeContentsToDisk(Representation entity) { // // char[] buffer = new char[4096]; // // File storeDirectory = Configuration // .getParameterValueAsFile(PENDING_DIR); // // File output = new File(storeDirectory, UUID.randomUUID().toString()); // // Reader reader = null; // Writer writer = null; // // try { // reader = Channels.newReader(entity.getChannel(), ENCODING); // writer = new OutputStreamWriter( // new FileOutputStream(output), ENCODING); // // int nchars = reader.read(buffer); // while (nchars >= 0) { // writer.write(buffer, 0, nchars); // nchars = reader.read(buffer); // } // // } catch (IOException consumed) { // // } finally { // closeReliably(reader); // closeReliably(writer); // } // return output; // } // // public static String readFileAsString(String filePath) // throws IOException { // // StringBuilder text = new StringBuilder(); // String nl = System.getProperty("line.separator"); // Scanner scanner = new Scanner(new FileInputStream(filePath), // ENCODING); // try { // while (scanner.hasNextLine()){ // text.append(scanner.nextLine() + nl); // } // } // finally{ // scanner.close(); // } // // return text.toString(); // } // // public static void closeReliably(Closeable closeable) { // // if (closeable != null) { // try { // closeable.close(); // } catch (IOException consumed) { // } // } // } // // public static String stripSignature(String signedString) { // // DocumentBuilder db = XMLUtils.newDocumentBuilder(false); // Document datumDoc = null; // String rdfEntry = ""; // try { // datumDoc = db.parse(new ByteArrayInputStream(signedString // .getBytes(ENCODING))); // // // Create a deep copy of the document and strip signature elements. // Document copy = (Document) datumDoc.cloneNode(true); // MetadataUtils.stripSignatureElements(copy); // rdfEntry = XMLUtils.documentToString(copy); // } catch (SAXException e) { // throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, // "Unable to parse metadata: " + e.getMessage(), e); // } catch (IOException e) { // throw new ResourceException(e); // } // // return rdfEntry; // } // // public static Document extractXmlDocument(String rdf){ // Document datumDoc = null; // // try { // // datumDoc = extractXmlDocument(new ByteArrayInputStream( // rdf.getBytes(ENCODING))); // // } catch (UnsupportedEncodingException e) { // throw new ResourceException(e); // } // // return datumDoc; // } // // public static Document extractXmlDocument(InputStream stream) { // // DocumentBuilder db = XMLUtils.newDocumentBuilder(false); // Document datumDoc = null; // // try { // // datumDoc = db.parse(stream); // // } catch (SAXException e) { // throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, // "unable to parse metadata: " + e.getMessage(), e); // } catch (IOException e) { // throw new ResourceException(e); // } // // return datumDoc; // } // // public static boolean createIfNotExists(String path) { // // File dir = new File(path); // if (!dir.exists()) { // if (!dir.mkdirs()) { // return false; // } // } // // return true; // } // // } // Path: server/war/src/main/java/eu/stratuslab/marketplace/server/store/file/FlatFileStore.java import eu.stratuslab.marketplace.server.utils.MetadataFileUtils; import java.io.File; import java.io.IOException; import java.util.List; import java.util.logging.Logger; import org.restlet.data.Status; import org.restlet.resource.ResourceException; import org.w3c.dom.Document; import eu.stratuslab.marketplace.XMLUtils; import eu.stratuslab.marketplace.metadata.MetadataUtils; /** * Created as part of the StratusLab project (http://stratuslab.eu), * co-funded by the European Commission under the Grant Agreement * INSFO-RI-261552. * * Copyright (c) 2011 * * 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 eu.stratuslab.marketplace.server.store.file; public class FlatFileStore extends FileStore { private String dataDir; private static final Logger LOGGER = Logger.getLogger("org.restlet"); public FlatFileStore(String dataDir){ this.dataDir = dataDir + File.separator + "metadata";
MetadataFileUtils.createIfNotExists(dataDir);
j8spec/j8spec
src/test/java/j8spec/J8SpecFlowRandomOrderTest.java
// Path: src/main/java/j8spec/J8Spec.java // public static synchronized void beforeAll(UnsafeBlock block) { // isValidContext("beforeAll"); // contexts.get().current().addBeforeAll(block); // } // // Path: src/main/java/j8spec/J8Spec.java // public static synchronized void beforeEach(UnsafeBlock block) { // isValidContext("beforeEach"); // contexts.get().current().addBeforeEach(block); // } // // Path: src/main/java/j8spec/J8Spec.java // public static synchronized void it(String description, UnsafeBlock block) { // it(description, identity(), block); // } // // Path: src/main/java/j8spec/J8Spec.java // public static synchronized List<Example> read(Class<?> specClass) { // contexts.set(new ExampleGroupContext()); // try { // ExampleGroupDefinition exampleGroupDefinition = newExampleGroupDefinition(specClass, contexts.get()); // // exampleGroupDefinition.accept(new DuplicatedBlockValidator()); // // BlockExecutionStrategySelector strategySelector = new BlockExecutionStrategySelector(); // exampleGroupDefinition.accept(strategySelector); // // ExampleBuilder exampleBuilder = new ExampleBuilder(strategySelector.strategy()); // exampleGroupDefinition.accept(exampleBuilder); // // return exampleBuilder.build(); // } finally { // contexts.set(null); // } // }
import j8spec.annotation.RandomOrder; import org.junit.Test; import java.util.ArrayList; import java.util.List; import static j8spec.J8Spec.beforeAll; import static j8spec.J8Spec.beforeEach; import static j8spec.J8Spec.it; import static j8spec.J8Spec.read; import static java.util.Arrays.asList; import static java.util.Collections.unmodifiableList; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.not; import static org.junit.Assert.assertThat;
package j8spec; public class J8SpecFlowRandomOrderTest { static class RandomAsDefaultOrderSpec {{
// Path: src/main/java/j8spec/J8Spec.java // public static synchronized void beforeAll(UnsafeBlock block) { // isValidContext("beforeAll"); // contexts.get().current().addBeforeAll(block); // } // // Path: src/main/java/j8spec/J8Spec.java // public static synchronized void beforeEach(UnsafeBlock block) { // isValidContext("beforeEach"); // contexts.get().current().addBeforeEach(block); // } // // Path: src/main/java/j8spec/J8Spec.java // public static synchronized void it(String description, UnsafeBlock block) { // it(description, identity(), block); // } // // Path: src/main/java/j8spec/J8Spec.java // public static synchronized List<Example> read(Class<?> specClass) { // contexts.set(new ExampleGroupContext()); // try { // ExampleGroupDefinition exampleGroupDefinition = newExampleGroupDefinition(specClass, contexts.get()); // // exampleGroupDefinition.accept(new DuplicatedBlockValidator()); // // BlockExecutionStrategySelector strategySelector = new BlockExecutionStrategySelector(); // exampleGroupDefinition.accept(strategySelector); // // ExampleBuilder exampleBuilder = new ExampleBuilder(strategySelector.strategy()); // exampleGroupDefinition.accept(exampleBuilder); // // return exampleBuilder.build(); // } finally { // contexts.set(null); // } // } // Path: src/test/java/j8spec/J8SpecFlowRandomOrderTest.java import j8spec.annotation.RandomOrder; import org.junit.Test; import java.util.ArrayList; import java.util.List; import static j8spec.J8Spec.beforeAll; import static j8spec.J8Spec.beforeEach; import static j8spec.J8Spec.it; import static j8spec.J8Spec.read; import static java.util.Arrays.asList; import static java.util.Collections.unmodifiableList; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.not; import static org.junit.Assert.assertThat; package j8spec; public class J8SpecFlowRandomOrderTest { static class RandomAsDefaultOrderSpec {{
it("block 1", () -> log.add("block 1"));
j8spec/j8spec
src/test/java/j8spec/J8SpecFlowRandomOrderTest.java
// Path: src/main/java/j8spec/J8Spec.java // public static synchronized void beforeAll(UnsafeBlock block) { // isValidContext("beforeAll"); // contexts.get().current().addBeforeAll(block); // } // // Path: src/main/java/j8spec/J8Spec.java // public static synchronized void beforeEach(UnsafeBlock block) { // isValidContext("beforeEach"); // contexts.get().current().addBeforeEach(block); // } // // Path: src/main/java/j8spec/J8Spec.java // public static synchronized void it(String description, UnsafeBlock block) { // it(description, identity(), block); // } // // Path: src/main/java/j8spec/J8Spec.java // public static synchronized List<Example> read(Class<?> specClass) { // contexts.set(new ExampleGroupContext()); // try { // ExampleGroupDefinition exampleGroupDefinition = newExampleGroupDefinition(specClass, contexts.get()); // // exampleGroupDefinition.accept(new DuplicatedBlockValidator()); // // BlockExecutionStrategySelector strategySelector = new BlockExecutionStrategySelector(); // exampleGroupDefinition.accept(strategySelector); // // ExampleBuilder exampleBuilder = new ExampleBuilder(strategySelector.strategy()); // exampleGroupDefinition.accept(exampleBuilder); // // return exampleBuilder.build(); // } finally { // contexts.set(null); // } // }
import j8spec.annotation.RandomOrder; import org.junit.Test; import java.util.ArrayList; import java.util.List; import static j8spec.J8Spec.beforeAll; import static j8spec.J8Spec.beforeEach; import static j8spec.J8Spec.it; import static j8spec.J8Spec.read; import static java.util.Arrays.asList; import static java.util.Collections.unmodifiableList; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.not; import static org.junit.Assert.assertThat;
package j8spec; public class J8SpecFlowRandomOrderTest { static class RandomAsDefaultOrderSpec {{ it("block 1", () -> log.add("block 1")); it("block 2", () -> log.add("block 2")); it("block 3", () -> log.add("block 3")); it("block 4", () -> log.add("block 4")); it("block 5", () -> log.add("block 5")); it("block 6", () -> log.add("block 6")); it("block 7", () -> log.add("block 7")); it("block 8", () -> log.add("block 8")); it("block 9", () -> log.add("block 9")); }} @RandomOrder(seed = 0) static class SingleExampleGroupWithRandomOrderSpec {{
// Path: src/main/java/j8spec/J8Spec.java // public static synchronized void beforeAll(UnsafeBlock block) { // isValidContext("beforeAll"); // contexts.get().current().addBeforeAll(block); // } // // Path: src/main/java/j8spec/J8Spec.java // public static synchronized void beforeEach(UnsafeBlock block) { // isValidContext("beforeEach"); // contexts.get().current().addBeforeEach(block); // } // // Path: src/main/java/j8spec/J8Spec.java // public static synchronized void it(String description, UnsafeBlock block) { // it(description, identity(), block); // } // // Path: src/main/java/j8spec/J8Spec.java // public static synchronized List<Example> read(Class<?> specClass) { // contexts.set(new ExampleGroupContext()); // try { // ExampleGroupDefinition exampleGroupDefinition = newExampleGroupDefinition(specClass, contexts.get()); // // exampleGroupDefinition.accept(new DuplicatedBlockValidator()); // // BlockExecutionStrategySelector strategySelector = new BlockExecutionStrategySelector(); // exampleGroupDefinition.accept(strategySelector); // // ExampleBuilder exampleBuilder = new ExampleBuilder(strategySelector.strategy()); // exampleGroupDefinition.accept(exampleBuilder); // // return exampleBuilder.build(); // } finally { // contexts.set(null); // } // } // Path: src/test/java/j8spec/J8SpecFlowRandomOrderTest.java import j8spec.annotation.RandomOrder; import org.junit.Test; import java.util.ArrayList; import java.util.List; import static j8spec.J8Spec.beforeAll; import static j8spec.J8Spec.beforeEach; import static j8spec.J8Spec.it; import static j8spec.J8Spec.read; import static java.util.Arrays.asList; import static java.util.Collections.unmodifiableList; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.not; import static org.junit.Assert.assertThat; package j8spec; public class J8SpecFlowRandomOrderTest { static class RandomAsDefaultOrderSpec {{ it("block 1", () -> log.add("block 1")); it("block 2", () -> log.add("block 2")); it("block 3", () -> log.add("block 3")); it("block 4", () -> log.add("block 4")); it("block 5", () -> log.add("block 5")); it("block 6", () -> log.add("block 6")); it("block 7", () -> log.add("block 7")); it("block 8", () -> log.add("block 8")); it("block 9", () -> log.add("block 9")); }} @RandomOrder(seed = 0) static class SingleExampleGroupWithRandomOrderSpec {{
beforeAll(() -> log.add("before all 1"));
j8spec/j8spec
src/test/java/j8spec/J8SpecFlowRandomOrderTest.java
// Path: src/main/java/j8spec/J8Spec.java // public static synchronized void beforeAll(UnsafeBlock block) { // isValidContext("beforeAll"); // contexts.get().current().addBeforeAll(block); // } // // Path: src/main/java/j8spec/J8Spec.java // public static synchronized void beforeEach(UnsafeBlock block) { // isValidContext("beforeEach"); // contexts.get().current().addBeforeEach(block); // } // // Path: src/main/java/j8spec/J8Spec.java // public static synchronized void it(String description, UnsafeBlock block) { // it(description, identity(), block); // } // // Path: src/main/java/j8spec/J8Spec.java // public static synchronized List<Example> read(Class<?> specClass) { // contexts.set(new ExampleGroupContext()); // try { // ExampleGroupDefinition exampleGroupDefinition = newExampleGroupDefinition(specClass, contexts.get()); // // exampleGroupDefinition.accept(new DuplicatedBlockValidator()); // // BlockExecutionStrategySelector strategySelector = new BlockExecutionStrategySelector(); // exampleGroupDefinition.accept(strategySelector); // // ExampleBuilder exampleBuilder = new ExampleBuilder(strategySelector.strategy()); // exampleGroupDefinition.accept(exampleBuilder); // // return exampleBuilder.build(); // } finally { // contexts.set(null); // } // }
import j8spec.annotation.RandomOrder; import org.junit.Test; import java.util.ArrayList; import java.util.List; import static j8spec.J8Spec.beforeAll; import static j8spec.J8Spec.beforeEach; import static j8spec.J8Spec.it; import static j8spec.J8Spec.read; import static java.util.Arrays.asList; import static java.util.Collections.unmodifiableList; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.not; import static org.junit.Assert.assertThat;
package j8spec; public class J8SpecFlowRandomOrderTest { static class RandomAsDefaultOrderSpec {{ it("block 1", () -> log.add("block 1")); it("block 2", () -> log.add("block 2")); it("block 3", () -> log.add("block 3")); it("block 4", () -> log.add("block 4")); it("block 5", () -> log.add("block 5")); it("block 6", () -> log.add("block 6")); it("block 7", () -> log.add("block 7")); it("block 8", () -> log.add("block 8")); it("block 9", () -> log.add("block 9")); }} @RandomOrder(seed = 0) static class SingleExampleGroupWithRandomOrderSpec {{ beforeAll(() -> log.add("before all 1"));
// Path: src/main/java/j8spec/J8Spec.java // public static synchronized void beforeAll(UnsafeBlock block) { // isValidContext("beforeAll"); // contexts.get().current().addBeforeAll(block); // } // // Path: src/main/java/j8spec/J8Spec.java // public static synchronized void beforeEach(UnsafeBlock block) { // isValidContext("beforeEach"); // contexts.get().current().addBeforeEach(block); // } // // Path: src/main/java/j8spec/J8Spec.java // public static synchronized void it(String description, UnsafeBlock block) { // it(description, identity(), block); // } // // Path: src/main/java/j8spec/J8Spec.java // public static synchronized List<Example> read(Class<?> specClass) { // contexts.set(new ExampleGroupContext()); // try { // ExampleGroupDefinition exampleGroupDefinition = newExampleGroupDefinition(specClass, contexts.get()); // // exampleGroupDefinition.accept(new DuplicatedBlockValidator()); // // BlockExecutionStrategySelector strategySelector = new BlockExecutionStrategySelector(); // exampleGroupDefinition.accept(strategySelector); // // ExampleBuilder exampleBuilder = new ExampleBuilder(strategySelector.strategy()); // exampleGroupDefinition.accept(exampleBuilder); // // return exampleBuilder.build(); // } finally { // contexts.set(null); // } // } // Path: src/test/java/j8spec/J8SpecFlowRandomOrderTest.java import j8spec.annotation.RandomOrder; import org.junit.Test; import java.util.ArrayList; import java.util.List; import static j8spec.J8Spec.beforeAll; import static j8spec.J8Spec.beforeEach; import static j8spec.J8Spec.it; import static j8spec.J8Spec.read; import static java.util.Arrays.asList; import static java.util.Collections.unmodifiableList; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.not; import static org.junit.Assert.assertThat; package j8spec; public class J8SpecFlowRandomOrderTest { static class RandomAsDefaultOrderSpec {{ it("block 1", () -> log.add("block 1")); it("block 2", () -> log.add("block 2")); it("block 3", () -> log.add("block 3")); it("block 4", () -> log.add("block 4")); it("block 5", () -> log.add("block 5")); it("block 6", () -> log.add("block 6")); it("block 7", () -> log.add("block 7")); it("block 8", () -> log.add("block 8")); it("block 9", () -> log.add("block 9")); }} @RandomOrder(seed = 0) static class SingleExampleGroupWithRandomOrderSpec {{ beforeAll(() -> log.add("before all 1"));
beforeEach(() -> log.add("before each 1"));
j8spec/j8spec
src/test/java/j8spec/J8SpecFlowRandomOrderTest.java
// Path: src/main/java/j8spec/J8Spec.java // public static synchronized void beforeAll(UnsafeBlock block) { // isValidContext("beforeAll"); // contexts.get().current().addBeforeAll(block); // } // // Path: src/main/java/j8spec/J8Spec.java // public static synchronized void beforeEach(UnsafeBlock block) { // isValidContext("beforeEach"); // contexts.get().current().addBeforeEach(block); // } // // Path: src/main/java/j8spec/J8Spec.java // public static synchronized void it(String description, UnsafeBlock block) { // it(description, identity(), block); // } // // Path: src/main/java/j8spec/J8Spec.java // public static synchronized List<Example> read(Class<?> specClass) { // contexts.set(new ExampleGroupContext()); // try { // ExampleGroupDefinition exampleGroupDefinition = newExampleGroupDefinition(specClass, contexts.get()); // // exampleGroupDefinition.accept(new DuplicatedBlockValidator()); // // BlockExecutionStrategySelector strategySelector = new BlockExecutionStrategySelector(); // exampleGroupDefinition.accept(strategySelector); // // ExampleBuilder exampleBuilder = new ExampleBuilder(strategySelector.strategy()); // exampleGroupDefinition.accept(exampleBuilder); // // return exampleBuilder.build(); // } finally { // contexts.set(null); // } // }
import j8spec.annotation.RandomOrder; import org.junit.Test; import java.util.ArrayList; import java.util.List; import static j8spec.J8Spec.beforeAll; import static j8spec.J8Spec.beforeEach; import static j8spec.J8Spec.it; import static j8spec.J8Spec.read; import static java.util.Arrays.asList; import static java.util.Collections.unmodifiableList; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.not; import static org.junit.Assert.assertThat;
it("block 7", () -> log.add("block 7")); it("block 8", () -> log.add("block 8")); it("block 9", () -> log.add("block 9")); }} @RandomOrder(seed = 0) static class SingleExampleGroupWithRandomOrderSpec {{ beforeAll(() -> log.add("before all 1")); beforeEach(() -> log.add("before each 1")); it("block 1", () -> log.add("block 1")); it("block 2", () -> log.add("block 2")); it("block 3", () -> log.add("block 3")); it("block 4", () -> log.add("block 4")); it("block 5", () -> log.add("block 5")); }} @RandomOrder(seed = 0) static class SuperSpec {} static class SubSpec extends SuperSpec {{ it("block 1", () -> log.add("block 1")); it("block 2", () -> log.add("block 2")); it("block 3", () -> log.add("block 3")); }} private static List<String> log; private List<String> executeSpec(Class<?> specClass) throws Throwable { log = new ArrayList<>();
// Path: src/main/java/j8spec/J8Spec.java // public static synchronized void beforeAll(UnsafeBlock block) { // isValidContext("beforeAll"); // contexts.get().current().addBeforeAll(block); // } // // Path: src/main/java/j8spec/J8Spec.java // public static synchronized void beforeEach(UnsafeBlock block) { // isValidContext("beforeEach"); // contexts.get().current().addBeforeEach(block); // } // // Path: src/main/java/j8spec/J8Spec.java // public static synchronized void it(String description, UnsafeBlock block) { // it(description, identity(), block); // } // // Path: src/main/java/j8spec/J8Spec.java // public static synchronized List<Example> read(Class<?> specClass) { // contexts.set(new ExampleGroupContext()); // try { // ExampleGroupDefinition exampleGroupDefinition = newExampleGroupDefinition(specClass, contexts.get()); // // exampleGroupDefinition.accept(new DuplicatedBlockValidator()); // // BlockExecutionStrategySelector strategySelector = new BlockExecutionStrategySelector(); // exampleGroupDefinition.accept(strategySelector); // // ExampleBuilder exampleBuilder = new ExampleBuilder(strategySelector.strategy()); // exampleGroupDefinition.accept(exampleBuilder); // // return exampleBuilder.build(); // } finally { // contexts.set(null); // } // } // Path: src/test/java/j8spec/J8SpecFlowRandomOrderTest.java import j8spec.annotation.RandomOrder; import org.junit.Test; import java.util.ArrayList; import java.util.List; import static j8spec.J8Spec.beforeAll; import static j8spec.J8Spec.beforeEach; import static j8spec.J8Spec.it; import static j8spec.J8Spec.read; import static java.util.Arrays.asList; import static java.util.Collections.unmodifiableList; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.not; import static org.junit.Assert.assertThat; it("block 7", () -> log.add("block 7")); it("block 8", () -> log.add("block 8")); it("block 9", () -> log.add("block 9")); }} @RandomOrder(seed = 0) static class SingleExampleGroupWithRandomOrderSpec {{ beforeAll(() -> log.add("before all 1")); beforeEach(() -> log.add("before each 1")); it("block 1", () -> log.add("block 1")); it("block 2", () -> log.add("block 2")); it("block 3", () -> log.add("block 3")); it("block 4", () -> log.add("block 4")); it("block 5", () -> log.add("block 5")); }} @RandomOrder(seed = 0) static class SuperSpec {} static class SubSpec extends SuperSpec {{ it("block 1", () -> log.add("block 1")); it("block 2", () -> log.add("block 2")); it("block 3", () -> log.add("block 3")); }} private static List<String> log; private List<String> executeSpec(Class<?> specClass) throws Throwable { log = new ArrayList<>();
for (Example example : read(specClass)) {
j8spec/j8spec
src/main/java/j8spec/ExampleGroupDefinition.java
// Path: src/main/java/j8spec/BlockDefinition.java // static void visitAll(BlockDefinitionVisitor visitor, Collection<BlockDefinition> blockDefinitions) { // for (BlockDefinition blockDefinition : blockDefinitions) { // blockDefinition.accept(visitor); // } // }
import j8spec.annotation.DefinedOrder; import j8spec.annotation.RandomOrder; import java.util.LinkedList; import java.util.List; import static j8spec.BlockExecutionFlag.DEFAULT; import static j8spec.BlockDefinition.visitAll;
} <T> void addVarInitializer(Var<T> var, UnsafeFunction<T> initFunction) { varInitializers.add(new BlockDefinitions.VarInitializer<>(var, initFunction)); } void addBeforeAll(UnsafeBlock beforeAllBlock) { hooks.add(new BlockDefinitions.BeforeAll(beforeAllBlock)); } void addBeforeEach(UnsafeBlock beforeEachBlock) { hooks.add(new BlockDefinitions.BeforeEach(beforeEachBlock)); } void addAfterEach(UnsafeBlock afterEachBlock) { hooks.add(new BlockDefinitions.AfterEach(afterEachBlock)); } void addAfterAll(UnsafeBlock afterAllBlock) { hooks.add(new BlockDefinitions.AfterAll(afterAllBlock)); } void addExample(ExampleConfiguration exampleConfig, UnsafeBlock block) { blockDefinitions.add(new BlockDefinitions.Example(exampleConfig, block)); } @Override public void accept(BlockDefinitionVisitor visitor) { visitor.startGroup(config);
// Path: src/main/java/j8spec/BlockDefinition.java // static void visitAll(BlockDefinitionVisitor visitor, Collection<BlockDefinition> blockDefinitions) { // for (BlockDefinition blockDefinition : blockDefinitions) { // blockDefinition.accept(visitor); // } // } // Path: src/main/java/j8spec/ExampleGroupDefinition.java import j8spec.annotation.DefinedOrder; import j8spec.annotation.RandomOrder; import java.util.LinkedList; import java.util.List; import static j8spec.BlockExecutionFlag.DEFAULT; import static j8spec.BlockDefinition.visitAll; } <T> void addVarInitializer(Var<T> var, UnsafeFunction<T> initFunction) { varInitializers.add(new BlockDefinitions.VarInitializer<>(var, initFunction)); } void addBeforeAll(UnsafeBlock beforeAllBlock) { hooks.add(new BlockDefinitions.BeforeAll(beforeAllBlock)); } void addBeforeEach(UnsafeBlock beforeEachBlock) { hooks.add(new BlockDefinitions.BeforeEach(beforeEachBlock)); } void addAfterEach(UnsafeBlock afterEachBlock) { hooks.add(new BlockDefinitions.AfterEach(afterEachBlock)); } void addAfterAll(UnsafeBlock afterAllBlock) { hooks.add(new BlockDefinitions.AfterAll(afterAllBlock)); } void addExample(ExampleConfiguration exampleConfig, UnsafeBlock block) { blockDefinitions.add(new BlockDefinitions.Example(exampleConfig, block)); } @Override public void accept(BlockDefinitionVisitor visitor) { visitor.startGroup(config);
visitAll(visitor, varInitializers);
j8spec/j8spec
src/test/java/j8spec/J8SpecFocusTest.java
// Path: src/main/java/j8spec/J8Spec.java // public static synchronized void fcontext(String description, SafeBlock block) { // notAllowedWhenCIModeEnabled("fcontext"); // isValidContext("fcontext"); // ExampleGroupConfiguration config = new ExampleGroupConfiguration.Builder() // .description(description) // .executionFlag(FOCUSED) // .build(); // contexts.get().current().addGroup(config, block); // } // // Path: src/main/java/j8spec/J8Spec.java // public static synchronized void fdescribe(String description, SafeBlock block) { // notAllowedWhenCIModeEnabled("fdescribe"); // isValidContext("fdescribe"); // ExampleGroupConfiguration config = new ExampleGroupConfiguration.Builder() // .description(description) // .executionFlag(FOCUSED) // .build(); // contexts.get().current().addGroup(config, block); // } // // Path: src/main/java/j8spec/J8Spec.java // public static synchronized void fit(String description, UnsafeBlock block) { // fit(description, identity(), block); // } // // Path: src/main/java/j8spec/J8Spec.java // public static synchronized List<Example> read(Class<?> specClass) { // contexts.set(new ExampleGroupContext()); // try { // ExampleGroupDefinition exampleGroupDefinition = newExampleGroupDefinition(specClass, contexts.get()); // // exampleGroupDefinition.accept(new DuplicatedBlockValidator()); // // BlockExecutionStrategySelector strategySelector = new BlockExecutionStrategySelector(); // exampleGroupDefinition.accept(strategySelector); // // ExampleBuilder exampleBuilder = new ExampleBuilder(strategySelector.strategy()); // exampleGroupDefinition.accept(exampleBuilder); // // return exampleBuilder.build(); // } finally { // contexts.set(null); // } // }
import org.junit.Test; import static j8spec.J8Spec.fcontext; import static j8spec.J8Spec.fdescribe; import static j8spec.J8Spec.fit; import static j8spec.J8Spec.read;
package j8spec; public class J8SpecFocusTest { static class FocusedExampleBlockOverwrittenSpec {{
// Path: src/main/java/j8spec/J8Spec.java // public static synchronized void fcontext(String description, SafeBlock block) { // notAllowedWhenCIModeEnabled("fcontext"); // isValidContext("fcontext"); // ExampleGroupConfiguration config = new ExampleGroupConfiguration.Builder() // .description(description) // .executionFlag(FOCUSED) // .build(); // contexts.get().current().addGroup(config, block); // } // // Path: src/main/java/j8spec/J8Spec.java // public static synchronized void fdescribe(String description, SafeBlock block) { // notAllowedWhenCIModeEnabled("fdescribe"); // isValidContext("fdescribe"); // ExampleGroupConfiguration config = new ExampleGroupConfiguration.Builder() // .description(description) // .executionFlag(FOCUSED) // .build(); // contexts.get().current().addGroup(config, block); // } // // Path: src/main/java/j8spec/J8Spec.java // public static synchronized void fit(String description, UnsafeBlock block) { // fit(description, identity(), block); // } // // Path: src/main/java/j8spec/J8Spec.java // public static synchronized List<Example> read(Class<?> specClass) { // contexts.set(new ExampleGroupContext()); // try { // ExampleGroupDefinition exampleGroupDefinition = newExampleGroupDefinition(specClass, contexts.get()); // // exampleGroupDefinition.accept(new DuplicatedBlockValidator()); // // BlockExecutionStrategySelector strategySelector = new BlockExecutionStrategySelector(); // exampleGroupDefinition.accept(strategySelector); // // ExampleBuilder exampleBuilder = new ExampleBuilder(strategySelector.strategy()); // exampleGroupDefinition.accept(exampleBuilder); // // return exampleBuilder.build(); // } finally { // contexts.set(null); // } // } // Path: src/test/java/j8spec/J8SpecFocusTest.java import org.junit.Test; import static j8spec.J8Spec.fcontext; import static j8spec.J8Spec.fdescribe; import static j8spec.J8Spec.fit; import static j8spec.J8Spec.read; package j8spec; public class J8SpecFocusTest { static class FocusedExampleBlockOverwrittenSpec {{
fit("some text", UnsafeBlock.NOOP);
j8spec/j8spec
src/test/java/j8spec/J8SpecFocusTest.java
// Path: src/main/java/j8spec/J8Spec.java // public static synchronized void fcontext(String description, SafeBlock block) { // notAllowedWhenCIModeEnabled("fcontext"); // isValidContext("fcontext"); // ExampleGroupConfiguration config = new ExampleGroupConfiguration.Builder() // .description(description) // .executionFlag(FOCUSED) // .build(); // contexts.get().current().addGroup(config, block); // } // // Path: src/main/java/j8spec/J8Spec.java // public static synchronized void fdescribe(String description, SafeBlock block) { // notAllowedWhenCIModeEnabled("fdescribe"); // isValidContext("fdescribe"); // ExampleGroupConfiguration config = new ExampleGroupConfiguration.Builder() // .description(description) // .executionFlag(FOCUSED) // .build(); // contexts.get().current().addGroup(config, block); // } // // Path: src/main/java/j8spec/J8Spec.java // public static synchronized void fit(String description, UnsafeBlock block) { // fit(description, identity(), block); // } // // Path: src/main/java/j8spec/J8Spec.java // public static synchronized List<Example> read(Class<?> specClass) { // contexts.set(new ExampleGroupContext()); // try { // ExampleGroupDefinition exampleGroupDefinition = newExampleGroupDefinition(specClass, contexts.get()); // // exampleGroupDefinition.accept(new DuplicatedBlockValidator()); // // BlockExecutionStrategySelector strategySelector = new BlockExecutionStrategySelector(); // exampleGroupDefinition.accept(strategySelector); // // ExampleBuilder exampleBuilder = new ExampleBuilder(strategySelector.strategy()); // exampleGroupDefinition.accept(exampleBuilder); // // return exampleBuilder.build(); // } finally { // contexts.set(null); // } // }
import org.junit.Test; import static j8spec.J8Spec.fcontext; import static j8spec.J8Spec.fdescribe; import static j8spec.J8Spec.fit; import static j8spec.J8Spec.read;
package j8spec; public class J8SpecFocusTest { static class FocusedExampleBlockOverwrittenSpec {{ fit("some text", UnsafeBlock.NOOP); fit("some text", UnsafeBlock.NOOP); }} static class FocusedExampleWithCollectorOverwrittenSpec {{ fit("some text", c -> c, UnsafeBlock.NOOP); fit("some text", UnsafeBlock.NOOP); }} @Test(expected = Exceptions.IllegalContext.class) public void does_not_allow_fdescribe_method_direct_invocation() {
// Path: src/main/java/j8spec/J8Spec.java // public static synchronized void fcontext(String description, SafeBlock block) { // notAllowedWhenCIModeEnabled("fcontext"); // isValidContext("fcontext"); // ExampleGroupConfiguration config = new ExampleGroupConfiguration.Builder() // .description(description) // .executionFlag(FOCUSED) // .build(); // contexts.get().current().addGroup(config, block); // } // // Path: src/main/java/j8spec/J8Spec.java // public static synchronized void fdescribe(String description, SafeBlock block) { // notAllowedWhenCIModeEnabled("fdescribe"); // isValidContext("fdescribe"); // ExampleGroupConfiguration config = new ExampleGroupConfiguration.Builder() // .description(description) // .executionFlag(FOCUSED) // .build(); // contexts.get().current().addGroup(config, block); // } // // Path: src/main/java/j8spec/J8Spec.java // public static synchronized void fit(String description, UnsafeBlock block) { // fit(description, identity(), block); // } // // Path: src/main/java/j8spec/J8Spec.java // public static synchronized List<Example> read(Class<?> specClass) { // contexts.set(new ExampleGroupContext()); // try { // ExampleGroupDefinition exampleGroupDefinition = newExampleGroupDefinition(specClass, contexts.get()); // // exampleGroupDefinition.accept(new DuplicatedBlockValidator()); // // BlockExecutionStrategySelector strategySelector = new BlockExecutionStrategySelector(); // exampleGroupDefinition.accept(strategySelector); // // ExampleBuilder exampleBuilder = new ExampleBuilder(strategySelector.strategy()); // exampleGroupDefinition.accept(exampleBuilder); // // return exampleBuilder.build(); // } finally { // contexts.set(null); // } // } // Path: src/test/java/j8spec/J8SpecFocusTest.java import org.junit.Test; import static j8spec.J8Spec.fcontext; import static j8spec.J8Spec.fdescribe; import static j8spec.J8Spec.fit; import static j8spec.J8Spec.read; package j8spec; public class J8SpecFocusTest { static class FocusedExampleBlockOverwrittenSpec {{ fit("some text", UnsafeBlock.NOOP); fit("some text", UnsafeBlock.NOOP); }} static class FocusedExampleWithCollectorOverwrittenSpec {{ fit("some text", c -> c, UnsafeBlock.NOOP); fit("some text", UnsafeBlock.NOOP); }} @Test(expected = Exceptions.IllegalContext.class) public void does_not_allow_fdescribe_method_direct_invocation() {
fdescribe("some text", SafeBlock.NOOP);
j8spec/j8spec
src/test/java/j8spec/J8SpecFocusTest.java
// Path: src/main/java/j8spec/J8Spec.java // public static synchronized void fcontext(String description, SafeBlock block) { // notAllowedWhenCIModeEnabled("fcontext"); // isValidContext("fcontext"); // ExampleGroupConfiguration config = new ExampleGroupConfiguration.Builder() // .description(description) // .executionFlag(FOCUSED) // .build(); // contexts.get().current().addGroup(config, block); // } // // Path: src/main/java/j8spec/J8Spec.java // public static synchronized void fdescribe(String description, SafeBlock block) { // notAllowedWhenCIModeEnabled("fdescribe"); // isValidContext("fdescribe"); // ExampleGroupConfiguration config = new ExampleGroupConfiguration.Builder() // .description(description) // .executionFlag(FOCUSED) // .build(); // contexts.get().current().addGroup(config, block); // } // // Path: src/main/java/j8spec/J8Spec.java // public static synchronized void fit(String description, UnsafeBlock block) { // fit(description, identity(), block); // } // // Path: src/main/java/j8spec/J8Spec.java // public static synchronized List<Example> read(Class<?> specClass) { // contexts.set(new ExampleGroupContext()); // try { // ExampleGroupDefinition exampleGroupDefinition = newExampleGroupDefinition(specClass, contexts.get()); // // exampleGroupDefinition.accept(new DuplicatedBlockValidator()); // // BlockExecutionStrategySelector strategySelector = new BlockExecutionStrategySelector(); // exampleGroupDefinition.accept(strategySelector); // // ExampleBuilder exampleBuilder = new ExampleBuilder(strategySelector.strategy()); // exampleGroupDefinition.accept(exampleBuilder); // // return exampleBuilder.build(); // } finally { // contexts.set(null); // } // }
import org.junit.Test; import static j8spec.J8Spec.fcontext; import static j8spec.J8Spec.fdescribe; import static j8spec.J8Spec.fit; import static j8spec.J8Spec.read;
package j8spec; public class J8SpecFocusTest { static class FocusedExampleBlockOverwrittenSpec {{ fit("some text", UnsafeBlock.NOOP); fit("some text", UnsafeBlock.NOOP); }} static class FocusedExampleWithCollectorOverwrittenSpec {{ fit("some text", c -> c, UnsafeBlock.NOOP); fit("some text", UnsafeBlock.NOOP); }} @Test(expected = Exceptions.IllegalContext.class) public void does_not_allow_fdescribe_method_direct_invocation() { fdescribe("some text", SafeBlock.NOOP); } @Test(expected = Exceptions.IllegalContext.class) public void does_not_allow_fcontext_method_direct_invocation() {
// Path: src/main/java/j8spec/J8Spec.java // public static synchronized void fcontext(String description, SafeBlock block) { // notAllowedWhenCIModeEnabled("fcontext"); // isValidContext("fcontext"); // ExampleGroupConfiguration config = new ExampleGroupConfiguration.Builder() // .description(description) // .executionFlag(FOCUSED) // .build(); // contexts.get().current().addGroup(config, block); // } // // Path: src/main/java/j8spec/J8Spec.java // public static synchronized void fdescribe(String description, SafeBlock block) { // notAllowedWhenCIModeEnabled("fdescribe"); // isValidContext("fdescribe"); // ExampleGroupConfiguration config = new ExampleGroupConfiguration.Builder() // .description(description) // .executionFlag(FOCUSED) // .build(); // contexts.get().current().addGroup(config, block); // } // // Path: src/main/java/j8spec/J8Spec.java // public static synchronized void fit(String description, UnsafeBlock block) { // fit(description, identity(), block); // } // // Path: src/main/java/j8spec/J8Spec.java // public static synchronized List<Example> read(Class<?> specClass) { // contexts.set(new ExampleGroupContext()); // try { // ExampleGroupDefinition exampleGroupDefinition = newExampleGroupDefinition(specClass, contexts.get()); // // exampleGroupDefinition.accept(new DuplicatedBlockValidator()); // // BlockExecutionStrategySelector strategySelector = new BlockExecutionStrategySelector(); // exampleGroupDefinition.accept(strategySelector); // // ExampleBuilder exampleBuilder = new ExampleBuilder(strategySelector.strategy()); // exampleGroupDefinition.accept(exampleBuilder); // // return exampleBuilder.build(); // } finally { // contexts.set(null); // } // } // Path: src/test/java/j8spec/J8SpecFocusTest.java import org.junit.Test; import static j8spec.J8Spec.fcontext; import static j8spec.J8Spec.fdescribe; import static j8spec.J8Spec.fit; import static j8spec.J8Spec.read; package j8spec; public class J8SpecFocusTest { static class FocusedExampleBlockOverwrittenSpec {{ fit("some text", UnsafeBlock.NOOP); fit("some text", UnsafeBlock.NOOP); }} static class FocusedExampleWithCollectorOverwrittenSpec {{ fit("some text", c -> c, UnsafeBlock.NOOP); fit("some text", UnsafeBlock.NOOP); }} @Test(expected = Exceptions.IllegalContext.class) public void does_not_allow_fdescribe_method_direct_invocation() { fdescribe("some text", SafeBlock.NOOP); } @Test(expected = Exceptions.IllegalContext.class) public void does_not_allow_fcontext_method_direct_invocation() {
fcontext("some text", SafeBlock.NOOP);
j8spec/j8spec
src/test/java/j8spec/J8SpecFocusTest.java
// Path: src/main/java/j8spec/J8Spec.java // public static synchronized void fcontext(String description, SafeBlock block) { // notAllowedWhenCIModeEnabled("fcontext"); // isValidContext("fcontext"); // ExampleGroupConfiguration config = new ExampleGroupConfiguration.Builder() // .description(description) // .executionFlag(FOCUSED) // .build(); // contexts.get().current().addGroup(config, block); // } // // Path: src/main/java/j8spec/J8Spec.java // public static synchronized void fdescribe(String description, SafeBlock block) { // notAllowedWhenCIModeEnabled("fdescribe"); // isValidContext("fdescribe"); // ExampleGroupConfiguration config = new ExampleGroupConfiguration.Builder() // .description(description) // .executionFlag(FOCUSED) // .build(); // contexts.get().current().addGroup(config, block); // } // // Path: src/main/java/j8spec/J8Spec.java // public static synchronized void fit(String description, UnsafeBlock block) { // fit(description, identity(), block); // } // // Path: src/main/java/j8spec/J8Spec.java // public static synchronized List<Example> read(Class<?> specClass) { // contexts.set(new ExampleGroupContext()); // try { // ExampleGroupDefinition exampleGroupDefinition = newExampleGroupDefinition(specClass, contexts.get()); // // exampleGroupDefinition.accept(new DuplicatedBlockValidator()); // // BlockExecutionStrategySelector strategySelector = new BlockExecutionStrategySelector(); // exampleGroupDefinition.accept(strategySelector); // // ExampleBuilder exampleBuilder = new ExampleBuilder(strategySelector.strategy()); // exampleGroupDefinition.accept(exampleBuilder); // // return exampleBuilder.build(); // } finally { // contexts.set(null); // } // }
import org.junit.Test; import static j8spec.J8Spec.fcontext; import static j8spec.J8Spec.fdescribe; import static j8spec.J8Spec.fit; import static j8spec.J8Spec.read;
package j8spec; public class J8SpecFocusTest { static class FocusedExampleBlockOverwrittenSpec {{ fit("some text", UnsafeBlock.NOOP); fit("some text", UnsafeBlock.NOOP); }} static class FocusedExampleWithCollectorOverwrittenSpec {{ fit("some text", c -> c, UnsafeBlock.NOOP); fit("some text", UnsafeBlock.NOOP); }} @Test(expected = Exceptions.IllegalContext.class) public void does_not_allow_fdescribe_method_direct_invocation() { fdescribe("some text", SafeBlock.NOOP); } @Test(expected = Exceptions.IllegalContext.class) public void does_not_allow_fcontext_method_direct_invocation() { fcontext("some text", SafeBlock.NOOP); } @Test(expected = Exceptions.IllegalContext.class) public void does_not_allow_fit_method_direct_invocation() { fit("some text", UnsafeBlock.NOOP); } @Test(expected = Exceptions.IllegalContext.class) public void does_not_allow_fit_method_with_collector_direct_invocation() { fit("some text", c -> c, UnsafeBlock.NOOP); } @Test(expected = Exceptions.BlockAlreadyDefined.class) public void does_not_allow_focused_example_to_be_replaced() {
// Path: src/main/java/j8spec/J8Spec.java // public static synchronized void fcontext(String description, SafeBlock block) { // notAllowedWhenCIModeEnabled("fcontext"); // isValidContext("fcontext"); // ExampleGroupConfiguration config = new ExampleGroupConfiguration.Builder() // .description(description) // .executionFlag(FOCUSED) // .build(); // contexts.get().current().addGroup(config, block); // } // // Path: src/main/java/j8spec/J8Spec.java // public static synchronized void fdescribe(String description, SafeBlock block) { // notAllowedWhenCIModeEnabled("fdescribe"); // isValidContext("fdescribe"); // ExampleGroupConfiguration config = new ExampleGroupConfiguration.Builder() // .description(description) // .executionFlag(FOCUSED) // .build(); // contexts.get().current().addGroup(config, block); // } // // Path: src/main/java/j8spec/J8Spec.java // public static synchronized void fit(String description, UnsafeBlock block) { // fit(description, identity(), block); // } // // Path: src/main/java/j8spec/J8Spec.java // public static synchronized List<Example> read(Class<?> specClass) { // contexts.set(new ExampleGroupContext()); // try { // ExampleGroupDefinition exampleGroupDefinition = newExampleGroupDefinition(specClass, contexts.get()); // // exampleGroupDefinition.accept(new DuplicatedBlockValidator()); // // BlockExecutionStrategySelector strategySelector = new BlockExecutionStrategySelector(); // exampleGroupDefinition.accept(strategySelector); // // ExampleBuilder exampleBuilder = new ExampleBuilder(strategySelector.strategy()); // exampleGroupDefinition.accept(exampleBuilder); // // return exampleBuilder.build(); // } finally { // contexts.set(null); // } // } // Path: src/test/java/j8spec/J8SpecFocusTest.java import org.junit.Test; import static j8spec.J8Spec.fcontext; import static j8spec.J8Spec.fdescribe; import static j8spec.J8Spec.fit; import static j8spec.J8Spec.read; package j8spec; public class J8SpecFocusTest { static class FocusedExampleBlockOverwrittenSpec {{ fit("some text", UnsafeBlock.NOOP); fit("some text", UnsafeBlock.NOOP); }} static class FocusedExampleWithCollectorOverwrittenSpec {{ fit("some text", c -> c, UnsafeBlock.NOOP); fit("some text", UnsafeBlock.NOOP); }} @Test(expected = Exceptions.IllegalContext.class) public void does_not_allow_fdescribe_method_direct_invocation() { fdescribe("some text", SafeBlock.NOOP); } @Test(expected = Exceptions.IllegalContext.class) public void does_not_allow_fcontext_method_direct_invocation() { fcontext("some text", SafeBlock.NOOP); } @Test(expected = Exceptions.IllegalContext.class) public void does_not_allow_fit_method_direct_invocation() { fit("some text", UnsafeBlock.NOOP); } @Test(expected = Exceptions.IllegalContext.class) public void does_not_allow_fit_method_with_collector_direct_invocation() { fit("some text", c -> c, UnsafeBlock.NOOP); } @Test(expected = Exceptions.BlockAlreadyDefined.class) public void does_not_allow_focused_example_to_be_replaced() {
read(FocusedExampleBlockOverwrittenSpec.class);
j8spec/j8spec
src/test/java/j8spec/VarTest.java
// Path: src/main/java/j8spec/J8Spec.java // public static <T> Var<T> var() { // return new Var<>(); // }
import org.junit.Test; import static j8spec.J8Spec.var; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat;
package j8spec; public class VarTest { @Test public void stores_value_in_variable() {
// Path: src/main/java/j8spec/J8Spec.java // public static <T> Var<T> var() { // return new Var<>(); // } // Path: src/test/java/j8spec/VarTest.java import org.junit.Test; import static j8spec.J8Spec.var; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; package j8spec; public class VarTest { @Test public void stores_value_in_variable() {
final Var<String> s = var();
j8spec/j8spec
src/main/java/j8spec/J8Spec.java
// Path: src/main/java/j8spec/ExampleGroupDefinition.java // static ExampleGroupDefinition newExampleGroupDefinition( // Class<?> specClass, // ExampleGroupContext context // ) { // ExampleGroupConfiguration.Builder configBuilder = new ExampleGroupConfiguration.Builder() // .description(specClass.getName()) // .executionFlag(DEFAULT); // // configureExecutionOrder(specClass, configBuilder); // // ExampleGroupDefinition group = new ExampleGroupDefinition(configBuilder.build(), context); // context.switchTo(group); // // try { // specClass.newInstance(); // } catch (Exceptions.Base e) { // throw e; // } catch (Exception e) { // throw new Exceptions.SpecInitializationFailed(specClass, e); // } // // return group; // }
import java.util.List; import java.util.function.Function; import static j8spec.BlockExecutionFlag.DEFAULT; import static j8spec.BlockExecutionFlag.FOCUSED; import static j8spec.BlockExecutionFlag.IGNORED; import static j8spec.ExampleGroupDefinition.newExampleGroupDefinition; import static java.util.function.Function.identity;
* @since 3.1.0 */ public static <T> T var(Var<T> var) { return var.value; } /** * Stores the given value in the provided variable object. * * @param var variable object * @param value value to be stored * @param <T> type of value the variable object can store * @return value stored in the variable object * @since 3.1.0 */ public static <T> T var(Var<T> var, T value) { return var.value = value; } /** * Uses the given spec class to build and populate a list of {@link Example} objects ready to be executed. * * @param specClass class with a public default constructor that contains the spec definition * @return {@link Example} objects that represent the spec definition and can be executed * @throws Exceptions.SpecInitializationFailed if it is not possible to create an instance of <code>specClass</code> * @since 2.0.0 */ public static synchronized List<Example> read(Class<?> specClass) { contexts.set(new ExampleGroupContext()); try {
// Path: src/main/java/j8spec/ExampleGroupDefinition.java // static ExampleGroupDefinition newExampleGroupDefinition( // Class<?> specClass, // ExampleGroupContext context // ) { // ExampleGroupConfiguration.Builder configBuilder = new ExampleGroupConfiguration.Builder() // .description(specClass.getName()) // .executionFlag(DEFAULT); // // configureExecutionOrder(specClass, configBuilder); // // ExampleGroupDefinition group = new ExampleGroupDefinition(configBuilder.build(), context); // context.switchTo(group); // // try { // specClass.newInstance(); // } catch (Exceptions.Base e) { // throw e; // } catch (Exception e) { // throw new Exceptions.SpecInitializationFailed(specClass, e); // } // // return group; // } // Path: src/main/java/j8spec/J8Spec.java import java.util.List; import java.util.function.Function; import static j8spec.BlockExecutionFlag.DEFAULT; import static j8spec.BlockExecutionFlag.FOCUSED; import static j8spec.BlockExecutionFlag.IGNORED; import static j8spec.ExampleGroupDefinition.newExampleGroupDefinition; import static java.util.function.Function.identity; * @since 3.1.0 */ public static <T> T var(Var<T> var) { return var.value; } /** * Stores the given value in the provided variable object. * * @param var variable object * @param value value to be stored * @param <T> type of value the variable object can store * @return value stored in the variable object * @since 3.1.0 */ public static <T> T var(Var<T> var, T value) { return var.value = value; } /** * Uses the given spec class to build and populate a list of {@link Example} objects ready to be executed. * * @param specClass class with a public default constructor that contains the spec definition * @return {@link Example} objects that represent the spec definition and can be executed * @throws Exceptions.SpecInitializationFailed if it is not possible to create an instance of <code>specClass</code> * @since 2.0.0 */ public static synchronized List<Example> read(Class<?> specClass) { contexts.set(new ExampleGroupContext()); try {
ExampleGroupDefinition exampleGroupDefinition = newExampleGroupDefinition(specClass, contexts.get());
j8spec/j8spec
src/test/java/j8spec/J8SpecIgnoreTest.java
// Path: src/main/java/j8spec/J8Spec.java // public static synchronized List<Example> read(Class<?> specClass) { // contexts.set(new ExampleGroupContext()); // try { // ExampleGroupDefinition exampleGroupDefinition = newExampleGroupDefinition(specClass, contexts.get()); // // exampleGroupDefinition.accept(new DuplicatedBlockValidator()); // // BlockExecutionStrategySelector strategySelector = new BlockExecutionStrategySelector(); // exampleGroupDefinition.accept(strategySelector); // // ExampleBuilder exampleBuilder = new ExampleBuilder(strategySelector.strategy()); // exampleGroupDefinition.accept(exampleBuilder); // // return exampleBuilder.build(); // } finally { // contexts.set(null); // } // } // // Path: src/main/java/j8spec/J8Spec.java // public static synchronized void xcontext(String description, SafeBlock block) { // notAllowedWhenCIModeEnabled("xcontext"); // isValidContext("xcontext"); // ExampleGroupConfiguration config = new ExampleGroupConfiguration.Builder() // .description(description) // .executionFlag(IGNORED) // .build(); // contexts.get().current().addGroup(config, block); // } // // Path: src/main/java/j8spec/J8Spec.java // public static synchronized void xdescribe(String description, SafeBlock block) { // notAllowedWhenCIModeEnabled("xdescribe"); // isValidContext("xdescribe"); // ExampleGroupConfiguration config = new ExampleGroupConfiguration.Builder() // .description(description) // .executionFlag(IGNORED) // .build(); // contexts.get().current().addGroup(config, block); // } // // Path: src/main/java/j8spec/J8Spec.java // public static synchronized void xit(String description, UnsafeBlock block) { // xit(description, identity(), block); // }
import org.junit.Test; import static j8spec.J8Spec.read; import static j8spec.J8Spec.xcontext; import static j8spec.J8Spec.xdescribe; import static j8spec.J8Spec.xit;
package j8spec; public class J8SpecIgnoreTest { static class IgnoredExampleOverwrittenSpec {{
// Path: src/main/java/j8spec/J8Spec.java // public static synchronized List<Example> read(Class<?> specClass) { // contexts.set(new ExampleGroupContext()); // try { // ExampleGroupDefinition exampleGroupDefinition = newExampleGroupDefinition(specClass, contexts.get()); // // exampleGroupDefinition.accept(new DuplicatedBlockValidator()); // // BlockExecutionStrategySelector strategySelector = new BlockExecutionStrategySelector(); // exampleGroupDefinition.accept(strategySelector); // // ExampleBuilder exampleBuilder = new ExampleBuilder(strategySelector.strategy()); // exampleGroupDefinition.accept(exampleBuilder); // // return exampleBuilder.build(); // } finally { // contexts.set(null); // } // } // // Path: src/main/java/j8spec/J8Spec.java // public static synchronized void xcontext(String description, SafeBlock block) { // notAllowedWhenCIModeEnabled("xcontext"); // isValidContext("xcontext"); // ExampleGroupConfiguration config = new ExampleGroupConfiguration.Builder() // .description(description) // .executionFlag(IGNORED) // .build(); // contexts.get().current().addGroup(config, block); // } // // Path: src/main/java/j8spec/J8Spec.java // public static synchronized void xdescribe(String description, SafeBlock block) { // notAllowedWhenCIModeEnabled("xdescribe"); // isValidContext("xdescribe"); // ExampleGroupConfiguration config = new ExampleGroupConfiguration.Builder() // .description(description) // .executionFlag(IGNORED) // .build(); // contexts.get().current().addGroup(config, block); // } // // Path: src/main/java/j8spec/J8Spec.java // public static synchronized void xit(String description, UnsafeBlock block) { // xit(description, identity(), block); // } // Path: src/test/java/j8spec/J8SpecIgnoreTest.java import org.junit.Test; import static j8spec.J8Spec.read; import static j8spec.J8Spec.xcontext; import static j8spec.J8Spec.xdescribe; import static j8spec.J8Spec.xit; package j8spec; public class J8SpecIgnoreTest { static class IgnoredExampleOverwrittenSpec {{
xit("some text", UnsafeBlock.NOOP);
j8spec/j8spec
src/test/java/j8spec/J8SpecIgnoreTest.java
// Path: src/main/java/j8spec/J8Spec.java // public static synchronized List<Example> read(Class<?> specClass) { // contexts.set(new ExampleGroupContext()); // try { // ExampleGroupDefinition exampleGroupDefinition = newExampleGroupDefinition(specClass, contexts.get()); // // exampleGroupDefinition.accept(new DuplicatedBlockValidator()); // // BlockExecutionStrategySelector strategySelector = new BlockExecutionStrategySelector(); // exampleGroupDefinition.accept(strategySelector); // // ExampleBuilder exampleBuilder = new ExampleBuilder(strategySelector.strategy()); // exampleGroupDefinition.accept(exampleBuilder); // // return exampleBuilder.build(); // } finally { // contexts.set(null); // } // } // // Path: src/main/java/j8spec/J8Spec.java // public static synchronized void xcontext(String description, SafeBlock block) { // notAllowedWhenCIModeEnabled("xcontext"); // isValidContext("xcontext"); // ExampleGroupConfiguration config = new ExampleGroupConfiguration.Builder() // .description(description) // .executionFlag(IGNORED) // .build(); // contexts.get().current().addGroup(config, block); // } // // Path: src/main/java/j8spec/J8Spec.java // public static synchronized void xdescribe(String description, SafeBlock block) { // notAllowedWhenCIModeEnabled("xdescribe"); // isValidContext("xdescribe"); // ExampleGroupConfiguration config = new ExampleGroupConfiguration.Builder() // .description(description) // .executionFlag(IGNORED) // .build(); // contexts.get().current().addGroup(config, block); // } // // Path: src/main/java/j8spec/J8Spec.java // public static synchronized void xit(String description, UnsafeBlock block) { // xit(description, identity(), block); // }
import org.junit.Test; import static j8spec.J8Spec.read; import static j8spec.J8Spec.xcontext; import static j8spec.J8Spec.xdescribe; import static j8spec.J8Spec.xit;
package j8spec; public class J8SpecIgnoreTest { static class IgnoredExampleOverwrittenSpec {{ xit("some text", UnsafeBlock.NOOP); xit("some text", UnsafeBlock.NOOP); }} static class IgnoredExampleWithCollectorOverwrittenSpec {{ xit("some text", c -> c, UnsafeBlock.NOOP); xit("some text", UnsafeBlock.NOOP); }} @Test(expected = Exceptions.IllegalContext.class) public void does_not_allow_xdescribe_method_direct_invocation() {
// Path: src/main/java/j8spec/J8Spec.java // public static synchronized List<Example> read(Class<?> specClass) { // contexts.set(new ExampleGroupContext()); // try { // ExampleGroupDefinition exampleGroupDefinition = newExampleGroupDefinition(specClass, contexts.get()); // // exampleGroupDefinition.accept(new DuplicatedBlockValidator()); // // BlockExecutionStrategySelector strategySelector = new BlockExecutionStrategySelector(); // exampleGroupDefinition.accept(strategySelector); // // ExampleBuilder exampleBuilder = new ExampleBuilder(strategySelector.strategy()); // exampleGroupDefinition.accept(exampleBuilder); // // return exampleBuilder.build(); // } finally { // contexts.set(null); // } // } // // Path: src/main/java/j8spec/J8Spec.java // public static synchronized void xcontext(String description, SafeBlock block) { // notAllowedWhenCIModeEnabled("xcontext"); // isValidContext("xcontext"); // ExampleGroupConfiguration config = new ExampleGroupConfiguration.Builder() // .description(description) // .executionFlag(IGNORED) // .build(); // contexts.get().current().addGroup(config, block); // } // // Path: src/main/java/j8spec/J8Spec.java // public static synchronized void xdescribe(String description, SafeBlock block) { // notAllowedWhenCIModeEnabled("xdescribe"); // isValidContext("xdescribe"); // ExampleGroupConfiguration config = new ExampleGroupConfiguration.Builder() // .description(description) // .executionFlag(IGNORED) // .build(); // contexts.get().current().addGroup(config, block); // } // // Path: src/main/java/j8spec/J8Spec.java // public static synchronized void xit(String description, UnsafeBlock block) { // xit(description, identity(), block); // } // Path: src/test/java/j8spec/J8SpecIgnoreTest.java import org.junit.Test; import static j8spec.J8Spec.read; import static j8spec.J8Spec.xcontext; import static j8spec.J8Spec.xdescribe; import static j8spec.J8Spec.xit; package j8spec; public class J8SpecIgnoreTest { static class IgnoredExampleOverwrittenSpec {{ xit("some text", UnsafeBlock.NOOP); xit("some text", UnsafeBlock.NOOP); }} static class IgnoredExampleWithCollectorOverwrittenSpec {{ xit("some text", c -> c, UnsafeBlock.NOOP); xit("some text", UnsafeBlock.NOOP); }} @Test(expected = Exceptions.IllegalContext.class) public void does_not_allow_xdescribe_method_direct_invocation() {
xdescribe("some text", SafeBlock.NOOP);
j8spec/j8spec
src/test/java/j8spec/J8SpecIgnoreTest.java
// Path: src/main/java/j8spec/J8Spec.java // public static synchronized List<Example> read(Class<?> specClass) { // contexts.set(new ExampleGroupContext()); // try { // ExampleGroupDefinition exampleGroupDefinition = newExampleGroupDefinition(specClass, contexts.get()); // // exampleGroupDefinition.accept(new DuplicatedBlockValidator()); // // BlockExecutionStrategySelector strategySelector = new BlockExecutionStrategySelector(); // exampleGroupDefinition.accept(strategySelector); // // ExampleBuilder exampleBuilder = new ExampleBuilder(strategySelector.strategy()); // exampleGroupDefinition.accept(exampleBuilder); // // return exampleBuilder.build(); // } finally { // contexts.set(null); // } // } // // Path: src/main/java/j8spec/J8Spec.java // public static synchronized void xcontext(String description, SafeBlock block) { // notAllowedWhenCIModeEnabled("xcontext"); // isValidContext("xcontext"); // ExampleGroupConfiguration config = new ExampleGroupConfiguration.Builder() // .description(description) // .executionFlag(IGNORED) // .build(); // contexts.get().current().addGroup(config, block); // } // // Path: src/main/java/j8spec/J8Spec.java // public static synchronized void xdescribe(String description, SafeBlock block) { // notAllowedWhenCIModeEnabled("xdescribe"); // isValidContext("xdescribe"); // ExampleGroupConfiguration config = new ExampleGroupConfiguration.Builder() // .description(description) // .executionFlag(IGNORED) // .build(); // contexts.get().current().addGroup(config, block); // } // // Path: src/main/java/j8spec/J8Spec.java // public static synchronized void xit(String description, UnsafeBlock block) { // xit(description, identity(), block); // }
import org.junit.Test; import static j8spec.J8Spec.read; import static j8spec.J8Spec.xcontext; import static j8spec.J8Spec.xdescribe; import static j8spec.J8Spec.xit;
package j8spec; public class J8SpecIgnoreTest { static class IgnoredExampleOverwrittenSpec {{ xit("some text", UnsafeBlock.NOOP); xit("some text", UnsafeBlock.NOOP); }} static class IgnoredExampleWithCollectorOverwrittenSpec {{ xit("some text", c -> c, UnsafeBlock.NOOP); xit("some text", UnsafeBlock.NOOP); }} @Test(expected = Exceptions.IllegalContext.class) public void does_not_allow_xdescribe_method_direct_invocation() { xdescribe("some text", SafeBlock.NOOP); } @Test(expected = Exceptions.IllegalContext.class) public void does_not_allow_xcontext_method_direct_invocation() {
// Path: src/main/java/j8spec/J8Spec.java // public static synchronized List<Example> read(Class<?> specClass) { // contexts.set(new ExampleGroupContext()); // try { // ExampleGroupDefinition exampleGroupDefinition = newExampleGroupDefinition(specClass, contexts.get()); // // exampleGroupDefinition.accept(new DuplicatedBlockValidator()); // // BlockExecutionStrategySelector strategySelector = new BlockExecutionStrategySelector(); // exampleGroupDefinition.accept(strategySelector); // // ExampleBuilder exampleBuilder = new ExampleBuilder(strategySelector.strategy()); // exampleGroupDefinition.accept(exampleBuilder); // // return exampleBuilder.build(); // } finally { // contexts.set(null); // } // } // // Path: src/main/java/j8spec/J8Spec.java // public static synchronized void xcontext(String description, SafeBlock block) { // notAllowedWhenCIModeEnabled("xcontext"); // isValidContext("xcontext"); // ExampleGroupConfiguration config = new ExampleGroupConfiguration.Builder() // .description(description) // .executionFlag(IGNORED) // .build(); // contexts.get().current().addGroup(config, block); // } // // Path: src/main/java/j8spec/J8Spec.java // public static synchronized void xdescribe(String description, SafeBlock block) { // notAllowedWhenCIModeEnabled("xdescribe"); // isValidContext("xdescribe"); // ExampleGroupConfiguration config = new ExampleGroupConfiguration.Builder() // .description(description) // .executionFlag(IGNORED) // .build(); // contexts.get().current().addGroup(config, block); // } // // Path: src/main/java/j8spec/J8Spec.java // public static synchronized void xit(String description, UnsafeBlock block) { // xit(description, identity(), block); // } // Path: src/test/java/j8spec/J8SpecIgnoreTest.java import org.junit.Test; import static j8spec.J8Spec.read; import static j8spec.J8Spec.xcontext; import static j8spec.J8Spec.xdescribe; import static j8spec.J8Spec.xit; package j8spec; public class J8SpecIgnoreTest { static class IgnoredExampleOverwrittenSpec {{ xit("some text", UnsafeBlock.NOOP); xit("some text", UnsafeBlock.NOOP); }} static class IgnoredExampleWithCollectorOverwrittenSpec {{ xit("some text", c -> c, UnsafeBlock.NOOP); xit("some text", UnsafeBlock.NOOP); }} @Test(expected = Exceptions.IllegalContext.class) public void does_not_allow_xdescribe_method_direct_invocation() { xdescribe("some text", SafeBlock.NOOP); } @Test(expected = Exceptions.IllegalContext.class) public void does_not_allow_xcontext_method_direct_invocation() {
xcontext("some text", SafeBlock.NOOP);
j8spec/j8spec
src/test/java/j8spec/J8SpecIgnoreTest.java
// Path: src/main/java/j8spec/J8Spec.java // public static synchronized List<Example> read(Class<?> specClass) { // contexts.set(new ExampleGroupContext()); // try { // ExampleGroupDefinition exampleGroupDefinition = newExampleGroupDefinition(specClass, contexts.get()); // // exampleGroupDefinition.accept(new DuplicatedBlockValidator()); // // BlockExecutionStrategySelector strategySelector = new BlockExecutionStrategySelector(); // exampleGroupDefinition.accept(strategySelector); // // ExampleBuilder exampleBuilder = new ExampleBuilder(strategySelector.strategy()); // exampleGroupDefinition.accept(exampleBuilder); // // return exampleBuilder.build(); // } finally { // contexts.set(null); // } // } // // Path: src/main/java/j8spec/J8Spec.java // public static synchronized void xcontext(String description, SafeBlock block) { // notAllowedWhenCIModeEnabled("xcontext"); // isValidContext("xcontext"); // ExampleGroupConfiguration config = new ExampleGroupConfiguration.Builder() // .description(description) // .executionFlag(IGNORED) // .build(); // contexts.get().current().addGroup(config, block); // } // // Path: src/main/java/j8spec/J8Spec.java // public static synchronized void xdescribe(String description, SafeBlock block) { // notAllowedWhenCIModeEnabled("xdescribe"); // isValidContext("xdescribe"); // ExampleGroupConfiguration config = new ExampleGroupConfiguration.Builder() // .description(description) // .executionFlag(IGNORED) // .build(); // contexts.get().current().addGroup(config, block); // } // // Path: src/main/java/j8spec/J8Spec.java // public static synchronized void xit(String description, UnsafeBlock block) { // xit(description, identity(), block); // }
import org.junit.Test; import static j8spec.J8Spec.read; import static j8spec.J8Spec.xcontext; import static j8spec.J8Spec.xdescribe; import static j8spec.J8Spec.xit;
package j8spec; public class J8SpecIgnoreTest { static class IgnoredExampleOverwrittenSpec {{ xit("some text", UnsafeBlock.NOOP); xit("some text", UnsafeBlock.NOOP); }} static class IgnoredExampleWithCollectorOverwrittenSpec {{ xit("some text", c -> c, UnsafeBlock.NOOP); xit("some text", UnsafeBlock.NOOP); }} @Test(expected = Exceptions.IllegalContext.class) public void does_not_allow_xdescribe_method_direct_invocation() { xdescribe("some text", SafeBlock.NOOP); } @Test(expected = Exceptions.IllegalContext.class) public void does_not_allow_xcontext_method_direct_invocation() { xcontext("some text", SafeBlock.NOOP); } @Test(expected = Exceptions.IllegalContext.class) public void does_not_allow_xit_method_direct_invocation() { xit("some text", UnsafeBlock.NOOP); } @Test(expected = Exceptions.IllegalContext.class) public void does_not_allow_xit_method_direct_invocation_with_collector() { xit("some text", c -> c, UnsafeBlock.NOOP); } @Test(expected = Exceptions.BlockAlreadyDefined.class) public void does_not_allow_ignored_example_to_be_replaced() {
// Path: src/main/java/j8spec/J8Spec.java // public static synchronized List<Example> read(Class<?> specClass) { // contexts.set(new ExampleGroupContext()); // try { // ExampleGroupDefinition exampleGroupDefinition = newExampleGroupDefinition(specClass, contexts.get()); // // exampleGroupDefinition.accept(new DuplicatedBlockValidator()); // // BlockExecutionStrategySelector strategySelector = new BlockExecutionStrategySelector(); // exampleGroupDefinition.accept(strategySelector); // // ExampleBuilder exampleBuilder = new ExampleBuilder(strategySelector.strategy()); // exampleGroupDefinition.accept(exampleBuilder); // // return exampleBuilder.build(); // } finally { // contexts.set(null); // } // } // // Path: src/main/java/j8spec/J8Spec.java // public static synchronized void xcontext(String description, SafeBlock block) { // notAllowedWhenCIModeEnabled("xcontext"); // isValidContext("xcontext"); // ExampleGroupConfiguration config = new ExampleGroupConfiguration.Builder() // .description(description) // .executionFlag(IGNORED) // .build(); // contexts.get().current().addGroup(config, block); // } // // Path: src/main/java/j8spec/J8Spec.java // public static synchronized void xdescribe(String description, SafeBlock block) { // notAllowedWhenCIModeEnabled("xdescribe"); // isValidContext("xdescribe"); // ExampleGroupConfiguration config = new ExampleGroupConfiguration.Builder() // .description(description) // .executionFlag(IGNORED) // .build(); // contexts.get().current().addGroup(config, block); // } // // Path: src/main/java/j8spec/J8Spec.java // public static synchronized void xit(String description, UnsafeBlock block) { // xit(description, identity(), block); // } // Path: src/test/java/j8spec/J8SpecIgnoreTest.java import org.junit.Test; import static j8spec.J8Spec.read; import static j8spec.J8Spec.xcontext; import static j8spec.J8Spec.xdescribe; import static j8spec.J8Spec.xit; package j8spec; public class J8SpecIgnoreTest { static class IgnoredExampleOverwrittenSpec {{ xit("some text", UnsafeBlock.NOOP); xit("some text", UnsafeBlock.NOOP); }} static class IgnoredExampleWithCollectorOverwrittenSpec {{ xit("some text", c -> c, UnsafeBlock.NOOP); xit("some text", UnsafeBlock.NOOP); }} @Test(expected = Exceptions.IllegalContext.class) public void does_not_allow_xdescribe_method_direct_invocation() { xdescribe("some text", SafeBlock.NOOP); } @Test(expected = Exceptions.IllegalContext.class) public void does_not_allow_xcontext_method_direct_invocation() { xcontext("some text", SafeBlock.NOOP); } @Test(expected = Exceptions.IllegalContext.class) public void does_not_allow_xit_method_direct_invocation() { xit("some text", UnsafeBlock.NOOP); } @Test(expected = Exceptions.IllegalContext.class) public void does_not_allow_xit_method_direct_invocation_with_collector() { xit("some text", c -> c, UnsafeBlock.NOOP); } @Test(expected = Exceptions.BlockAlreadyDefined.class) public void does_not_allow_ignored_example_to_be_replaced() {
read(IgnoredExampleOverwrittenSpec.class);
j8spec/j8spec
src/test/java/j8spec/ExampleBuilderTest.java
// Path: src/main/java/j8spec/J8Spec.java // public static <T> Var<T> var() { // return new Var<>(); // }
import org.junit.Test; import java.util.LinkedList; import java.util.List; import static j8spec.BlockExecutionFlag.FOCUSED; import static j8spec.BlockExecutionFlag.IGNORED; import static j8spec.BlockExecutionStrategy.BLACK_LIST; import static j8spec.BlockExecutionStrategy.WHITE_LIST; import static j8spec.UnsafeBlock.NOOP; import static j8spec.J8Spec.var; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify;
.startGroup(groupConfig().description("describe A").executionFlag(FOCUSED).build()) .example(exampleConfig().description("block A1").build(), executed) .example(exampleConfig().description("block A2").build(), executed) .startGroup(groupConfig().description("describe A A").build()) .example(exampleConfig().description("block A A 1").build(), executed) .example(exampleConfig().description("block A A 2").build(), executed) .endGroup() .endGroup() .endGroup() ); verify(executed, times(4)).tryToExecute(); verify(ignored, never()).tryToExecute(); } @Test public void builds_examples_with_excepted_exception() { ExampleBuilder builder = new ExampleBuilder(BLACK_LIST); builder .startGroup(groupConfig().description("SampleSpec").definedOrder().build()) .example(exampleConfig().description("block 1").expected(Exception.class).build(), NOOP) .endGroup(); List<Example> examples = builder.build(); assertThat(examples.get(0).expected(), is(equalTo(Exception.class))); } @Test public void initializes_variables_before_hooks() throws Throwable { final List<Object> values = new LinkedList<>();
// Path: src/main/java/j8spec/J8Spec.java // public static <T> Var<T> var() { // return new Var<>(); // } // Path: src/test/java/j8spec/ExampleBuilderTest.java import org.junit.Test; import java.util.LinkedList; import java.util.List; import static j8spec.BlockExecutionFlag.FOCUSED; import static j8spec.BlockExecutionFlag.IGNORED; import static j8spec.BlockExecutionStrategy.BLACK_LIST; import static j8spec.BlockExecutionStrategy.WHITE_LIST; import static j8spec.UnsafeBlock.NOOP; import static j8spec.J8Spec.var; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; .startGroup(groupConfig().description("describe A").executionFlag(FOCUSED).build()) .example(exampleConfig().description("block A1").build(), executed) .example(exampleConfig().description("block A2").build(), executed) .startGroup(groupConfig().description("describe A A").build()) .example(exampleConfig().description("block A A 1").build(), executed) .example(exampleConfig().description("block A A 2").build(), executed) .endGroup() .endGroup() .endGroup() ); verify(executed, times(4)).tryToExecute(); verify(ignored, never()).tryToExecute(); } @Test public void builds_examples_with_excepted_exception() { ExampleBuilder builder = new ExampleBuilder(BLACK_LIST); builder .startGroup(groupConfig().description("SampleSpec").definedOrder().build()) .example(exampleConfig().description("block 1").expected(Exception.class).build(), NOOP) .endGroup(); List<Example> examples = builder.build(); assertThat(examples.get(0).expected(), is(equalTo(Exception.class))); } @Test public void initializes_variables_before_hooks() throws Throwable { final List<Object> values = new LinkedList<>();
final Var<String> v1 = var();
j8spec/j8spec
src/test/java/j8spec/DuplicatedBlockValidatorTest.java
// Path: src/main/java/j8spec/J8Spec.java // public static <T> Var<T> var() { // return new Var<>(); // }
import org.junit.Test; import static j8spec.UnsafeBlock.NOOP; import static j8spec.J8Spec.var;
} @Test(expected = Exceptions.BlockAlreadyDefined.class) public void indicates_if_a_example_group_has_been_defined_with_the_same_description() { validator .startGroup(groupConfig().description("spec").build()) .startGroup(groupConfig().description("group 1").build()) .example(exampleConfig().description("example 1").build(), NOOP) .endGroup() .startGroup(groupConfig().description("group 1").build()) .example(exampleConfig().description("example 1").build(), NOOP) .endGroup() .endGroup(); } @Test() public void accepts_examples_with_same_description_in_different_groups() { validator .startGroup(groupConfig().description("spec").build()) .startGroup(groupConfig().description("group 1").build()) .example(exampleConfig().description("example 1").build(), NOOP) .endGroup() .startGroup(groupConfig().description("group 2").build()) .example(exampleConfig().description("example 1").build(), NOOP) .endGroup() .endGroup(); } @Test(expected = Exceptions.VariableInitializerAlreadyDefined.class) public void indicates_if_an_initializer_has_been_defined_for_the_same_variable() {
// Path: src/main/java/j8spec/J8Spec.java // public static <T> Var<T> var() { // return new Var<>(); // } // Path: src/test/java/j8spec/DuplicatedBlockValidatorTest.java import org.junit.Test; import static j8spec.UnsafeBlock.NOOP; import static j8spec.J8Spec.var; } @Test(expected = Exceptions.BlockAlreadyDefined.class) public void indicates_if_a_example_group_has_been_defined_with_the_same_description() { validator .startGroup(groupConfig().description("spec").build()) .startGroup(groupConfig().description("group 1").build()) .example(exampleConfig().description("example 1").build(), NOOP) .endGroup() .startGroup(groupConfig().description("group 1").build()) .example(exampleConfig().description("example 1").build(), NOOP) .endGroup() .endGroup(); } @Test() public void accepts_examples_with_same_description_in_different_groups() { validator .startGroup(groupConfig().description("spec").build()) .startGroup(groupConfig().description("group 1").build()) .example(exampleConfig().description("example 1").build(), NOOP) .endGroup() .startGroup(groupConfig().description("group 2").build()) .example(exampleConfig().description("example 1").build(), NOOP) .endGroup() .endGroup(); } @Test(expected = Exceptions.VariableInitializerAlreadyDefined.class) public void indicates_if_an_initializer_has_been_defined_for_the_same_variable() {
Var<String> v1 = var();
wssccc/ngscript
ngscript-core/src/main/java/org/ngscript/runtime/vo/MethodTypeMap.java
// Path: ngscript-core/src/main/java/org/ngscript/runtime/utils/TypeCheck.java // public class TypeCheck { // // static final HashMap<Class, HashSet<Class>> typeHierarchy = new HashMap<Class, HashSet<Class>>(); // // static { // HashSet<Class> intSet // = new HashSet<Class>(Arrays.asList(Integer.class, Object.class, int.class, float.class, double.class)); // typeHierarchy.put(Integer.class, intSet); // typeHierarchy.put(int.class, intSet); // // HashSet<Class> doubleSet = new HashSet<Class>(Arrays.asList(Double.class, Object.class, double.class)); // // typeHierarchy.put(Double.class, doubleSet); // typeHierarchy.put(double.class, doubleSet); // } // // public static HashSet<Class> getSuperClasses(Class cls) { // if (typeHierarchy.containsKey(cls)) { // return typeHierarchy.get(cls); // } else { // //collect super classes // HashSet<Class> classes = new HashSet<Class>(); // Class cursor = cls; // classes.add(cls); // while (true) { // cursor = cursor.getSuperclass(); // if (cursor != null) { // classes.add(cursor); // } else { // break; // } // } // typeHierarchy.put(cls, classes); // return classes; // } // } // // public static boolean typeAcceptable(Class[] in, Class[] def) { // if (def.length > 0 && def[def.length - 1].isArray()) { // //multi // if (_typeAcceptable(in, def, def.length - 1)) { // Class defLastType = def[def.length - 1].getComponentType(); // //check def.length-1 to in.length-1 // for (int i = def.length - 1; i < in.length; i++) { // if (!_typeCheck(in[i], defLastType)) { // return false; // } // } // return true; // } else { // return false; // } // } else { // if (in.length != def.length) { // return false; // } // return _typeAcceptable(in, def, def.length); // } // } // // static boolean _typeAcceptable(Class[] in, Class[] def, int n) { // for (int i = 0; i < n; i++) { // if (!_typeCheck(in[i], def[i])) { // return false; // } // } // return true; // } // // static boolean _typeCheck(Class in, Class def) { // //null is acceptable for any Object type // return (in == null || getSuperClasses(in).contains(def)); // } // }
import org.ngscript.runtime.utils.TypeCheck; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.HashMap; import java.util.List; import java.util.Map;
/* * Copyright 2021 wssccc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.ngscript.runtime.vo; public class MethodTypeMap { Map<String, Method> map = new HashMap<>(); public static MethodTypeMap INSTANCE = new MethodTypeMap(); private MethodTypeMap() { } public Method getProperMethod(String methodName, List<Method> methods, Class[] types) { if (methods.size() == 1) { return methods.get(0); } else { int typeHash = typeHash(types); String key = methodName + "#" + typeHash; if (map.containsKey(key)) { return map.get(key); } else { for (Method m : methods) { if (Modifier.isPublic(m.getDeclaringClass().getModifiers()) && Modifier.isPublic(m.getModifiers())) {
// Path: ngscript-core/src/main/java/org/ngscript/runtime/utils/TypeCheck.java // public class TypeCheck { // // static final HashMap<Class, HashSet<Class>> typeHierarchy = new HashMap<Class, HashSet<Class>>(); // // static { // HashSet<Class> intSet // = new HashSet<Class>(Arrays.asList(Integer.class, Object.class, int.class, float.class, double.class)); // typeHierarchy.put(Integer.class, intSet); // typeHierarchy.put(int.class, intSet); // // HashSet<Class> doubleSet = new HashSet<Class>(Arrays.asList(Double.class, Object.class, double.class)); // // typeHierarchy.put(Double.class, doubleSet); // typeHierarchy.put(double.class, doubleSet); // } // // public static HashSet<Class> getSuperClasses(Class cls) { // if (typeHierarchy.containsKey(cls)) { // return typeHierarchy.get(cls); // } else { // //collect super classes // HashSet<Class> classes = new HashSet<Class>(); // Class cursor = cls; // classes.add(cls); // while (true) { // cursor = cursor.getSuperclass(); // if (cursor != null) { // classes.add(cursor); // } else { // break; // } // } // typeHierarchy.put(cls, classes); // return classes; // } // } // // public static boolean typeAcceptable(Class[] in, Class[] def) { // if (def.length > 0 && def[def.length - 1].isArray()) { // //multi // if (_typeAcceptable(in, def, def.length - 1)) { // Class defLastType = def[def.length - 1].getComponentType(); // //check def.length-1 to in.length-1 // for (int i = def.length - 1; i < in.length; i++) { // if (!_typeCheck(in[i], defLastType)) { // return false; // } // } // return true; // } else { // return false; // } // } else { // if (in.length != def.length) { // return false; // } // return _typeAcceptable(in, def, def.length); // } // } // // static boolean _typeAcceptable(Class[] in, Class[] def, int n) { // for (int i = 0; i < n; i++) { // if (!_typeCheck(in[i], def[i])) { // return false; // } // } // return true; // } // // static boolean _typeCheck(Class in, Class def) { // //null is acceptable for any Object type // return (in == null || getSuperClasses(in).contains(def)); // } // } // Path: ngscript-core/src/main/java/org/ngscript/runtime/vo/MethodTypeMap.java import org.ngscript.runtime.utils.TypeCheck; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.HashMap; import java.util.List; import java.util.Map; /* * Copyright 2021 wssccc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.ngscript.runtime.vo; public class MethodTypeMap { Map<String, Method> map = new HashMap<>(); public static MethodTypeMap INSTANCE = new MethodTypeMap(); private MethodTypeMap() { } public Method getProperMethod(String methodName, List<Method> methods, Class[] types) { if (methods.size() == 1) { return methods.get(0); } else { int typeHash = typeHash(types); String key = methodName + "#" + typeHash; if (map.containsKey(key)) { return map.get(key); } else { for (Method m : methods) { if (Modifier.isPublic(m.getDeclaringClass().getModifiers()) && Modifier.isPublic(m.getModifiers())) {
if (TypeCheck.typeAcceptable(types, m.getParameterTypes())) {
wssccc/ngscript
ngscript-core/src/main/java/org/ngscript/parser/lexer/Lexer.java
// Path: ngscript-parseroid/src/main/java/org/ngscript/parseroid/parser/Token.java // public class Token { // // public String type; // public String value; // public int line; // // public boolean isValidPos() { // return line != -1; // } // // public Token(String type) { // this.type = type; // this.line = -1; // } // // public Token(String type, int line) { // this.type = type; // this.line = line; // } // // public Token(String type, int line, String value) { // this.type = type; // this.line = line; // this.value = value; // } // // @Override // public String toString() { // return "[" + type + (value == null ? "" : "," + value) + "]" + (line >= 0 ? (" line:" + line) : ("")); // } // // }
import org.ngscript.parseroid.parser.Token; import java.util.*;
/* * Copyright 2021 wssccc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.ngscript.parser.lexer; /** * @author wssccc */ public class Lexer { private static final Set<String> KEYWORDS = Collections.unmodifiableSet(new HashSet<>(Arrays.asList( "var", "true", "false", "null", "undefined", "import", "function", "new", "if", "return", "break", "continue", "while", "switch", "case", "default", "typeof", "try", "catch", "finally", "go", "throw", "for", "else", "val"))); SourceReader reader;
// Path: ngscript-parseroid/src/main/java/org/ngscript/parseroid/parser/Token.java // public class Token { // // public String type; // public String value; // public int line; // // public boolean isValidPos() { // return line != -1; // } // // public Token(String type) { // this.type = type; // this.line = -1; // } // // public Token(String type, int line) { // this.type = type; // this.line = line; // } // // public Token(String type, int line, String value) { // this.type = type; // this.line = line; // this.value = value; // } // // @Override // public String toString() { // return "[" + type + (value == null ? "" : "," + value) + "]" + (line >= 0 ? (" line:" + line) : ("")); // } // // } // Path: ngscript-core/src/main/java/org/ngscript/parser/lexer/Lexer.java import org.ngscript.parseroid.parser.Token; import java.util.*; /* * Copyright 2021 wssccc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.ngscript.parser.lexer; /** * @author wssccc */ public class Lexer { private static final Set<String> KEYWORDS = Collections.unmodifiableSet(new HashSet<>(Arrays.asList( "var", "true", "false", "null", "undefined", "import", "function", "new", "if", "return", "break", "continue", "while", "switch", "case", "default", "typeof", "try", "catch", "finally", "go", "throw", "for", "else", "val"))); SourceReader reader;
public static List<Token> scan(String string) throws LexerException {
wssccc/ngscript
ngscript-core/src/main/java/org/ngscript/compiler/Assembler.java
// Path: ngscript-parseroid/src/main/java/org/ngscript/parseroid/parser/AstNode.java // public class AstNode { // // public Token token; // public List<AstNode> contents; // // public AstNode(Token token) { // this.token = token; // this.contents = new ArrayList<>(); // } // // public AstNode(Token token, ArrayList<AstNode> children) { // this.token = token; // this.contents = children; // } // // public AstNode getNode(String type) { // for (AstNode content : contents) { // if (content.token.type.equals(type)) { // return content; // } // } // return null; // } // // @Override // public String toString() { // return toString(0, "", " "); // } // // String toString(int nest, String margin, String subMargin) { // StringBuilder builder = new StringBuilder(margin); // builder.append("|-"); // builder.append(token.toString()); // builder.append("\n"); // for (int i = 0; i < contents.size(); i++) { // if (i != contents.size() - 1) { // builder.append(contents.get(i).toString(nest + 1, subMargin, subMargin + "| ")); // } else { // builder.append(contents.get(i).toString(nest + 1, subMargin, subMargin + " ")); // } // } // return builder.toString(); // } // // }
import org.ngscript.parseroid.parser.AstNode; import java.util.*;
/* * Copyright 2021 wssccc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.ngscript.compiler; /** * @author wssccc */ public class Assembler { List<Instruction> instructions = new ArrayList<>(); Map<String, Integer> labels = new HashMap<>(); public void doOptimize() { this.instructions = optimize(instructions); } public List<Instruction> optimize(List<Instruction> ins2) { ins2.add(new Instruction("", "", "")); List<Instruction> ins = new ArrayList<>(); for (int i = 0; i < ins2.size() - 1; i++) { Instruction instruction = ins2.get(i); Instruction next = ins2.get(i + 1); if ("push_eax".equals(next.op)) { instruction.op += "_pe"; ++i; } ins.add(instruction); } return ins; }
// Path: ngscript-parseroid/src/main/java/org/ngscript/parseroid/parser/AstNode.java // public class AstNode { // // public Token token; // public List<AstNode> contents; // // public AstNode(Token token) { // this.token = token; // this.contents = new ArrayList<>(); // } // // public AstNode(Token token, ArrayList<AstNode> children) { // this.token = token; // this.contents = children; // } // // public AstNode getNode(String type) { // for (AstNode content : contents) { // if (content.token.type.equals(type)) { // return content; // } // } // return null; // } // // @Override // public String toString() { // return toString(0, "", " "); // } // // String toString(int nest, String margin, String subMargin) { // StringBuilder builder = new StringBuilder(margin); // builder.append("|-"); // builder.append(token.toString()); // builder.append("\n"); // for (int i = 0; i < contents.size(); i++) { // if (i != contents.size() - 1) { // builder.append(contents.get(i).toString(nest + 1, subMargin, subMargin + "| ")); // } else { // builder.append(contents.get(i).toString(nest + 1, subMargin, subMargin + " ")); // } // } // return builder.toString(); // } // // } // Path: ngscript-core/src/main/java/org/ngscript/compiler/Assembler.java import org.ngscript.parseroid.parser.AstNode; import java.util.*; /* * Copyright 2021 wssccc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.ngscript.compiler; /** * @author wssccc */ public class Assembler { List<Instruction> instructions = new ArrayList<>(); Map<String, Integer> labels = new HashMap<>(); public void doOptimize() { this.instructions = optimize(instructions); } public List<Instruction> optimize(List<Instruction> ins2) { ins2.add(new Instruction("", "", "")); List<Instruction> ins = new ArrayList<>(); for (int i = 0; i < ins2.size() - 1; i++) { Instruction instruction = ins2.get(i); Instruction next = ins2.get(i + 1); if ("push_eax".equals(next.op)) { instruction.op += "_pe"; ++i; } ins.add(instruction); } return ins; }
public String label(String name, AstNode ast) {
wssccc/ngscript
ngscript-examples/src/main/java/org/ngscript/examples/RoseRender.java
// Path: ngscript-core/src/main/java/org/ngscript/Ngscript.java // @Slf4j // public class Ngscript { // // Configuration configuration; // NgLalrParser parser; // Compiler compiler; // VirtualMachine vm = new VirtualMachine(new PrintWriter(System.out), new PrintWriter(System.err)); // // public Ngscript() { // this(Configuration.DEFAULT); // } // // public Ngscript(Configuration configuration) { // this.configuration = configuration; // this.compiler = new Compiler(configuration); // this.parser = new NgLalrParser(configuration); // } // // public Object eval(String code) throws ParserException, CompilerException { // feed(code); // return vm.eax; // } // // public boolean feed(String code) throws CompilerException, LexerException, ParserException { // List<Token> tokens = Lexer.scan(code); // if (!configuration.isInteractive()) { // tokens.add(new Token(Symbol.EOF.identifier)); // } // Token[] ts = tokens.toArray(new Token[0]); // boolean compiled = parser.feed(ts); // if (compiled) { // AstNode ast = parser.getResult(); // parser.reduce(ast); // NgLalrParser.removeNULL(ast); // if (configuration.isGenerateDebugInfo()) { // log.info(ast.toString()); // } // // // List<Instruction> ins = compiler.compileCode(ast, code); // if (configuration.isGenerateDebugInfo()) { // log.info(ins.toString()); // } // vm.loadInstructions(ins); // vm.run(); // } // return compiled; // } // }
import org.apache.commons.io.IOUtils; import org.ngscript.Ngscript; import java.nio.charset.StandardCharsets;
/* * Copyright 2021 wssccc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.ngscript.examples; /** * @author wssccc */ public class RoseRender { public static void main(String[] args) throws Exception { long time = System.currentTimeMillis();
// Path: ngscript-core/src/main/java/org/ngscript/Ngscript.java // @Slf4j // public class Ngscript { // // Configuration configuration; // NgLalrParser parser; // Compiler compiler; // VirtualMachine vm = new VirtualMachine(new PrintWriter(System.out), new PrintWriter(System.err)); // // public Ngscript() { // this(Configuration.DEFAULT); // } // // public Ngscript(Configuration configuration) { // this.configuration = configuration; // this.compiler = new Compiler(configuration); // this.parser = new NgLalrParser(configuration); // } // // public Object eval(String code) throws ParserException, CompilerException { // feed(code); // return vm.eax; // } // // public boolean feed(String code) throws CompilerException, LexerException, ParserException { // List<Token> tokens = Lexer.scan(code); // if (!configuration.isInteractive()) { // tokens.add(new Token(Symbol.EOF.identifier)); // } // Token[] ts = tokens.toArray(new Token[0]); // boolean compiled = parser.feed(ts); // if (compiled) { // AstNode ast = parser.getResult(); // parser.reduce(ast); // NgLalrParser.removeNULL(ast); // if (configuration.isGenerateDebugInfo()) { // log.info(ast.toString()); // } // // // List<Instruction> ins = compiler.compileCode(ast, code); // if (configuration.isGenerateDebugInfo()) { // log.info(ins.toString()); // } // vm.loadInstructions(ins); // vm.run(); // } // return compiled; // } // } // Path: ngscript-examples/src/main/java/org/ngscript/examples/RoseRender.java import org.apache.commons.io.IOUtils; import org.ngscript.Ngscript; import java.nio.charset.StandardCharsets; /* * Copyright 2021 wssccc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.ngscript.examples; /** * @author wssccc */ public class RoseRender { public static void main(String[] args) throws Exception { long time = System.currentTimeMillis();
new Ngscript().eval(IOUtils.toString(Thread.currentThread().getContextClassLoader().getResourceAsStream("RoseRender.ngs"), StandardCharsets.UTF_8));
wssccc/ngscript
ngscript-core/src/main/java/org/ngscript/runtime/Environment.java
// Path: ngscript-core/src/main/java/org/ngscript/runtime/vo/JavaMemRef.java // @Slf4j // public class JavaMemRef extends VmMemRef { // // private Object obj; // private Field field; // // public JavaMemRef(Object obj, Field field) { // this.obj = obj; // this.field = field; // } // // @Override // public Object read() { // try { // return field.get(obj); // } catch (IllegalArgumentException | IllegalAccessException ex) { // log.error("error read " + field.getName() + " of " + obj.getClass().getName(), ex); // } // return null; // } // // @Override // public void write(Object v) { // try { // field.set(obj, v); // } catch (IllegalArgumentException | IllegalAccessException ex) { // log.error("error write " + field.getName() + " of " + obj.getClass().getName(), ex); // } // } // // } // // Path: ngscript-core/src/main/java/org/ngscript/runtime/vo/JavaMethod.java // public class JavaMethod implements VmMethod { // // public Object caller; // public ArrayList<Method> methods; // String methodName; // // public JavaMethod(Object caller, ArrayList<Method> methods) { // this.caller = caller; // this.methods = methods; // init(); // } // // public JavaMethod(Object caller, Method method) { // this.caller = caller; // this.methods = new ArrayList<>(); // this.methods.add(method); // init(); // } // // void init() { // Method m1 = methods.get(0); // methodName = m1.getDeclaringClass().getName() + "#" + m1.getName(); // } // // @Override // public void invoke(VirtualMachine vm, Object[] args) throws Exception { // Class[] types = vm.getParamTypes(2); // Method properMethod = MethodTypeMap.INSTANCE.getProperMethod(methodName, methods, types); // if (properMethod == null) { // throw new VmRuntimeException(vm, "no proper method found for " + methods + "[" + Arrays.toString(types) + "]"); // } // if (properMethod.isVarArgs()) { // args = VarArgHelper.packVarArgs(args); // } // try { // Object val = properMethod.invoke(caller, args); // if (val instanceof Long) { // val = ((Long) val).intValue(); // } // vm.eax.write(val); // } catch (Exception ex) { // vm.exception.write(new VmRuntimeException(vm, ex.getCause() == null ? ex.toString() : ex.getCause().toString())); // Op.restore_machine_state(vm, null, null); // } // } // } // // Path: ngscript-core/src/main/java/org/ngscript/runtime/vo/VmMemRef.java // public class VmMemRef { // // private Object value; // @Getter // private final boolean immutable; // // public VmMemRef() { // this(null, false); // } // // public VmMemRef(Object obj_v) { // this(obj_v, false); // } // // public VmMemRef(Object value, boolean immutable) { // this.value = value; // this.immutable = immutable; // } // // public void write(Object v) { // if (immutable && value != null) { // throw new RuntimeException("immutable"); // } // this.value = v; // } // // public Object read() { // return this.value; // } // // @Override // public String toString() { // return "VmMemRef{" + "value=" + value + '}'; // } // // } // // Path: ngscript-core/src/main/java/org/ngscript/runtime/vo/undefined.java // public class undefined { // // private undefined() { // } // // @Override // public String toString() { // return "undefined"; // } // // public static final undefined value = new undefined(); // }
import org.ngscript.runtime.vo.JavaMemRef; import org.ngscript.runtime.vo.JavaMethod; import org.ngscript.runtime.vo.VmMemRef; import org.ngscript.runtime.vo.undefined; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.HashMap; import java.util.Map;
/* * Copyright 2021 wssccc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.ngscript.runtime; /** * @author wssccc */ public class Environment { Map<String, VmMemRef> data = new HashMap<>(); Environment parent; public Environment(Environment parent) { this.parent = parent; } public VmMemRef lookup(String member, VirtualMachine vm, boolean isMember) throws VmRuntimeException { //registers switch (member) { case "this": return vm.env; case "%eax": return vm.eax; case "%env": return vm.env; case "%exception": return vm.exception; default: VmMemRef ref = data.get(member); if (ref != null) { return ref; } else { ref = lookupHash(member, vm, isMember); data.put(member, ref); return ref; } } } private VmMemRef lookupHash(String member, VirtualMachine vm, boolean isMember) throws VmRuntimeException { if (isMember) { //throw new Runtime-Exception("no member " + varName + " found.");
// Path: ngscript-core/src/main/java/org/ngscript/runtime/vo/JavaMemRef.java // @Slf4j // public class JavaMemRef extends VmMemRef { // // private Object obj; // private Field field; // // public JavaMemRef(Object obj, Field field) { // this.obj = obj; // this.field = field; // } // // @Override // public Object read() { // try { // return field.get(obj); // } catch (IllegalArgumentException | IllegalAccessException ex) { // log.error("error read " + field.getName() + " of " + obj.getClass().getName(), ex); // } // return null; // } // // @Override // public void write(Object v) { // try { // field.set(obj, v); // } catch (IllegalArgumentException | IllegalAccessException ex) { // log.error("error write " + field.getName() + " of " + obj.getClass().getName(), ex); // } // } // // } // // Path: ngscript-core/src/main/java/org/ngscript/runtime/vo/JavaMethod.java // public class JavaMethod implements VmMethod { // // public Object caller; // public ArrayList<Method> methods; // String methodName; // // public JavaMethod(Object caller, ArrayList<Method> methods) { // this.caller = caller; // this.methods = methods; // init(); // } // // public JavaMethod(Object caller, Method method) { // this.caller = caller; // this.methods = new ArrayList<>(); // this.methods.add(method); // init(); // } // // void init() { // Method m1 = methods.get(0); // methodName = m1.getDeclaringClass().getName() + "#" + m1.getName(); // } // // @Override // public void invoke(VirtualMachine vm, Object[] args) throws Exception { // Class[] types = vm.getParamTypes(2); // Method properMethod = MethodTypeMap.INSTANCE.getProperMethod(methodName, methods, types); // if (properMethod == null) { // throw new VmRuntimeException(vm, "no proper method found for " + methods + "[" + Arrays.toString(types) + "]"); // } // if (properMethod.isVarArgs()) { // args = VarArgHelper.packVarArgs(args); // } // try { // Object val = properMethod.invoke(caller, args); // if (val instanceof Long) { // val = ((Long) val).intValue(); // } // vm.eax.write(val); // } catch (Exception ex) { // vm.exception.write(new VmRuntimeException(vm, ex.getCause() == null ? ex.toString() : ex.getCause().toString())); // Op.restore_machine_state(vm, null, null); // } // } // } // // Path: ngscript-core/src/main/java/org/ngscript/runtime/vo/VmMemRef.java // public class VmMemRef { // // private Object value; // @Getter // private final boolean immutable; // // public VmMemRef() { // this(null, false); // } // // public VmMemRef(Object obj_v) { // this(obj_v, false); // } // // public VmMemRef(Object value, boolean immutable) { // this.value = value; // this.immutable = immutable; // } // // public void write(Object v) { // if (immutable && value != null) { // throw new RuntimeException("immutable"); // } // this.value = v; // } // // public Object read() { // return this.value; // } // // @Override // public String toString() { // return "VmMemRef{" + "value=" + value + '}'; // } // // } // // Path: ngscript-core/src/main/java/org/ngscript/runtime/vo/undefined.java // public class undefined { // // private undefined() { // } // // @Override // public String toString() { // return "undefined"; // } // // public static final undefined value = new undefined(); // } // Path: ngscript-core/src/main/java/org/ngscript/runtime/Environment.java import org.ngscript.runtime.vo.JavaMemRef; import org.ngscript.runtime.vo.JavaMethod; import org.ngscript.runtime.vo.VmMemRef; import org.ngscript.runtime.vo.undefined; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; /* * Copyright 2021 wssccc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.ngscript.runtime; /** * @author wssccc */ public class Environment { Map<String, VmMemRef> data = new HashMap<>(); Environment parent; public Environment(Environment parent) { this.parent = parent; } public VmMemRef lookup(String member, VirtualMachine vm, boolean isMember) throws VmRuntimeException { //registers switch (member) { case "this": return vm.env; case "%eax": return vm.eax; case "%env": return vm.env; case "%exception": return vm.exception; default: VmMemRef ref = data.get(member); if (ref != null) { return ref; } else { ref = lookupHash(member, vm, isMember); data.put(member, ref); return ref; } } } private VmMemRef lookupHash(String member, VirtualMachine vm, boolean isMember) throws VmRuntimeException { if (isMember) { //throw new Runtime-Exception("no member " + varName + " found.");
VmMemRef mem = new VmMemRef(undefined.value);
wssccc/ngscript
ngscript-core/src/main/java/org/ngscript/runtime/Environment.java
// Path: ngscript-core/src/main/java/org/ngscript/runtime/vo/JavaMemRef.java // @Slf4j // public class JavaMemRef extends VmMemRef { // // private Object obj; // private Field field; // // public JavaMemRef(Object obj, Field field) { // this.obj = obj; // this.field = field; // } // // @Override // public Object read() { // try { // return field.get(obj); // } catch (IllegalArgumentException | IllegalAccessException ex) { // log.error("error read " + field.getName() + " of " + obj.getClass().getName(), ex); // } // return null; // } // // @Override // public void write(Object v) { // try { // field.set(obj, v); // } catch (IllegalArgumentException | IllegalAccessException ex) { // log.error("error write " + field.getName() + " of " + obj.getClass().getName(), ex); // } // } // // } // // Path: ngscript-core/src/main/java/org/ngscript/runtime/vo/JavaMethod.java // public class JavaMethod implements VmMethod { // // public Object caller; // public ArrayList<Method> methods; // String methodName; // // public JavaMethod(Object caller, ArrayList<Method> methods) { // this.caller = caller; // this.methods = methods; // init(); // } // // public JavaMethod(Object caller, Method method) { // this.caller = caller; // this.methods = new ArrayList<>(); // this.methods.add(method); // init(); // } // // void init() { // Method m1 = methods.get(0); // methodName = m1.getDeclaringClass().getName() + "#" + m1.getName(); // } // // @Override // public void invoke(VirtualMachine vm, Object[] args) throws Exception { // Class[] types = vm.getParamTypes(2); // Method properMethod = MethodTypeMap.INSTANCE.getProperMethod(methodName, methods, types); // if (properMethod == null) { // throw new VmRuntimeException(vm, "no proper method found for " + methods + "[" + Arrays.toString(types) + "]"); // } // if (properMethod.isVarArgs()) { // args = VarArgHelper.packVarArgs(args); // } // try { // Object val = properMethod.invoke(caller, args); // if (val instanceof Long) { // val = ((Long) val).intValue(); // } // vm.eax.write(val); // } catch (Exception ex) { // vm.exception.write(new VmRuntimeException(vm, ex.getCause() == null ? ex.toString() : ex.getCause().toString())); // Op.restore_machine_state(vm, null, null); // } // } // } // // Path: ngscript-core/src/main/java/org/ngscript/runtime/vo/VmMemRef.java // public class VmMemRef { // // private Object value; // @Getter // private final boolean immutable; // // public VmMemRef() { // this(null, false); // } // // public VmMemRef(Object obj_v) { // this(obj_v, false); // } // // public VmMemRef(Object value, boolean immutable) { // this.value = value; // this.immutable = immutable; // } // // public void write(Object v) { // if (immutable && value != null) { // throw new RuntimeException("immutable"); // } // this.value = v; // } // // public Object read() { // return this.value; // } // // @Override // public String toString() { // return "VmMemRef{" + "value=" + value + '}'; // } // // } // // Path: ngscript-core/src/main/java/org/ngscript/runtime/vo/undefined.java // public class undefined { // // private undefined() { // } // // @Override // public String toString() { // return "undefined"; // } // // public static final undefined value = new undefined(); // }
import org.ngscript.runtime.vo.JavaMemRef; import org.ngscript.runtime.vo.JavaMethod; import org.ngscript.runtime.vo.VmMemRef; import org.ngscript.runtime.vo.undefined; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.HashMap; import java.util.Map;
} //try java.lang try { Class cls = Class.forName("java.lang." + member); return new VmMemRef(cls); } catch (ClassNotFoundException ex) { } throw new VmRuntimeException(vm, member + " is not declared"); } } public static Object lookupNative(Object nativeObj, String member, VirtualMachine vm) { if (nativeObj instanceof Class) { //try obj as a class ref Object obj = _lookupNative(nativeObj, (Class) nativeObj, member, vm); if (obj != null) { return obj; } } //regards obj as an Object return _lookupNative(nativeObj, nativeObj.getClass(), member, vm); } public static Object _lookupNative(Object nativeObj, Class cls, String member, VirtualMachine vm) { //try field try { Field field = cls.getField(member);
// Path: ngscript-core/src/main/java/org/ngscript/runtime/vo/JavaMemRef.java // @Slf4j // public class JavaMemRef extends VmMemRef { // // private Object obj; // private Field field; // // public JavaMemRef(Object obj, Field field) { // this.obj = obj; // this.field = field; // } // // @Override // public Object read() { // try { // return field.get(obj); // } catch (IllegalArgumentException | IllegalAccessException ex) { // log.error("error read " + field.getName() + " of " + obj.getClass().getName(), ex); // } // return null; // } // // @Override // public void write(Object v) { // try { // field.set(obj, v); // } catch (IllegalArgumentException | IllegalAccessException ex) { // log.error("error write " + field.getName() + " of " + obj.getClass().getName(), ex); // } // } // // } // // Path: ngscript-core/src/main/java/org/ngscript/runtime/vo/JavaMethod.java // public class JavaMethod implements VmMethod { // // public Object caller; // public ArrayList<Method> methods; // String methodName; // // public JavaMethod(Object caller, ArrayList<Method> methods) { // this.caller = caller; // this.methods = methods; // init(); // } // // public JavaMethod(Object caller, Method method) { // this.caller = caller; // this.methods = new ArrayList<>(); // this.methods.add(method); // init(); // } // // void init() { // Method m1 = methods.get(0); // methodName = m1.getDeclaringClass().getName() + "#" + m1.getName(); // } // // @Override // public void invoke(VirtualMachine vm, Object[] args) throws Exception { // Class[] types = vm.getParamTypes(2); // Method properMethod = MethodTypeMap.INSTANCE.getProperMethod(methodName, methods, types); // if (properMethod == null) { // throw new VmRuntimeException(vm, "no proper method found for " + methods + "[" + Arrays.toString(types) + "]"); // } // if (properMethod.isVarArgs()) { // args = VarArgHelper.packVarArgs(args); // } // try { // Object val = properMethod.invoke(caller, args); // if (val instanceof Long) { // val = ((Long) val).intValue(); // } // vm.eax.write(val); // } catch (Exception ex) { // vm.exception.write(new VmRuntimeException(vm, ex.getCause() == null ? ex.toString() : ex.getCause().toString())); // Op.restore_machine_state(vm, null, null); // } // } // } // // Path: ngscript-core/src/main/java/org/ngscript/runtime/vo/VmMemRef.java // public class VmMemRef { // // private Object value; // @Getter // private final boolean immutable; // // public VmMemRef() { // this(null, false); // } // // public VmMemRef(Object obj_v) { // this(obj_v, false); // } // // public VmMemRef(Object value, boolean immutable) { // this.value = value; // this.immutable = immutable; // } // // public void write(Object v) { // if (immutable && value != null) { // throw new RuntimeException("immutable"); // } // this.value = v; // } // // public Object read() { // return this.value; // } // // @Override // public String toString() { // return "VmMemRef{" + "value=" + value + '}'; // } // // } // // Path: ngscript-core/src/main/java/org/ngscript/runtime/vo/undefined.java // public class undefined { // // private undefined() { // } // // @Override // public String toString() { // return "undefined"; // } // // public static final undefined value = new undefined(); // } // Path: ngscript-core/src/main/java/org/ngscript/runtime/Environment.java import org.ngscript.runtime.vo.JavaMemRef; import org.ngscript.runtime.vo.JavaMethod; import org.ngscript.runtime.vo.VmMemRef; import org.ngscript.runtime.vo.undefined; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; } //try java.lang try { Class cls = Class.forName("java.lang." + member); return new VmMemRef(cls); } catch (ClassNotFoundException ex) { } throw new VmRuntimeException(vm, member + " is not declared"); } } public static Object lookupNative(Object nativeObj, String member, VirtualMachine vm) { if (nativeObj instanceof Class) { //try obj as a class ref Object obj = _lookupNative(nativeObj, (Class) nativeObj, member, vm); if (obj != null) { return obj; } } //regards obj as an Object return _lookupNative(nativeObj, nativeObj.getClass(), member, vm); } public static Object _lookupNative(Object nativeObj, Class cls, String member, VirtualMachine vm) { //try field try { Field field = cls.getField(member);
return new JavaMemRef(nativeObj, field);
wssccc/ngscript
ngscript-core/src/main/java/org/ngscript/runtime/Environment.java
// Path: ngscript-core/src/main/java/org/ngscript/runtime/vo/JavaMemRef.java // @Slf4j // public class JavaMemRef extends VmMemRef { // // private Object obj; // private Field field; // // public JavaMemRef(Object obj, Field field) { // this.obj = obj; // this.field = field; // } // // @Override // public Object read() { // try { // return field.get(obj); // } catch (IllegalArgumentException | IllegalAccessException ex) { // log.error("error read " + field.getName() + " of " + obj.getClass().getName(), ex); // } // return null; // } // // @Override // public void write(Object v) { // try { // field.set(obj, v); // } catch (IllegalArgumentException | IllegalAccessException ex) { // log.error("error write " + field.getName() + " of " + obj.getClass().getName(), ex); // } // } // // } // // Path: ngscript-core/src/main/java/org/ngscript/runtime/vo/JavaMethod.java // public class JavaMethod implements VmMethod { // // public Object caller; // public ArrayList<Method> methods; // String methodName; // // public JavaMethod(Object caller, ArrayList<Method> methods) { // this.caller = caller; // this.methods = methods; // init(); // } // // public JavaMethod(Object caller, Method method) { // this.caller = caller; // this.methods = new ArrayList<>(); // this.methods.add(method); // init(); // } // // void init() { // Method m1 = methods.get(0); // methodName = m1.getDeclaringClass().getName() + "#" + m1.getName(); // } // // @Override // public void invoke(VirtualMachine vm, Object[] args) throws Exception { // Class[] types = vm.getParamTypes(2); // Method properMethod = MethodTypeMap.INSTANCE.getProperMethod(methodName, methods, types); // if (properMethod == null) { // throw new VmRuntimeException(vm, "no proper method found for " + methods + "[" + Arrays.toString(types) + "]"); // } // if (properMethod.isVarArgs()) { // args = VarArgHelper.packVarArgs(args); // } // try { // Object val = properMethod.invoke(caller, args); // if (val instanceof Long) { // val = ((Long) val).intValue(); // } // vm.eax.write(val); // } catch (Exception ex) { // vm.exception.write(new VmRuntimeException(vm, ex.getCause() == null ? ex.toString() : ex.getCause().toString())); // Op.restore_machine_state(vm, null, null); // } // } // } // // Path: ngscript-core/src/main/java/org/ngscript/runtime/vo/VmMemRef.java // public class VmMemRef { // // private Object value; // @Getter // private final boolean immutable; // // public VmMemRef() { // this(null, false); // } // // public VmMemRef(Object obj_v) { // this(obj_v, false); // } // // public VmMemRef(Object value, boolean immutable) { // this.value = value; // this.immutable = immutable; // } // // public void write(Object v) { // if (immutable && value != null) { // throw new RuntimeException("immutable"); // } // this.value = v; // } // // public Object read() { // return this.value; // } // // @Override // public String toString() { // return "VmMemRef{" + "value=" + value + '}'; // } // // } // // Path: ngscript-core/src/main/java/org/ngscript/runtime/vo/undefined.java // public class undefined { // // private undefined() { // } // // @Override // public String toString() { // return "undefined"; // } // // public static final undefined value = new undefined(); // }
import org.ngscript.runtime.vo.JavaMemRef; import org.ngscript.runtime.vo.JavaMethod; import org.ngscript.runtime.vo.VmMemRef; import org.ngscript.runtime.vo.undefined; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.HashMap; import java.util.Map;
if (nativeObj instanceof Class) { //try obj as a class ref Object obj = _lookupNative(nativeObj, (Class) nativeObj, member, vm); if (obj != null) { return obj; } } //regards obj as an Object return _lookupNative(nativeObj, nativeObj.getClass(), member, vm); } public static Object _lookupNative(Object nativeObj, Class cls, String member, VirtualMachine vm) { //try field try { Field field = cls.getField(member); return new JavaMemRef(nativeObj, field); } catch (NoSuchFieldException ex) { } //try method Method[] methods = cls.getMethods(); ArrayList<Method> ms = new ArrayList<Method>(); for (Method m : methods) { if (m.getName().equals(member)) { ms.add(m); } } if (!ms.isEmpty()) {
// Path: ngscript-core/src/main/java/org/ngscript/runtime/vo/JavaMemRef.java // @Slf4j // public class JavaMemRef extends VmMemRef { // // private Object obj; // private Field field; // // public JavaMemRef(Object obj, Field field) { // this.obj = obj; // this.field = field; // } // // @Override // public Object read() { // try { // return field.get(obj); // } catch (IllegalArgumentException | IllegalAccessException ex) { // log.error("error read " + field.getName() + " of " + obj.getClass().getName(), ex); // } // return null; // } // // @Override // public void write(Object v) { // try { // field.set(obj, v); // } catch (IllegalArgumentException | IllegalAccessException ex) { // log.error("error write " + field.getName() + " of " + obj.getClass().getName(), ex); // } // } // // } // // Path: ngscript-core/src/main/java/org/ngscript/runtime/vo/JavaMethod.java // public class JavaMethod implements VmMethod { // // public Object caller; // public ArrayList<Method> methods; // String methodName; // // public JavaMethod(Object caller, ArrayList<Method> methods) { // this.caller = caller; // this.methods = methods; // init(); // } // // public JavaMethod(Object caller, Method method) { // this.caller = caller; // this.methods = new ArrayList<>(); // this.methods.add(method); // init(); // } // // void init() { // Method m1 = methods.get(0); // methodName = m1.getDeclaringClass().getName() + "#" + m1.getName(); // } // // @Override // public void invoke(VirtualMachine vm, Object[] args) throws Exception { // Class[] types = vm.getParamTypes(2); // Method properMethod = MethodTypeMap.INSTANCE.getProperMethod(methodName, methods, types); // if (properMethod == null) { // throw new VmRuntimeException(vm, "no proper method found for " + methods + "[" + Arrays.toString(types) + "]"); // } // if (properMethod.isVarArgs()) { // args = VarArgHelper.packVarArgs(args); // } // try { // Object val = properMethod.invoke(caller, args); // if (val instanceof Long) { // val = ((Long) val).intValue(); // } // vm.eax.write(val); // } catch (Exception ex) { // vm.exception.write(new VmRuntimeException(vm, ex.getCause() == null ? ex.toString() : ex.getCause().toString())); // Op.restore_machine_state(vm, null, null); // } // } // } // // Path: ngscript-core/src/main/java/org/ngscript/runtime/vo/VmMemRef.java // public class VmMemRef { // // private Object value; // @Getter // private final boolean immutable; // // public VmMemRef() { // this(null, false); // } // // public VmMemRef(Object obj_v) { // this(obj_v, false); // } // // public VmMemRef(Object value, boolean immutable) { // this.value = value; // this.immutable = immutable; // } // // public void write(Object v) { // if (immutable && value != null) { // throw new RuntimeException("immutable"); // } // this.value = v; // } // // public Object read() { // return this.value; // } // // @Override // public String toString() { // return "VmMemRef{" + "value=" + value + '}'; // } // // } // // Path: ngscript-core/src/main/java/org/ngscript/runtime/vo/undefined.java // public class undefined { // // private undefined() { // } // // @Override // public String toString() { // return "undefined"; // } // // public static final undefined value = new undefined(); // } // Path: ngscript-core/src/main/java/org/ngscript/runtime/Environment.java import org.ngscript.runtime.vo.JavaMemRef; import org.ngscript.runtime.vo.JavaMethod; import org.ngscript.runtime.vo.VmMemRef; import org.ngscript.runtime.vo.undefined; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; if (nativeObj instanceof Class) { //try obj as a class ref Object obj = _lookupNative(nativeObj, (Class) nativeObj, member, vm); if (obj != null) { return obj; } } //regards obj as an Object return _lookupNative(nativeObj, nativeObj.getClass(), member, vm); } public static Object _lookupNative(Object nativeObj, Class cls, String member, VirtualMachine vm) { //try field try { Field field = cls.getField(member); return new JavaMemRef(nativeObj, field); } catch (NoSuchFieldException ex) { } //try method Method[] methods = cls.getMethods(); ArrayList<Method> ms = new ArrayList<Method>(); for (Method m : methods) { if (m.getName().equals(member)) { ms.add(m); } } if (!ms.isEmpty()) {
return new VmMemRef(new JavaMethod(nativeObj, ms));
wssccc/ngscript
ngscript-core/src/main/java/org/ngscript/runtime/utils/TypeOp.java
// Path: ngscript-core/src/main/java/org/ngscript/runtime/VmRuntimeException.java // public class VmRuntimeException extends RuntimeException { // // VirtualMachine vm; // // public VmRuntimeException(String message) { // super(message); // } // // public VmRuntimeException(Throwable cause) { // super(cause); // } // // public VmRuntimeException(VirtualMachine vm, String message) { // super(genInfoString(vm, message)); // this.vm = vm; // } // // final static String genInfoString(VirtualMachine vm, String message) { // try { // StringBuilder sb = new StringBuilder(); // sb // .append("\r\n========== VM ERROR ==========\r\n") // .append(message) // .append("\r\nnear code line ").append(vm.helptext.paramExtended).append("\r\n") // .append(vm.helptext.toString()) // .append("\r\n========== VM STATUS ==========\r\n") // .append("%eip = ").append(vm.getEip()).append("\r\n") // .append("ins = ").append(vm.instructions[vm.getEip() - 1]).append("\r\n") // .append("%env = ").append((vm.env.read()).toString()).append("\r\n") // .append("%eax = ").append(vm.eax.read() == null ? "null" : vm.eax.read().toString()).append("\r\n") // .append("==============================\r\n"); // return sb.toString(); // } catch (Exception ex) { // return message; // } // } // // }
import org.ngscript.runtime.VmRuntimeException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.logging.Level; import java.util.logging.Logger;
/* * Copyright 2021 wssccc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.ngscript.runtime.utils; /** * @author wssccc */ public class TypeOp { public static final int OP_ADD = '+'; public static final int OP_SUB = '-'; public static final int OP_MUL = '*'; public static final int OP_DIV = '/'; public static final int OP_EQ = '='; public static final int OP_MOD = '%';
// Path: ngscript-core/src/main/java/org/ngscript/runtime/VmRuntimeException.java // public class VmRuntimeException extends RuntimeException { // // VirtualMachine vm; // // public VmRuntimeException(String message) { // super(message); // } // // public VmRuntimeException(Throwable cause) { // super(cause); // } // // public VmRuntimeException(VirtualMachine vm, String message) { // super(genInfoString(vm, message)); // this.vm = vm; // } // // final static String genInfoString(VirtualMachine vm, String message) { // try { // StringBuilder sb = new StringBuilder(); // sb // .append("\r\n========== VM ERROR ==========\r\n") // .append(message) // .append("\r\nnear code line ").append(vm.helptext.paramExtended).append("\r\n") // .append(vm.helptext.toString()) // .append("\r\n========== VM STATUS ==========\r\n") // .append("%eip = ").append(vm.getEip()).append("\r\n") // .append("ins = ").append(vm.instructions[vm.getEip() - 1]).append("\r\n") // .append("%env = ").append((vm.env.read()).toString()).append("\r\n") // .append("%eax = ").append(vm.eax.read() == null ? "null" : vm.eax.read().toString()).append("\r\n") // .append("==============================\r\n"); // return sb.toString(); // } catch (Exception ex) { // return message; // } // } // // } // Path: ngscript-core/src/main/java/org/ngscript/runtime/utils/TypeOp.java import org.ngscript.runtime.VmRuntimeException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.logging.Level; import java.util.logging.Logger; /* * Copyright 2021 wssccc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.ngscript.runtime.utils; /** * @author wssccc */ public class TypeOp { public static final int OP_ADD = '+'; public static final int OP_SUB = '-'; public static final int OP_MUL = '*'; public static final int OP_DIV = '/'; public static final int OP_EQ = '='; public static final int OP_MOD = '%';
public static Object eval(int op, Object o1, Object o2) throws VmRuntimeException {
wssccc/ngscript
ngscript-core/src/main/java/org/ngscript/runtime/Context.java
// Path: ngscript-core/src/main/java/org/ngscript/compiler/Instruction.java // public class Instruction { // // public String op; // public String param; // public String paramExtended; // // public Instruction(String op) { // this.op = op; // } // // public Instruction(String op, String param) { // this.op = op; // this.param = param; // } // // public Instruction(String op, String param, String paramExtended) { // this.op = op; // this.param = param; // this.paramExtended = paramExtended; // } // // @Override // public String toString() { // if ("//".equals(op)) { // return op + ' ' + (param == null ? "" : param) + "\n"; // } else { // return String.format("%-15s%-30s", op, (param == null ? "" : param) + (paramExtended == null ? "" : "," + paramExtended)) + "\n"; // } // // } // // } // // Path: ngscript-parseroid/src/main/java/org/ngscript/utils/FastStack.java // public class FastStack<T> { // // T[] elements; // int size = 0; // // public FastStack(int initialCapacity) { // elements = (T[]) new Object[initialCapacity]; // } // // public T peek() { // return peek(0); // } // // public T peek(int offset) { // return elements[size - 1 - offset]; // } // // public void push(T e) { // elements[size++] = e; // if (size == elements.length) { // doubleCapacity(); // } // } // // public void add(T e) { // push(e); // } // // public T pop() { // return elements[--size]; // } // // public void pop(int n) { // size -= n; // } // // public T get(int i) { // return elements[i]; // } // // public int size() { // return size; // } // // public void clear() { // size = 0; // } // // public List<T> last(int n) { // T[] subElements = (T[]) new Object[n]; // System.arraycopy(elements, size - n, subElements, 0, subElements.length); // return new ArrayList<>(Arrays.asList(subElements)); // } // // public boolean isEmpty() { // return size == 0; // } // // private void doubleCapacity() { // T[] newElements = (T[]) new Object[elements.length << 1]; // System.arraycopy(elements, 0, newElements, 0, elements.length); // elements = newElements; // } // // @Override // public String toString() { // return Arrays.toString(elements); // } // }
import org.ngscript.compiler.Instruction; import org.ngscript.utils.FastStack;
/* * Copyright 2021 wssccc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.ngscript.runtime; /** * @author wssccc */ public class Context { Object eax; Environment env; int eip;
// Path: ngscript-core/src/main/java/org/ngscript/compiler/Instruction.java // public class Instruction { // // public String op; // public String param; // public String paramExtended; // // public Instruction(String op) { // this.op = op; // } // // public Instruction(String op, String param) { // this.op = op; // this.param = param; // } // // public Instruction(String op, String param, String paramExtended) { // this.op = op; // this.param = param; // this.paramExtended = paramExtended; // } // // @Override // public String toString() { // if ("//".equals(op)) { // return op + ' ' + (param == null ? "" : param) + "\n"; // } else { // return String.format("%-15s%-30s", op, (param == null ? "" : param) + (paramExtended == null ? "" : "," + paramExtended)) + "\n"; // } // // } // // } // // Path: ngscript-parseroid/src/main/java/org/ngscript/utils/FastStack.java // public class FastStack<T> { // // T[] elements; // int size = 0; // // public FastStack(int initialCapacity) { // elements = (T[]) new Object[initialCapacity]; // } // // public T peek() { // return peek(0); // } // // public T peek(int offset) { // return elements[size - 1 - offset]; // } // // public void push(T e) { // elements[size++] = e; // if (size == elements.length) { // doubleCapacity(); // } // } // // public void add(T e) { // push(e); // } // // public T pop() { // return elements[--size]; // } // // public void pop(int n) { // size -= n; // } // // public T get(int i) { // return elements[i]; // } // // public int size() { // return size; // } // // public void clear() { // size = 0; // } // // public List<T> last(int n) { // T[] subElements = (T[]) new Object[n]; // System.arraycopy(elements, size - n, subElements, 0, subElements.length); // return new ArrayList<>(Arrays.asList(subElements)); // } // // public boolean isEmpty() { // return size == 0; // } // // private void doubleCapacity() { // T[] newElements = (T[]) new Object[elements.length << 1]; // System.arraycopy(elements, 0, newElements, 0, elements.length); // elements = newElements; // } // // @Override // public String toString() { // return Arrays.toString(elements); // } // } // Path: ngscript-core/src/main/java/org/ngscript/runtime/Context.java import org.ngscript.compiler.Instruction; import org.ngscript.utils.FastStack; /* * Copyright 2021 wssccc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.ngscript.runtime; /** * @author wssccc */ public class Context { Object eax; Environment env; int eip;
Instruction hint;
wssccc/ngscript
ngscript-core/src/main/java/org/ngscript/runtime/Context.java
// Path: ngscript-core/src/main/java/org/ngscript/compiler/Instruction.java // public class Instruction { // // public String op; // public String param; // public String paramExtended; // // public Instruction(String op) { // this.op = op; // } // // public Instruction(String op, String param) { // this.op = op; // this.param = param; // } // // public Instruction(String op, String param, String paramExtended) { // this.op = op; // this.param = param; // this.paramExtended = paramExtended; // } // // @Override // public String toString() { // if ("//".equals(op)) { // return op + ' ' + (param == null ? "" : param) + "\n"; // } else { // return String.format("%-15s%-30s", op, (param == null ? "" : param) + (paramExtended == null ? "" : "," + paramExtended)) + "\n"; // } // // } // // } // // Path: ngscript-parseroid/src/main/java/org/ngscript/utils/FastStack.java // public class FastStack<T> { // // T[] elements; // int size = 0; // // public FastStack(int initialCapacity) { // elements = (T[]) new Object[initialCapacity]; // } // // public T peek() { // return peek(0); // } // // public T peek(int offset) { // return elements[size - 1 - offset]; // } // // public void push(T e) { // elements[size++] = e; // if (size == elements.length) { // doubleCapacity(); // } // } // // public void add(T e) { // push(e); // } // // public T pop() { // return elements[--size]; // } // // public void pop(int n) { // size -= n; // } // // public T get(int i) { // return elements[i]; // } // // public int size() { // return size; // } // // public void clear() { // size = 0; // } // // public List<T> last(int n) { // T[] subElements = (T[]) new Object[n]; // System.arraycopy(elements, size - n, subElements, 0, subElements.length); // return new ArrayList<>(Arrays.asList(subElements)); // } // // public boolean isEmpty() { // return size == 0; // } // // private void doubleCapacity() { // T[] newElements = (T[]) new Object[elements.length << 1]; // System.arraycopy(elements, 0, newElements, 0, elements.length); // elements = newElements; // } // // @Override // public String toString() { // return Arrays.toString(elements); // } // }
import org.ngscript.compiler.Instruction; import org.ngscript.utils.FastStack;
/* * Copyright 2021 wssccc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.ngscript.runtime; /** * @author wssccc */ public class Context { Object eax; Environment env; int eip; Instruction hint; int stackSize; int callStackSize;
// Path: ngscript-core/src/main/java/org/ngscript/compiler/Instruction.java // public class Instruction { // // public String op; // public String param; // public String paramExtended; // // public Instruction(String op) { // this.op = op; // } // // public Instruction(String op, String param) { // this.op = op; // this.param = param; // } // // public Instruction(String op, String param, String paramExtended) { // this.op = op; // this.param = param; // this.paramExtended = paramExtended; // } // // @Override // public String toString() { // if ("//".equals(op)) { // return op + ' ' + (param == null ? "" : param) + "\n"; // } else { // return String.format("%-15s%-30s", op, (param == null ? "" : param) + (paramExtended == null ? "" : "," + paramExtended)) + "\n"; // } // // } // // } // // Path: ngscript-parseroid/src/main/java/org/ngscript/utils/FastStack.java // public class FastStack<T> { // // T[] elements; // int size = 0; // // public FastStack(int initialCapacity) { // elements = (T[]) new Object[initialCapacity]; // } // // public T peek() { // return peek(0); // } // // public T peek(int offset) { // return elements[size - 1 - offset]; // } // // public void push(T e) { // elements[size++] = e; // if (size == elements.length) { // doubleCapacity(); // } // } // // public void add(T e) { // push(e); // } // // public T pop() { // return elements[--size]; // } // // public void pop(int n) { // size -= n; // } // // public T get(int i) { // return elements[i]; // } // // public int size() { // return size; // } // // public void clear() { // size = 0; // } // // public List<T> last(int n) { // T[] subElements = (T[]) new Object[n]; // System.arraycopy(elements, size - n, subElements, 0, subElements.length); // return new ArrayList<>(Arrays.asList(subElements)); // } // // public boolean isEmpty() { // return size == 0; // } // // private void doubleCapacity() { // T[] newElements = (T[]) new Object[elements.length << 1]; // System.arraycopy(elements, 0, newElements, 0, elements.length); // elements = newElements; // } // // @Override // public String toString() { // return Arrays.toString(elements); // } // } // Path: ngscript-core/src/main/java/org/ngscript/runtime/Context.java import org.ngscript.compiler.Instruction; import org.ngscript.utils.FastStack; /* * Copyright 2021 wssccc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.ngscript.runtime; /** * @author wssccc */ public class Context { Object eax; Environment env; int eip; Instruction hint; int stackSize; int callStackSize;
FastStack<Object> stack;
wssccc/ngscript
ngscript-parseroid/src/main/java/org/ngscript/parseroid/table/Item.java
// Path: ngscript-parseroid/src/main/java/org/ngscript/parseroid/grammar/Production.java // public class Production implements Serializable { // // public Symbol sym; // public Symbol[] produces; // public int id; // // public Production(Symbol sym, Symbol[] produces, int id) { // this.sym = sym; // this.produces = produces; // this.id = id; // } // // public boolean almostEquals(Production other) { // if (this.sym != other.sym) { // return false; // } // if (other.produces.length != this.produces.length) { // return false; // } // for (int i = 0; i < produces.length; i++) { // if (other.produces[i] != this.produces[i]) { // return false; // } // } // return true; // } // // @Override // public String toString() { // StringBuilder sb = new StringBuilder(); // sb.append(sym.identifier); // sb.append("->"); // for (Symbol produce : produces) { // sb.append(produce.identifier); // } // return sb.toString(); // } // // } // // Path: ngscript-parseroid/src/main/java/org/ngscript/parseroid/grammar/Symbol.java // @ToString // @EqualsAndHashCode // public class Symbol implements Serializable{ // // public static final Symbol NULL = new Symbol("NULL", true); // public static final Symbol EOF = new Symbol("EOF", true); // public static final Symbol ERROR = new Symbol("ERROR", true); // // public String identifier; // public boolean isTerminal; // // private Symbol(String identifier, boolean isTerminal) { // this.identifier = identifier; // this.isTerminal = isTerminal; // } // // public static Symbol create(String identifier, boolean isTerminal) { // return new Symbol(identifier, isTerminal); // } // }
import org.ngscript.parseroid.grammar.Production; import org.ngscript.parseroid.grammar.Symbol; import java.util.HashMap; import java.util.Map;
/* * Copyright 2021 wssccc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.ngscript.parseroid.table; /** * @author wssccc */ public class Item { Production production; int pos;
// Path: ngscript-parseroid/src/main/java/org/ngscript/parseroid/grammar/Production.java // public class Production implements Serializable { // // public Symbol sym; // public Symbol[] produces; // public int id; // // public Production(Symbol sym, Symbol[] produces, int id) { // this.sym = sym; // this.produces = produces; // this.id = id; // } // // public boolean almostEquals(Production other) { // if (this.sym != other.sym) { // return false; // } // if (other.produces.length != this.produces.length) { // return false; // } // for (int i = 0; i < produces.length; i++) { // if (other.produces[i] != this.produces[i]) { // return false; // } // } // return true; // } // // @Override // public String toString() { // StringBuilder sb = new StringBuilder(); // sb.append(sym.identifier); // sb.append("->"); // for (Symbol produce : produces) { // sb.append(produce.identifier); // } // return sb.toString(); // } // // } // // Path: ngscript-parseroid/src/main/java/org/ngscript/parseroid/grammar/Symbol.java // @ToString // @EqualsAndHashCode // public class Symbol implements Serializable{ // // public static final Symbol NULL = new Symbol("NULL", true); // public static final Symbol EOF = new Symbol("EOF", true); // public static final Symbol ERROR = new Symbol("ERROR", true); // // public String identifier; // public boolean isTerminal; // // private Symbol(String identifier, boolean isTerminal) { // this.identifier = identifier; // this.isTerminal = isTerminal; // } // // public static Symbol create(String identifier, boolean isTerminal) { // return new Symbol(identifier, isTerminal); // } // } // Path: ngscript-parseroid/src/main/java/org/ngscript/parseroid/table/Item.java import org.ngscript.parseroid.grammar.Production; import org.ngscript.parseroid.grammar.Symbol; import java.util.HashMap; import java.util.Map; /* * Copyright 2021 wssccc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.ngscript.parseroid.table; /** * @author wssccc */ public class Item { Production production; int pos;
Map<String, Symbol> lookahead = new HashMap<>();
wssccc/ngscript
ngscript-core/src/main/java/org/ngscript/compiler/Compiler.java
// Path: ngscript-core/src/main/java/org/ngscript/Configuration.java // @Data // public class Configuration { // // public static final Configuration DEFAULT = new Configuration(); // // boolean generateDebugInfo = false; // boolean interactive = false; // // } // // Path: ngscript-parseroid/src/main/java/org/ngscript/parseroid/parser/AstNode.java // public class AstNode { // // public Token token; // public List<AstNode> contents; // // public AstNode(Token token) { // this.token = token; // this.contents = new ArrayList<>(); // } // // public AstNode(Token token, ArrayList<AstNode> children) { // this.token = token; // this.contents = children; // } // // public AstNode getNode(String type) { // for (AstNode content : contents) { // if (content.token.type.equals(type)) { // return content; // } // } // return null; // } // // @Override // public String toString() { // return toString(0, "", " "); // } // // String toString(int nest, String margin, String subMargin) { // StringBuilder builder = new StringBuilder(margin); // builder.append("|-"); // builder.append(token.toString()); // builder.append("\n"); // for (int i = 0; i < contents.size(); i++) { // if (i != contents.size() - 1) { // builder.append(contents.get(i).toString(nest + 1, subMargin, subMargin + "| ")); // } else { // builder.append(contents.get(i).toString(nest + 1, subMargin, subMargin + " ")); // } // } // return builder.toString(); // } // // }
import org.ngscript.Configuration; import org.ngscript.parseroid.parser.AstNode; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.*;
/* * Copyright 2021 wssccc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.ngscript.compiler; /** * @author wssccc */ public class Compiler { private static final Set<String> BINARY_OP = new HashSet<>(Arrays.asList("bit_xor", "bit_or", "bit_and", "eq", "neq", "lt", "gt", "le", "ge", "veq", "vneq", "mul", "mod", "div", "add", "sub"));
// Path: ngscript-core/src/main/java/org/ngscript/Configuration.java // @Data // public class Configuration { // // public static final Configuration DEFAULT = new Configuration(); // // boolean generateDebugInfo = false; // boolean interactive = false; // // } // // Path: ngscript-parseroid/src/main/java/org/ngscript/parseroid/parser/AstNode.java // public class AstNode { // // public Token token; // public List<AstNode> contents; // // public AstNode(Token token) { // this.token = token; // this.contents = new ArrayList<>(); // } // // public AstNode(Token token, ArrayList<AstNode> children) { // this.token = token; // this.contents = children; // } // // public AstNode getNode(String type) { // for (AstNode content : contents) { // if (content.token.type.equals(type)) { // return content; // } // } // return null; // } // // @Override // public String toString() { // return toString(0, "", " "); // } // // String toString(int nest, String margin, String subMargin) { // StringBuilder builder = new StringBuilder(margin); // builder.append("|-"); // builder.append(token.toString()); // builder.append("\n"); // for (int i = 0; i < contents.size(); i++) { // if (i != contents.size() - 1) { // builder.append(contents.get(i).toString(nest + 1, subMargin, subMargin + "| ")); // } else { // builder.append(contents.get(i).toString(nest + 1, subMargin, subMargin + " ")); // } // } // return builder.toString(); // } // // } // Path: ngscript-core/src/main/java/org/ngscript/compiler/Compiler.java import org.ngscript.Configuration; import org.ngscript.parseroid.parser.AstNode; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.*; /* * Copyright 2021 wssccc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.ngscript.compiler; /** * @author wssccc */ public class Compiler { private static final Set<String> BINARY_OP = new HashSet<>(Arrays.asList("bit_xor", "bit_or", "bit_and", "eq", "neq", "lt", "gt", "le", "ge", "veq", "vneq", "mul", "mod", "div", "add", "sub"));
Configuration configuration;
wssccc/ngscript
ngscript-core/src/main/java/org/ngscript/compiler/Compiler.java
// Path: ngscript-core/src/main/java/org/ngscript/Configuration.java // @Data // public class Configuration { // // public static final Configuration DEFAULT = new Configuration(); // // boolean generateDebugInfo = false; // boolean interactive = false; // // } // // Path: ngscript-parseroid/src/main/java/org/ngscript/parseroid/parser/AstNode.java // public class AstNode { // // public Token token; // public List<AstNode> contents; // // public AstNode(Token token) { // this.token = token; // this.contents = new ArrayList<>(); // } // // public AstNode(Token token, ArrayList<AstNode> children) { // this.token = token; // this.contents = children; // } // // public AstNode getNode(String type) { // for (AstNode content : contents) { // if (content.token.type.equals(type)) { // return content; // } // } // return null; // } // // @Override // public String toString() { // return toString(0, "", " "); // } // // String toString(int nest, String margin, String subMargin) { // StringBuilder builder = new StringBuilder(margin); // builder.append("|-"); // builder.append(token.toString()); // builder.append("\n"); // for (int i = 0; i < contents.size(); i++) { // if (i != contents.size() - 1) { // builder.append(contents.get(i).toString(nest + 1, subMargin, subMargin + "| ")); // } else { // builder.append(contents.get(i).toString(nest + 1, subMargin, subMargin + " ")); // } // } // return builder.toString(); // } // // }
import org.ngscript.Configuration; import org.ngscript.parseroid.parser.AstNode; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.*;
/* * Copyright 2021 wssccc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.ngscript.compiler; /** * @author wssccc */ public class Compiler { private static final Set<String> BINARY_OP = new HashSet<>(Arrays.asList("bit_xor", "bit_or", "bit_and", "eq", "neq", "lt", "gt", "le", "ge", "veq", "vneq", "mul", "mod", "div", "add", "sub")); Configuration configuration; Assembler assembler = new Assembler(); Scanner scanner; int printedLines; Deque<String> continueLabels = new ArrayDeque<>(); Deque<String> breakLabels = new ArrayDeque<>(); Deque<String> finallyLabels = new ArrayDeque<>(); public Compiler(Configuration configuration) { this.configuration = configuration; }
// Path: ngscript-core/src/main/java/org/ngscript/Configuration.java // @Data // public class Configuration { // // public static final Configuration DEFAULT = new Configuration(); // // boolean generateDebugInfo = false; // boolean interactive = false; // // } // // Path: ngscript-parseroid/src/main/java/org/ngscript/parseroid/parser/AstNode.java // public class AstNode { // // public Token token; // public List<AstNode> contents; // // public AstNode(Token token) { // this.token = token; // this.contents = new ArrayList<>(); // } // // public AstNode(Token token, ArrayList<AstNode> children) { // this.token = token; // this.contents = children; // } // // public AstNode getNode(String type) { // for (AstNode content : contents) { // if (content.token.type.equals(type)) { // return content; // } // } // return null; // } // // @Override // public String toString() { // return toString(0, "", " "); // } // // String toString(int nest, String margin, String subMargin) { // StringBuilder builder = new StringBuilder(margin); // builder.append("|-"); // builder.append(token.toString()); // builder.append("\n"); // for (int i = 0; i < contents.size(); i++) { // if (i != contents.size() - 1) { // builder.append(contents.get(i).toString(nest + 1, subMargin, subMargin + "| ")); // } else { // builder.append(contents.get(i).toString(nest + 1, subMargin, subMargin + " ")); // } // } // return builder.toString(); // } // // } // Path: ngscript-core/src/main/java/org/ngscript/compiler/Compiler.java import org.ngscript.Configuration; import org.ngscript.parseroid.parser.AstNode; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.*; /* * Copyright 2021 wssccc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.ngscript.compiler; /** * @author wssccc */ public class Compiler { private static final Set<String> BINARY_OP = new HashSet<>(Arrays.asList("bit_xor", "bit_or", "bit_and", "eq", "neq", "lt", "gt", "le", "ge", "veq", "vneq", "mul", "mod", "div", "add", "sub")); Configuration configuration; Assembler assembler = new Assembler(); Scanner scanner; int printedLines; Deque<String> continueLabels = new ArrayDeque<>(); Deque<String> breakLabels = new ArrayDeque<>(); Deque<String> finallyLabels = new ArrayDeque<>(); public Compiler(Configuration configuration) { this.configuration = configuration; }
public List<Instruction> compileCode(AstNode ast, String sourceCode) throws CompilerException {
wssccc/ngscript
ngscript-core/src/main/java/org/ngscript/runtime/OpUtils.java
// Path: ngscript-core/src/main/java/org/ngscript/runtime/vo/VmMemRef.java // public class VmMemRef { // // private Object value; // @Getter // private final boolean immutable; // // public VmMemRef() { // this(null, false); // } // // public VmMemRef(Object obj_v) { // this(obj_v, false); // } // // public VmMemRef(Object value, boolean immutable) { // this.value = value; // this.immutable = immutable; // } // // public void write(Object v) { // if (immutable && value != null) { // throw new RuntimeException("immutable"); // } // this.value = v; // } // // public Object read() { // return this.value; // } // // @Override // public String toString() { // return "VmMemRef{" + "value=" + value + '}'; // } // // } // // Path: ngscript-core/src/main/java/org/ngscript/runtime/vo/undefined.java // public class undefined { // // private undefined() { // } // // @Override // public String toString() { // return "undefined"; // } // // public static final undefined value = new undefined(); // }
import org.ngscript.runtime.vo.VmMemRef; import org.ngscript.runtime.vo.undefined;
if (obj instanceof Double) { return ((Double) obj).intValue(); } if (obj instanceof Long) { Long l = (Long) obj; return l.intValue(); } throw new VmRuntimeException(vm, "invalid type"); } static boolean testEq(Object obj1, Object obj2) { if (obj1 == obj2) { return true; } if (obj1 == null || obj2 == null) { return false; } return obj1.toString().equals(obj2.toString()); } static boolean testValue(Object testObj) { boolean val = false; if (testObj == null) { val = false; } else if (testObj instanceof Boolean) { val = ((Boolean) testObj); } else if (testObj instanceof Integer) { val = ((Integer) testObj) != 0; } else if (testObj instanceof Double) { val = Math.abs((Double) testObj) > Double.MIN_NORMAL;
// Path: ngscript-core/src/main/java/org/ngscript/runtime/vo/VmMemRef.java // public class VmMemRef { // // private Object value; // @Getter // private final boolean immutable; // // public VmMemRef() { // this(null, false); // } // // public VmMemRef(Object obj_v) { // this(obj_v, false); // } // // public VmMemRef(Object value, boolean immutable) { // this.value = value; // this.immutable = immutable; // } // // public void write(Object v) { // if (immutable && value != null) { // throw new RuntimeException("immutable"); // } // this.value = v; // } // // public Object read() { // return this.value; // } // // @Override // public String toString() { // return "VmMemRef{" + "value=" + value + '}'; // } // // } // // Path: ngscript-core/src/main/java/org/ngscript/runtime/vo/undefined.java // public class undefined { // // private undefined() { // } // // @Override // public String toString() { // return "undefined"; // } // // public static final undefined value = new undefined(); // } // Path: ngscript-core/src/main/java/org/ngscript/runtime/OpUtils.java import org.ngscript.runtime.vo.VmMemRef; import org.ngscript.runtime.vo.undefined; if (obj instanceof Double) { return ((Double) obj).intValue(); } if (obj instanceof Long) { Long l = (Long) obj; return l.intValue(); } throw new VmRuntimeException(vm, "invalid type"); } static boolean testEq(Object obj1, Object obj2) { if (obj1 == obj2) { return true; } if (obj1 == null || obj2 == null) { return false; } return obj1.toString().equals(obj2.toString()); } static boolean testValue(Object testObj) { boolean val = false; if (testObj == null) { val = false; } else if (testObj instanceof Boolean) { val = ((Boolean) testObj); } else if (testObj instanceof Integer) { val = ((Integer) testObj) != 0; } else if (testObj instanceof Double) { val = Math.abs((Double) testObj) > Double.MIN_NORMAL;
} else if (testObj instanceof undefined) {
wssccc/ngscript
ngscript-core/src/main/java/org/ngscript/runtime/OpUtils.java
// Path: ngscript-core/src/main/java/org/ngscript/runtime/vo/VmMemRef.java // public class VmMemRef { // // private Object value; // @Getter // private final boolean immutable; // // public VmMemRef() { // this(null, false); // } // // public VmMemRef(Object obj_v) { // this(obj_v, false); // } // // public VmMemRef(Object value, boolean immutable) { // this.value = value; // this.immutable = immutable; // } // // public void write(Object v) { // if (immutable && value != null) { // throw new RuntimeException("immutable"); // } // this.value = v; // } // // public Object read() { // return this.value; // } // // @Override // public String toString() { // return "VmMemRef{" + "value=" + value + '}'; // } // // } // // Path: ngscript-core/src/main/java/org/ngscript/runtime/vo/undefined.java // public class undefined { // // private undefined() { // } // // @Override // public String toString() { // return "undefined"; // } // // public static final undefined value = new undefined(); // }
import org.ngscript.runtime.vo.VmMemRef; import org.ngscript.runtime.vo.undefined;
static boolean testEq(Object obj1, Object obj2) { if (obj1 == obj2) { return true; } if (obj1 == null || obj2 == null) { return false; } return obj1.toString().equals(obj2.toString()); } static boolean testValue(Object testObj) { boolean val = false; if (testObj == null) { val = false; } else if (testObj instanceof Boolean) { val = ((Boolean) testObj); } else if (testObj instanceof Integer) { val = ((Integer) testObj) != 0; } else if (testObj instanceof Double) { val = Math.abs((Double) testObj) > Double.MIN_NORMAL; } else if (testObj instanceof undefined) { val = false; } else { //is an object val = true; } return val; } static void addEax(VirtualMachine vm, int num, boolean rewrite) {
// Path: ngscript-core/src/main/java/org/ngscript/runtime/vo/VmMemRef.java // public class VmMemRef { // // private Object value; // @Getter // private final boolean immutable; // // public VmMemRef() { // this(null, false); // } // // public VmMemRef(Object obj_v) { // this(obj_v, false); // } // // public VmMemRef(Object value, boolean immutable) { // this.value = value; // this.immutable = immutable; // } // // public void write(Object v) { // if (immutable && value != null) { // throw new RuntimeException("immutable"); // } // this.value = v; // } // // public Object read() { // return this.value; // } // // @Override // public String toString() { // return "VmMemRef{" + "value=" + value + '}'; // } // // } // // Path: ngscript-core/src/main/java/org/ngscript/runtime/vo/undefined.java // public class undefined { // // private undefined() { // } // // @Override // public String toString() { // return "undefined"; // } // // public static final undefined value = new undefined(); // } // Path: ngscript-core/src/main/java/org/ngscript/runtime/OpUtils.java import org.ngscript.runtime.vo.VmMemRef; import org.ngscript.runtime.vo.undefined; static boolean testEq(Object obj1, Object obj2) { if (obj1 == obj2) { return true; } if (obj1 == null || obj2 == null) { return false; } return obj1.toString().equals(obj2.toString()); } static boolean testValue(Object testObj) { boolean val = false; if (testObj == null) { val = false; } else if (testObj instanceof Boolean) { val = ((Boolean) testObj); } else if (testObj instanceof Integer) { val = ((Integer) testObj) != 0; } else if (testObj instanceof Double) { val = Math.abs((Double) testObj) > Double.MIN_NORMAL; } else if (testObj instanceof undefined) { val = false; } else { //is an object val = true; } return val; } static void addEax(VirtualMachine vm, int num, boolean rewrite) {
VmMemRef addr = (VmMemRef) vm.eax.read();
psidnell/ofexport2
src/test/java/org/psidnell/omnifocus/model/ProjectTest.java
// Path: src/main/java/org/psidnell/omnifocus/ApplicationContextFactory.java // public class ApplicationContextFactory { // // public static final String CONFIG_XML = "/config.xml"; // private static final String CONFIG_PROPERTIES = "/config.properties"; // // public static ApplicationContext getContext() { // return new ClassPathXmlApplicationContext(CONFIG_XML); // } // // public static Properties getConfigProperties() throws IOException { // try ( // InputStream in = ApplicationContextFactory.class.getResourceAsStream(CONFIG_PROPERTIES)) { // if (in == null) { // throw new IOException("config not found"); // } // Properties config = new Properties(); // config.load(in); // return config; // } // } // }
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.Test; import org.psidnell.omnifocus.ApplicationContextFactory; import org.springframework.context.ApplicationContext;
/* * Copyright 2015 Paul Sidnell * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.psidnell.omnifocus.model; public class ProjectTest { private NodeFactory nodeFactory; @Before public void setup () {
// Path: src/main/java/org/psidnell/omnifocus/ApplicationContextFactory.java // public class ApplicationContextFactory { // // public static final String CONFIG_XML = "/config.xml"; // private static final String CONFIG_PROPERTIES = "/config.properties"; // // public static ApplicationContext getContext() { // return new ClassPathXmlApplicationContext(CONFIG_XML); // } // // public static Properties getConfigProperties() throws IOException { // try ( // InputStream in = ApplicationContextFactory.class.getResourceAsStream(CONFIG_PROPERTIES)) { // if (in == null) { // throw new IOException("config not found"); // } // Properties config = new Properties(); // config.load(in); // return config; // } // } // } // Path: src/test/java/org/psidnell/omnifocus/model/ProjectTest.java import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.Test; import org.psidnell.omnifocus.ApplicationContextFactory; import org.springframework.context.ApplicationContext; /* * Copyright 2015 Paul Sidnell * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.psidnell.omnifocus.model; public class ProjectTest { private NodeFactory nodeFactory; @Before public void setup () {
ApplicationContext appContext = ApplicationContextFactory.getContext();
psidnell/ofexport2
src/main/java/org/psidnell/omnifocus/format/FreeMarkerFormatter.java
// Path: src/main/java/org/psidnell/omnifocus/ApplicationContextFactory.java // public class ApplicationContextFactory { // // public static final String CONFIG_XML = "/config.xml"; // private static final String CONFIG_PROPERTIES = "/config.properties"; // // public static ApplicationContext getContext() { // return new ClassPathXmlApplicationContext(CONFIG_XML); // } // // public static Properties getConfigProperties() throws IOException { // try ( // InputStream in = ApplicationContextFactory.class.getResourceAsStream(CONFIG_PROPERTIES)) { // if (in == null) { // throw new IOException("config not found"); // } // Properties config = new Properties(); // config.load(in); // return config; // } // } // } // // Path: src/main/java/org/psidnell/omnifocus/model/Node.java // public interface Node { // // String getName(); // // void setName(String name); // // String getId(); // // void setId(String id); // // int getRank(); // // void setRank(int rank); // // String getType(); // // boolean isRoot(); // // boolean isMarked(); // // void setMarked(boolean marked); // // void cascadeMarked(); // // void setConfigParams(ConfigParams config); // // java.util.Date getDateAdded(); // // void setDateAdded(java.util.Date date); // // org.psidnell.omnifocus.expr.Date getAdded(); // // java.util.Date getDateModified(); // // void setDateModified(java.util.Date date); // // org.psidnell.omnifocus.expr.Date getModified(); // }
import freemarker.template.TemplateExceptionHandler; import java.io.IOException; import java.io.InputStream; import java.io.Writer; import java.util.HashMap; import org.psidnell.omnifocus.ApplicationContextFactory; import org.psidnell.omnifocus.model.Node; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import freemarker.cache.ClassTemplateLoader; import freemarker.cache.TemplateLoader; import freemarker.template.Configuration; import freemarker.template.Template; import freemarker.template.TemplateException;
/* * Copyright 2015 Paul Sidnell * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.psidnell.omnifocus.format; /** * @author psidnell * * Formats the node structure using a FreeMarker template. * */ public class FreeMarkerFormatter implements Formatter { private static final Logger LOGGER = LoggerFactory.getLogger(FreeMarkerFormatter.class); private static final String TEMPLATES = "/templates"; private Template template; private String templateName; public FreeMarkerFormatter(String templateName) throws IOException { // If the resource doesn't exist abort so we can look elsewhere try ( InputStream in = this.getClass().getResourceAsStream(TEMPLATES + "/" + templateName)) { if (in == null) { throw new IOException("Resource not found:" + templateName); } } this.templateName = templateName; Configuration cfg = new Configuration(Configuration.VERSION_2_3_21); TemplateLoader templateLoader = new ClassTemplateLoader(this.getClass(), TEMPLATES); cfg.setTemplateLoader(templateLoader); cfg.setDefaultEncoding("UTF-8"); cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER); // This is fatal - bomb out of application try { template = cfg.getTemplate(templateName); } catch (IOException e) { throw new IllegalArgumentException(e); } } @Override
// Path: src/main/java/org/psidnell/omnifocus/ApplicationContextFactory.java // public class ApplicationContextFactory { // // public static final String CONFIG_XML = "/config.xml"; // private static final String CONFIG_PROPERTIES = "/config.properties"; // // public static ApplicationContext getContext() { // return new ClassPathXmlApplicationContext(CONFIG_XML); // } // // public static Properties getConfigProperties() throws IOException { // try ( // InputStream in = ApplicationContextFactory.class.getResourceAsStream(CONFIG_PROPERTIES)) { // if (in == null) { // throw new IOException("config not found"); // } // Properties config = new Properties(); // config.load(in); // return config; // } // } // } // // Path: src/main/java/org/psidnell/omnifocus/model/Node.java // public interface Node { // // String getName(); // // void setName(String name); // // String getId(); // // void setId(String id); // // int getRank(); // // void setRank(int rank); // // String getType(); // // boolean isRoot(); // // boolean isMarked(); // // void setMarked(boolean marked); // // void cascadeMarked(); // // void setConfigParams(ConfigParams config); // // java.util.Date getDateAdded(); // // void setDateAdded(java.util.Date date); // // org.psidnell.omnifocus.expr.Date getAdded(); // // java.util.Date getDateModified(); // // void setDateModified(java.util.Date date); // // org.psidnell.omnifocus.expr.Date getModified(); // } // Path: src/main/java/org/psidnell/omnifocus/format/FreeMarkerFormatter.java import freemarker.template.TemplateExceptionHandler; import java.io.IOException; import java.io.InputStream; import java.io.Writer; import java.util.HashMap; import org.psidnell.omnifocus.ApplicationContextFactory; import org.psidnell.omnifocus.model.Node; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import freemarker.cache.ClassTemplateLoader; import freemarker.cache.TemplateLoader; import freemarker.template.Configuration; import freemarker.template.Template; import freemarker.template.TemplateException; /* * Copyright 2015 Paul Sidnell * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.psidnell.omnifocus.format; /** * @author psidnell * * Formats the node structure using a FreeMarker template. * */ public class FreeMarkerFormatter implements Formatter { private static final Logger LOGGER = LoggerFactory.getLogger(FreeMarkerFormatter.class); private static final String TEMPLATES = "/templates"; private Template template; private String templateName; public FreeMarkerFormatter(String templateName) throws IOException { // If the resource doesn't exist abort so we can look elsewhere try ( InputStream in = this.getClass().getResourceAsStream(TEMPLATES + "/" + templateName)) { if (in == null) { throw new IOException("Resource not found:" + templateName); } } this.templateName = templateName; Configuration cfg = new Configuration(Configuration.VERSION_2_3_21); TemplateLoader templateLoader = new ClassTemplateLoader(this.getClass(), TEMPLATES); cfg.setTemplateLoader(templateLoader); cfg.setDefaultEncoding("UTF-8"); cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER); // This is fatal - bomb out of application try { template = cfg.getTemplate(templateName); } catch (IOException e) { throw new IllegalArgumentException(e); } } @Override
public void format(Node root, Writer out) throws IOException, TemplateException {
psidnell/ofexport2
src/main/java/org/psidnell/omnifocus/format/FreeMarkerFormatter.java
// Path: src/main/java/org/psidnell/omnifocus/ApplicationContextFactory.java // public class ApplicationContextFactory { // // public static final String CONFIG_XML = "/config.xml"; // private static final String CONFIG_PROPERTIES = "/config.properties"; // // public static ApplicationContext getContext() { // return new ClassPathXmlApplicationContext(CONFIG_XML); // } // // public static Properties getConfigProperties() throws IOException { // try ( // InputStream in = ApplicationContextFactory.class.getResourceAsStream(CONFIG_PROPERTIES)) { // if (in == null) { // throw new IOException("config not found"); // } // Properties config = new Properties(); // config.load(in); // return config; // } // } // } // // Path: src/main/java/org/psidnell/omnifocus/model/Node.java // public interface Node { // // String getName(); // // void setName(String name); // // String getId(); // // void setId(String id); // // int getRank(); // // void setRank(int rank); // // String getType(); // // boolean isRoot(); // // boolean isMarked(); // // void setMarked(boolean marked); // // void cascadeMarked(); // // void setConfigParams(ConfigParams config); // // java.util.Date getDateAdded(); // // void setDateAdded(java.util.Date date); // // org.psidnell.omnifocus.expr.Date getAdded(); // // java.util.Date getDateModified(); // // void setDateModified(java.util.Date date); // // org.psidnell.omnifocus.expr.Date getModified(); // }
import freemarker.template.TemplateExceptionHandler; import java.io.IOException; import java.io.InputStream; import java.io.Writer; import java.util.HashMap; import org.psidnell.omnifocus.ApplicationContextFactory; import org.psidnell.omnifocus.model.Node; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import freemarker.cache.ClassTemplateLoader; import freemarker.cache.TemplateLoader; import freemarker.template.Configuration; import freemarker.template.Template; import freemarker.template.TemplateException;
/* * Copyright 2015 Paul Sidnell * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.psidnell.omnifocus.format; /** * @author psidnell * * Formats the node structure using a FreeMarker template. * */ public class FreeMarkerFormatter implements Formatter { private static final Logger LOGGER = LoggerFactory.getLogger(FreeMarkerFormatter.class); private static final String TEMPLATES = "/templates"; private Template template; private String templateName; public FreeMarkerFormatter(String templateName) throws IOException { // If the resource doesn't exist abort so we can look elsewhere try ( InputStream in = this.getClass().getResourceAsStream(TEMPLATES + "/" + templateName)) { if (in == null) { throw new IOException("Resource not found:" + templateName); } } this.templateName = templateName; Configuration cfg = new Configuration(Configuration.VERSION_2_3_21); TemplateLoader templateLoader = new ClassTemplateLoader(this.getClass(), TEMPLATES); cfg.setTemplateLoader(templateLoader); cfg.setDefaultEncoding("UTF-8"); cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER); // This is fatal - bomb out of application try { template = cfg.getTemplate(templateName); } catch (IOException e) { throw new IllegalArgumentException(e); } } @Override public void format(Node root, Writer out) throws IOException, TemplateException { HashMap<String, Object> fmRoot = new HashMap<>(); fmRoot.put("root", root);
// Path: src/main/java/org/psidnell/omnifocus/ApplicationContextFactory.java // public class ApplicationContextFactory { // // public static final String CONFIG_XML = "/config.xml"; // private static final String CONFIG_PROPERTIES = "/config.properties"; // // public static ApplicationContext getContext() { // return new ClassPathXmlApplicationContext(CONFIG_XML); // } // // public static Properties getConfigProperties() throws IOException { // try ( // InputStream in = ApplicationContextFactory.class.getResourceAsStream(CONFIG_PROPERTIES)) { // if (in == null) { // throw new IOException("config not found"); // } // Properties config = new Properties(); // config.load(in); // return config; // } // } // } // // Path: src/main/java/org/psidnell/omnifocus/model/Node.java // public interface Node { // // String getName(); // // void setName(String name); // // String getId(); // // void setId(String id); // // int getRank(); // // void setRank(int rank); // // String getType(); // // boolean isRoot(); // // boolean isMarked(); // // void setMarked(boolean marked); // // void cascadeMarked(); // // void setConfigParams(ConfigParams config); // // java.util.Date getDateAdded(); // // void setDateAdded(java.util.Date date); // // org.psidnell.omnifocus.expr.Date getAdded(); // // java.util.Date getDateModified(); // // void setDateModified(java.util.Date date); // // org.psidnell.omnifocus.expr.Date getModified(); // } // Path: src/main/java/org/psidnell/omnifocus/format/FreeMarkerFormatter.java import freemarker.template.TemplateExceptionHandler; import java.io.IOException; import java.io.InputStream; import java.io.Writer; import java.util.HashMap; import org.psidnell.omnifocus.ApplicationContextFactory; import org.psidnell.omnifocus.model.Node; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import freemarker.cache.ClassTemplateLoader; import freemarker.cache.TemplateLoader; import freemarker.template.Configuration; import freemarker.template.Template; import freemarker.template.TemplateException; /* * Copyright 2015 Paul Sidnell * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.psidnell.omnifocus.format; /** * @author psidnell * * Formats the node structure using a FreeMarker template. * */ public class FreeMarkerFormatter implements Formatter { private static final Logger LOGGER = LoggerFactory.getLogger(FreeMarkerFormatter.class); private static final String TEMPLATES = "/templates"; private Template template; private String templateName; public FreeMarkerFormatter(String templateName) throws IOException { // If the resource doesn't exist abort so we can look elsewhere try ( InputStream in = this.getClass().getResourceAsStream(TEMPLATES + "/" + templateName)) { if (in == null) { throw new IOException("Resource not found:" + templateName); } } this.templateName = templateName; Configuration cfg = new Configuration(Configuration.VERSION_2_3_21); TemplateLoader templateLoader = new ClassTemplateLoader(this.getClass(), TEMPLATES); cfg.setTemplateLoader(templateLoader); cfg.setDefaultEncoding("UTF-8"); cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER); // This is fatal - bomb out of application try { template = cfg.getTemplate(templateName); } catch (IOException e) { throw new IllegalArgumentException(e); } } @Override public void format(Node root, Writer out) throws IOException, TemplateException { HashMap<String, Object> fmRoot = new HashMap<>(); fmRoot.put("root", root);
fmRoot.put("config", ApplicationContextFactory.getConfigProperties());
psidnell/ofexport2
src/main/java/org/psidnell/omnifocus/visitor/VisitorDescriptor.java
// Path: src/main/java/org/psidnell/omnifocus/model/NodeImpl.java // public abstract class NodeImpl extends ExpressionFunctions implements Node { // // protected String name; // // private String id = UUID.randomUUID().toString(); // // private int rank; // // private boolean marked = false; // // private Date dateAdded; // // private Date dateModified; // // @Override // @SQLiteProperty // @ExprAttribute(help = "item name/text.") // public String getName() { // return name; // } // // @Override // public void setName(String name) { // this.name = name; // } // // @Override // @SQLiteProperty(name = "persistentIdentifier") // public String getId() { // return id; // } // // @Override // public void setId(String id) { // this.id = id; // } // // @Override // @SQLiteProperty // @ExprAttribute(help = "used to define sort order of items.") // public int getRank() { // return rank; // } // // @Override // public void setRank(int rank) { // this.rank = rank; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((id == null) ? 0 : id.hashCode()); // return result; // } // // @Override // @JsonIgnore // public boolean isRoot() { // if (getType().equals(Folder.TYPE) && ((Folder) this).getProjectModeParent() == null) { // return true; // } else if (getType().equals(Context.TYPE) && ((Context) this).getContextModeParent() == null) { // return true; // } // return false; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // NodeImpl other = (NodeImpl) obj; // if (id == null) { // if (other.id != null) { // return false; // } // } else if (!id.equals(other.id)) { // return false; // } // return true; // } // // @Override // public String toString() { // return getType() + ":'" + name + "'"; // } // // @Override // @JsonIgnore // public boolean isMarked() { // return marked; // } // // @Override // public void setMarked(boolean marked) { // this.marked = marked; // } // // @ExprAttribute(help = "true for all nodes.") // @JsonIgnore // public boolean isAll() { // return true; // } // // @Override // @SQLiteProperty // public Date getDateAdded() { // return dateAdded; // } // // @Override // public void setDateAdded(Date date) { // this.dateAdded = date; // } // // @Override // @SQLiteProperty // public Date getDateModified() { // return dateModified; // } // // @Override // public void setDateModified(Date date) { // this.dateModified = date; // } // // @ExprAttribute(help = "added date.") // @JsonIgnore // @Override // public org.psidnell.omnifocus.expr.Date getAdded() { // return new org.psidnell.omnifocus.expr.Date(dateAdded, config); // } // // @ExprAttribute(help = "modified date.") // @JsonIgnore // @Override // public org.psidnell.omnifocus.expr.Date getModified() { // return new org.psidnell.omnifocus.expr.Date(dateModified, config); // } // }
import org.psidnell.omnifocus.model.NodeImpl;
/* * Copyright 2015 Paul Sidnell * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.psidnell.omnifocus.visitor; /** * @author psidnell * * Describes what nodes should be visited during traversal. */ public class VisitorDescriptor { private boolean visitTasks = false; private boolean visitProjects = false; private boolean visitContexts = false; private boolean filterTasks = false; private boolean filterProjects = false; private boolean filterContexts = false; private boolean visitFolders = false; private boolean filterFolders; public VisitorDescriptor visitAll() { visitTasks = true; visitContexts = true; visitProjects = true; visitFolders = true; return this; } public VisitorDescriptor filterAll() { filterTasks = true; filterContexts = true; filterProjects = true; filterFolders = true; return this; } @SafeVarargs
// Path: src/main/java/org/psidnell/omnifocus/model/NodeImpl.java // public abstract class NodeImpl extends ExpressionFunctions implements Node { // // protected String name; // // private String id = UUID.randomUUID().toString(); // // private int rank; // // private boolean marked = false; // // private Date dateAdded; // // private Date dateModified; // // @Override // @SQLiteProperty // @ExprAttribute(help = "item name/text.") // public String getName() { // return name; // } // // @Override // public void setName(String name) { // this.name = name; // } // // @Override // @SQLiteProperty(name = "persistentIdentifier") // public String getId() { // return id; // } // // @Override // public void setId(String id) { // this.id = id; // } // // @Override // @SQLiteProperty // @ExprAttribute(help = "used to define sort order of items.") // public int getRank() { // return rank; // } // // @Override // public void setRank(int rank) { // this.rank = rank; // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((id == null) ? 0 : id.hashCode()); // return result; // } // // @Override // @JsonIgnore // public boolean isRoot() { // if (getType().equals(Folder.TYPE) && ((Folder) this).getProjectModeParent() == null) { // return true; // } else if (getType().equals(Context.TYPE) && ((Context) this).getContextModeParent() == null) { // return true; // } // return false; // } // // @Override // public boolean equals(Object obj) { // if (this == obj) { // return true; // } // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // NodeImpl other = (NodeImpl) obj; // if (id == null) { // if (other.id != null) { // return false; // } // } else if (!id.equals(other.id)) { // return false; // } // return true; // } // // @Override // public String toString() { // return getType() + ":'" + name + "'"; // } // // @Override // @JsonIgnore // public boolean isMarked() { // return marked; // } // // @Override // public void setMarked(boolean marked) { // this.marked = marked; // } // // @ExprAttribute(help = "true for all nodes.") // @JsonIgnore // public boolean isAll() { // return true; // } // // @Override // @SQLiteProperty // public Date getDateAdded() { // return dateAdded; // } // // @Override // public void setDateAdded(Date date) { // this.dateAdded = date; // } // // @Override // @SQLiteProperty // public Date getDateModified() { // return dateModified; // } // // @Override // public void setDateModified(Date date) { // this.dateModified = date; // } // // @ExprAttribute(help = "added date.") // @JsonIgnore // @Override // public org.psidnell.omnifocus.expr.Date getAdded() { // return new org.psidnell.omnifocus.expr.Date(dateAdded, config); // } // // @ExprAttribute(help = "modified date.") // @JsonIgnore // @Override // public org.psidnell.omnifocus.expr.Date getModified() { // return new org.psidnell.omnifocus.expr.Date(dateModified, config); // } // } // Path: src/main/java/org/psidnell/omnifocus/visitor/VisitorDescriptor.java import org.psidnell.omnifocus.model.NodeImpl; /* * Copyright 2015 Paul Sidnell * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.psidnell.omnifocus.visitor; /** * @author psidnell * * Describes what nodes should be visited during traversal. */ public class VisitorDescriptor { private boolean visitTasks = false; private boolean visitProjects = false; private boolean visitContexts = false; private boolean filterTasks = false; private boolean filterProjects = false; private boolean filterContexts = false; private boolean visitFolders = false; private boolean filterFolders; public VisitorDescriptor visitAll() { visitTasks = true; visitContexts = true; visitProjects = true; visitFolders = true; return this; } public VisitorDescriptor filterAll() { filterTasks = true; filterContexts = true; filterProjects = true; filterFolders = true; return this; } @SafeVarargs
public final VisitorDescriptor visit(Class<? extends NodeImpl>... classes) {