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
NeoTech-Software/Android-Retainable-Tasks
demo/src/main/java/org/neotech/app/retainabletasksdemo/activity/DemoActivityLifeCycleLibrary.java
// Path: demo/src/main/java/org/neotech/app/retainabletasksdemo/OnAlertDialogClickListener.java // public interface OnAlertDialogClickListener { // void onDialogFragmentClick(DialogFragment fragment, int which); // } // // Path: demo/src/main/java/org/neotech/app/retainabletasksdemo/ProgressDialog.java // public class ProgressDialog extends DialogFragment implements DialogInterface.OnClickListener { // // public static ProgressDialog getExistingInstance(FragmentManager fragmentManager, String tag){ // return (ProgressDialog) fragmentManager.findFragmentByTag(tag); // } // // public static ProgressDialog showIfNotShowing(FragmentManager fragmentManager, String tag){ // ProgressDialog fragment = (ProgressDialog) fragmentManager.findFragmentByTag(tag); // // if (fragment == null) { // fragment = new ProgressDialog(); // } else if(fragment.isAdded()){ // return fragment; // } // // fragment.show(fragmentManager, tag); // return fragment; // } // // private TextView progressPercentage; // private TextView progressCount; // private ProgressBar progressBar; // private int progress = 0; // // @NonNull // @Override // public Dialog onCreateDialog(Bundle savedInstanceState) { // final AlertDialog.Builder builder = new AlertDialog.Builder(getContext()); // // @SuppressLint("InflateParams") // final View view = LayoutInflater.from(builder.getContext()).inflate(R.layout.dialog_progress, null, false); // progressPercentage = (TextView) view.findViewById(R.id.progress_percentage); // progressCount = (TextView) view.findViewById(R.id.progress_count); // progressBar = (ProgressBar) view.findViewById(android.R.id.progress); // progressBar.setMax(100); // progressBar.setIndeterminate(false); // // builder.setView(view); // builder.setTitle(R.string.dialog_progress_title); // builder.setPositiveButton(R.string.action_cancel, this); // setCancelable(false); // return builder.create(); // } // // @Override // public void onViewCreated(View view, Bundle savedInstanceState) { // if(savedInstanceState != null) { // progress = savedInstanceState.getInt("progress"); // } // setProgress(progress); // } // // @Override // public void onSaveInstanceState(Bundle outState) { // super.onSaveInstanceState(outState); // outState.putInt("progress", progress); // } // // @SuppressLint("SetTextI18n") // public void setProgress(int progress){ // if(getDialog() != null) { // progressBar.setProgress(progress); // int percentage = (int) Math.round(((double) progress / (double) progressBar.getMax()) * 100.0); // progressPercentage.setText("" + percentage + "%"); // progressCount.setText(progress + "/" + progressBar.getMax()); // } // this.progress = progress; // } // // @Override // public void onClick(DialogInterface dialog, int which) { // ((OnAlertDialogClickListener) getActivity()).onDialogFragmentClick(this, which); // } // } // // Path: demo/src/main/java/org/neotech/app/retainabletasksdemo/tasks/SimpleTask.java // public class SimpleTask extends Task<Integer, String> { // // public SimpleTask(String tag) { // super(tag); // } // // @Override // protected String doInBackground() { // for(int i = 0; i < 100; i++) { // if(isCancelled()){ // break; // } // SystemClock.sleep(50); // publishProgress(i); // } // return "Result"; // } // // @Override // protected void onPostExecute() { // Log.i("SimpleTask", "SimpleTask.onPostExecute()"); // } // }
import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.google.android.material.snackbar.Snackbar; import androidx.fragment.app.DialogFragment; import androidx.appcompat.app.AppCompatActivity; import android.view.View; import org.neotech.app.retainabletasksdemo.OnAlertDialogClickListener; import org.neotech.app.retainabletasksdemo.ProgressDialog; import org.neotech.app.retainabletasksdemo.R; import org.neotech.app.retainabletasksdemo.tasks.SimpleTask; import org.neotech.library.retainabletasks.*;
package org.neotech.app.retainabletasksdemo.activity; /** * This demo activity shows how the lifecycle library from the Google Architecture Library can be * used to hook the activity lifecycle calls to the TaskManagerLifeCycleProxy. This example also * uses the annotations just like the DemoActivityAnnotations. * <p> * Created by Rolf Smit on 8-Nov-17. */ public final class DemoActivityLifeCycleLibrary extends AppCompatActivity implements View.OnClickListener, OnAlertDialogClickListener, TaskManagerOwner { private static final String TASK_PROGRESS = "progress-dialog"; private static final String DIALOG_PROGRESS = "progress-dialog";
// Path: demo/src/main/java/org/neotech/app/retainabletasksdemo/OnAlertDialogClickListener.java // public interface OnAlertDialogClickListener { // void onDialogFragmentClick(DialogFragment fragment, int which); // } // // Path: demo/src/main/java/org/neotech/app/retainabletasksdemo/ProgressDialog.java // public class ProgressDialog extends DialogFragment implements DialogInterface.OnClickListener { // // public static ProgressDialog getExistingInstance(FragmentManager fragmentManager, String tag){ // return (ProgressDialog) fragmentManager.findFragmentByTag(tag); // } // // public static ProgressDialog showIfNotShowing(FragmentManager fragmentManager, String tag){ // ProgressDialog fragment = (ProgressDialog) fragmentManager.findFragmentByTag(tag); // // if (fragment == null) { // fragment = new ProgressDialog(); // } else if(fragment.isAdded()){ // return fragment; // } // // fragment.show(fragmentManager, tag); // return fragment; // } // // private TextView progressPercentage; // private TextView progressCount; // private ProgressBar progressBar; // private int progress = 0; // // @NonNull // @Override // public Dialog onCreateDialog(Bundle savedInstanceState) { // final AlertDialog.Builder builder = new AlertDialog.Builder(getContext()); // // @SuppressLint("InflateParams") // final View view = LayoutInflater.from(builder.getContext()).inflate(R.layout.dialog_progress, null, false); // progressPercentage = (TextView) view.findViewById(R.id.progress_percentage); // progressCount = (TextView) view.findViewById(R.id.progress_count); // progressBar = (ProgressBar) view.findViewById(android.R.id.progress); // progressBar.setMax(100); // progressBar.setIndeterminate(false); // // builder.setView(view); // builder.setTitle(R.string.dialog_progress_title); // builder.setPositiveButton(R.string.action_cancel, this); // setCancelable(false); // return builder.create(); // } // // @Override // public void onViewCreated(View view, Bundle savedInstanceState) { // if(savedInstanceState != null) { // progress = savedInstanceState.getInt("progress"); // } // setProgress(progress); // } // // @Override // public void onSaveInstanceState(Bundle outState) { // super.onSaveInstanceState(outState); // outState.putInt("progress", progress); // } // // @SuppressLint("SetTextI18n") // public void setProgress(int progress){ // if(getDialog() != null) { // progressBar.setProgress(progress); // int percentage = (int) Math.round(((double) progress / (double) progressBar.getMax()) * 100.0); // progressPercentage.setText("" + percentage + "%"); // progressCount.setText(progress + "/" + progressBar.getMax()); // } // this.progress = progress; // } // // @Override // public void onClick(DialogInterface dialog, int which) { // ((OnAlertDialogClickListener) getActivity()).onDialogFragmentClick(this, which); // } // } // // Path: demo/src/main/java/org/neotech/app/retainabletasksdemo/tasks/SimpleTask.java // public class SimpleTask extends Task<Integer, String> { // // public SimpleTask(String tag) { // super(tag); // } // // @Override // protected String doInBackground() { // for(int i = 0; i < 100; i++) { // if(isCancelled()){ // break; // } // SystemClock.sleep(50); // publishProgress(i); // } // return "Result"; // } // // @Override // protected void onPostExecute() { // Log.i("SimpleTask", "SimpleTask.onPostExecute()"); // } // } // Path: demo/src/main/java/org/neotech/app/retainabletasksdemo/activity/DemoActivityLifeCycleLibrary.java import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.google.android.material.snackbar.Snackbar; import androidx.fragment.app.DialogFragment; import androidx.appcompat.app.AppCompatActivity; import android.view.View; import org.neotech.app.retainabletasksdemo.OnAlertDialogClickListener; import org.neotech.app.retainabletasksdemo.ProgressDialog; import org.neotech.app.retainabletasksdemo.R; import org.neotech.app.retainabletasksdemo.tasks.SimpleTask; import org.neotech.library.retainabletasks.*; package org.neotech.app.retainabletasksdemo.activity; /** * This demo activity shows how the lifecycle library from the Google Architecture Library can be * used to hook the activity lifecycle calls to the TaskManagerLifeCycleProxy. This example also * uses the annotations just like the DemoActivityAnnotations. * <p> * Created by Rolf Smit on 8-Nov-17. */ public final class DemoActivityLifeCycleLibrary extends AppCompatActivity implements View.OnClickListener, OnAlertDialogClickListener, TaskManagerOwner { private static final String TASK_PROGRESS = "progress-dialog"; private static final String DIALOG_PROGRESS = "progress-dialog";
private ProgressDialog progressDialog;
NeoTech-Software/Android-Retainable-Tasks
demo/src/main/java/org/neotech/app/retainabletasksdemo/activity/DemoActivityLifeCycleLibrary.java
// Path: demo/src/main/java/org/neotech/app/retainabletasksdemo/OnAlertDialogClickListener.java // public interface OnAlertDialogClickListener { // void onDialogFragmentClick(DialogFragment fragment, int which); // } // // Path: demo/src/main/java/org/neotech/app/retainabletasksdemo/ProgressDialog.java // public class ProgressDialog extends DialogFragment implements DialogInterface.OnClickListener { // // public static ProgressDialog getExistingInstance(FragmentManager fragmentManager, String tag){ // return (ProgressDialog) fragmentManager.findFragmentByTag(tag); // } // // public static ProgressDialog showIfNotShowing(FragmentManager fragmentManager, String tag){ // ProgressDialog fragment = (ProgressDialog) fragmentManager.findFragmentByTag(tag); // // if (fragment == null) { // fragment = new ProgressDialog(); // } else if(fragment.isAdded()){ // return fragment; // } // // fragment.show(fragmentManager, tag); // return fragment; // } // // private TextView progressPercentage; // private TextView progressCount; // private ProgressBar progressBar; // private int progress = 0; // // @NonNull // @Override // public Dialog onCreateDialog(Bundle savedInstanceState) { // final AlertDialog.Builder builder = new AlertDialog.Builder(getContext()); // // @SuppressLint("InflateParams") // final View view = LayoutInflater.from(builder.getContext()).inflate(R.layout.dialog_progress, null, false); // progressPercentage = (TextView) view.findViewById(R.id.progress_percentage); // progressCount = (TextView) view.findViewById(R.id.progress_count); // progressBar = (ProgressBar) view.findViewById(android.R.id.progress); // progressBar.setMax(100); // progressBar.setIndeterminate(false); // // builder.setView(view); // builder.setTitle(R.string.dialog_progress_title); // builder.setPositiveButton(R.string.action_cancel, this); // setCancelable(false); // return builder.create(); // } // // @Override // public void onViewCreated(View view, Bundle savedInstanceState) { // if(savedInstanceState != null) { // progress = savedInstanceState.getInt("progress"); // } // setProgress(progress); // } // // @Override // public void onSaveInstanceState(Bundle outState) { // super.onSaveInstanceState(outState); // outState.putInt("progress", progress); // } // // @SuppressLint("SetTextI18n") // public void setProgress(int progress){ // if(getDialog() != null) { // progressBar.setProgress(progress); // int percentage = (int) Math.round(((double) progress / (double) progressBar.getMax()) * 100.0); // progressPercentage.setText("" + percentage + "%"); // progressCount.setText(progress + "/" + progressBar.getMax()); // } // this.progress = progress; // } // // @Override // public void onClick(DialogInterface dialog, int which) { // ((OnAlertDialogClickListener) getActivity()).onDialogFragmentClick(this, which); // } // } // // Path: demo/src/main/java/org/neotech/app/retainabletasksdemo/tasks/SimpleTask.java // public class SimpleTask extends Task<Integer, String> { // // public SimpleTask(String tag) { // super(tag); // } // // @Override // protected String doInBackground() { // for(int i = 0; i < 100; i++) { // if(isCancelled()){ // break; // } // SystemClock.sleep(50); // publishProgress(i); // } // return "Result"; // } // // @Override // protected void onPostExecute() { // Log.i("SimpleTask", "SimpleTask.onPostExecute()"); // } // }
import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.google.android.material.snackbar.Snackbar; import androidx.fragment.app.DialogFragment; import androidx.appcompat.app.AppCompatActivity; import android.view.View; import org.neotech.app.retainabletasksdemo.OnAlertDialogClickListener; import org.neotech.app.retainabletasksdemo.ProgressDialog; import org.neotech.app.retainabletasksdemo.R; import org.neotech.app.retainabletasksdemo.tasks.SimpleTask; import org.neotech.library.retainabletasks.*;
if (savedInstanceState == null) { // After starting this activity directly start the task. execute(); } } @Override public void onClick(View v) { // On click execute the task execute(); } @Override public void onDialogFragmentClick(DialogFragment fragment, int which) { getTaskManager().cancel(TASK_PROGRESS); } @Override public TaskManager getTaskManager() { return taskManagerLifeCycleProxy.getTaskManager(); } @Override public Task.Callback onPreAttach(@NonNull Task<?, ?> task) { return null; } public void execute(){ if(!getTaskManager().isActive(TASK_PROGRESS)) {
// Path: demo/src/main/java/org/neotech/app/retainabletasksdemo/OnAlertDialogClickListener.java // public interface OnAlertDialogClickListener { // void onDialogFragmentClick(DialogFragment fragment, int which); // } // // Path: demo/src/main/java/org/neotech/app/retainabletasksdemo/ProgressDialog.java // public class ProgressDialog extends DialogFragment implements DialogInterface.OnClickListener { // // public static ProgressDialog getExistingInstance(FragmentManager fragmentManager, String tag){ // return (ProgressDialog) fragmentManager.findFragmentByTag(tag); // } // // public static ProgressDialog showIfNotShowing(FragmentManager fragmentManager, String tag){ // ProgressDialog fragment = (ProgressDialog) fragmentManager.findFragmentByTag(tag); // // if (fragment == null) { // fragment = new ProgressDialog(); // } else if(fragment.isAdded()){ // return fragment; // } // // fragment.show(fragmentManager, tag); // return fragment; // } // // private TextView progressPercentage; // private TextView progressCount; // private ProgressBar progressBar; // private int progress = 0; // // @NonNull // @Override // public Dialog onCreateDialog(Bundle savedInstanceState) { // final AlertDialog.Builder builder = new AlertDialog.Builder(getContext()); // // @SuppressLint("InflateParams") // final View view = LayoutInflater.from(builder.getContext()).inflate(R.layout.dialog_progress, null, false); // progressPercentage = (TextView) view.findViewById(R.id.progress_percentage); // progressCount = (TextView) view.findViewById(R.id.progress_count); // progressBar = (ProgressBar) view.findViewById(android.R.id.progress); // progressBar.setMax(100); // progressBar.setIndeterminate(false); // // builder.setView(view); // builder.setTitle(R.string.dialog_progress_title); // builder.setPositiveButton(R.string.action_cancel, this); // setCancelable(false); // return builder.create(); // } // // @Override // public void onViewCreated(View view, Bundle savedInstanceState) { // if(savedInstanceState != null) { // progress = savedInstanceState.getInt("progress"); // } // setProgress(progress); // } // // @Override // public void onSaveInstanceState(Bundle outState) { // super.onSaveInstanceState(outState); // outState.putInt("progress", progress); // } // // @SuppressLint("SetTextI18n") // public void setProgress(int progress){ // if(getDialog() != null) { // progressBar.setProgress(progress); // int percentage = (int) Math.round(((double) progress / (double) progressBar.getMax()) * 100.0); // progressPercentage.setText("" + percentage + "%"); // progressCount.setText(progress + "/" + progressBar.getMax()); // } // this.progress = progress; // } // // @Override // public void onClick(DialogInterface dialog, int which) { // ((OnAlertDialogClickListener) getActivity()).onDialogFragmentClick(this, which); // } // } // // Path: demo/src/main/java/org/neotech/app/retainabletasksdemo/tasks/SimpleTask.java // public class SimpleTask extends Task<Integer, String> { // // public SimpleTask(String tag) { // super(tag); // } // // @Override // protected String doInBackground() { // for(int i = 0; i < 100; i++) { // if(isCancelled()){ // break; // } // SystemClock.sleep(50); // publishProgress(i); // } // return "Result"; // } // // @Override // protected void onPostExecute() { // Log.i("SimpleTask", "SimpleTask.onPostExecute()"); // } // } // Path: demo/src/main/java/org/neotech/app/retainabletasksdemo/activity/DemoActivityLifeCycleLibrary.java import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.google.android.material.snackbar.Snackbar; import androidx.fragment.app.DialogFragment; import androidx.appcompat.app.AppCompatActivity; import android.view.View; import org.neotech.app.retainabletasksdemo.OnAlertDialogClickListener; import org.neotech.app.retainabletasksdemo.ProgressDialog; import org.neotech.app.retainabletasksdemo.R; import org.neotech.app.retainabletasksdemo.tasks.SimpleTask; import org.neotech.library.retainabletasks.*; if (savedInstanceState == null) { // After starting this activity directly start the task. execute(); } } @Override public void onClick(View v) { // On click execute the task execute(); } @Override public void onDialogFragmentClick(DialogFragment fragment, int which) { getTaskManager().cancel(TASK_PROGRESS); } @Override public TaskManager getTaskManager() { return taskManagerLifeCycleProxy.getTaskManager(); } @Override public Task.Callback onPreAttach(@NonNull Task<?, ?> task) { return null; } public void execute(){ if(!getTaskManager().isActive(TASK_PROGRESS)) {
getTaskManager().execute(new SimpleTask(TASK_PROGRESS));
NeoTech-Software/Android-Retainable-Tasks
library/src/main/java/org/neotech/library/retainabletasks/internal/TaskRetainingFragment.java
// Path: library/src/main/java/org/neotech/library/retainabletasks/internal/utilities/HolderFragmentManager.java // @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) // public final class HolderFragmentManager<F extends Fragment> { // // private static final String TAG = HolderFragmentManager.class.getSimpleName(); // // private final String desiredTagInFragmentManager; // private final Class<F> holderFragmentClass; // // private final Map<Activity, F> mNotCommittedActivityHolders = new HashMap<>(); // private final Map<Fragment, F> mNotCommittedFragmentHolders = new HashMap<>(); // // // public HolderFragmentManager(Class<F> holderFragmentClass, String desiredTagInFragmentManager){ // this.desiredTagInFragmentManager = desiredTagInFragmentManager; // this.holderFragmentClass = holderFragmentClass; // Log.d(TAG, "Test: " + holderFragmentClass.getName()); // } // // private final Application.ActivityLifecycleCallbacks mActivityCallbacks = // new EmptyActivityLifecycleCallbacks() { // @Override // public void onActivityDestroyed(Activity activity) { // F fragment = mNotCommittedActivityHolders.remove(activity); // if (fragment != null) { // Log.e(TAG, "Failed to save a holder fragment for " + activity + " with type: " + holderFragmentClass.getName()); // } // } // }; // // private boolean mActivityCallbacksIsAdded = false; // // private final FragmentManager.FragmentLifecycleCallbacks mParentDestroyedCallback = // new FragmentManager.FragmentLifecycleCallbacks() { // @Override // public void onFragmentDestroyed(FragmentManager fm, Fragment parentFragment) { // super.onFragmentDestroyed(fm, parentFragment); // F fragment = mNotCommittedFragmentHolders.remove(parentFragment); // if (fragment != null) { // Log.e(TAG, "Failed to save a holder fragment for " + parentFragment); // } // } // }; // // /** // * This method must be called when an instance of the given retainable fragment is created! // * // * @param fragment the retainable fragment instance that has just been created. // */ // public void onHolderFragmentCreated(F fragment) { // Fragment parentFragment = fragment.getParentFragment(); // if (parentFragment != null) { // mNotCommittedFragmentHolders.remove(parentFragment); // parentFragment.getFragmentManager().unregisterFragmentLifecycleCallbacks( // mParentDestroyedCallback); // } else { // mNotCommittedActivityHolders.remove(fragment.getActivity()); // } // } // // private F findHolderFragment(FragmentManager manager) { // if (manager.isDestroyed()) { // throw new IllegalStateException("Can't access ViewModels from onDestroy"); // } // // return (F) manager.findFragmentByTag(desiredTagInFragmentManager); // } // // private F createHolderFragmentInstance(){ // //noinspection TryWithIdenticalCatches below API 19 catch branches with Reflection exceptions cannot be merged. // try { // return holderFragmentClass.newInstance(); // } catch (InstantiationException e) { // throw new IllegalStateException("Could not create an instance of the given holder fragment class, make sure the class has an public empty constructor!", e); // } catch (IllegalAccessException e) { // throw new IllegalStateException("Could not create an instance of the given holder fragment class, make sure the class has an public empty constructor!", e); // } // } // // private F createHolderFragment(FragmentManager fragmentManager) { // F holder = createHolderFragmentInstance(); // fragmentManager.beginTransaction().add(holder, desiredTagInFragmentManager).commitAllowingStateLoss(); // return holder; // } // // public F retainableFragmentFor(FragmentActivity activity) { // FragmentManager fm = activity.getSupportFragmentManager(); // F holder = findHolderFragment(fm); // if (holder != null) { // return holder; // } // // /* // It can happen that a previous call to a this method for this specific activity has not been // committed yet, but we do need the same instance of the retainable fragment here. // */ // holder = mNotCommittedActivityHolders.get(activity); // if (holder != null) { // return holder; // } // // /* // Register LifecycleCallbacks, if not yet done, so that the not committed holders can be // cleared when the activity is destroyed to prevent memory leaks. // */ // if (!mActivityCallbacksIsAdded) { // mActivityCallbacksIsAdded = true; // activity.getApplication().registerActivityLifecycleCallbacks(mActivityCallbacks); // } // holder = createHolderFragment(fm); // mNotCommittedActivityHolders.put(activity, holder); // return holder; // } // // public F retainableFragmentFor(Fragment forFragment) { // FragmentManager fm = forFragment.getChildFragmentManager(); // F holder = findHolderFragment(fm); // if (holder != null) { // return holder; // } // // /* // It can happen that a previous call to a this method for this specific fragment has not been // committed yet, but we do need the same instance of the retainable fragment here. // */ // holder = mNotCommittedFragmentHolders.get(forFragment); // if (holder != null) { // return holder; // } // // /* // Register LifecycleCallbacks so that the not committed holders can be cleared when the // fragment is destroyed to prevent memory leaks. // */ // forFragment.getFragmentManager().registerFragmentLifecycleCallbacks(mParentDestroyedCallback, false); // holder = createHolderFragment(fm); // mNotCommittedFragmentHolders.put(forFragment, holder); // return holder; // } // }
import android.os.Bundle; import androidx.annotation.RestrictTo; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentActivity; import org.neotech.library.retainabletasks.internal.utilities.HolderFragmentManager;
package org.neotech.library.retainabletasks.internal; /** * Created by Rolf on 29-2-2016. */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) public final class TaskRetainingFragment extends Fragment { public static final String FRAGMENT_TAG = "org.neotech.library.retainabletasks.TaskRetainingFragment";
// Path: library/src/main/java/org/neotech/library/retainabletasks/internal/utilities/HolderFragmentManager.java // @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) // public final class HolderFragmentManager<F extends Fragment> { // // private static final String TAG = HolderFragmentManager.class.getSimpleName(); // // private final String desiredTagInFragmentManager; // private final Class<F> holderFragmentClass; // // private final Map<Activity, F> mNotCommittedActivityHolders = new HashMap<>(); // private final Map<Fragment, F> mNotCommittedFragmentHolders = new HashMap<>(); // // // public HolderFragmentManager(Class<F> holderFragmentClass, String desiredTagInFragmentManager){ // this.desiredTagInFragmentManager = desiredTagInFragmentManager; // this.holderFragmentClass = holderFragmentClass; // Log.d(TAG, "Test: " + holderFragmentClass.getName()); // } // // private final Application.ActivityLifecycleCallbacks mActivityCallbacks = // new EmptyActivityLifecycleCallbacks() { // @Override // public void onActivityDestroyed(Activity activity) { // F fragment = mNotCommittedActivityHolders.remove(activity); // if (fragment != null) { // Log.e(TAG, "Failed to save a holder fragment for " + activity + " with type: " + holderFragmentClass.getName()); // } // } // }; // // private boolean mActivityCallbacksIsAdded = false; // // private final FragmentManager.FragmentLifecycleCallbacks mParentDestroyedCallback = // new FragmentManager.FragmentLifecycleCallbacks() { // @Override // public void onFragmentDestroyed(FragmentManager fm, Fragment parentFragment) { // super.onFragmentDestroyed(fm, parentFragment); // F fragment = mNotCommittedFragmentHolders.remove(parentFragment); // if (fragment != null) { // Log.e(TAG, "Failed to save a holder fragment for " + parentFragment); // } // } // }; // // /** // * This method must be called when an instance of the given retainable fragment is created! // * // * @param fragment the retainable fragment instance that has just been created. // */ // public void onHolderFragmentCreated(F fragment) { // Fragment parentFragment = fragment.getParentFragment(); // if (parentFragment != null) { // mNotCommittedFragmentHolders.remove(parentFragment); // parentFragment.getFragmentManager().unregisterFragmentLifecycleCallbacks( // mParentDestroyedCallback); // } else { // mNotCommittedActivityHolders.remove(fragment.getActivity()); // } // } // // private F findHolderFragment(FragmentManager manager) { // if (manager.isDestroyed()) { // throw new IllegalStateException("Can't access ViewModels from onDestroy"); // } // // return (F) manager.findFragmentByTag(desiredTagInFragmentManager); // } // // private F createHolderFragmentInstance(){ // //noinspection TryWithIdenticalCatches below API 19 catch branches with Reflection exceptions cannot be merged. // try { // return holderFragmentClass.newInstance(); // } catch (InstantiationException e) { // throw new IllegalStateException("Could not create an instance of the given holder fragment class, make sure the class has an public empty constructor!", e); // } catch (IllegalAccessException e) { // throw new IllegalStateException("Could not create an instance of the given holder fragment class, make sure the class has an public empty constructor!", e); // } // } // // private F createHolderFragment(FragmentManager fragmentManager) { // F holder = createHolderFragmentInstance(); // fragmentManager.beginTransaction().add(holder, desiredTagInFragmentManager).commitAllowingStateLoss(); // return holder; // } // // public F retainableFragmentFor(FragmentActivity activity) { // FragmentManager fm = activity.getSupportFragmentManager(); // F holder = findHolderFragment(fm); // if (holder != null) { // return holder; // } // // /* // It can happen that a previous call to a this method for this specific activity has not been // committed yet, but we do need the same instance of the retainable fragment here. // */ // holder = mNotCommittedActivityHolders.get(activity); // if (holder != null) { // return holder; // } // // /* // Register LifecycleCallbacks, if not yet done, so that the not committed holders can be // cleared when the activity is destroyed to prevent memory leaks. // */ // if (!mActivityCallbacksIsAdded) { // mActivityCallbacksIsAdded = true; // activity.getApplication().registerActivityLifecycleCallbacks(mActivityCallbacks); // } // holder = createHolderFragment(fm); // mNotCommittedActivityHolders.put(activity, holder); // return holder; // } // // public F retainableFragmentFor(Fragment forFragment) { // FragmentManager fm = forFragment.getChildFragmentManager(); // F holder = findHolderFragment(fm); // if (holder != null) { // return holder; // } // // /* // It can happen that a previous call to a this method for this specific fragment has not been // committed yet, but we do need the same instance of the retainable fragment here. // */ // holder = mNotCommittedFragmentHolders.get(forFragment); // if (holder != null) { // return holder; // } // // /* // Register LifecycleCallbacks so that the not committed holders can be cleared when the // fragment is destroyed to prevent memory leaks. // */ // forFragment.getFragmentManager().registerFragmentLifecycleCallbacks(mParentDestroyedCallback, false); // holder = createHolderFragment(fm); // mNotCommittedFragmentHolders.put(forFragment, holder); // return holder; // } // } // Path: library/src/main/java/org/neotech/library/retainabletasks/internal/TaskRetainingFragment.java import android.os.Bundle; import androidx.annotation.RestrictTo; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentActivity; import org.neotech.library.retainabletasks.internal.utilities.HolderFragmentManager; package org.neotech.library.retainabletasks.internal; /** * Created by Rolf on 29-2-2016. */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) public final class TaskRetainingFragment extends Fragment { public static final String FRAGMENT_TAG = "org.neotech.library.retainabletasks.TaskRetainingFragment";
private static final HolderFragmentManager<TaskRetainingFragment> sHolderFragmentManager = new HolderFragmentManager<>(TaskRetainingFragment.class, FRAGMENT_TAG);
NeoTech-Software/Android-Retainable-Tasks
demo/src/main/java/org/neotech/app/retainabletasksdemo/activity/DemoActivityFragments.java
// Path: demo/src/main/java/org/neotech/app/retainabletasksdemo/TestFragment.java // public class TestFragment extends TaskFragmentCompat implements View.OnClickListener, Task.AdvancedCallback { // // private Button button; // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View view = inflater.inflate(R.layout.fragment_test, container, false); // button = (Button) view.findViewById(R.id.button_task); // button.setOnClickListener(this); // return view; // } // // @Override // public void onClick(View v) { // CountDownTask task = new CountDownTask("CountDownTask", 10); // getTaskManager().execute(task, this); // button.setEnabled(false); // } // // @Override // public Task.Callback onPreAttach(@NonNull Task<?, ?> task) { // button.setEnabled(false); // button.setText("" + task.getLastKnownProgress()); // return this; // } // // @Override // public void onPreExecute(Task<?, ?> task) { // // } // // @Override // public void onPostExecute(Task<?, ?> task) { // button.setEnabled(true); // button.setText(R.string.task_fragment_based); // Snackbar.make(getView(), getString(R.string.toast_task_finished, getString(R.string.task_fragment_based)), Snackbar.LENGTH_LONG).show(); // } // // @Override // public void onCanceled(Task<?, ?> task) { // // } // // @Override // public void onProgressUpdate(Task<?, ?> task, Object progress) { // button.setText("" + (int) progress); // } // }
import android.content.res.Configuration; import android.os.Bundle; import com.google.android.material.navigation.NavigationView; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import androidx.fragment.app.FragmentTransaction; import androidx.core.view.GravityCompat; import androidx.drawerlayout.widget.DrawerLayout; import androidx.appcompat.app.ActionBarDrawerToggle; import androidx.appcompat.app.AppCompatActivity; import android.util.Log; import android.view.MenuItem; import android.view.View; import org.neotech.app.retainabletasksdemo.R; import org.neotech.app.retainabletasksdemo.TestFragment; import java.util.HashMap;
package org.neotech.app.retainabletasksdemo.activity; public final class DemoActivityFragments extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener { private static final String[] FRAGMENT_TAGS = new String[]{"Fragment 1", "Fragment 2", "Fragment 3"}; private FragmentAdapter adapter; private ActionBarDrawerToggle toggle; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_demo_fragments); adapter = new FragmentAdapter(getSupportFragmentManager(), R.id.fragment_container, 3); for (String FRAGMENT_TAG : FRAGMENT_TAGS) {
// Path: demo/src/main/java/org/neotech/app/retainabletasksdemo/TestFragment.java // public class TestFragment extends TaskFragmentCompat implements View.OnClickListener, Task.AdvancedCallback { // // private Button button; // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // View view = inflater.inflate(R.layout.fragment_test, container, false); // button = (Button) view.findViewById(R.id.button_task); // button.setOnClickListener(this); // return view; // } // // @Override // public void onClick(View v) { // CountDownTask task = new CountDownTask("CountDownTask", 10); // getTaskManager().execute(task, this); // button.setEnabled(false); // } // // @Override // public Task.Callback onPreAttach(@NonNull Task<?, ?> task) { // button.setEnabled(false); // button.setText("" + task.getLastKnownProgress()); // return this; // } // // @Override // public void onPreExecute(Task<?, ?> task) { // // } // // @Override // public void onPostExecute(Task<?, ?> task) { // button.setEnabled(true); // button.setText(R.string.task_fragment_based); // Snackbar.make(getView(), getString(R.string.toast_task_finished, getString(R.string.task_fragment_based)), Snackbar.LENGTH_LONG).show(); // } // // @Override // public void onCanceled(Task<?, ?> task) { // // } // // @Override // public void onProgressUpdate(Task<?, ?> task, Object progress) { // button.setText("" + (int) progress); // } // } // Path: demo/src/main/java/org/neotech/app/retainabletasksdemo/activity/DemoActivityFragments.java import android.content.res.Configuration; import android.os.Bundle; import com.google.android.material.navigation.NavigationView; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import androidx.fragment.app.FragmentTransaction; import androidx.core.view.GravityCompat; import androidx.drawerlayout.widget.DrawerLayout; import androidx.appcompat.app.ActionBarDrawerToggle; import androidx.appcompat.app.AppCompatActivity; import android.util.Log; import android.view.MenuItem; import android.view.View; import org.neotech.app.retainabletasksdemo.R; import org.neotech.app.retainabletasksdemo.TestFragment; import java.util.HashMap; package org.neotech.app.retainabletasksdemo.activity; public final class DemoActivityFragments extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener { private static final String[] FRAGMENT_TAGS = new String[]{"Fragment 1", "Fragment 2", "Fragment 3"}; private FragmentAdapter adapter; private ActionBarDrawerToggle toggle; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_demo_fragments); adapter = new FragmentAdapter(getSupportFragmentManager(), R.id.fragment_container, 3); for (String FRAGMENT_TAG : FRAGMENT_TAGS) {
adapter.addFragment(FRAGMENT_TAG, TestFragment.class);
NeoTech-Software/Android-Retainable-Tasks
library/src/main/java/org/neotech/library/retainabletasks/internal/TaskRetainingFragmentLegacy.java
// Path: library/src/main/java/org/neotech/library/retainabletasks/internal/utilities/HolderFragmentManagerLegacy.java // @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) // public final class HolderFragmentManagerLegacy<F extends Fragment> { // // private static final String TAG = HolderFragmentManagerLegacy.class.getSimpleName(); // // private final String desiredTagInFragmentManager; // private final Class<F> holderFragmentClass; // // private final Map<Activity, F> mNotCommittedActivityHolders = new HashMap<>(); // // public HolderFragmentManagerLegacy(Class<F> holderFragmentClass, String desiredTagInFragmentManager){ // this.desiredTagInFragmentManager = desiredTagInFragmentManager; // this.holderFragmentClass = holderFragmentClass; // } // // private Application.ActivityLifecycleCallbacks mActivityCallbacks = // new EmptyActivityLifecycleCallbacks() { // @Override // public void onActivityDestroyed(Activity activity) { // F fragment = mNotCommittedActivityHolders.remove(activity); // if (fragment != null) { // Log.e(TAG, "Failed to save a ViewModel for " + activity); // } // } // }; // // private boolean mActivityCallbacksIsAdded = false; // // private F findHolderFragment(FragmentManager manager) { // if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN_MR1 && manager.isDestroyed()) { // throw new IllegalStateException("Can't access ViewModels from onDestroy"); // } // // return (F) manager.findFragmentByTag(desiredTagInFragmentManager); // } // // private F createHolderFragmentInstance(){ // try { // return holderFragmentClass.newInstance(); // } catch (InstantiationException e) { // throw new IllegalStateException("Could not create an instance of the given holder fragment class, make sure the class has an public empty constructor!", e); // } catch (IllegalAccessException e) { // throw new IllegalStateException("Could not create an instance of the given holder fragment class, make sure the class has an public empty constructor!", e); // } // } // // private F createHolderFragment(FragmentManager fragmentManager) { // F holder = createHolderFragmentInstance(); // fragmentManager.beginTransaction().add(holder, desiredTagInFragmentManager).commitAllowingStateLoss(); // return holder; // } // // public F retainableFragmentFor(Activity activity) { // FragmentManager fm = activity.getFragmentManager(); // F holder = findHolderFragment(fm); // if (holder != null) { // return holder; // } // holder = mNotCommittedActivityHolders.get(activity); // if (holder != null) { // return holder; // } // // if (!mActivityCallbacksIsAdded) { // mActivityCallbacksIsAdded = true; // activity.getApplication().registerActivityLifecycleCallbacks(mActivityCallbacks); // } // holder = createHolderFragment(fm); // mNotCommittedActivityHolders.put(activity, holder); // return holder; // } // // public F retainableFragmentFor(Fragment fragment) { // final Activity root; // if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { // //Get the root activity // while (fragment.getParentFragment() != null) { // fragment = fragment.getParentFragment(); // } // root = fragment.getActivity(); // } else { // root = fragment.getActivity(); // } // // return retainableFragmentFor(root); // } // }
import android.app.Activity; import android.app.Fragment; import androidx.annotation.RestrictTo; import org.neotech.library.retainabletasks.internal.utilities.HolderFragmentManagerLegacy;
package org.neotech.library.retainabletasks.internal; /** * Created by Rolf on 29-2-2016. */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) public final class TaskRetainingFragmentLegacy extends Fragment { public static final String FRAGMENT_TAG = "org.neotech.library.retainabletasks.TaskRetainingFragment";
// Path: library/src/main/java/org/neotech/library/retainabletasks/internal/utilities/HolderFragmentManagerLegacy.java // @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) // public final class HolderFragmentManagerLegacy<F extends Fragment> { // // private static final String TAG = HolderFragmentManagerLegacy.class.getSimpleName(); // // private final String desiredTagInFragmentManager; // private final Class<F> holderFragmentClass; // // private final Map<Activity, F> mNotCommittedActivityHolders = new HashMap<>(); // // public HolderFragmentManagerLegacy(Class<F> holderFragmentClass, String desiredTagInFragmentManager){ // this.desiredTagInFragmentManager = desiredTagInFragmentManager; // this.holderFragmentClass = holderFragmentClass; // } // // private Application.ActivityLifecycleCallbacks mActivityCallbacks = // new EmptyActivityLifecycleCallbacks() { // @Override // public void onActivityDestroyed(Activity activity) { // F fragment = mNotCommittedActivityHolders.remove(activity); // if (fragment != null) { // Log.e(TAG, "Failed to save a ViewModel for " + activity); // } // } // }; // // private boolean mActivityCallbacksIsAdded = false; // // private F findHolderFragment(FragmentManager manager) { // if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN_MR1 && manager.isDestroyed()) { // throw new IllegalStateException("Can't access ViewModels from onDestroy"); // } // // return (F) manager.findFragmentByTag(desiredTagInFragmentManager); // } // // private F createHolderFragmentInstance(){ // try { // return holderFragmentClass.newInstance(); // } catch (InstantiationException e) { // throw new IllegalStateException("Could not create an instance of the given holder fragment class, make sure the class has an public empty constructor!", e); // } catch (IllegalAccessException e) { // throw new IllegalStateException("Could not create an instance of the given holder fragment class, make sure the class has an public empty constructor!", e); // } // } // // private F createHolderFragment(FragmentManager fragmentManager) { // F holder = createHolderFragmentInstance(); // fragmentManager.beginTransaction().add(holder, desiredTagInFragmentManager).commitAllowingStateLoss(); // return holder; // } // // public F retainableFragmentFor(Activity activity) { // FragmentManager fm = activity.getFragmentManager(); // F holder = findHolderFragment(fm); // if (holder != null) { // return holder; // } // holder = mNotCommittedActivityHolders.get(activity); // if (holder != null) { // return holder; // } // // if (!mActivityCallbacksIsAdded) { // mActivityCallbacksIsAdded = true; // activity.getApplication().registerActivityLifecycleCallbacks(mActivityCallbacks); // } // holder = createHolderFragment(fm); // mNotCommittedActivityHolders.put(activity, holder); // return holder; // } // // public F retainableFragmentFor(Fragment fragment) { // final Activity root; // if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { // //Get the root activity // while (fragment.getParentFragment() != null) { // fragment = fragment.getParentFragment(); // } // root = fragment.getActivity(); // } else { // root = fragment.getActivity(); // } // // return retainableFragmentFor(root); // } // } // Path: library/src/main/java/org/neotech/library/retainabletasks/internal/TaskRetainingFragmentLegacy.java import android.app.Activity; import android.app.Fragment; import androidx.annotation.RestrictTo; import org.neotech.library.retainabletasks.internal.utilities.HolderFragmentManagerLegacy; package org.neotech.library.retainabletasks.internal; /** * Created by Rolf on 29-2-2016. */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) public final class TaskRetainingFragmentLegacy extends Fragment { public static final String FRAGMENT_TAG = "org.neotech.library.retainabletasks.TaskRetainingFragment";
private static final HolderFragmentManagerLegacy<TaskRetainingFragmentLegacy> sHolderFragmentManager = new HolderFragmentManagerLegacy<>(TaskRetainingFragmentLegacy.class, FRAGMENT_TAG);
msk610/Chemtris
desktop/src/com/bms/chemtris/desktop/DesktopLauncher.java
// Path: core/src/com/bms/chemtris/ChemtrisGame.java // public class ChemtrisGame extends Game { // // @Override // public void create () { // ScoreManager.setup(); // setScreen(new Splash()); // } // // @Override // public void render () { // //render super class // super.render(); // // } // // }
import com.badlogic.gdx.backends.lwjgl.LwjglApplication; import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration; import com.bms.chemtris.ChemtrisGame;
package com.bms.chemtris.desktop; public class DesktopLauncher { public static void main (String[] arg) { LwjglApplicationConfiguration config = new LwjglApplicationConfiguration(); config.title = "Chemtris"; //config.width = 1000; //config.height = 800;
// Path: core/src/com/bms/chemtris/ChemtrisGame.java // public class ChemtrisGame extends Game { // // @Override // public void create () { // ScoreManager.setup(); // setScreen(new Splash()); // } // // @Override // public void render () { // //render super class // super.render(); // // } // // } // Path: desktop/src/com/bms/chemtris/desktop/DesktopLauncher.java import com.badlogic.gdx.backends.lwjgl.LwjglApplication; import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration; import com.bms.chemtris.ChemtrisGame; package com.bms.chemtris.desktop; public class DesktopLauncher { public static void main (String[] arg) { LwjglApplicationConfiguration config = new LwjglApplicationConfiguration(); config.title = "Chemtris"; //config.width = 1000; //config.height = 800;
new LwjglApplication(new ChemtrisGame(), config);
msk610/Chemtris
android/src/com/bms/chemtris/AndroidLauncher.java
// Path: core/src/com/bms/chemtris/ChemtrisGame.java // public class ChemtrisGame extends Game { // // @Override // public void create () { // ScoreManager.setup(); // setScreen(new Splash()); // } // // @Override // public void render () { // //render super class // super.render(); // // } // // }
import android.os.Bundle; import com.badlogic.gdx.backends.android.AndroidApplication; import com.badlogic.gdx.backends.android.AndroidApplicationConfiguration; import com.bms.chemtris.ChemtrisGame;
package com.bms.chemtris; public class AndroidLauncher extends AndroidApplication { @Override protected void onCreate (Bundle savedInstanceState) { super.onCreate(savedInstanceState); AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
// Path: core/src/com/bms/chemtris/ChemtrisGame.java // public class ChemtrisGame extends Game { // // @Override // public void create () { // ScoreManager.setup(); // setScreen(new Splash()); // } // // @Override // public void render () { // //render super class // super.render(); // // } // // } // Path: android/src/com/bms/chemtris/AndroidLauncher.java import android.os.Bundle; import com.badlogic.gdx.backends.android.AndroidApplication; import com.badlogic.gdx.backends.android.AndroidApplicationConfiguration; import com.bms.chemtris.ChemtrisGame; package com.bms.chemtris; public class AndroidLauncher extends AndroidApplication { @Override protected void onCreate (Bundle savedInstanceState) { super.onCreate(savedInstanceState); AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
initialize(new ChemtrisGame(), config);
msk610/Chemtris
core/src/com/bms/chemtris/asset/LabelLoader.java
// Path: core/src/com/bms/chemtris/game/ScoreManager.java // public class ScoreManager { // // //preference to store score // private static Preferences scoreManager = Gdx.app.getPreferences("com.bms.chemtris"); // // //level strings // public static final String LEVEL_1 = "level1", // LEVEL_2 = "level2", // LEVEL_3 = "level3", // LEVEL_4 = "level4", // LEVEL_5 = "level5", // LEVEL_6 = "level6", // H2O = "water", // CH4 = "methane"; // // //constructor // public static void setup(){ // //initializing high scores for each level // if(!scoreManager.contains(LEVEL_1)){ // scoreManager.putInteger(LEVEL_1,0); // } // if(!scoreManager.contains(LEVEL_2)){ // scoreManager.putInteger(LEVEL_2,0); // } // if(!scoreManager.contains(LEVEL_3)){ // scoreManager.putInteger(LEVEL_3,0); // } // if(!scoreManager.contains(LEVEL_4)){ // scoreManager.putInteger(LEVEL_4,0); // } // if(!scoreManager.contains(LEVEL_5)){ // scoreManager.putInteger(LEVEL_5,0); // } // if(!scoreManager.contains(LEVEL_6)){ // scoreManager.putInteger(LEVEL_6,0); // } // if(!scoreManager.contains(H2O)){ // scoreManager.putInteger(H2O,0); // } // if(!scoreManager.contains(CH4)){ // scoreManager.putInteger(CH4,0); // } // } // // //method to return high score of a level // public static int getScore(String key){ // return scoreManager.getInteger(key); // } // // //method to set high score of a level // public static void setScore(String key, int score){ // scoreManager.putInteger(key,score); // scoreManager.flush(); // } // // //method to check if ever scored // public static boolean scored(){ // if(scoreManager.getInteger(LEVEL_1) > 0){ // return true; // } // else if(scoreManager.getInteger(LEVEL_2) > 0){ // return true; // } // else if(scoreManager.getInteger(LEVEL_3) > 0){ // return true; // } // else if(scoreManager.getInteger(LEVEL_4) > 0){ // return true; // } // else if(scoreManager.getInteger(LEVEL_5) > 0){ // return true; // } // else if(scoreManager.getInteger(LEVEL_6) > 0){ // return true; // } // else{ // return false; // } // } // }
import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.scenes.scene2d.ui.Label; import com.badlogic.gdx.scenes.scene2d.ui.Label.LabelStyle; import com.bms.chemtris.game.ScoreManager;
package com.bms.chemtris.asset; /** * Class to load labels. */ public class LabelLoader { //heading label style private static final LabelStyle headingStyle = new LabelStyle(FontLoader.font(2.8f), Color.WHITE); private static final LabelStyle bodyStyle = new LabelStyle(FontLoader.font(1.2f), Color.WHITE); private static final LabelStyle scoreStyle = new LabelStyle(FontLoader.font(.75f),Color.WHITE); //method to make heading labels public static Label headingLabel(String title){ Label heading = new Label(title,headingStyle); heading.setPosition(Gdx.graphics.getWidth()/2 - Gdx.graphics.getWidth()/4, Gdx.graphics.getHeight()/2 + Gdx.graphics.getHeight()/4); return heading; } //method to make score labels public static Label levelScore(int level, String tag){ //get score from tag
// Path: core/src/com/bms/chemtris/game/ScoreManager.java // public class ScoreManager { // // //preference to store score // private static Preferences scoreManager = Gdx.app.getPreferences("com.bms.chemtris"); // // //level strings // public static final String LEVEL_1 = "level1", // LEVEL_2 = "level2", // LEVEL_3 = "level3", // LEVEL_4 = "level4", // LEVEL_5 = "level5", // LEVEL_6 = "level6", // H2O = "water", // CH4 = "methane"; // // //constructor // public static void setup(){ // //initializing high scores for each level // if(!scoreManager.contains(LEVEL_1)){ // scoreManager.putInteger(LEVEL_1,0); // } // if(!scoreManager.contains(LEVEL_2)){ // scoreManager.putInteger(LEVEL_2,0); // } // if(!scoreManager.contains(LEVEL_3)){ // scoreManager.putInteger(LEVEL_3,0); // } // if(!scoreManager.contains(LEVEL_4)){ // scoreManager.putInteger(LEVEL_4,0); // } // if(!scoreManager.contains(LEVEL_5)){ // scoreManager.putInteger(LEVEL_5,0); // } // if(!scoreManager.contains(LEVEL_6)){ // scoreManager.putInteger(LEVEL_6,0); // } // if(!scoreManager.contains(H2O)){ // scoreManager.putInteger(H2O,0); // } // if(!scoreManager.contains(CH4)){ // scoreManager.putInteger(CH4,0); // } // } // // //method to return high score of a level // public static int getScore(String key){ // return scoreManager.getInteger(key); // } // // //method to set high score of a level // public static void setScore(String key, int score){ // scoreManager.putInteger(key,score); // scoreManager.flush(); // } // // //method to check if ever scored // public static boolean scored(){ // if(scoreManager.getInteger(LEVEL_1) > 0){ // return true; // } // else if(scoreManager.getInteger(LEVEL_2) > 0){ // return true; // } // else if(scoreManager.getInteger(LEVEL_3) > 0){ // return true; // } // else if(scoreManager.getInteger(LEVEL_4) > 0){ // return true; // } // else if(scoreManager.getInteger(LEVEL_5) > 0){ // return true; // } // else if(scoreManager.getInteger(LEVEL_6) > 0){ // return true; // } // else{ // return false; // } // } // } // Path: core/src/com/bms/chemtris/asset/LabelLoader.java import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.scenes.scene2d.ui.Label; import com.badlogic.gdx.scenes.scene2d.ui.Label.LabelStyle; import com.bms.chemtris.game.ScoreManager; package com.bms.chemtris.asset; /** * Class to load labels. */ public class LabelLoader { //heading label style private static final LabelStyle headingStyle = new LabelStyle(FontLoader.font(2.8f), Color.WHITE); private static final LabelStyle bodyStyle = new LabelStyle(FontLoader.font(1.2f), Color.WHITE); private static final LabelStyle scoreStyle = new LabelStyle(FontLoader.font(.75f),Color.WHITE); //method to make heading labels public static Label headingLabel(String title){ Label heading = new Label(title,headingStyle); heading.setPosition(Gdx.graphics.getWidth()/2 - Gdx.graphics.getWidth()/4, Gdx.graphics.getHeight()/2 + Gdx.graphics.getHeight()/4); return heading; } //method to make score labels public static Label levelScore(int level, String tag){ //get score from tag
int score = ScoreManager.getScore(tag);
msk610/Chemtris
core/src/com/bms/chemtris/screen/Splash.java
// Path: core/src/com/bms/chemtris/asset/TextureLoader.java // public class TextureLoader { // // //splash image texture // private static Texture splash = new Texture("img/splash.png"); // //tutorial image texture // private static Texture tuts = new Texture("img/tutorial.png"); // private static Texture h2o = new Texture("img/wat.png"); // private static Texture ch4 = new Texture("img/ch4.png"); // // //method to load splash texture // public static Texture getSplash(){ // //set a linear filter to clean image // splash.setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear); // //return image // return splash; // } // // //method to load tutorial texture // public static Texture getTut(){ // //set a linear filter to clean image // tuts.setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear); // //return image // return tuts; // } // // //method to load tutorial texture // public static Texture getWat(){ // //set a linear filter to clean image // h2o.setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear); // //return image // return h2o; // } // // //method to load tutorial texture // public static Texture getCh4(){ // //set a linear filter to clean image // ch4.setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear); // //return image // return ch4; // } // // //method to dispose splash texture // public static void disposeSplash(){ // splash.dispose(); // } // // public static void disposeTuts(){ // tuts.dispose(); // } // // public static void disposeWat(){ // h2o.dispose(); // } // // public static void disposeCh4(){ // ch4.dispose(); // } // } // // Path: core/src/com/bms/chemtris/render/Background.java // public class Background { // //member to render background shape // private static final ShapeRenderer shapeRenderer = new ShapeRenderer(); // //light color // private static final Color light = new Color(126f/255f,165f/255f,232f/255f,1f); // //medium color // private static final Color medium = new Color(223f/255f,96f/255f,213f/255f,1f); // //normal color // private static final Color normal = new Color(.94f,.35f,.52f,1f); // //dark color // private static final Color dark = new Color(.99f,.78f,.77f,1f); // // //method to render gradient background // public static void render(){ // //set viewport // Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); // //temporarily clear to normal color // Gdx.gl.glClearColor(42 / 255f, 66 / 255f, 101 / 255f, 1); // Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT); // // //start gradient rendering // shapeRenderer.begin(ShapeRenderer.ShapeType.Filled); // //set colors and size // shapeRenderer.rect(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight(), // dark,normal,medium,light); // //end gradient rendering // shapeRenderer.end(); // // } // // } // // Path: core/src/com/bms/chemtris/tween/SpriteAccessor.java // public class SpriteAccessor implements TweenAccessor<Sprite> { // // //alpha color to effect transparency // public static final int ALPHA = 0; // // //get the alpha value // @Override // public int getValues(Sprite target, int tweenType, float[] returnValues) { // switch (tweenType){ // case ALPHA: // returnValues[0] = target.getColor().a; // return 1; // default: // assert false; // return -1; // } // } // // //set the alpha values // @Override // public void setValues(Sprite target, int tweenType, float[] newValues) { // switch (tweenType){ // case ALPHA: // target.setColor(target.getColor().r, target.getColor().g, target.getColor().b, newValues[0]); // break; // default: // assert false; // break; // } // } // }
import com.badlogic.gdx.Game; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Screen; import com.badlogic.gdx.graphics.g2d.Sprite; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.bms.chemtris.asset.TextureLoader; import com.bms.chemtris.render.Background; import com.bms.chemtris.tween.SpriteAccessor; import aurelienribon.tweenengine.BaseTween; import aurelienribon.tweenengine.Tween; import aurelienribon.tweenengine.TweenCallback; import aurelienribon.tweenengine.TweenManager;
package com.bms.chemtris.screen; /** * Screen to display splash image. */ public class Splash implements Screen { //batch to draw images private SpriteBatch batch; //splash sprite private Sprite splash; //tween animation manager private TweenManager tween; @Override public void show() { //initialize sprite batch batch = new SpriteBatch(); //initialize splash sprite
// Path: core/src/com/bms/chemtris/asset/TextureLoader.java // public class TextureLoader { // // //splash image texture // private static Texture splash = new Texture("img/splash.png"); // //tutorial image texture // private static Texture tuts = new Texture("img/tutorial.png"); // private static Texture h2o = new Texture("img/wat.png"); // private static Texture ch4 = new Texture("img/ch4.png"); // // //method to load splash texture // public static Texture getSplash(){ // //set a linear filter to clean image // splash.setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear); // //return image // return splash; // } // // //method to load tutorial texture // public static Texture getTut(){ // //set a linear filter to clean image // tuts.setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear); // //return image // return tuts; // } // // //method to load tutorial texture // public static Texture getWat(){ // //set a linear filter to clean image // h2o.setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear); // //return image // return h2o; // } // // //method to load tutorial texture // public static Texture getCh4(){ // //set a linear filter to clean image // ch4.setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear); // //return image // return ch4; // } // // //method to dispose splash texture // public static void disposeSplash(){ // splash.dispose(); // } // // public static void disposeTuts(){ // tuts.dispose(); // } // // public static void disposeWat(){ // h2o.dispose(); // } // // public static void disposeCh4(){ // ch4.dispose(); // } // } // // Path: core/src/com/bms/chemtris/render/Background.java // public class Background { // //member to render background shape // private static final ShapeRenderer shapeRenderer = new ShapeRenderer(); // //light color // private static final Color light = new Color(126f/255f,165f/255f,232f/255f,1f); // //medium color // private static final Color medium = new Color(223f/255f,96f/255f,213f/255f,1f); // //normal color // private static final Color normal = new Color(.94f,.35f,.52f,1f); // //dark color // private static final Color dark = new Color(.99f,.78f,.77f,1f); // // //method to render gradient background // public static void render(){ // //set viewport // Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); // //temporarily clear to normal color // Gdx.gl.glClearColor(42 / 255f, 66 / 255f, 101 / 255f, 1); // Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT); // // //start gradient rendering // shapeRenderer.begin(ShapeRenderer.ShapeType.Filled); // //set colors and size // shapeRenderer.rect(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight(), // dark,normal,medium,light); // //end gradient rendering // shapeRenderer.end(); // // } // // } // // Path: core/src/com/bms/chemtris/tween/SpriteAccessor.java // public class SpriteAccessor implements TweenAccessor<Sprite> { // // //alpha color to effect transparency // public static final int ALPHA = 0; // // //get the alpha value // @Override // public int getValues(Sprite target, int tweenType, float[] returnValues) { // switch (tweenType){ // case ALPHA: // returnValues[0] = target.getColor().a; // return 1; // default: // assert false; // return -1; // } // } // // //set the alpha values // @Override // public void setValues(Sprite target, int tweenType, float[] newValues) { // switch (tweenType){ // case ALPHA: // target.setColor(target.getColor().r, target.getColor().g, target.getColor().b, newValues[0]); // break; // default: // assert false; // break; // } // } // } // Path: core/src/com/bms/chemtris/screen/Splash.java import com.badlogic.gdx.Game; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Screen; import com.badlogic.gdx.graphics.g2d.Sprite; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.bms.chemtris.asset.TextureLoader; import com.bms.chemtris.render.Background; import com.bms.chemtris.tween.SpriteAccessor; import aurelienribon.tweenengine.BaseTween; import aurelienribon.tweenengine.Tween; import aurelienribon.tweenengine.TweenCallback; import aurelienribon.tweenengine.TweenManager; package com.bms.chemtris.screen; /** * Screen to display splash image. */ public class Splash implements Screen { //batch to draw images private SpriteBatch batch; //splash sprite private Sprite splash; //tween animation manager private TweenManager tween; @Override public void show() { //initialize sprite batch batch = new SpriteBatch(); //initialize splash sprite
splash = new Sprite(TextureLoader.getSplash());
msk610/Chemtris
core/src/com/bms/chemtris/screen/Splash.java
// Path: core/src/com/bms/chemtris/asset/TextureLoader.java // public class TextureLoader { // // //splash image texture // private static Texture splash = new Texture("img/splash.png"); // //tutorial image texture // private static Texture tuts = new Texture("img/tutorial.png"); // private static Texture h2o = new Texture("img/wat.png"); // private static Texture ch4 = new Texture("img/ch4.png"); // // //method to load splash texture // public static Texture getSplash(){ // //set a linear filter to clean image // splash.setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear); // //return image // return splash; // } // // //method to load tutorial texture // public static Texture getTut(){ // //set a linear filter to clean image // tuts.setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear); // //return image // return tuts; // } // // //method to load tutorial texture // public static Texture getWat(){ // //set a linear filter to clean image // h2o.setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear); // //return image // return h2o; // } // // //method to load tutorial texture // public static Texture getCh4(){ // //set a linear filter to clean image // ch4.setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear); // //return image // return ch4; // } // // //method to dispose splash texture // public static void disposeSplash(){ // splash.dispose(); // } // // public static void disposeTuts(){ // tuts.dispose(); // } // // public static void disposeWat(){ // h2o.dispose(); // } // // public static void disposeCh4(){ // ch4.dispose(); // } // } // // Path: core/src/com/bms/chemtris/render/Background.java // public class Background { // //member to render background shape // private static final ShapeRenderer shapeRenderer = new ShapeRenderer(); // //light color // private static final Color light = new Color(126f/255f,165f/255f,232f/255f,1f); // //medium color // private static final Color medium = new Color(223f/255f,96f/255f,213f/255f,1f); // //normal color // private static final Color normal = new Color(.94f,.35f,.52f,1f); // //dark color // private static final Color dark = new Color(.99f,.78f,.77f,1f); // // //method to render gradient background // public static void render(){ // //set viewport // Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); // //temporarily clear to normal color // Gdx.gl.glClearColor(42 / 255f, 66 / 255f, 101 / 255f, 1); // Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT); // // //start gradient rendering // shapeRenderer.begin(ShapeRenderer.ShapeType.Filled); // //set colors and size // shapeRenderer.rect(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight(), // dark,normal,medium,light); // //end gradient rendering // shapeRenderer.end(); // // } // // } // // Path: core/src/com/bms/chemtris/tween/SpriteAccessor.java // public class SpriteAccessor implements TweenAccessor<Sprite> { // // //alpha color to effect transparency // public static final int ALPHA = 0; // // //get the alpha value // @Override // public int getValues(Sprite target, int tweenType, float[] returnValues) { // switch (tweenType){ // case ALPHA: // returnValues[0] = target.getColor().a; // return 1; // default: // assert false; // return -1; // } // } // // //set the alpha values // @Override // public void setValues(Sprite target, int tweenType, float[] newValues) { // switch (tweenType){ // case ALPHA: // target.setColor(target.getColor().r, target.getColor().g, target.getColor().b, newValues[0]); // break; // default: // assert false; // break; // } // } // }
import com.badlogic.gdx.Game; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Screen; import com.badlogic.gdx.graphics.g2d.Sprite; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.bms.chemtris.asset.TextureLoader; import com.bms.chemtris.render.Background; import com.bms.chemtris.tween.SpriteAccessor; import aurelienribon.tweenengine.BaseTween; import aurelienribon.tweenengine.Tween; import aurelienribon.tweenengine.TweenCallback; import aurelienribon.tweenengine.TweenManager;
package com.bms.chemtris.screen; /** * Screen to display splash image. */ public class Splash implements Screen { //batch to draw images private SpriteBatch batch; //splash sprite private Sprite splash; //tween animation manager private TweenManager tween; @Override public void show() { //initialize sprite batch batch = new SpriteBatch(); //initialize splash sprite splash = new Sprite(TextureLoader.getSplash()); //set splash size splash.setSize(Gdx.graphics.getWidth(),Gdx.graphics.getHeight()); //setup animation tween = new TweenManager();
// Path: core/src/com/bms/chemtris/asset/TextureLoader.java // public class TextureLoader { // // //splash image texture // private static Texture splash = new Texture("img/splash.png"); // //tutorial image texture // private static Texture tuts = new Texture("img/tutorial.png"); // private static Texture h2o = new Texture("img/wat.png"); // private static Texture ch4 = new Texture("img/ch4.png"); // // //method to load splash texture // public static Texture getSplash(){ // //set a linear filter to clean image // splash.setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear); // //return image // return splash; // } // // //method to load tutorial texture // public static Texture getTut(){ // //set a linear filter to clean image // tuts.setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear); // //return image // return tuts; // } // // //method to load tutorial texture // public static Texture getWat(){ // //set a linear filter to clean image // h2o.setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear); // //return image // return h2o; // } // // //method to load tutorial texture // public static Texture getCh4(){ // //set a linear filter to clean image // ch4.setFilter(Texture.TextureFilter.Linear, Texture.TextureFilter.Linear); // //return image // return ch4; // } // // //method to dispose splash texture // public static void disposeSplash(){ // splash.dispose(); // } // // public static void disposeTuts(){ // tuts.dispose(); // } // // public static void disposeWat(){ // h2o.dispose(); // } // // public static void disposeCh4(){ // ch4.dispose(); // } // } // // Path: core/src/com/bms/chemtris/render/Background.java // public class Background { // //member to render background shape // private static final ShapeRenderer shapeRenderer = new ShapeRenderer(); // //light color // private static final Color light = new Color(126f/255f,165f/255f,232f/255f,1f); // //medium color // private static final Color medium = new Color(223f/255f,96f/255f,213f/255f,1f); // //normal color // private static final Color normal = new Color(.94f,.35f,.52f,1f); // //dark color // private static final Color dark = new Color(.99f,.78f,.77f,1f); // // //method to render gradient background // public static void render(){ // //set viewport // Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); // //temporarily clear to normal color // Gdx.gl.glClearColor(42 / 255f, 66 / 255f, 101 / 255f, 1); // Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT); // // //start gradient rendering // shapeRenderer.begin(ShapeRenderer.ShapeType.Filled); // //set colors and size // shapeRenderer.rect(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight(), // dark,normal,medium,light); // //end gradient rendering // shapeRenderer.end(); // // } // // } // // Path: core/src/com/bms/chemtris/tween/SpriteAccessor.java // public class SpriteAccessor implements TweenAccessor<Sprite> { // // //alpha color to effect transparency // public static final int ALPHA = 0; // // //get the alpha value // @Override // public int getValues(Sprite target, int tweenType, float[] returnValues) { // switch (tweenType){ // case ALPHA: // returnValues[0] = target.getColor().a; // return 1; // default: // assert false; // return -1; // } // } // // //set the alpha values // @Override // public void setValues(Sprite target, int tweenType, float[] newValues) { // switch (tweenType){ // case ALPHA: // target.setColor(target.getColor().r, target.getColor().g, target.getColor().b, newValues[0]); // break; // default: // assert false; // break; // } // } // } // Path: core/src/com/bms/chemtris/screen/Splash.java import com.badlogic.gdx.Game; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Screen; import com.badlogic.gdx.graphics.g2d.Sprite; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.bms.chemtris.asset.TextureLoader; import com.bms.chemtris.render.Background; import com.bms.chemtris.tween.SpriteAccessor; import aurelienribon.tweenengine.BaseTween; import aurelienribon.tweenengine.Tween; import aurelienribon.tweenengine.TweenCallback; import aurelienribon.tweenengine.TweenManager; package com.bms.chemtris.screen; /** * Screen to display splash image. */ public class Splash implements Screen { //batch to draw images private SpriteBatch batch; //splash sprite private Sprite splash; //tween animation manager private TweenManager tween; @Override public void show() { //initialize sprite batch batch = new SpriteBatch(); //initialize splash sprite splash = new Sprite(TextureLoader.getSplash()); //set splash size splash.setSize(Gdx.graphics.getWidth(),Gdx.graphics.getHeight()); //setup animation tween = new TweenManager();
Tween.registerAccessor(Sprite.class, new SpriteAccessor());
msk610/Chemtris
core/src/com/bms/chemtris/models/Platform.java
// Path: core/src/com/bms/chemtris/render/WireframeShader.java // public class WireframeShader extends DefaultShader { // // public static final int PRIMITIVE_TYPE = GL20.GL_LINE_STRIP; // private int mSavedPrimitiveType; // // public WireframeShader(Renderable renderable) { // super(renderable); // } // // public WireframeShader(Renderable renderable, Config config) { // super(renderable, config); // } // // public WireframeShader(Renderable renderable, Config config, String prefix) { // super(renderable, config, prefix); // } // // public WireframeShader(Renderable renderable, Config config, String prefix, String vertexShader, String fragmentShader) { // super(renderable, config, prefix, vertexShader, fragmentShader); // } // // public WireframeShader(Renderable renderable, Config config, ShaderProgram shaderProgram) { // super(renderable, config, shaderProgram); // } // // @Override // public void render(Renderable renderable) { // setPrimitiveType(renderable); // super.render(renderable); // restorePrimitiveType(renderable); // } // // @Override // public void render(Renderable renderable, Attributes combinedAttributes) { // setPrimitiveType(renderable); // super.render(renderable, combinedAttributes); // restorePrimitiveType(renderable); // } // // private void restorePrimitiveType(Renderable renderable) { // renderable.meshPart.primitiveType = mSavedPrimitiveType; // } // // private void setPrimitiveType(Renderable renderable) { // mSavedPrimitiveType = renderable.meshPart.primitiveType; // renderable.meshPart.primitiveType = PRIMITIVE_TYPE; // } // }
import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.PerspectiveCamera; import com.badlogic.gdx.graphics.VertexAttributes; import com.badlogic.gdx.graphics.g3d.Environment; import com.badlogic.gdx.graphics.g3d.Material; import com.badlogic.gdx.graphics.g3d.Model; import com.badlogic.gdx.graphics.g3d.ModelBatch; import com.badlogic.gdx.graphics.g3d.ModelInstance; import com.badlogic.gdx.graphics.g3d.Renderable; import com.badlogic.gdx.graphics.g3d.Shader; import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute; import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight; import com.badlogic.gdx.graphics.g3d.utils.DefaultShaderProvider; import com.badlogic.gdx.graphics.g3d.utils.ModelBuilder; import com.badlogic.gdx.utils.Array; import com.bms.chemtris.render.WireframeShader;
package com.bms.chemtris.models; /** * Class to make platform. */ public class Platform { //platform parts public Array<ModelInstance> parts; //platform wires public Array<ModelInstance> wires; //platform box public ModelInstance box; private static Environment environment; //rendering environment //ModelBatch Renderer and Wireframe shader private static final ModelBatch fillRenderer = new ModelBatch(); private static final ModelBatch wireRenderer = new ModelBatch(new DefaultShaderProvider() { @Override protected Shader createShader(Renderable renderable) {
// Path: core/src/com/bms/chemtris/render/WireframeShader.java // public class WireframeShader extends DefaultShader { // // public static final int PRIMITIVE_TYPE = GL20.GL_LINE_STRIP; // private int mSavedPrimitiveType; // // public WireframeShader(Renderable renderable) { // super(renderable); // } // // public WireframeShader(Renderable renderable, Config config) { // super(renderable, config); // } // // public WireframeShader(Renderable renderable, Config config, String prefix) { // super(renderable, config, prefix); // } // // public WireframeShader(Renderable renderable, Config config, String prefix, String vertexShader, String fragmentShader) { // super(renderable, config, prefix, vertexShader, fragmentShader); // } // // public WireframeShader(Renderable renderable, Config config, ShaderProgram shaderProgram) { // super(renderable, config, shaderProgram); // } // // @Override // public void render(Renderable renderable) { // setPrimitiveType(renderable); // super.render(renderable); // restorePrimitiveType(renderable); // } // // @Override // public void render(Renderable renderable, Attributes combinedAttributes) { // setPrimitiveType(renderable); // super.render(renderable, combinedAttributes); // restorePrimitiveType(renderable); // } // // private void restorePrimitiveType(Renderable renderable) { // renderable.meshPart.primitiveType = mSavedPrimitiveType; // } // // private void setPrimitiveType(Renderable renderable) { // mSavedPrimitiveType = renderable.meshPart.primitiveType; // renderable.meshPart.primitiveType = PRIMITIVE_TYPE; // } // } // Path: core/src/com/bms/chemtris/models/Platform.java import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.PerspectiveCamera; import com.badlogic.gdx.graphics.VertexAttributes; import com.badlogic.gdx.graphics.g3d.Environment; import com.badlogic.gdx.graphics.g3d.Material; import com.badlogic.gdx.graphics.g3d.Model; import com.badlogic.gdx.graphics.g3d.ModelBatch; import com.badlogic.gdx.graphics.g3d.ModelInstance; import com.badlogic.gdx.graphics.g3d.Renderable; import com.badlogic.gdx.graphics.g3d.Shader; import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute; import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight; import com.badlogic.gdx.graphics.g3d.utils.DefaultShaderProvider; import com.badlogic.gdx.graphics.g3d.utils.ModelBuilder; import com.badlogic.gdx.utils.Array; import com.bms.chemtris.render.WireframeShader; package com.bms.chemtris.models; /** * Class to make platform. */ public class Platform { //platform parts public Array<ModelInstance> parts; //platform wires public Array<ModelInstance> wires; //platform box public ModelInstance box; private static Environment environment; //rendering environment //ModelBatch Renderer and Wireframe shader private static final ModelBatch fillRenderer = new ModelBatch(); private static final ModelBatch wireRenderer = new ModelBatch(new DefaultShaderProvider() { @Override protected Shader createShader(Renderable renderable) {
return new WireframeShader(renderable, config);
msk610/Chemtris
core/src/com/bms/chemtris/elements/Element.java
// Path: core/src/com/bms/chemtris/render/WireframeShader.java // public class WireframeShader extends DefaultShader { // // public static final int PRIMITIVE_TYPE = GL20.GL_LINE_STRIP; // private int mSavedPrimitiveType; // // public WireframeShader(Renderable renderable) { // super(renderable); // } // // public WireframeShader(Renderable renderable, Config config) { // super(renderable, config); // } // // public WireframeShader(Renderable renderable, Config config, String prefix) { // super(renderable, config, prefix); // } // // public WireframeShader(Renderable renderable, Config config, String prefix, String vertexShader, String fragmentShader) { // super(renderable, config, prefix, vertexShader, fragmentShader); // } // // public WireframeShader(Renderable renderable, Config config, ShaderProgram shaderProgram) { // super(renderable, config, shaderProgram); // } // // @Override // public void render(Renderable renderable) { // setPrimitiveType(renderable); // super.render(renderable); // restorePrimitiveType(renderable); // } // // @Override // public void render(Renderable renderable, Attributes combinedAttributes) { // setPrimitiveType(renderable); // super.render(renderable, combinedAttributes); // restorePrimitiveType(renderable); // } // // private void restorePrimitiveType(Renderable renderable) { // renderable.meshPart.primitiveType = mSavedPrimitiveType; // } // // private void setPrimitiveType(Renderable renderable) { // mSavedPrimitiveType = renderable.meshPart.primitiveType; // renderable.meshPart.primitiveType = PRIMITIVE_TYPE; // } // }
import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.PerspectiveCamera; import com.badlogic.gdx.graphics.g3d.Environment; import com.badlogic.gdx.graphics.g3d.ModelBatch; import com.badlogic.gdx.graphics.g3d.ModelInstance; import com.badlogic.gdx.graphics.g3d.Renderable; import com.badlogic.gdx.graphics.g3d.Shader; import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute; import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight; import com.badlogic.gdx.graphics.g3d.utils.DefaultShaderProvider; import com.badlogic.gdx.graphics.g3d.utils.ModelBuilder; import com.badlogic.gdx.math.Vector3; import com.bms.chemtris.render.WireframeShader;
package com.bms.chemtris.elements; /** * Class to make an element. */ public class Element { //collision matrix private boolean [][][] matrix; //model instances public ModelInstance atom, shadow, frame; //number of valence electrons private int valence; //perspective camera private PerspectiveCamera camera; private static Environment environment; //rendering environment //ModelBatch Renderer and Wireframe shader private static final ModelBatch fillRenderer = new ModelBatch(); private static final ModelBatch wireRenderer = new ModelBatch(new DefaultShaderProvider() { @Override protected Shader createShader(Renderable renderable) {
// Path: core/src/com/bms/chemtris/render/WireframeShader.java // public class WireframeShader extends DefaultShader { // // public static final int PRIMITIVE_TYPE = GL20.GL_LINE_STRIP; // private int mSavedPrimitiveType; // // public WireframeShader(Renderable renderable) { // super(renderable); // } // // public WireframeShader(Renderable renderable, Config config) { // super(renderable, config); // } // // public WireframeShader(Renderable renderable, Config config, String prefix) { // super(renderable, config, prefix); // } // // public WireframeShader(Renderable renderable, Config config, String prefix, String vertexShader, String fragmentShader) { // super(renderable, config, prefix, vertexShader, fragmentShader); // } // // public WireframeShader(Renderable renderable, Config config, ShaderProgram shaderProgram) { // super(renderable, config, shaderProgram); // } // // @Override // public void render(Renderable renderable) { // setPrimitiveType(renderable); // super.render(renderable); // restorePrimitiveType(renderable); // } // // @Override // public void render(Renderable renderable, Attributes combinedAttributes) { // setPrimitiveType(renderable); // super.render(renderable, combinedAttributes); // restorePrimitiveType(renderable); // } // // private void restorePrimitiveType(Renderable renderable) { // renderable.meshPart.primitiveType = mSavedPrimitiveType; // } // // private void setPrimitiveType(Renderable renderable) { // mSavedPrimitiveType = renderable.meshPart.primitiveType; // renderable.meshPart.primitiveType = PRIMITIVE_TYPE; // } // } // Path: core/src/com/bms/chemtris/elements/Element.java import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.PerspectiveCamera; import com.badlogic.gdx.graphics.g3d.Environment; import com.badlogic.gdx.graphics.g3d.ModelBatch; import com.badlogic.gdx.graphics.g3d.ModelInstance; import com.badlogic.gdx.graphics.g3d.Renderable; import com.badlogic.gdx.graphics.g3d.Shader; import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute; import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight; import com.badlogic.gdx.graphics.g3d.utils.DefaultShaderProvider; import com.badlogic.gdx.graphics.g3d.utils.ModelBuilder; import com.badlogic.gdx.math.Vector3; import com.bms.chemtris.render.WireframeShader; package com.bms.chemtris.elements; /** * Class to make an element. */ public class Element { //collision matrix private boolean [][][] matrix; //model instances public ModelInstance atom, shadow, frame; //number of valence electrons private int valence; //perspective camera private PerspectiveCamera camera; private static Environment environment; //rendering environment //ModelBatch Renderer and Wireframe shader private static final ModelBatch fillRenderer = new ModelBatch(); private static final ModelBatch wireRenderer = new ModelBatch(new DefaultShaderProvider() { @Override protected Shader createShader(Renderable renderable) {
return new WireframeShader(renderable, config);
msk610/Chemtris
core/src/com/bms/chemtris/models/GameModel.java
// Path: core/src/com/bms/chemtris/render/WireframeShader.java // public class WireframeShader extends DefaultShader { // // public static final int PRIMITIVE_TYPE = GL20.GL_LINE_STRIP; // private int mSavedPrimitiveType; // // public WireframeShader(Renderable renderable) { // super(renderable); // } // // public WireframeShader(Renderable renderable, Config config) { // super(renderable, config); // } // // public WireframeShader(Renderable renderable, Config config, String prefix) { // super(renderable, config, prefix); // } // // public WireframeShader(Renderable renderable, Config config, String prefix, String vertexShader, String fragmentShader) { // super(renderable, config, prefix, vertexShader, fragmentShader); // } // // public WireframeShader(Renderable renderable, Config config, ShaderProgram shaderProgram) { // super(renderable, config, shaderProgram); // } // // @Override // public void render(Renderable renderable) { // setPrimitiveType(renderable); // super.render(renderable); // restorePrimitiveType(renderable); // } // // @Override // public void render(Renderable renderable, Attributes combinedAttributes) { // setPrimitiveType(renderable); // super.render(renderable, combinedAttributes); // restorePrimitiveType(renderable); // } // // private void restorePrimitiveType(Renderable renderable) { // renderable.meshPart.primitiveType = mSavedPrimitiveType; // } // // private void setPrimitiveType(Renderable renderable) { // mSavedPrimitiveType = renderable.meshPart.primitiveType; // renderable.meshPart.primitiveType = PRIMITIVE_TYPE; // } // }
import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.PerspectiveCamera; import com.badlogic.gdx.graphics.VertexAttributes; import com.badlogic.gdx.graphics.g3d.Environment; import com.badlogic.gdx.graphics.g3d.Material; import com.badlogic.gdx.graphics.g3d.Model; import com.badlogic.gdx.graphics.g3d.ModelBatch; import com.badlogic.gdx.graphics.g3d.ModelInstance; import com.badlogic.gdx.graphics.g3d.Renderable; import com.badlogic.gdx.graphics.g3d.Shader; import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute; import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight; import com.badlogic.gdx.graphics.g3d.utils.DefaultShaderProvider; import com.badlogic.gdx.graphics.g3d.utils.ModelBuilder; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.utils.Array; import com.bms.chemtris.render.WireframeShader;
package com.bms.chemtris.models; /** * Class to control all game models. */ public abstract class GameModel { public Array<ModelInstance> parts; //model parts public Array<ModelInstance>shadow; //model shadow public Array<ModelInstance>frame; //model frame //model builder to make the model private static final ModelBuilder builder = new ModelBuilder(); //3d models to make up the parts public static final Model white = builder.createBox( 1f,1f,1f, new Material(ColorAttribute.createDiffuse(Color.WHITE)), VertexAttributes.Usage.Position | VertexAttributes.Usage.Normal ); public static final Model gray = builder.createBox( 1f,1f,1f, new Material(ColorAttribute.createDiffuse(105/255f,105/255f,105/255f,1f)), VertexAttributes.Usage.Position | VertexAttributes.Usage.Normal ); public static final Model wire = builder.createBox( 1.01f,1.01f,1.01f, new Material(ColorAttribute.createDiffuse(184/255f,182/255f,182/255f,1f)), VertexAttributes.Usage.Position | VertexAttributes.Usage.Normal ); private static Environment environment; //rendering environment //ModelBatch Renderer and Wireframe shader private static final ModelBatch fillRenderer = new ModelBatch(); private static final ModelBatch wireRenderer = new ModelBatch(new DefaultShaderProvider() { @Override protected Shader createShader(Renderable renderable) {
// Path: core/src/com/bms/chemtris/render/WireframeShader.java // public class WireframeShader extends DefaultShader { // // public static final int PRIMITIVE_TYPE = GL20.GL_LINE_STRIP; // private int mSavedPrimitiveType; // // public WireframeShader(Renderable renderable) { // super(renderable); // } // // public WireframeShader(Renderable renderable, Config config) { // super(renderable, config); // } // // public WireframeShader(Renderable renderable, Config config, String prefix) { // super(renderable, config, prefix); // } // // public WireframeShader(Renderable renderable, Config config, String prefix, String vertexShader, String fragmentShader) { // super(renderable, config, prefix, vertexShader, fragmentShader); // } // // public WireframeShader(Renderable renderable, Config config, ShaderProgram shaderProgram) { // super(renderable, config, shaderProgram); // } // // @Override // public void render(Renderable renderable) { // setPrimitiveType(renderable); // super.render(renderable); // restorePrimitiveType(renderable); // } // // @Override // public void render(Renderable renderable, Attributes combinedAttributes) { // setPrimitiveType(renderable); // super.render(renderable, combinedAttributes); // restorePrimitiveType(renderable); // } // // private void restorePrimitiveType(Renderable renderable) { // renderable.meshPart.primitiveType = mSavedPrimitiveType; // } // // private void setPrimitiveType(Renderable renderable) { // mSavedPrimitiveType = renderable.meshPart.primitiveType; // renderable.meshPart.primitiveType = PRIMITIVE_TYPE; // } // } // Path: core/src/com/bms/chemtris/models/GameModel.java import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.PerspectiveCamera; import com.badlogic.gdx.graphics.VertexAttributes; import com.badlogic.gdx.graphics.g3d.Environment; import com.badlogic.gdx.graphics.g3d.Material; import com.badlogic.gdx.graphics.g3d.Model; import com.badlogic.gdx.graphics.g3d.ModelBatch; import com.badlogic.gdx.graphics.g3d.ModelInstance; import com.badlogic.gdx.graphics.g3d.Renderable; import com.badlogic.gdx.graphics.g3d.Shader; import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute; import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight; import com.badlogic.gdx.graphics.g3d.utils.DefaultShaderProvider; import com.badlogic.gdx.graphics.g3d.utils.ModelBuilder; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.utils.Array; import com.bms.chemtris.render.WireframeShader; package com.bms.chemtris.models; /** * Class to control all game models. */ public abstract class GameModel { public Array<ModelInstance> parts; //model parts public Array<ModelInstance>shadow; //model shadow public Array<ModelInstance>frame; //model frame //model builder to make the model private static final ModelBuilder builder = new ModelBuilder(); //3d models to make up the parts public static final Model white = builder.createBox( 1f,1f,1f, new Material(ColorAttribute.createDiffuse(Color.WHITE)), VertexAttributes.Usage.Position | VertexAttributes.Usage.Normal ); public static final Model gray = builder.createBox( 1f,1f,1f, new Material(ColorAttribute.createDiffuse(105/255f,105/255f,105/255f,1f)), VertexAttributes.Usage.Position | VertexAttributes.Usage.Normal ); public static final Model wire = builder.createBox( 1.01f,1.01f,1.01f, new Material(ColorAttribute.createDiffuse(184/255f,182/255f,182/255f,1f)), VertexAttributes.Usage.Position | VertexAttributes.Usage.Normal ); private static Environment environment; //rendering environment //ModelBatch Renderer and Wireframe shader private static final ModelBatch fillRenderer = new ModelBatch(); private static final ModelBatch wireRenderer = new ModelBatch(new DefaultShaderProvider() { @Override protected Shader createShader(Renderable renderable) {
return new WireframeShader(renderable, config);
msk610/Chemtris
core/src/com/bms/chemtris/ChemtrisGame.java
// Path: core/src/com/bms/chemtris/game/ScoreManager.java // public class ScoreManager { // // //preference to store score // private static Preferences scoreManager = Gdx.app.getPreferences("com.bms.chemtris"); // // //level strings // public static final String LEVEL_1 = "level1", // LEVEL_2 = "level2", // LEVEL_3 = "level3", // LEVEL_4 = "level4", // LEVEL_5 = "level5", // LEVEL_6 = "level6", // H2O = "water", // CH4 = "methane"; // // //constructor // public static void setup(){ // //initializing high scores for each level // if(!scoreManager.contains(LEVEL_1)){ // scoreManager.putInteger(LEVEL_1,0); // } // if(!scoreManager.contains(LEVEL_2)){ // scoreManager.putInteger(LEVEL_2,0); // } // if(!scoreManager.contains(LEVEL_3)){ // scoreManager.putInteger(LEVEL_3,0); // } // if(!scoreManager.contains(LEVEL_4)){ // scoreManager.putInteger(LEVEL_4,0); // } // if(!scoreManager.contains(LEVEL_5)){ // scoreManager.putInteger(LEVEL_5,0); // } // if(!scoreManager.contains(LEVEL_6)){ // scoreManager.putInteger(LEVEL_6,0); // } // if(!scoreManager.contains(H2O)){ // scoreManager.putInteger(H2O,0); // } // if(!scoreManager.contains(CH4)){ // scoreManager.putInteger(CH4,0); // } // } // // //method to return high score of a level // public static int getScore(String key){ // return scoreManager.getInteger(key); // } // // //method to set high score of a level // public static void setScore(String key, int score){ // scoreManager.putInteger(key,score); // scoreManager.flush(); // } // // //method to check if ever scored // public static boolean scored(){ // if(scoreManager.getInteger(LEVEL_1) > 0){ // return true; // } // else if(scoreManager.getInteger(LEVEL_2) > 0){ // return true; // } // else if(scoreManager.getInteger(LEVEL_3) > 0){ // return true; // } // else if(scoreManager.getInteger(LEVEL_4) > 0){ // return true; // } // else if(scoreManager.getInteger(LEVEL_5) > 0){ // return true; // } // else if(scoreManager.getInteger(LEVEL_6) > 0){ // return true; // } // else{ // return false; // } // } // } // // Path: core/src/com/bms/chemtris/screen/Splash.java // public class Splash implements Screen { // //batch to draw images // private SpriteBatch batch; // //splash sprite // private Sprite splash; // //tween animation manager // private TweenManager tween; // // @Override // public void show() { // //initialize sprite batch // batch = new SpriteBatch(); // //initialize splash sprite // splash = new Sprite(TextureLoader.getSplash()); // //set splash size // splash.setSize(Gdx.graphics.getWidth(),Gdx.graphics.getHeight()); // // // //setup animation // tween = new TweenManager(); // Tween.registerAccessor(Sprite.class, new SpriteAccessor()); // // //FadeIN // Tween.set(splash,SpriteAccessor.ALPHA).target(0).start(tween); // Tween.to(splash,SpriteAccessor.ALPHA,1.5f).target(1).start(tween); // // //FadeOut // Tween.to(splash,SpriteAccessor.ALPHA,2f).target(0).delay(1.25f).setCallback(new TweenCallback() { // @Override // public void onEvent(int type, BaseTween<?> source) { // ((Game)Gdx.app.getApplicationListener()).setScreen(new MainMenu()); // } // }).start(tween); // // // } // // @Override // public void render(float delta) { // //render background // Background.render(); // //update tween // tween.update(delta); // //Render the sprite // batch.begin(); // splash.draw(batch); // batch.end(); // // } // // @Override // public void resize(int width, int height) { // //update size // splash.setSize(width,height); // } // // @Override // public void pause() {} // // @Override // public void resume() {} // // @Override // public void hide() {} // // @Override // public void dispose() { // //dispose assets // batch.dispose(); // TextureLoader.disposeSplash(); // } // }
import com.badlogic.gdx.Game; import com.bms.chemtris.game.ScoreManager; import com.bms.chemtris.screen.Splash;
package com.bms.chemtris; public class ChemtrisGame extends Game { @Override public void create () {
// Path: core/src/com/bms/chemtris/game/ScoreManager.java // public class ScoreManager { // // //preference to store score // private static Preferences scoreManager = Gdx.app.getPreferences("com.bms.chemtris"); // // //level strings // public static final String LEVEL_1 = "level1", // LEVEL_2 = "level2", // LEVEL_3 = "level3", // LEVEL_4 = "level4", // LEVEL_5 = "level5", // LEVEL_6 = "level6", // H2O = "water", // CH4 = "methane"; // // //constructor // public static void setup(){ // //initializing high scores for each level // if(!scoreManager.contains(LEVEL_1)){ // scoreManager.putInteger(LEVEL_1,0); // } // if(!scoreManager.contains(LEVEL_2)){ // scoreManager.putInteger(LEVEL_2,0); // } // if(!scoreManager.contains(LEVEL_3)){ // scoreManager.putInteger(LEVEL_3,0); // } // if(!scoreManager.contains(LEVEL_4)){ // scoreManager.putInteger(LEVEL_4,0); // } // if(!scoreManager.contains(LEVEL_5)){ // scoreManager.putInteger(LEVEL_5,0); // } // if(!scoreManager.contains(LEVEL_6)){ // scoreManager.putInteger(LEVEL_6,0); // } // if(!scoreManager.contains(H2O)){ // scoreManager.putInteger(H2O,0); // } // if(!scoreManager.contains(CH4)){ // scoreManager.putInteger(CH4,0); // } // } // // //method to return high score of a level // public static int getScore(String key){ // return scoreManager.getInteger(key); // } // // //method to set high score of a level // public static void setScore(String key, int score){ // scoreManager.putInteger(key,score); // scoreManager.flush(); // } // // //method to check if ever scored // public static boolean scored(){ // if(scoreManager.getInteger(LEVEL_1) > 0){ // return true; // } // else if(scoreManager.getInteger(LEVEL_2) > 0){ // return true; // } // else if(scoreManager.getInteger(LEVEL_3) > 0){ // return true; // } // else if(scoreManager.getInteger(LEVEL_4) > 0){ // return true; // } // else if(scoreManager.getInteger(LEVEL_5) > 0){ // return true; // } // else if(scoreManager.getInteger(LEVEL_6) > 0){ // return true; // } // else{ // return false; // } // } // } // // Path: core/src/com/bms/chemtris/screen/Splash.java // public class Splash implements Screen { // //batch to draw images // private SpriteBatch batch; // //splash sprite // private Sprite splash; // //tween animation manager // private TweenManager tween; // // @Override // public void show() { // //initialize sprite batch // batch = new SpriteBatch(); // //initialize splash sprite // splash = new Sprite(TextureLoader.getSplash()); // //set splash size // splash.setSize(Gdx.graphics.getWidth(),Gdx.graphics.getHeight()); // // // //setup animation // tween = new TweenManager(); // Tween.registerAccessor(Sprite.class, new SpriteAccessor()); // // //FadeIN // Tween.set(splash,SpriteAccessor.ALPHA).target(0).start(tween); // Tween.to(splash,SpriteAccessor.ALPHA,1.5f).target(1).start(tween); // // //FadeOut // Tween.to(splash,SpriteAccessor.ALPHA,2f).target(0).delay(1.25f).setCallback(new TweenCallback() { // @Override // public void onEvent(int type, BaseTween<?> source) { // ((Game)Gdx.app.getApplicationListener()).setScreen(new MainMenu()); // } // }).start(tween); // // // } // // @Override // public void render(float delta) { // //render background // Background.render(); // //update tween // tween.update(delta); // //Render the sprite // batch.begin(); // splash.draw(batch); // batch.end(); // // } // // @Override // public void resize(int width, int height) { // //update size // splash.setSize(width,height); // } // // @Override // public void pause() {} // // @Override // public void resume() {} // // @Override // public void hide() {} // // @Override // public void dispose() { // //dispose assets // batch.dispose(); // TextureLoader.disposeSplash(); // } // } // Path: core/src/com/bms/chemtris/ChemtrisGame.java import com.badlogic.gdx.Game; import com.bms.chemtris.game.ScoreManager; import com.bms.chemtris.screen.Splash; package com.bms.chemtris; public class ChemtrisGame extends Game { @Override public void create () {
ScoreManager.setup();
msk610/Chemtris
core/src/com/bms/chemtris/ChemtrisGame.java
// Path: core/src/com/bms/chemtris/game/ScoreManager.java // public class ScoreManager { // // //preference to store score // private static Preferences scoreManager = Gdx.app.getPreferences("com.bms.chemtris"); // // //level strings // public static final String LEVEL_1 = "level1", // LEVEL_2 = "level2", // LEVEL_3 = "level3", // LEVEL_4 = "level4", // LEVEL_5 = "level5", // LEVEL_6 = "level6", // H2O = "water", // CH4 = "methane"; // // //constructor // public static void setup(){ // //initializing high scores for each level // if(!scoreManager.contains(LEVEL_1)){ // scoreManager.putInteger(LEVEL_1,0); // } // if(!scoreManager.contains(LEVEL_2)){ // scoreManager.putInteger(LEVEL_2,0); // } // if(!scoreManager.contains(LEVEL_3)){ // scoreManager.putInteger(LEVEL_3,0); // } // if(!scoreManager.contains(LEVEL_4)){ // scoreManager.putInteger(LEVEL_4,0); // } // if(!scoreManager.contains(LEVEL_5)){ // scoreManager.putInteger(LEVEL_5,0); // } // if(!scoreManager.contains(LEVEL_6)){ // scoreManager.putInteger(LEVEL_6,0); // } // if(!scoreManager.contains(H2O)){ // scoreManager.putInteger(H2O,0); // } // if(!scoreManager.contains(CH4)){ // scoreManager.putInteger(CH4,0); // } // } // // //method to return high score of a level // public static int getScore(String key){ // return scoreManager.getInteger(key); // } // // //method to set high score of a level // public static void setScore(String key, int score){ // scoreManager.putInteger(key,score); // scoreManager.flush(); // } // // //method to check if ever scored // public static boolean scored(){ // if(scoreManager.getInteger(LEVEL_1) > 0){ // return true; // } // else if(scoreManager.getInteger(LEVEL_2) > 0){ // return true; // } // else if(scoreManager.getInteger(LEVEL_3) > 0){ // return true; // } // else if(scoreManager.getInteger(LEVEL_4) > 0){ // return true; // } // else if(scoreManager.getInteger(LEVEL_5) > 0){ // return true; // } // else if(scoreManager.getInteger(LEVEL_6) > 0){ // return true; // } // else{ // return false; // } // } // } // // Path: core/src/com/bms/chemtris/screen/Splash.java // public class Splash implements Screen { // //batch to draw images // private SpriteBatch batch; // //splash sprite // private Sprite splash; // //tween animation manager // private TweenManager tween; // // @Override // public void show() { // //initialize sprite batch // batch = new SpriteBatch(); // //initialize splash sprite // splash = new Sprite(TextureLoader.getSplash()); // //set splash size // splash.setSize(Gdx.graphics.getWidth(),Gdx.graphics.getHeight()); // // // //setup animation // tween = new TweenManager(); // Tween.registerAccessor(Sprite.class, new SpriteAccessor()); // // //FadeIN // Tween.set(splash,SpriteAccessor.ALPHA).target(0).start(tween); // Tween.to(splash,SpriteAccessor.ALPHA,1.5f).target(1).start(tween); // // //FadeOut // Tween.to(splash,SpriteAccessor.ALPHA,2f).target(0).delay(1.25f).setCallback(new TweenCallback() { // @Override // public void onEvent(int type, BaseTween<?> source) { // ((Game)Gdx.app.getApplicationListener()).setScreen(new MainMenu()); // } // }).start(tween); // // // } // // @Override // public void render(float delta) { // //render background // Background.render(); // //update tween // tween.update(delta); // //Render the sprite // batch.begin(); // splash.draw(batch); // batch.end(); // // } // // @Override // public void resize(int width, int height) { // //update size // splash.setSize(width,height); // } // // @Override // public void pause() {} // // @Override // public void resume() {} // // @Override // public void hide() {} // // @Override // public void dispose() { // //dispose assets // batch.dispose(); // TextureLoader.disposeSplash(); // } // }
import com.badlogic.gdx.Game; import com.bms.chemtris.game.ScoreManager; import com.bms.chemtris.screen.Splash;
package com.bms.chemtris; public class ChemtrisGame extends Game { @Override public void create () { ScoreManager.setup();
// Path: core/src/com/bms/chemtris/game/ScoreManager.java // public class ScoreManager { // // //preference to store score // private static Preferences scoreManager = Gdx.app.getPreferences("com.bms.chemtris"); // // //level strings // public static final String LEVEL_1 = "level1", // LEVEL_2 = "level2", // LEVEL_3 = "level3", // LEVEL_4 = "level4", // LEVEL_5 = "level5", // LEVEL_6 = "level6", // H2O = "water", // CH4 = "methane"; // // //constructor // public static void setup(){ // //initializing high scores for each level // if(!scoreManager.contains(LEVEL_1)){ // scoreManager.putInteger(LEVEL_1,0); // } // if(!scoreManager.contains(LEVEL_2)){ // scoreManager.putInteger(LEVEL_2,0); // } // if(!scoreManager.contains(LEVEL_3)){ // scoreManager.putInteger(LEVEL_3,0); // } // if(!scoreManager.contains(LEVEL_4)){ // scoreManager.putInteger(LEVEL_4,0); // } // if(!scoreManager.contains(LEVEL_5)){ // scoreManager.putInteger(LEVEL_5,0); // } // if(!scoreManager.contains(LEVEL_6)){ // scoreManager.putInteger(LEVEL_6,0); // } // if(!scoreManager.contains(H2O)){ // scoreManager.putInteger(H2O,0); // } // if(!scoreManager.contains(CH4)){ // scoreManager.putInteger(CH4,0); // } // } // // //method to return high score of a level // public static int getScore(String key){ // return scoreManager.getInteger(key); // } // // //method to set high score of a level // public static void setScore(String key, int score){ // scoreManager.putInteger(key,score); // scoreManager.flush(); // } // // //method to check if ever scored // public static boolean scored(){ // if(scoreManager.getInteger(LEVEL_1) > 0){ // return true; // } // else if(scoreManager.getInteger(LEVEL_2) > 0){ // return true; // } // else if(scoreManager.getInteger(LEVEL_3) > 0){ // return true; // } // else if(scoreManager.getInteger(LEVEL_4) > 0){ // return true; // } // else if(scoreManager.getInteger(LEVEL_5) > 0){ // return true; // } // else if(scoreManager.getInteger(LEVEL_6) > 0){ // return true; // } // else{ // return false; // } // } // } // // Path: core/src/com/bms/chemtris/screen/Splash.java // public class Splash implements Screen { // //batch to draw images // private SpriteBatch batch; // //splash sprite // private Sprite splash; // //tween animation manager // private TweenManager tween; // // @Override // public void show() { // //initialize sprite batch // batch = new SpriteBatch(); // //initialize splash sprite // splash = new Sprite(TextureLoader.getSplash()); // //set splash size // splash.setSize(Gdx.graphics.getWidth(),Gdx.graphics.getHeight()); // // // //setup animation // tween = new TweenManager(); // Tween.registerAccessor(Sprite.class, new SpriteAccessor()); // // //FadeIN // Tween.set(splash,SpriteAccessor.ALPHA).target(0).start(tween); // Tween.to(splash,SpriteAccessor.ALPHA,1.5f).target(1).start(tween); // // //FadeOut // Tween.to(splash,SpriteAccessor.ALPHA,2f).target(0).delay(1.25f).setCallback(new TweenCallback() { // @Override // public void onEvent(int type, BaseTween<?> source) { // ((Game)Gdx.app.getApplicationListener()).setScreen(new MainMenu()); // } // }).start(tween); // // // } // // @Override // public void render(float delta) { // //render background // Background.render(); // //update tween // tween.update(delta); // //Render the sprite // batch.begin(); // splash.draw(batch); // batch.end(); // // } // // @Override // public void resize(int width, int height) { // //update size // splash.setSize(width,height); // } // // @Override // public void pause() {} // // @Override // public void resume() {} // // @Override // public void hide() {} // // @Override // public void dispose() { // //dispose assets // batch.dispose(); // TextureLoader.disposeSplash(); // } // } // Path: core/src/com/bms/chemtris/ChemtrisGame.java import com.badlogic.gdx.Game; import com.bms.chemtris.game.ScoreManager; import com.bms.chemtris.screen.Splash; package com.bms.chemtris; public class ChemtrisGame extends Game { @Override public void create () { ScoreManager.setup();
setScreen(new Splash());
openhealthdata/CCR-Validator
src/main/java/org/openhealthdata/validator/ValidatorServlet.java
// Path: src/main/java/org/openhealthdata/validator/drools/InternalKnowledgeBaseManager.java // public class InternalKnowledgeBaseManager implements KnowledgeBaseManager{ // // private KnowledgeBase kbase; // private static final String RULES_FOLDER = "/rules"; // private Logger logger = Logger.getLogger(this.getClass().getName()); // // public KnowledgeBase getKnowledgeBase() { // if( kbase == null ){ // try { // kbase = createKnowledgeBase(); // } catch (Exception e) { // String errorMessage = "unable to create knowledgeBase"; // logger.log(Level.SEVERE, errorMessage, e); // throw new RuntimeException(errorMessage, e); // } // } // return kbase; // } // // /* // * Create the KnowledgeBase from base rules in "core" and "v1" packages // */ // private KnowledgeBase createKnowledgeBase() throws URISyntaxException { // KnowledgeBuilder builder = KnowledgeBuilderFactory // .newKnowledgeBuilder(); // // Get the location of the root rules folder from the classpath // URL rules = this.getClass().getResource(RULES_FOLDER); // // Get file handler from the URL // File rDir = new File(rules.toURI()); // // Make sure it is a directory and load all subfolders // if (rDir.isDirectory()){ // for (File f : rDir.listFiles()){ // //only process directories // if (f.isDirectory()){ // addDirectory(f, builder); // } // } // } // // Create a new knowledgebase // KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(); // // Add the rule packages to the new knowledge base // kbase.addKnowledgePackages(builder.getKnowledgePackages()); // // return kbase; // } // // /* // * Add the knowledge resources in the directory into the KnowledgeBuilder // */ // private void addDirectory(File dir, KnowledgeBuilder kbuilder) { // // TODO Add non-DRL files - for future // logger.log(Level.INFO,"addDirectory: " + dir.getAbsolutePath()); // if (dir.isDirectory()) { // File[] resources = dir.listFiles(DroolsUtil // .getFilter(ResourceType.DRL)); // // if (resources != null) { // for (int i = 0; i < resources.length; i++) { // logger.log(Level.INFO,"adding: " + resources[i].getName()); // kbuilder.add(ResourceFactory.newFileResource(resources[i]), // ResourceType.DRL); // // check for any errors and stop processing if found // if (kbuilder.hasErrors()){ // KnowledgeBuilderErrors kbuilderErrors = kbuilder.getErrors(); // for(KnowledgeBuilderError error : kbuilderErrors){ // logger.log(Level.SEVERE, "kbuilder error: "+ error.getMessage()); // } // throw new RuntimeException(kbuilderErrors.toString()); } // } // } // } else { // throw new RuntimeException("File is not a directory:"+dir.getName()); // } // logger.log(Level.FINEST,"Builder Pkg: "+kbuilder.getKnowledgePackages().size()); // } // // }
import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import org.apache.commons.fileupload.*; import org.openhealthdata.validator.drools.InternalKnowledgeBaseManager; import java.util.*; import java.util.logging.Level; import java.util.logging.Logger;
/* * Copyright 2010 OpenHealthData, Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.openhealthdata.validator; public class ValidatorServlet extends HttpServlet { /** * */ private static final long serialVersionUID = 1L; private Logger logger = Logger.getLogger(this.getClass().getName()); /** * * @see Servlet#init(ServletConfig) */ public void init(ServletConfig config) throws ServletException {
// Path: src/main/java/org/openhealthdata/validator/drools/InternalKnowledgeBaseManager.java // public class InternalKnowledgeBaseManager implements KnowledgeBaseManager{ // // private KnowledgeBase kbase; // private static final String RULES_FOLDER = "/rules"; // private Logger logger = Logger.getLogger(this.getClass().getName()); // // public KnowledgeBase getKnowledgeBase() { // if( kbase == null ){ // try { // kbase = createKnowledgeBase(); // } catch (Exception e) { // String errorMessage = "unable to create knowledgeBase"; // logger.log(Level.SEVERE, errorMessage, e); // throw new RuntimeException(errorMessage, e); // } // } // return kbase; // } // // /* // * Create the KnowledgeBase from base rules in "core" and "v1" packages // */ // private KnowledgeBase createKnowledgeBase() throws URISyntaxException { // KnowledgeBuilder builder = KnowledgeBuilderFactory // .newKnowledgeBuilder(); // // Get the location of the root rules folder from the classpath // URL rules = this.getClass().getResource(RULES_FOLDER); // // Get file handler from the URL // File rDir = new File(rules.toURI()); // // Make sure it is a directory and load all subfolders // if (rDir.isDirectory()){ // for (File f : rDir.listFiles()){ // //only process directories // if (f.isDirectory()){ // addDirectory(f, builder); // } // } // } // // Create a new knowledgebase // KnowledgeBase kbase = KnowledgeBaseFactory.newKnowledgeBase(); // // Add the rule packages to the new knowledge base // kbase.addKnowledgePackages(builder.getKnowledgePackages()); // // return kbase; // } // // /* // * Add the knowledge resources in the directory into the KnowledgeBuilder // */ // private void addDirectory(File dir, KnowledgeBuilder kbuilder) { // // TODO Add non-DRL files - for future // logger.log(Level.INFO,"addDirectory: " + dir.getAbsolutePath()); // if (dir.isDirectory()) { // File[] resources = dir.listFiles(DroolsUtil // .getFilter(ResourceType.DRL)); // // if (resources != null) { // for (int i = 0; i < resources.length; i++) { // logger.log(Level.INFO,"adding: " + resources[i].getName()); // kbuilder.add(ResourceFactory.newFileResource(resources[i]), // ResourceType.DRL); // // check for any errors and stop processing if found // if (kbuilder.hasErrors()){ // KnowledgeBuilderErrors kbuilderErrors = kbuilder.getErrors(); // for(KnowledgeBuilderError error : kbuilderErrors){ // logger.log(Level.SEVERE, "kbuilder error: "+ error.getMessage()); // } // throw new RuntimeException(kbuilderErrors.toString()); } // } // } // } else { // throw new RuntimeException("File is not a directory:"+dir.getName()); // } // logger.log(Level.FINEST,"Builder Pkg: "+kbuilder.getKnowledgePackages().size()); // } // // } // Path: src/main/java/org/openhealthdata/validator/ValidatorServlet.java import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import org.apache.commons.fileupload.*; import org.openhealthdata.validator.drools.InternalKnowledgeBaseManager; import java.util.*; import java.util.logging.Level; import java.util.logging.Logger; /* * Copyright 2010 OpenHealthData, Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.openhealthdata.validator; public class ValidatorServlet extends HttpServlet { /** * */ private static final long serialVersionUID = 1L; private Logger logger = Logger.getLogger(this.getClass().getName()); /** * * @see Servlet#init(ServletConfig) */ public void init(ServletConfig config) throws ServletException {
validator = new ValidationManager(new InternalKnowledgeBaseManager());
openhealthdata/CCR-Validator
src/main/java/org/openhealthdata/validation/result/BaseValidationManager.java
// Path: src/main/java/org/openhealthdata/validation/result/ValidationResult.java // @XmlAccessorType(XmlAccessType.FIELD) // @XmlType(name = "", propOrder = { // "name", // "version" // }) // public static class Profile { // // @XmlElement(name = "Name", required = true) // protected String name; // @XmlElement(name = "Version") // protected String version; // @XmlAttribute // @XmlJavaTypeAdapter(CollapsedStringAdapter.class) // @XmlID // @XmlSchemaType(name = "ID") // protected String id; // // /** // * Gets the value of the name property. // * // * @return // * possible object is // * {@link String } // * // */ // public String getName() { // return name; // } // // /** // * Sets the value of the name property. // * // * @param value // * allowed object is // * {@link String } // * // */ // public void setName(String value) { // this.name = value; // } // // /** // * Gets the value of the version property. // * // * @return // * possible object is // * {@link String } // * // */ // public String getVersion() { // return version; // } // // /** // * Sets the value of the version property. // * // * @param value // * allowed object is // * {@link String } // * // */ // public void setVersion(String value) { // this.version = value; // } // // /** // * Gets the value of the id property. // * // * @return // * possible object is // * {@link String } // * // */ // public String getId() { // return id; // } // // /** // * Sets the value of the id property. // * // * @param value // * allowed object is // * {@link String } // * // */ // public void setId(String value) { // this.id = value; // } // // }
import java.util.LinkedList; import java.util.List; import org.openhealthdata.validation.result.ValidationResult.ValidationUsed.Profile;
} return trt; } /** * Get a list of Test results by status */ public List<TestResultType> getTestByStatus(String status) { LinkedList<TestResultType> rs = new LinkedList<TestResultType>(); for (TestResultType t : result.getTestResult()) { if (status.equals(t.getStatus())) { rs.add(t); } } return rs; } /** * Set the ValidationResult to manage from an existing ValidaitonResult */ public void setResult(ValidationResult result) { this.result = result; } /** * Add a new Test to the ValidationResult */ public TestResultType addTest(String testUID, String name, String description, String status, List<String> profiles) { TestResultType trt = addTest(testUID, name, description, status);
// Path: src/main/java/org/openhealthdata/validation/result/ValidationResult.java // @XmlAccessorType(XmlAccessType.FIELD) // @XmlType(name = "", propOrder = { // "name", // "version" // }) // public static class Profile { // // @XmlElement(name = "Name", required = true) // protected String name; // @XmlElement(name = "Version") // protected String version; // @XmlAttribute // @XmlJavaTypeAdapter(CollapsedStringAdapter.class) // @XmlID // @XmlSchemaType(name = "ID") // protected String id; // // /** // * Gets the value of the name property. // * // * @return // * possible object is // * {@link String } // * // */ // public String getName() { // return name; // } // // /** // * Sets the value of the name property. // * // * @param value // * allowed object is // * {@link String } // * // */ // public void setName(String value) { // this.name = value; // } // // /** // * Gets the value of the version property. // * // * @return // * possible object is // * {@link String } // * // */ // public String getVersion() { // return version; // } // // /** // * Sets the value of the version property. // * // * @param value // * allowed object is // * {@link String } // * // */ // public void setVersion(String value) { // this.version = value; // } // // /** // * Gets the value of the id property. // * // * @return // * possible object is // * {@link String } // * // */ // public String getId() { // return id; // } // // /** // * Sets the value of the id property. // * // * @param value // * allowed object is // * {@link String } // * // */ // public void setId(String value) { // this.id = value; // } // // } // Path: src/main/java/org/openhealthdata/validation/result/BaseValidationManager.java import java.util.LinkedList; import java.util.List; import org.openhealthdata.validation.result.ValidationResult.ValidationUsed.Profile; } return trt; } /** * Get a list of Test results by status */ public List<TestResultType> getTestByStatus(String status) { LinkedList<TestResultType> rs = new LinkedList<TestResultType>(); for (TestResultType t : result.getTestResult()) { if (status.equals(t.getStatus())) { rs.add(t); } } return rs; } /** * Set the ValidationResult to manage from an existing ValidaitonResult */ public void setResult(ValidationResult result) { this.result = result; } /** * Add a new Test to the ValidationResult */ public TestResultType addTest(String testUID, String name, String description, String status, List<String> profiles) { TestResultType trt = addTest(testUID, name, description, status);
List<Profile> profs = result.getValidationUsed().getProfile();
openhealthdata/CCR-Validator
src/main/java/org/openhealthdata/validation/SchemaValidator.java
// Path: src/main/java/org/openhealthdata/validation/result/ErrorType.java // @XmlAccessorType(XmlAccessType.FIELD) // @XmlType(name = "ErrorType", propOrder = { // "inFileLocation", // "xPathLocation", // "text", // "message" // }) // public class ErrorType { // public static final String FATAL = "fatal"; // public static final String WARN = "warn"; // public static final String INFO = "info"; // // @XmlElement(name = "InFileLocation") // protected InFileLocation inFileLocation; // @XmlElement(name = "XPathLocation") // protected String xPathLocation; // @XmlElement(name = "Text") // protected String text; // @XmlElement(name = "Message", required = true) // protected String message; // @XmlAttribute(required = true) // protected String serverity; // // /** // * Gets the value of the inFileLocation property. // * // * @return // * possible object is // * {@link InFileLocation } // * // */ // public InFileLocation getInFileLocation() { // return inFileLocation; // } // // /** // * Sets the value of the inFileLocation property. // * // * @param value // * allowed object is // * {@link InFileLocation } // * // */ // public void setInFileLocation(InFileLocation value) { // this.inFileLocation = value; // } // // /** // * Gets the value of the xPathLocation property. // * // * @return // * possible object is // * {@link String } // * // */ // public String getXPathLocation() { // return xPathLocation; // } // // /** // * Sets the value of the xPathLocation property. // * // * @param value // * allowed object is // * {@link String } // * // */ // public void setXPathLocation(String value) { // this.xPathLocation = value; // } // // /** // * Gets the value of the text property. // * // * @return // * possible object is // * {@link String } // * // */ // public String getText() { // return text; // } // // /** // * Sets the value of the text property. // * // * @param value // * allowed object is // * {@link String } // * // */ // public void setText(String value) { // this.text = value; // } // // /** // * Gets the value of the message property. // * // * @return // * possible object is // * {@link String } // * // */ // public String getMessage() { // return message; // } // // /** // * Sets the value of the message property. // * // * @param value // * allowed object is // * {@link String } // * // */ // public void setMessage(String value) { // this.message = value; // } // // /** // * Gets the value of the serverity property. // * // * @return // * possible object is // * {@link String } // * // */ // public String getServerity() { // return serverity; // } // // /** // * Sets the value of the serverity property. // * // * @param value // * allowed object is // * {@link String } // * // */ // public void setServerity(String value) { // this.serverity = value; // } // // }
import org.w3c.dom.Document; import java.util.List; import org.openhealthdata.validation.result.ErrorType;
/* * Copyright 2010 OpenHealthData, Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.openhealthdata.validation; /** * Abstract class for creating an XSD validator * @author swaldren * */ public abstract class SchemaValidator { protected String name; /** * Return <code>true</code> if the XML instance is valid, otherwise * return <code>false</code> * * @param xml XML instance to be validated * @return */ public abstract boolean isValid(Document xml); /** * Return a list of errors during the validation * @return */
// Path: src/main/java/org/openhealthdata/validation/result/ErrorType.java // @XmlAccessorType(XmlAccessType.FIELD) // @XmlType(name = "ErrorType", propOrder = { // "inFileLocation", // "xPathLocation", // "text", // "message" // }) // public class ErrorType { // public static final String FATAL = "fatal"; // public static final String WARN = "warn"; // public static final String INFO = "info"; // // @XmlElement(name = "InFileLocation") // protected InFileLocation inFileLocation; // @XmlElement(name = "XPathLocation") // protected String xPathLocation; // @XmlElement(name = "Text") // protected String text; // @XmlElement(name = "Message", required = true) // protected String message; // @XmlAttribute(required = true) // protected String serverity; // // /** // * Gets the value of the inFileLocation property. // * // * @return // * possible object is // * {@link InFileLocation } // * // */ // public InFileLocation getInFileLocation() { // return inFileLocation; // } // // /** // * Sets the value of the inFileLocation property. // * // * @param value // * allowed object is // * {@link InFileLocation } // * // */ // public void setInFileLocation(InFileLocation value) { // this.inFileLocation = value; // } // // /** // * Gets the value of the xPathLocation property. // * // * @return // * possible object is // * {@link String } // * // */ // public String getXPathLocation() { // return xPathLocation; // } // // /** // * Sets the value of the xPathLocation property. // * // * @param value // * allowed object is // * {@link String } // * // */ // public void setXPathLocation(String value) { // this.xPathLocation = value; // } // // /** // * Gets the value of the text property. // * // * @return // * possible object is // * {@link String } // * // */ // public String getText() { // return text; // } // // /** // * Sets the value of the text property. // * // * @param value // * allowed object is // * {@link String } // * // */ // public void setText(String value) { // this.text = value; // } // // /** // * Gets the value of the message property. // * // * @return // * possible object is // * {@link String } // * // */ // public String getMessage() { // return message; // } // // /** // * Sets the value of the message property. // * // * @param value // * allowed object is // * {@link String } // * // */ // public void setMessage(String value) { // this.message = value; // } // // /** // * Gets the value of the serverity property. // * // * @return // * possible object is // * {@link String } // * // */ // public String getServerity() { // return serverity; // } // // /** // * Sets the value of the serverity property. // * // * @param value // * allowed object is // * {@link String } // * // */ // public void setServerity(String value) { // this.serverity = value; // } // // } // Path: src/main/java/org/openhealthdata/validation/SchemaValidator.java import org.w3c.dom.Document; import java.util.List; import org.openhealthdata.validation.result.ErrorType; /* * Copyright 2010 OpenHealthData, Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.openhealthdata.validation; /** * Abstract class for creating an XSD validator * @author swaldren * */ public abstract class SchemaValidator { protected String name; /** * Return <code>true</code> if the XML instance is valid, otherwise * return <code>false</code> * * @param xml XML instance to be validated * @return */ public abstract boolean isValid(Document xml); /** * Return a list of errors during the validation * @return */
public abstract List<ErrorType> getErrors();
msgpack/msgpack-ruby
ext/java/org/msgpack/jruby/Packer.java
// Path: ext/java/org/msgpack/jruby/ExtensionValue.java // @JRubyClass(name="MessagePack::ExtensionValue") // public class ExtensionValue extends RubyObject { // private static final long serialVersionUID = 8451274621449322492L; // private final Encoding binaryEncoding; // // private RubyFixnum type; // private RubyString payload; // // public ExtensionValue(Ruby runtime, RubyClass type) { // super(runtime, type); // this.binaryEncoding = runtime.getEncodingService().getAscii8bitEncoding(); // } // // public static class ExtensionValueAllocator implements ObjectAllocator { // public IRubyObject allocate(Ruby runtime, RubyClass klass) { // return new ExtensionValue(runtime, klass); // } // } // // public static ExtensionValue newExtensionValue(Ruby runtime, int type, byte[] payload) { // ExtensionValue v = new ExtensionValue(runtime, runtime.getModule("MessagePack").getClass("ExtensionValue")); // ByteList byteList = new ByteList(payload, runtime.getEncodingService().getAscii8bitEncoding()); // v.initialize(runtime.getCurrentContext(), runtime.newFixnum(type), runtime.newString(byteList)); // return v; // } // // @JRubyMethod(name = "initialize", required = 2, visibility = PRIVATE) // public IRubyObject initialize(ThreadContext ctx, IRubyObject type, IRubyObject payload) { // this.type = (RubyFixnum) type; // this.payload = (RubyString) payload; // return this; // } // // @JRubyMethod(name = {"to_s", "inspect"}) // @Override // public IRubyObject to_s() { // IRubyObject payloadStr = payload.callMethod(getRuntime().getCurrentContext(), "inspect"); // return getRuntime().newString(String.format("#<MessagePack::ExtensionValue @type=%d, @payload=%s>", type.getLongValue(), payloadStr)); // } // // @JRubyMethod(name = "hash") // @Override // public RubyFixnum hash() { // long hash = payload.hashCode() ^ (type.getLongValue() << 56); // return RubyFixnum.newFixnum(getRuntime(), hash); // } // // @JRubyMethod(name = "eql?") // public IRubyObject eql_p(ThreadContext ctx, IRubyObject o) { // Ruby runtime = ctx.runtime; // if (this == o) { // return runtime.getTrue(); // } // if (o instanceof ExtensionValue) { // ExtensionValue other = (ExtensionValue) o; // if (!this.type.eql_p(other.type).isTrue()) { // return runtime.getFalse(); // } else { // return this.payload.str_eql_p(ctx, other.payload); // } // } // return runtime.getFalse(); // } // // @JRubyMethod(name = "==") // public IRubyObject op_equal(ThreadContext ctx, IRubyObject o) { // Ruby runtime = ctx.runtime; // if (this == o) { // return runtime.getTrue(); // } // if (o instanceof ExtensionValue) { // ExtensionValue other = (ExtensionValue) o; // if (!this.type.op_equal(ctx, other.type).isTrue()) { // return runtime.getFalse(); // } else { // return this.payload.op_equal(ctx, other.payload); // } // } // return runtime.getFalse(); // } // // @JRubyMethod(name = "type") // public IRubyObject get_type() { // return type; // } // // @JRubyMethod // public IRubyObject payload() { // return payload; // } // // @JRubyMethod(name = "type=", required = 1) // public IRubyObject set_type(final IRubyObject tpe) { // type = (RubyFixnum)tpe; // return tpe; // } // // @JRubyMethod(name = "payload=", required = 1) // public IRubyObject set_payload(final IRubyObject pld) { // payload = (RubyString)pld; // return pld; // } // }
import org.jruby.Ruby; import org.jruby.RubyModule; import org.jruby.RubyClass; import org.jruby.RubyObject; import org.jruby.RubyArray; import org.jruby.RubyHash; import org.jruby.RubyIO; import org.jruby.RubyNumeric; import org.jruby.RubyInteger; import org.jruby.RubyFixnum; import org.jruby.runtime.Block; import org.jruby.runtime.builtin.IRubyObject; import org.jruby.anno.JRubyClass; import org.jruby.anno.JRubyMethod; import org.jruby.runtime.ThreadContext; import org.jruby.runtime.ObjectAllocator; import org.jruby.util.ByteList; import org.jruby.util.TypeConverter; import org.msgpack.jruby.ExtensionValue; import org.jcodings.Encoding; import static org.jruby.runtime.Visibility.PRIVATE;
@JRubyMethod(name = "write_bin") public IRubyObject writeBin(ThreadContext ctx, IRubyObject obj) { checkType(ctx, obj, org.jruby.RubyString.class); obj = ((org.jruby.RubyString) obj).encode(ctx, ctx.runtime.getEncodingService().getEncoding(binaryEncoding)); return write(ctx, obj); } @JRubyMethod(name = "write_hash") public IRubyObject writeHash(ThreadContext ctx, IRubyObject obj) { checkType(ctx, obj, org.jruby.RubyHash.class); return write(ctx, obj); } @JRubyMethod(name = "write_symbol") public IRubyObject writeSymbol(ThreadContext ctx, IRubyObject obj) { checkType(ctx, obj, org.jruby.RubySymbol.class); return write(ctx, obj); } @JRubyMethod(name = "write_int") public IRubyObject writeInt(ThreadContext ctx, IRubyObject obj) { if (!(obj instanceof RubyFixnum)) { checkType(ctx, obj, org.jruby.RubyBignum.class); } return write(ctx, obj); } @JRubyMethod(name = "write_extension") public IRubyObject writeExtension(ThreadContext ctx, IRubyObject obj) {
// Path: ext/java/org/msgpack/jruby/ExtensionValue.java // @JRubyClass(name="MessagePack::ExtensionValue") // public class ExtensionValue extends RubyObject { // private static final long serialVersionUID = 8451274621449322492L; // private final Encoding binaryEncoding; // // private RubyFixnum type; // private RubyString payload; // // public ExtensionValue(Ruby runtime, RubyClass type) { // super(runtime, type); // this.binaryEncoding = runtime.getEncodingService().getAscii8bitEncoding(); // } // // public static class ExtensionValueAllocator implements ObjectAllocator { // public IRubyObject allocate(Ruby runtime, RubyClass klass) { // return new ExtensionValue(runtime, klass); // } // } // // public static ExtensionValue newExtensionValue(Ruby runtime, int type, byte[] payload) { // ExtensionValue v = new ExtensionValue(runtime, runtime.getModule("MessagePack").getClass("ExtensionValue")); // ByteList byteList = new ByteList(payload, runtime.getEncodingService().getAscii8bitEncoding()); // v.initialize(runtime.getCurrentContext(), runtime.newFixnum(type), runtime.newString(byteList)); // return v; // } // // @JRubyMethod(name = "initialize", required = 2, visibility = PRIVATE) // public IRubyObject initialize(ThreadContext ctx, IRubyObject type, IRubyObject payload) { // this.type = (RubyFixnum) type; // this.payload = (RubyString) payload; // return this; // } // // @JRubyMethod(name = {"to_s", "inspect"}) // @Override // public IRubyObject to_s() { // IRubyObject payloadStr = payload.callMethod(getRuntime().getCurrentContext(), "inspect"); // return getRuntime().newString(String.format("#<MessagePack::ExtensionValue @type=%d, @payload=%s>", type.getLongValue(), payloadStr)); // } // // @JRubyMethod(name = "hash") // @Override // public RubyFixnum hash() { // long hash = payload.hashCode() ^ (type.getLongValue() << 56); // return RubyFixnum.newFixnum(getRuntime(), hash); // } // // @JRubyMethod(name = "eql?") // public IRubyObject eql_p(ThreadContext ctx, IRubyObject o) { // Ruby runtime = ctx.runtime; // if (this == o) { // return runtime.getTrue(); // } // if (o instanceof ExtensionValue) { // ExtensionValue other = (ExtensionValue) o; // if (!this.type.eql_p(other.type).isTrue()) { // return runtime.getFalse(); // } else { // return this.payload.str_eql_p(ctx, other.payload); // } // } // return runtime.getFalse(); // } // // @JRubyMethod(name = "==") // public IRubyObject op_equal(ThreadContext ctx, IRubyObject o) { // Ruby runtime = ctx.runtime; // if (this == o) { // return runtime.getTrue(); // } // if (o instanceof ExtensionValue) { // ExtensionValue other = (ExtensionValue) o; // if (!this.type.op_equal(ctx, other.type).isTrue()) { // return runtime.getFalse(); // } else { // return this.payload.op_equal(ctx, other.payload); // } // } // return runtime.getFalse(); // } // // @JRubyMethod(name = "type") // public IRubyObject get_type() { // return type; // } // // @JRubyMethod // public IRubyObject payload() { // return payload; // } // // @JRubyMethod(name = "type=", required = 1) // public IRubyObject set_type(final IRubyObject tpe) { // type = (RubyFixnum)tpe; // return tpe; // } // // @JRubyMethod(name = "payload=", required = 1) // public IRubyObject set_payload(final IRubyObject pld) { // payload = (RubyString)pld; // return pld; // } // } // Path: ext/java/org/msgpack/jruby/Packer.java import org.jruby.Ruby; import org.jruby.RubyModule; import org.jruby.RubyClass; import org.jruby.RubyObject; import org.jruby.RubyArray; import org.jruby.RubyHash; import org.jruby.RubyIO; import org.jruby.RubyNumeric; import org.jruby.RubyInteger; import org.jruby.RubyFixnum; import org.jruby.runtime.Block; import org.jruby.runtime.builtin.IRubyObject; import org.jruby.anno.JRubyClass; import org.jruby.anno.JRubyMethod; import org.jruby.runtime.ThreadContext; import org.jruby.runtime.ObjectAllocator; import org.jruby.util.ByteList; import org.jruby.util.TypeConverter; import org.msgpack.jruby.ExtensionValue; import org.jcodings.Encoding; import static org.jruby.runtime.Visibility.PRIVATE; @JRubyMethod(name = "write_bin") public IRubyObject writeBin(ThreadContext ctx, IRubyObject obj) { checkType(ctx, obj, org.jruby.RubyString.class); obj = ((org.jruby.RubyString) obj).encode(ctx, ctx.runtime.getEncodingService().getEncoding(binaryEncoding)); return write(ctx, obj); } @JRubyMethod(name = "write_hash") public IRubyObject writeHash(ThreadContext ctx, IRubyObject obj) { checkType(ctx, obj, org.jruby.RubyHash.class); return write(ctx, obj); } @JRubyMethod(name = "write_symbol") public IRubyObject writeSymbol(ThreadContext ctx, IRubyObject obj) { checkType(ctx, obj, org.jruby.RubySymbol.class); return write(ctx, obj); } @JRubyMethod(name = "write_int") public IRubyObject writeInt(ThreadContext ctx, IRubyObject obj) { if (!(obj instanceof RubyFixnum)) { checkType(ctx, obj, org.jruby.RubyBignum.class); } return write(ctx, obj); } @JRubyMethod(name = "write_extension") public IRubyObject writeExtension(ThreadContext ctx, IRubyObject obj) {
if (!(obj instanceof ExtensionValue)) {
atam4j/atam4j
atam4j/src/test/java/me/atam/atam4j/Atam4jIntegrationTest.java
// Path: dummy-tests/src/test/java/me/atam/atam4j/dummytests/PassingTestWithNoCategory.java // @Monitor // public class PassingTestWithNoCategory { // // @Test // public void testThatPasses(){ // Assert.assertTrue(true); // } // } // // Path: atam4j/src/main/java/me/atam/atam4j/resources/TestStatusResource.java // @Path("/tests") // @Produces("application/json") // public class TestStatusResource { // // private final TestRunListener testRunListener; // // public TestStatusResource(TestRunListener testRunListener) { // this.testRunListener = testRunListener; // } // // @GET // public Response getTestStatus(){ // return buildResponse(testRunListener.getTestsRunResult()); // } // // @GET // @Path("{category}") // public Response getTestStatusForACategory(@PathParam("category") String category) { // return buildResponse(testRunListener.getTestsRunResult(category)); // } // // private Response buildResponse(TestsRunResult testRunResult) { // if (testRunResult.getStatus().equals(TestsRunResult.Status.FAILURES)) { // return Response.status(Response.Status.INTERNAL_SERVER_ERROR) // .entity(testRunResult) // .build(); // } else if (testRunResult.getStatus().equals(TestsRunResult.Status.CATEGORY_NOT_FOUND)) { // return Response.status(Response.Status.NOT_FOUND) // .build(); // } else { // return Response.status(Response.Status.OK) // .entity(testRunResult) // .build(); // } // } // } // // Path: atam4j-domain/src/main/java/me/atam/atam4jdomain/TestsRunResult.java // public final class TestsRunResult { // // private final Collection<IndividualTestResult> tests; // private final Status status; // // public TestsRunResult(final @JsonProperty("tests") Collection<IndividualTestResult> tests, // final @JsonProperty("status") Status status) { // this.tests = tests; // this.status = status; // // } // // public TestsRunResult(final Collection<IndividualTestResult> tests) { // this.tests = tests; // this.status = buildStatus(tests); // } // // public Collection<IndividualTestResult> getTests() { // return tests; // } // // // // // public Status getStatus() { // return status; // } // // private Status buildStatus(final Collection<IndividualTestResult> testResults) { // if (testResults.isEmpty()) { // return Status.CATEGORY_NOT_FOUND; // } // return testResults.stream() // .filter(testReport -> !testReport.isPassed()) // .findAny() // .map(failures -> Status.FAILURES) // .orElse(Status.ALL_OK); // } // // public Optional<IndividualTestResult> getTestByClassAndName(String className, String testName) { // return tests.stream().filter(t -> t.getTestClass().equals(className)).filter(t -> t.getTestName().equals(testName)).findFirst(); // } // // public enum Status { // TOO_EARLY("Too early to tell - tests not complete yet"), // CATEGORY_NOT_FOUND("This category does not exist"), // ALL_OK("All is A OK!"), // FAILURES("Failures"); // // private final String message; // // Status(String message) { // this.message = message; // } // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // TestsRunResult that = (TestsRunResult) o; // // if (tests != null ? !tests.equals(that.tests) : that.tests != null) return false; // return status == that.status; // // } // // @Override // public int hashCode() { // int result = tests != null ? tests.hashCode() : 0; // result = 31 * result + (status != null ? status.hashCode() : 0); // return result; // } // // @Override // public String toString() { // return "TestsRunResult{" + // "tests=" + tests + // ", status=" + status + // '}'; // } // }
import io.dropwizard.jersey.setup.JerseyEnvironment; import me.atam.atam4j.dummytests.PassingTestWithNoCategory; import me.atam.atam4j.resources.TestStatusResource; import me.atam.atam4jdomain.TestsRunResult; import org.hamcrest.CoreMatchers; import org.junit.After; import org.junit.Test; import org.mockito.ArgumentCaptor; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify;
package me.atam.atam4j; public class Atam4jIntegrationTest { Atam4j atam4j = null; @Test public void givenHealthCheckManagerWithPassingTest_whenInitialized_thenTestsAreHealthy() throws Exception{ JerseyEnvironment jerseyEnvironment = mock(JerseyEnvironment.class);
// Path: dummy-tests/src/test/java/me/atam/atam4j/dummytests/PassingTestWithNoCategory.java // @Monitor // public class PassingTestWithNoCategory { // // @Test // public void testThatPasses(){ // Assert.assertTrue(true); // } // } // // Path: atam4j/src/main/java/me/atam/atam4j/resources/TestStatusResource.java // @Path("/tests") // @Produces("application/json") // public class TestStatusResource { // // private final TestRunListener testRunListener; // // public TestStatusResource(TestRunListener testRunListener) { // this.testRunListener = testRunListener; // } // // @GET // public Response getTestStatus(){ // return buildResponse(testRunListener.getTestsRunResult()); // } // // @GET // @Path("{category}") // public Response getTestStatusForACategory(@PathParam("category") String category) { // return buildResponse(testRunListener.getTestsRunResult(category)); // } // // private Response buildResponse(TestsRunResult testRunResult) { // if (testRunResult.getStatus().equals(TestsRunResult.Status.FAILURES)) { // return Response.status(Response.Status.INTERNAL_SERVER_ERROR) // .entity(testRunResult) // .build(); // } else if (testRunResult.getStatus().equals(TestsRunResult.Status.CATEGORY_NOT_FOUND)) { // return Response.status(Response.Status.NOT_FOUND) // .build(); // } else { // return Response.status(Response.Status.OK) // .entity(testRunResult) // .build(); // } // } // } // // Path: atam4j-domain/src/main/java/me/atam/atam4jdomain/TestsRunResult.java // public final class TestsRunResult { // // private final Collection<IndividualTestResult> tests; // private final Status status; // // public TestsRunResult(final @JsonProperty("tests") Collection<IndividualTestResult> tests, // final @JsonProperty("status") Status status) { // this.tests = tests; // this.status = status; // // } // // public TestsRunResult(final Collection<IndividualTestResult> tests) { // this.tests = tests; // this.status = buildStatus(tests); // } // // public Collection<IndividualTestResult> getTests() { // return tests; // } // // // // // public Status getStatus() { // return status; // } // // private Status buildStatus(final Collection<IndividualTestResult> testResults) { // if (testResults.isEmpty()) { // return Status.CATEGORY_NOT_FOUND; // } // return testResults.stream() // .filter(testReport -> !testReport.isPassed()) // .findAny() // .map(failures -> Status.FAILURES) // .orElse(Status.ALL_OK); // } // // public Optional<IndividualTestResult> getTestByClassAndName(String className, String testName) { // return tests.stream().filter(t -> t.getTestClass().equals(className)).filter(t -> t.getTestName().equals(testName)).findFirst(); // } // // public enum Status { // TOO_EARLY("Too early to tell - tests not complete yet"), // CATEGORY_NOT_FOUND("This category does not exist"), // ALL_OK("All is A OK!"), // FAILURES("Failures"); // // private final String message; // // Status(String message) { // this.message = message; // } // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // TestsRunResult that = (TestsRunResult) o; // // if (tests != null ? !tests.equals(that.tests) : that.tests != null) return false; // return status == that.status; // // } // // @Override // public int hashCode() { // int result = tests != null ? tests.hashCode() : 0; // result = 31 * result + (status != null ? status.hashCode() : 0); // return result; // } // // @Override // public String toString() { // return "TestsRunResult{" + // "tests=" + tests + // ", status=" + status + // '}'; // } // } // Path: atam4j/src/test/java/me/atam/atam4j/Atam4jIntegrationTest.java import io.dropwizard.jersey.setup.JerseyEnvironment; import me.atam.atam4j.dummytests.PassingTestWithNoCategory; import me.atam.atam4j.resources.TestStatusResource; import me.atam.atam4jdomain.TestsRunResult; import org.hamcrest.CoreMatchers; import org.junit.After; import org.junit.Test; import org.mockito.ArgumentCaptor; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; package me.atam.atam4j; public class Atam4jIntegrationTest { Atam4j atam4j = null; @Test public void givenHealthCheckManagerWithPassingTest_whenInitialized_thenTestsAreHealthy() throws Exception{ JerseyEnvironment jerseyEnvironment = mock(JerseyEnvironment.class);
ArgumentCaptor<TestStatusResource> argumentCaptor = ArgumentCaptor.forClass(TestStatusResource.class);
atam4j/atam4j
atam4j/src/test/java/me/atam/atam4j/Atam4jIntegrationTest.java
// Path: dummy-tests/src/test/java/me/atam/atam4j/dummytests/PassingTestWithNoCategory.java // @Monitor // public class PassingTestWithNoCategory { // // @Test // public void testThatPasses(){ // Assert.assertTrue(true); // } // } // // Path: atam4j/src/main/java/me/atam/atam4j/resources/TestStatusResource.java // @Path("/tests") // @Produces("application/json") // public class TestStatusResource { // // private final TestRunListener testRunListener; // // public TestStatusResource(TestRunListener testRunListener) { // this.testRunListener = testRunListener; // } // // @GET // public Response getTestStatus(){ // return buildResponse(testRunListener.getTestsRunResult()); // } // // @GET // @Path("{category}") // public Response getTestStatusForACategory(@PathParam("category") String category) { // return buildResponse(testRunListener.getTestsRunResult(category)); // } // // private Response buildResponse(TestsRunResult testRunResult) { // if (testRunResult.getStatus().equals(TestsRunResult.Status.FAILURES)) { // return Response.status(Response.Status.INTERNAL_SERVER_ERROR) // .entity(testRunResult) // .build(); // } else if (testRunResult.getStatus().equals(TestsRunResult.Status.CATEGORY_NOT_FOUND)) { // return Response.status(Response.Status.NOT_FOUND) // .build(); // } else { // return Response.status(Response.Status.OK) // .entity(testRunResult) // .build(); // } // } // } // // Path: atam4j-domain/src/main/java/me/atam/atam4jdomain/TestsRunResult.java // public final class TestsRunResult { // // private final Collection<IndividualTestResult> tests; // private final Status status; // // public TestsRunResult(final @JsonProperty("tests") Collection<IndividualTestResult> tests, // final @JsonProperty("status") Status status) { // this.tests = tests; // this.status = status; // // } // // public TestsRunResult(final Collection<IndividualTestResult> tests) { // this.tests = tests; // this.status = buildStatus(tests); // } // // public Collection<IndividualTestResult> getTests() { // return tests; // } // // // // // public Status getStatus() { // return status; // } // // private Status buildStatus(final Collection<IndividualTestResult> testResults) { // if (testResults.isEmpty()) { // return Status.CATEGORY_NOT_FOUND; // } // return testResults.stream() // .filter(testReport -> !testReport.isPassed()) // .findAny() // .map(failures -> Status.FAILURES) // .orElse(Status.ALL_OK); // } // // public Optional<IndividualTestResult> getTestByClassAndName(String className, String testName) { // return tests.stream().filter(t -> t.getTestClass().equals(className)).filter(t -> t.getTestName().equals(testName)).findFirst(); // } // // public enum Status { // TOO_EARLY("Too early to tell - tests not complete yet"), // CATEGORY_NOT_FOUND("This category does not exist"), // ALL_OK("All is A OK!"), // FAILURES("Failures"); // // private final String message; // // Status(String message) { // this.message = message; // } // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // TestsRunResult that = (TestsRunResult) o; // // if (tests != null ? !tests.equals(that.tests) : that.tests != null) return false; // return status == that.status; // // } // // @Override // public int hashCode() { // int result = tests != null ? tests.hashCode() : 0; // result = 31 * result + (status != null ? status.hashCode() : 0); // return result; // } // // @Override // public String toString() { // return "TestsRunResult{" + // "tests=" + tests + // ", status=" + status + // '}'; // } // }
import io.dropwizard.jersey.setup.JerseyEnvironment; import me.atam.atam4j.dummytests.PassingTestWithNoCategory; import me.atam.atam4j.resources.TestStatusResource; import me.atam.atam4jdomain.TestsRunResult; import org.hamcrest.CoreMatchers; import org.junit.After; import org.junit.Test; import org.mockito.ArgumentCaptor; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify;
package me.atam.atam4j; public class Atam4jIntegrationTest { Atam4j atam4j = null; @Test public void givenHealthCheckManagerWithPassingTest_whenInitialized_thenTestsAreHealthy() throws Exception{ JerseyEnvironment jerseyEnvironment = mock(JerseyEnvironment.class); ArgumentCaptor<TestStatusResource> argumentCaptor = ArgumentCaptor.forClass(TestStatusResource.class); atam4j = new Atam4j.Atam4jBuilder(jerseyEnvironment)
// Path: dummy-tests/src/test/java/me/atam/atam4j/dummytests/PassingTestWithNoCategory.java // @Monitor // public class PassingTestWithNoCategory { // // @Test // public void testThatPasses(){ // Assert.assertTrue(true); // } // } // // Path: atam4j/src/main/java/me/atam/atam4j/resources/TestStatusResource.java // @Path("/tests") // @Produces("application/json") // public class TestStatusResource { // // private final TestRunListener testRunListener; // // public TestStatusResource(TestRunListener testRunListener) { // this.testRunListener = testRunListener; // } // // @GET // public Response getTestStatus(){ // return buildResponse(testRunListener.getTestsRunResult()); // } // // @GET // @Path("{category}") // public Response getTestStatusForACategory(@PathParam("category") String category) { // return buildResponse(testRunListener.getTestsRunResult(category)); // } // // private Response buildResponse(TestsRunResult testRunResult) { // if (testRunResult.getStatus().equals(TestsRunResult.Status.FAILURES)) { // return Response.status(Response.Status.INTERNAL_SERVER_ERROR) // .entity(testRunResult) // .build(); // } else if (testRunResult.getStatus().equals(TestsRunResult.Status.CATEGORY_NOT_FOUND)) { // return Response.status(Response.Status.NOT_FOUND) // .build(); // } else { // return Response.status(Response.Status.OK) // .entity(testRunResult) // .build(); // } // } // } // // Path: atam4j-domain/src/main/java/me/atam/atam4jdomain/TestsRunResult.java // public final class TestsRunResult { // // private final Collection<IndividualTestResult> tests; // private final Status status; // // public TestsRunResult(final @JsonProperty("tests") Collection<IndividualTestResult> tests, // final @JsonProperty("status") Status status) { // this.tests = tests; // this.status = status; // // } // // public TestsRunResult(final Collection<IndividualTestResult> tests) { // this.tests = tests; // this.status = buildStatus(tests); // } // // public Collection<IndividualTestResult> getTests() { // return tests; // } // // // // // public Status getStatus() { // return status; // } // // private Status buildStatus(final Collection<IndividualTestResult> testResults) { // if (testResults.isEmpty()) { // return Status.CATEGORY_NOT_FOUND; // } // return testResults.stream() // .filter(testReport -> !testReport.isPassed()) // .findAny() // .map(failures -> Status.FAILURES) // .orElse(Status.ALL_OK); // } // // public Optional<IndividualTestResult> getTestByClassAndName(String className, String testName) { // return tests.stream().filter(t -> t.getTestClass().equals(className)).filter(t -> t.getTestName().equals(testName)).findFirst(); // } // // public enum Status { // TOO_EARLY("Too early to tell - tests not complete yet"), // CATEGORY_NOT_FOUND("This category does not exist"), // ALL_OK("All is A OK!"), // FAILURES("Failures"); // // private final String message; // // Status(String message) { // this.message = message; // } // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // TestsRunResult that = (TestsRunResult) o; // // if (tests != null ? !tests.equals(that.tests) : that.tests != null) return false; // return status == that.status; // // } // // @Override // public int hashCode() { // int result = tests != null ? tests.hashCode() : 0; // result = 31 * result + (status != null ? status.hashCode() : 0); // return result; // } // // @Override // public String toString() { // return "TestsRunResult{" + // "tests=" + tests + // ", status=" + status + // '}'; // } // } // Path: atam4j/src/test/java/me/atam/atam4j/Atam4jIntegrationTest.java import io.dropwizard.jersey.setup.JerseyEnvironment; import me.atam.atam4j.dummytests.PassingTestWithNoCategory; import me.atam.atam4j.resources.TestStatusResource; import me.atam.atam4jdomain.TestsRunResult; import org.hamcrest.CoreMatchers; import org.junit.After; import org.junit.Test; import org.mockito.ArgumentCaptor; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; package me.atam.atam4j; public class Atam4jIntegrationTest { Atam4j atam4j = null; @Test public void givenHealthCheckManagerWithPassingTest_whenInitialized_thenTestsAreHealthy() throws Exception{ JerseyEnvironment jerseyEnvironment = mock(JerseyEnvironment.class); ArgumentCaptor<TestStatusResource> argumentCaptor = ArgumentCaptor.forClass(TestStatusResource.class); atam4j = new Atam4j.Atam4jBuilder(jerseyEnvironment)
.withTestClasses(PassingTestWithNoCategory.class)
atam4j/atam4j
atam4j/src/test/java/me/atam/atam4j/Atam4jIntegrationTest.java
// Path: dummy-tests/src/test/java/me/atam/atam4j/dummytests/PassingTestWithNoCategory.java // @Monitor // public class PassingTestWithNoCategory { // // @Test // public void testThatPasses(){ // Assert.assertTrue(true); // } // } // // Path: atam4j/src/main/java/me/atam/atam4j/resources/TestStatusResource.java // @Path("/tests") // @Produces("application/json") // public class TestStatusResource { // // private final TestRunListener testRunListener; // // public TestStatusResource(TestRunListener testRunListener) { // this.testRunListener = testRunListener; // } // // @GET // public Response getTestStatus(){ // return buildResponse(testRunListener.getTestsRunResult()); // } // // @GET // @Path("{category}") // public Response getTestStatusForACategory(@PathParam("category") String category) { // return buildResponse(testRunListener.getTestsRunResult(category)); // } // // private Response buildResponse(TestsRunResult testRunResult) { // if (testRunResult.getStatus().equals(TestsRunResult.Status.FAILURES)) { // return Response.status(Response.Status.INTERNAL_SERVER_ERROR) // .entity(testRunResult) // .build(); // } else if (testRunResult.getStatus().equals(TestsRunResult.Status.CATEGORY_NOT_FOUND)) { // return Response.status(Response.Status.NOT_FOUND) // .build(); // } else { // return Response.status(Response.Status.OK) // .entity(testRunResult) // .build(); // } // } // } // // Path: atam4j-domain/src/main/java/me/atam/atam4jdomain/TestsRunResult.java // public final class TestsRunResult { // // private final Collection<IndividualTestResult> tests; // private final Status status; // // public TestsRunResult(final @JsonProperty("tests") Collection<IndividualTestResult> tests, // final @JsonProperty("status") Status status) { // this.tests = tests; // this.status = status; // // } // // public TestsRunResult(final Collection<IndividualTestResult> tests) { // this.tests = tests; // this.status = buildStatus(tests); // } // // public Collection<IndividualTestResult> getTests() { // return tests; // } // // // // // public Status getStatus() { // return status; // } // // private Status buildStatus(final Collection<IndividualTestResult> testResults) { // if (testResults.isEmpty()) { // return Status.CATEGORY_NOT_FOUND; // } // return testResults.stream() // .filter(testReport -> !testReport.isPassed()) // .findAny() // .map(failures -> Status.FAILURES) // .orElse(Status.ALL_OK); // } // // public Optional<IndividualTestResult> getTestByClassAndName(String className, String testName) { // return tests.stream().filter(t -> t.getTestClass().equals(className)).filter(t -> t.getTestName().equals(testName)).findFirst(); // } // // public enum Status { // TOO_EARLY("Too early to tell - tests not complete yet"), // CATEGORY_NOT_FOUND("This category does not exist"), // ALL_OK("All is A OK!"), // FAILURES("Failures"); // // private final String message; // // Status(String message) { // this.message = message; // } // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // TestsRunResult that = (TestsRunResult) o; // // if (tests != null ? !tests.equals(that.tests) : that.tests != null) return false; // return status == that.status; // // } // // @Override // public int hashCode() { // int result = tests != null ? tests.hashCode() : 0; // result = 31 * result + (status != null ? status.hashCode() : 0); // return result; // } // // @Override // public String toString() { // return "TestsRunResult{" + // "tests=" + tests + // ", status=" + status + // '}'; // } // }
import io.dropwizard.jersey.setup.JerseyEnvironment; import me.atam.atam4j.dummytests.PassingTestWithNoCategory; import me.atam.atam4j.resources.TestStatusResource; import me.atam.atam4jdomain.TestsRunResult; import org.hamcrest.CoreMatchers; import org.junit.After; import org.junit.Test; import org.mockito.ArgumentCaptor; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify;
TestStatusResource value = argumentCaptor.getValue(); assertNotNull(value); checkThatWeEventuallyGetSuccess(value); } @Test public void givenHealthCheckManagerUsingAnnotationScanning_whenInitialized_thenTestsAreHealthy() throws Exception{ JerseyEnvironment jerseyEnvironment = mock(JerseyEnvironment.class); ArgumentCaptor<TestStatusResource> argumentCaptor = ArgumentCaptor.forClass(TestStatusResource.class); atam4j = new Atam4j.Atam4jBuilder(jerseyEnvironment) .withInitialDelay(0) .build(); atam4j.start(); verify(jerseyEnvironment).register(argumentCaptor.capture()); TestStatusResource value = argumentCaptor.getValue(); assertNotNull(value); checkThatWeEventuallyGetSuccess(value); } @After public void tearDown() throws Exception { atam4j.stop(); } private void checkThatWeEventuallyGetSuccess(TestStatusResource resource) {
// Path: dummy-tests/src/test/java/me/atam/atam4j/dummytests/PassingTestWithNoCategory.java // @Monitor // public class PassingTestWithNoCategory { // // @Test // public void testThatPasses(){ // Assert.assertTrue(true); // } // } // // Path: atam4j/src/main/java/me/atam/atam4j/resources/TestStatusResource.java // @Path("/tests") // @Produces("application/json") // public class TestStatusResource { // // private final TestRunListener testRunListener; // // public TestStatusResource(TestRunListener testRunListener) { // this.testRunListener = testRunListener; // } // // @GET // public Response getTestStatus(){ // return buildResponse(testRunListener.getTestsRunResult()); // } // // @GET // @Path("{category}") // public Response getTestStatusForACategory(@PathParam("category") String category) { // return buildResponse(testRunListener.getTestsRunResult(category)); // } // // private Response buildResponse(TestsRunResult testRunResult) { // if (testRunResult.getStatus().equals(TestsRunResult.Status.FAILURES)) { // return Response.status(Response.Status.INTERNAL_SERVER_ERROR) // .entity(testRunResult) // .build(); // } else if (testRunResult.getStatus().equals(TestsRunResult.Status.CATEGORY_NOT_FOUND)) { // return Response.status(Response.Status.NOT_FOUND) // .build(); // } else { // return Response.status(Response.Status.OK) // .entity(testRunResult) // .build(); // } // } // } // // Path: atam4j-domain/src/main/java/me/atam/atam4jdomain/TestsRunResult.java // public final class TestsRunResult { // // private final Collection<IndividualTestResult> tests; // private final Status status; // // public TestsRunResult(final @JsonProperty("tests") Collection<IndividualTestResult> tests, // final @JsonProperty("status") Status status) { // this.tests = tests; // this.status = status; // // } // // public TestsRunResult(final Collection<IndividualTestResult> tests) { // this.tests = tests; // this.status = buildStatus(tests); // } // // public Collection<IndividualTestResult> getTests() { // return tests; // } // // // // // public Status getStatus() { // return status; // } // // private Status buildStatus(final Collection<IndividualTestResult> testResults) { // if (testResults.isEmpty()) { // return Status.CATEGORY_NOT_FOUND; // } // return testResults.stream() // .filter(testReport -> !testReport.isPassed()) // .findAny() // .map(failures -> Status.FAILURES) // .orElse(Status.ALL_OK); // } // // public Optional<IndividualTestResult> getTestByClassAndName(String className, String testName) { // return tests.stream().filter(t -> t.getTestClass().equals(className)).filter(t -> t.getTestName().equals(testName)).findFirst(); // } // // public enum Status { // TOO_EARLY("Too early to tell - tests not complete yet"), // CATEGORY_NOT_FOUND("This category does not exist"), // ALL_OK("All is A OK!"), // FAILURES("Failures"); // // private final String message; // // Status(String message) { // this.message = message; // } // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // TestsRunResult that = (TestsRunResult) o; // // if (tests != null ? !tests.equals(that.tests) : that.tests != null) return false; // return status == that.status; // // } // // @Override // public int hashCode() { // int result = tests != null ? tests.hashCode() : 0; // result = 31 * result + (status != null ? status.hashCode() : 0); // return result; // } // // @Override // public String toString() { // return "TestsRunResult{" + // "tests=" + tests + // ", status=" + status + // '}'; // } // } // Path: atam4j/src/test/java/me/atam/atam4j/Atam4jIntegrationTest.java import io.dropwizard.jersey.setup.JerseyEnvironment; import me.atam.atam4j.dummytests.PassingTestWithNoCategory; import me.atam.atam4j.resources.TestStatusResource; import me.atam.atam4jdomain.TestsRunResult; import org.hamcrest.CoreMatchers; import org.junit.After; import org.junit.Test; import org.mockito.ArgumentCaptor; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; TestStatusResource value = argumentCaptor.getValue(); assertNotNull(value); checkThatWeEventuallyGetSuccess(value); } @Test public void givenHealthCheckManagerUsingAnnotationScanning_whenInitialized_thenTestsAreHealthy() throws Exception{ JerseyEnvironment jerseyEnvironment = mock(JerseyEnvironment.class); ArgumentCaptor<TestStatusResource> argumentCaptor = ArgumentCaptor.forClass(TestStatusResource.class); atam4j = new Atam4j.Atam4jBuilder(jerseyEnvironment) .withInitialDelay(0) .build(); atam4j.start(); verify(jerseyEnvironment).register(argumentCaptor.capture()); TestStatusResource value = argumentCaptor.getValue(); assertNotNull(value); checkThatWeEventuallyGetSuccess(value); } @After public void tearDown() throws Exception { atam4j.stop(); } private void checkThatWeEventuallyGetSuccess(TestStatusResource resource) {
PollingPredicate<TestsRunResult> resultPollingPredicate = new PollingPredicate<>(UnitTestTimeouts.MAX_ATTEMPTS, UnitTestTimeouts.RETRY_POLL_INTERVAL_IN_MILLIS,
atam4j/atam4j
acceptance-tests/src/test/java/me/atam/atam4jsampleapp/testsupport/Atam4jApplicationStarter.java
// Path: acceptance-tests/src/main/java/me/atam/atam4jsampleapp/ApplicationConfiguration.java // public class ApplicationConfiguration extends Configuration { // // @JsonProperty // private int initialDelayInMillis; // // @JsonProperty // private Class[] testClasses; // private long periodInMillis; // // public Class[] getTestClasses(){ // return testClasses; // } // // public int getInitialDelayInMillis() { // return initialDelayInMillis; // } // // public long getPeriodInMillis() { // return periodInMillis; // } // } // // Path: acceptance-tests/src/main/java/me/atam/atam4jsampleapp/Atam4jTestApplication.java // public class Atam4jTestApplication extends Application<ApplicationConfiguration> { // // public static void main(String[] args) throws Exception { // if (args == null || args.length == 0) { // args = new String[]{"server", new File(Resources.getResource("atam4j-config.yml").toURI()).getAbsolutePath()}; // } // // new Atam4jTestApplication().run(args); // } // // @Override // public void run(final ApplicationConfiguration configuration, final Environment environment) throws Exception { // CustomListenerStatus customListenerStatus = new CustomListenerStatus(); // Atam4j atam4j = new Atam4j.Atam4jBuilder(environment.jersey()) // .withUnit(TimeUnit.MILLISECONDS) // .withInitialDelay(configuration.getInitialDelayInMillis()) // .withPeriod(configuration.getPeriodInMillis()) // .withTestClasses(configuration.getTestClasses()) // .withListener(new CustomListener(customListenerStatus)) // .build(); // // environment.lifecycle().manage(atam4j); // environment.jersey().register(new CustomListenerStatusResource(customListenerStatus)); // } // }
import io.dropwizard.testing.ConfigOverride; import io.dropwizard.testing.DropwizardTestSupport; import io.dropwizard.testing.ResourceHelpers; import me.atam.atam4jsampleapp.ApplicationConfiguration; import me.atam.atam4jsampleapp.Atam4jTestApplication;
package me.atam.atam4jsampleapp.testsupport; public class Atam4jApplicationStarter { public static DropwizardTestSupport<ApplicationConfiguration> startApplicationWith( int initialDelayInMillis, Class testClass, int periodInMillis) { ConfigOverride[] configOverrides = { ConfigOverride.config("testClasses", testClass.getName()), ConfigOverride.config("initialDelayInMillis", String.valueOf(initialDelayInMillis)), ConfigOverride.config("periodInMillis", String.valueOf(periodInMillis)) }; DropwizardTestSupport<ApplicationConfiguration> applicationConfigurationDropwizardTestSupport =
// Path: acceptance-tests/src/main/java/me/atam/atam4jsampleapp/ApplicationConfiguration.java // public class ApplicationConfiguration extends Configuration { // // @JsonProperty // private int initialDelayInMillis; // // @JsonProperty // private Class[] testClasses; // private long periodInMillis; // // public Class[] getTestClasses(){ // return testClasses; // } // // public int getInitialDelayInMillis() { // return initialDelayInMillis; // } // // public long getPeriodInMillis() { // return periodInMillis; // } // } // // Path: acceptance-tests/src/main/java/me/atam/atam4jsampleapp/Atam4jTestApplication.java // public class Atam4jTestApplication extends Application<ApplicationConfiguration> { // // public static void main(String[] args) throws Exception { // if (args == null || args.length == 0) { // args = new String[]{"server", new File(Resources.getResource("atam4j-config.yml").toURI()).getAbsolutePath()}; // } // // new Atam4jTestApplication().run(args); // } // // @Override // public void run(final ApplicationConfiguration configuration, final Environment environment) throws Exception { // CustomListenerStatus customListenerStatus = new CustomListenerStatus(); // Atam4j atam4j = new Atam4j.Atam4jBuilder(environment.jersey()) // .withUnit(TimeUnit.MILLISECONDS) // .withInitialDelay(configuration.getInitialDelayInMillis()) // .withPeriod(configuration.getPeriodInMillis()) // .withTestClasses(configuration.getTestClasses()) // .withListener(new CustomListener(customListenerStatus)) // .build(); // // environment.lifecycle().manage(atam4j); // environment.jersey().register(new CustomListenerStatusResource(customListenerStatus)); // } // } // Path: acceptance-tests/src/test/java/me/atam/atam4jsampleapp/testsupport/Atam4jApplicationStarter.java import io.dropwizard.testing.ConfigOverride; import io.dropwizard.testing.DropwizardTestSupport; import io.dropwizard.testing.ResourceHelpers; import me.atam.atam4jsampleapp.ApplicationConfiguration; import me.atam.atam4jsampleapp.Atam4jTestApplication; package me.atam.atam4jsampleapp.testsupport; public class Atam4jApplicationStarter { public static DropwizardTestSupport<ApplicationConfiguration> startApplicationWith( int initialDelayInMillis, Class testClass, int periodInMillis) { ConfigOverride[] configOverrides = { ConfigOverride.config("testClasses", testClass.getName()), ConfigOverride.config("initialDelayInMillis", String.valueOf(initialDelayInMillis)), ConfigOverride.config("periodInMillis", String.valueOf(periodInMillis)) }; DropwizardTestSupport<ApplicationConfiguration> applicationConfigurationDropwizardTestSupport =
new DropwizardTestSupport<>(Atam4jTestApplication.class,
atam4j/atam4j
atam4j/src/test/java/me/atam/atam4j/AcceptanceTestsRunnerTaskTest.java
// Path: dummy-tests/src/test/java/me/atam/atam4j/dummytests/FailingTest.java // public class FailingTest { // // @Test // public void testThatFails(){ // Assert.assertTrue("Was expecting false to be true", false); // } // } // // Path: dummy-tests/src/test/java/me/atam/atam4j/dummytests/PassingTestWithNoCategory.java // @Monitor // public class PassingTestWithNoCategory { // // @Test // public void testThatPasses(){ // Assert.assertTrue(true); // } // } // // Path: dummy-tests/src/test/java/me/atam/atam4j/dummytests/TestThatFailsOnInitialisation.java // public class TestThatFailsOnInitialisation { // // @Before // public void setUp() throws Exception { // throw new RuntimeException("Nasty Exception on setUp()"); // } // // @Test // public void testThatWouldPassIfRun(){ // Assert.assertTrue(true); // } // } // // Path: atam4j/src/main/java/me/atam/atam4j/health/AcceptanceTestsState.java // public class AcceptanceTestsState { // // private Optional<Result> result = Optional.empty(); // // public Optional<Result> getResult() { // return result; // } // // public void setResult(Result result) { // this.result = Optional.of(result); // } // // } // // Path: atam4j/src/main/java/me/atam/atam4j/logging/LoggingListener.java // public class LoggingListener extends RunListener { // private static Logger LOGGER = LoggerFactory.getLogger(LoggingListener.class); // // @Override // public void testRunStarted(Description description) throws Exception { // LOGGER.info("Starting tests at {}", new Date()); // } // // @Override // public void testRunFinished(Result result) throws Exception { // LOGGER.info("Tests finishes at {}", new Date()); // LOGGER.info("Report :: total run = {}, failures = {}, in time = {} milliseconds", // result.getRunCount(), // result.getFailureCount(), // result.getRunTime() // ); // } // // @Override // public void testStarted(Description description) throws Exception { // LOGGER.debug("Starting {}", description.getDisplayName()); // } // // @Override // public void testFinished(Description description) throws Exception { // LOGGER.debug("Finished {}", description.getDisplayName()); // } // // @Override // public void testFailure(Failure failure) throws Exception { // LOGGER.error( // String.format("Test %s failed: %s", // failure.getTestHeader(), // failure.getDescription() // ), // failure.getException() // ); // } // // @Override // public void testAssumptionFailure(Failure failure) { // LOGGER.error( // String.format("Test %s assumption failed: %s", // failure.getTestHeader(), // failure.getDescription() // ), // failure.getException() // ); // } // // @Override // public void testIgnored(Description description) throws Exception { // LOGGER.debug("Test {} ignored: ", description.getDisplayName()); // } // }
import me.atam.atam4j.dummytests.FailingTest; import me.atam.atam4j.dummytests.PassingTestWithNoCategory; import me.atam.atam4j.dummytests.TestThatFailsOnInitialisation; import me.atam.atam4j.health.AcceptanceTestsState; import me.atam.atam4j.logging.LoggingListener; import org.junit.Test; import org.junit.runner.Result; import uk.org.lidalia.slf4jtest.TestLogger; import uk.org.lidalia.slf4jtest.TestLoggerFactory; import static java.util.Arrays.asList; import static org.hamcrest.CoreMatchers.hasItem; import static org.junit.Assert.*;
package me.atam.atam4j; public class AcceptanceTestsRunnerTaskTest { AcceptanceTestsState acceptanceTestsState = new AcceptanceTestsState();
// Path: dummy-tests/src/test/java/me/atam/atam4j/dummytests/FailingTest.java // public class FailingTest { // // @Test // public void testThatFails(){ // Assert.assertTrue("Was expecting false to be true", false); // } // } // // Path: dummy-tests/src/test/java/me/atam/atam4j/dummytests/PassingTestWithNoCategory.java // @Monitor // public class PassingTestWithNoCategory { // // @Test // public void testThatPasses(){ // Assert.assertTrue(true); // } // } // // Path: dummy-tests/src/test/java/me/atam/atam4j/dummytests/TestThatFailsOnInitialisation.java // public class TestThatFailsOnInitialisation { // // @Before // public void setUp() throws Exception { // throw new RuntimeException("Nasty Exception on setUp()"); // } // // @Test // public void testThatWouldPassIfRun(){ // Assert.assertTrue(true); // } // } // // Path: atam4j/src/main/java/me/atam/atam4j/health/AcceptanceTestsState.java // public class AcceptanceTestsState { // // private Optional<Result> result = Optional.empty(); // // public Optional<Result> getResult() { // return result; // } // // public void setResult(Result result) { // this.result = Optional.of(result); // } // // } // // Path: atam4j/src/main/java/me/atam/atam4j/logging/LoggingListener.java // public class LoggingListener extends RunListener { // private static Logger LOGGER = LoggerFactory.getLogger(LoggingListener.class); // // @Override // public void testRunStarted(Description description) throws Exception { // LOGGER.info("Starting tests at {}", new Date()); // } // // @Override // public void testRunFinished(Result result) throws Exception { // LOGGER.info("Tests finishes at {}", new Date()); // LOGGER.info("Report :: total run = {}, failures = {}, in time = {} milliseconds", // result.getRunCount(), // result.getFailureCount(), // result.getRunTime() // ); // } // // @Override // public void testStarted(Description description) throws Exception { // LOGGER.debug("Starting {}", description.getDisplayName()); // } // // @Override // public void testFinished(Description description) throws Exception { // LOGGER.debug("Finished {}", description.getDisplayName()); // } // // @Override // public void testFailure(Failure failure) throws Exception { // LOGGER.error( // String.format("Test %s failed: %s", // failure.getTestHeader(), // failure.getDescription() // ), // failure.getException() // ); // } // // @Override // public void testAssumptionFailure(Failure failure) { // LOGGER.error( // String.format("Test %s assumption failed: %s", // failure.getTestHeader(), // failure.getDescription() // ), // failure.getException() // ); // } // // @Override // public void testIgnored(Description description) throws Exception { // LOGGER.debug("Test {} ignored: ", description.getDisplayName()); // } // } // Path: atam4j/src/test/java/me/atam/atam4j/AcceptanceTestsRunnerTaskTest.java import me.atam.atam4j.dummytests.FailingTest; import me.atam.atam4j.dummytests.PassingTestWithNoCategory; import me.atam.atam4j.dummytests.TestThatFailsOnInitialisation; import me.atam.atam4j.health.AcceptanceTestsState; import me.atam.atam4j.logging.LoggingListener; import org.junit.Test; import org.junit.runner.Result; import uk.org.lidalia.slf4jtest.TestLogger; import uk.org.lidalia.slf4jtest.TestLoggerFactory; import static java.util.Arrays.asList; import static org.hamcrest.CoreMatchers.hasItem; import static org.junit.Assert.*; package me.atam.atam4j; public class AcceptanceTestsRunnerTaskTest { AcceptanceTestsState acceptanceTestsState = new AcceptanceTestsState();
TestLogger logger = TestLoggerFactory.getTestLogger(LoggingListener.class);
atam4j/atam4j
atam4j/src/test/java/me/atam/atam4j/AcceptanceTestsRunnerTaskTest.java
// Path: dummy-tests/src/test/java/me/atam/atam4j/dummytests/FailingTest.java // public class FailingTest { // // @Test // public void testThatFails(){ // Assert.assertTrue("Was expecting false to be true", false); // } // } // // Path: dummy-tests/src/test/java/me/atam/atam4j/dummytests/PassingTestWithNoCategory.java // @Monitor // public class PassingTestWithNoCategory { // // @Test // public void testThatPasses(){ // Assert.assertTrue(true); // } // } // // Path: dummy-tests/src/test/java/me/atam/atam4j/dummytests/TestThatFailsOnInitialisation.java // public class TestThatFailsOnInitialisation { // // @Before // public void setUp() throws Exception { // throw new RuntimeException("Nasty Exception on setUp()"); // } // // @Test // public void testThatWouldPassIfRun(){ // Assert.assertTrue(true); // } // } // // Path: atam4j/src/main/java/me/atam/atam4j/health/AcceptanceTestsState.java // public class AcceptanceTestsState { // // private Optional<Result> result = Optional.empty(); // // public Optional<Result> getResult() { // return result; // } // // public void setResult(Result result) { // this.result = Optional.of(result); // } // // } // // Path: atam4j/src/main/java/me/atam/atam4j/logging/LoggingListener.java // public class LoggingListener extends RunListener { // private static Logger LOGGER = LoggerFactory.getLogger(LoggingListener.class); // // @Override // public void testRunStarted(Description description) throws Exception { // LOGGER.info("Starting tests at {}", new Date()); // } // // @Override // public void testRunFinished(Result result) throws Exception { // LOGGER.info("Tests finishes at {}", new Date()); // LOGGER.info("Report :: total run = {}, failures = {}, in time = {} milliseconds", // result.getRunCount(), // result.getFailureCount(), // result.getRunTime() // ); // } // // @Override // public void testStarted(Description description) throws Exception { // LOGGER.debug("Starting {}", description.getDisplayName()); // } // // @Override // public void testFinished(Description description) throws Exception { // LOGGER.debug("Finished {}", description.getDisplayName()); // } // // @Override // public void testFailure(Failure failure) throws Exception { // LOGGER.error( // String.format("Test %s failed: %s", // failure.getTestHeader(), // failure.getDescription() // ), // failure.getException() // ); // } // // @Override // public void testAssumptionFailure(Failure failure) { // LOGGER.error( // String.format("Test %s assumption failed: %s", // failure.getTestHeader(), // failure.getDescription() // ), // failure.getException() // ); // } // // @Override // public void testIgnored(Description description) throws Exception { // LOGGER.debug("Test {} ignored: ", description.getDisplayName()); // } // }
import me.atam.atam4j.dummytests.FailingTest; import me.atam.atam4j.dummytests.PassingTestWithNoCategory; import me.atam.atam4j.dummytests.TestThatFailsOnInitialisation; import me.atam.atam4j.health.AcceptanceTestsState; import me.atam.atam4j.logging.LoggingListener; import org.junit.Test; import org.junit.runner.Result; import uk.org.lidalia.slf4jtest.TestLogger; import uk.org.lidalia.slf4jtest.TestLoggerFactory; import static java.util.Arrays.asList; import static org.hamcrest.CoreMatchers.hasItem; import static org.junit.Assert.*;
package me.atam.atam4j; public class AcceptanceTestsRunnerTaskTest { AcceptanceTestsState acceptanceTestsState = new AcceptanceTestsState(); TestLogger logger = TestLoggerFactory.getTestLogger(LoggingListener.class); @Test public void testPassingTestsRun(){
// Path: dummy-tests/src/test/java/me/atam/atam4j/dummytests/FailingTest.java // public class FailingTest { // // @Test // public void testThatFails(){ // Assert.assertTrue("Was expecting false to be true", false); // } // } // // Path: dummy-tests/src/test/java/me/atam/atam4j/dummytests/PassingTestWithNoCategory.java // @Monitor // public class PassingTestWithNoCategory { // // @Test // public void testThatPasses(){ // Assert.assertTrue(true); // } // } // // Path: dummy-tests/src/test/java/me/atam/atam4j/dummytests/TestThatFailsOnInitialisation.java // public class TestThatFailsOnInitialisation { // // @Before // public void setUp() throws Exception { // throw new RuntimeException("Nasty Exception on setUp()"); // } // // @Test // public void testThatWouldPassIfRun(){ // Assert.assertTrue(true); // } // } // // Path: atam4j/src/main/java/me/atam/atam4j/health/AcceptanceTestsState.java // public class AcceptanceTestsState { // // private Optional<Result> result = Optional.empty(); // // public Optional<Result> getResult() { // return result; // } // // public void setResult(Result result) { // this.result = Optional.of(result); // } // // } // // Path: atam4j/src/main/java/me/atam/atam4j/logging/LoggingListener.java // public class LoggingListener extends RunListener { // private static Logger LOGGER = LoggerFactory.getLogger(LoggingListener.class); // // @Override // public void testRunStarted(Description description) throws Exception { // LOGGER.info("Starting tests at {}", new Date()); // } // // @Override // public void testRunFinished(Result result) throws Exception { // LOGGER.info("Tests finishes at {}", new Date()); // LOGGER.info("Report :: total run = {}, failures = {}, in time = {} milliseconds", // result.getRunCount(), // result.getFailureCount(), // result.getRunTime() // ); // } // // @Override // public void testStarted(Description description) throws Exception { // LOGGER.debug("Starting {}", description.getDisplayName()); // } // // @Override // public void testFinished(Description description) throws Exception { // LOGGER.debug("Finished {}", description.getDisplayName()); // } // // @Override // public void testFailure(Failure failure) throws Exception { // LOGGER.error( // String.format("Test %s failed: %s", // failure.getTestHeader(), // failure.getDescription() // ), // failure.getException() // ); // } // // @Override // public void testAssumptionFailure(Failure failure) { // LOGGER.error( // String.format("Test %s assumption failed: %s", // failure.getTestHeader(), // failure.getDescription() // ), // failure.getException() // ); // } // // @Override // public void testIgnored(Description description) throws Exception { // LOGGER.debug("Test {} ignored: ", description.getDisplayName()); // } // } // Path: atam4j/src/test/java/me/atam/atam4j/AcceptanceTestsRunnerTaskTest.java import me.atam.atam4j.dummytests.FailingTest; import me.atam.atam4j.dummytests.PassingTestWithNoCategory; import me.atam.atam4j.dummytests.TestThatFailsOnInitialisation; import me.atam.atam4j.health.AcceptanceTestsState; import me.atam.atam4j.logging.LoggingListener; import org.junit.Test; import org.junit.runner.Result; import uk.org.lidalia.slf4jtest.TestLogger; import uk.org.lidalia.slf4jtest.TestLoggerFactory; import static java.util.Arrays.asList; import static org.hamcrest.CoreMatchers.hasItem; import static org.junit.Assert.*; package me.atam.atam4j; public class AcceptanceTestsRunnerTaskTest { AcceptanceTestsState acceptanceTestsState = new AcceptanceTestsState(); TestLogger logger = TestLoggerFactory.getTestLogger(LoggingListener.class); @Test public void testPassingTestsRun(){
assertTrue(runTestsAndGetResult(PassingTestWithNoCategory.class).wasSuccessful());
atam4j/atam4j
atam4j/src/test/java/me/atam/atam4j/AcceptanceTestsRunnerTaskTest.java
// Path: dummy-tests/src/test/java/me/atam/atam4j/dummytests/FailingTest.java // public class FailingTest { // // @Test // public void testThatFails(){ // Assert.assertTrue("Was expecting false to be true", false); // } // } // // Path: dummy-tests/src/test/java/me/atam/atam4j/dummytests/PassingTestWithNoCategory.java // @Monitor // public class PassingTestWithNoCategory { // // @Test // public void testThatPasses(){ // Assert.assertTrue(true); // } // } // // Path: dummy-tests/src/test/java/me/atam/atam4j/dummytests/TestThatFailsOnInitialisation.java // public class TestThatFailsOnInitialisation { // // @Before // public void setUp() throws Exception { // throw new RuntimeException("Nasty Exception on setUp()"); // } // // @Test // public void testThatWouldPassIfRun(){ // Assert.assertTrue(true); // } // } // // Path: atam4j/src/main/java/me/atam/atam4j/health/AcceptanceTestsState.java // public class AcceptanceTestsState { // // private Optional<Result> result = Optional.empty(); // // public Optional<Result> getResult() { // return result; // } // // public void setResult(Result result) { // this.result = Optional.of(result); // } // // } // // Path: atam4j/src/main/java/me/atam/atam4j/logging/LoggingListener.java // public class LoggingListener extends RunListener { // private static Logger LOGGER = LoggerFactory.getLogger(LoggingListener.class); // // @Override // public void testRunStarted(Description description) throws Exception { // LOGGER.info("Starting tests at {}", new Date()); // } // // @Override // public void testRunFinished(Result result) throws Exception { // LOGGER.info("Tests finishes at {}", new Date()); // LOGGER.info("Report :: total run = {}, failures = {}, in time = {} milliseconds", // result.getRunCount(), // result.getFailureCount(), // result.getRunTime() // ); // } // // @Override // public void testStarted(Description description) throws Exception { // LOGGER.debug("Starting {}", description.getDisplayName()); // } // // @Override // public void testFinished(Description description) throws Exception { // LOGGER.debug("Finished {}", description.getDisplayName()); // } // // @Override // public void testFailure(Failure failure) throws Exception { // LOGGER.error( // String.format("Test %s failed: %s", // failure.getTestHeader(), // failure.getDescription() // ), // failure.getException() // ); // } // // @Override // public void testAssumptionFailure(Failure failure) { // LOGGER.error( // String.format("Test %s assumption failed: %s", // failure.getTestHeader(), // failure.getDescription() // ), // failure.getException() // ); // } // // @Override // public void testIgnored(Description description) throws Exception { // LOGGER.debug("Test {} ignored: ", description.getDisplayName()); // } // }
import me.atam.atam4j.dummytests.FailingTest; import me.atam.atam4j.dummytests.PassingTestWithNoCategory; import me.atam.atam4j.dummytests.TestThatFailsOnInitialisation; import me.atam.atam4j.health.AcceptanceTestsState; import me.atam.atam4j.logging.LoggingListener; import org.junit.Test; import org.junit.runner.Result; import uk.org.lidalia.slf4jtest.TestLogger; import uk.org.lidalia.slf4jtest.TestLoggerFactory; import static java.util.Arrays.asList; import static org.hamcrest.CoreMatchers.hasItem; import static org.junit.Assert.*;
package me.atam.atam4j; public class AcceptanceTestsRunnerTaskTest { AcceptanceTestsState acceptanceTestsState = new AcceptanceTestsState(); TestLogger logger = TestLoggerFactory.getTestLogger(LoggingListener.class); @Test public void testPassingTestsRun(){ assertTrue(runTestsAndGetResult(PassingTestWithNoCategory.class).wasSuccessful()); } @Test public void testFailingTestFailsAndErrorIsLogged(){
// Path: dummy-tests/src/test/java/me/atam/atam4j/dummytests/FailingTest.java // public class FailingTest { // // @Test // public void testThatFails(){ // Assert.assertTrue("Was expecting false to be true", false); // } // } // // Path: dummy-tests/src/test/java/me/atam/atam4j/dummytests/PassingTestWithNoCategory.java // @Monitor // public class PassingTestWithNoCategory { // // @Test // public void testThatPasses(){ // Assert.assertTrue(true); // } // } // // Path: dummy-tests/src/test/java/me/atam/atam4j/dummytests/TestThatFailsOnInitialisation.java // public class TestThatFailsOnInitialisation { // // @Before // public void setUp() throws Exception { // throw new RuntimeException("Nasty Exception on setUp()"); // } // // @Test // public void testThatWouldPassIfRun(){ // Assert.assertTrue(true); // } // } // // Path: atam4j/src/main/java/me/atam/atam4j/health/AcceptanceTestsState.java // public class AcceptanceTestsState { // // private Optional<Result> result = Optional.empty(); // // public Optional<Result> getResult() { // return result; // } // // public void setResult(Result result) { // this.result = Optional.of(result); // } // // } // // Path: atam4j/src/main/java/me/atam/atam4j/logging/LoggingListener.java // public class LoggingListener extends RunListener { // private static Logger LOGGER = LoggerFactory.getLogger(LoggingListener.class); // // @Override // public void testRunStarted(Description description) throws Exception { // LOGGER.info("Starting tests at {}", new Date()); // } // // @Override // public void testRunFinished(Result result) throws Exception { // LOGGER.info("Tests finishes at {}", new Date()); // LOGGER.info("Report :: total run = {}, failures = {}, in time = {} milliseconds", // result.getRunCount(), // result.getFailureCount(), // result.getRunTime() // ); // } // // @Override // public void testStarted(Description description) throws Exception { // LOGGER.debug("Starting {}", description.getDisplayName()); // } // // @Override // public void testFinished(Description description) throws Exception { // LOGGER.debug("Finished {}", description.getDisplayName()); // } // // @Override // public void testFailure(Failure failure) throws Exception { // LOGGER.error( // String.format("Test %s failed: %s", // failure.getTestHeader(), // failure.getDescription() // ), // failure.getException() // ); // } // // @Override // public void testAssumptionFailure(Failure failure) { // LOGGER.error( // String.format("Test %s assumption failed: %s", // failure.getTestHeader(), // failure.getDescription() // ), // failure.getException() // ); // } // // @Override // public void testIgnored(Description description) throws Exception { // LOGGER.debug("Test {} ignored: ", description.getDisplayName()); // } // } // Path: atam4j/src/test/java/me/atam/atam4j/AcceptanceTestsRunnerTaskTest.java import me.atam.atam4j.dummytests.FailingTest; import me.atam.atam4j.dummytests.PassingTestWithNoCategory; import me.atam.atam4j.dummytests.TestThatFailsOnInitialisation; import me.atam.atam4j.health.AcceptanceTestsState; import me.atam.atam4j.logging.LoggingListener; import org.junit.Test; import org.junit.runner.Result; import uk.org.lidalia.slf4jtest.TestLogger; import uk.org.lidalia.slf4jtest.TestLoggerFactory; import static java.util.Arrays.asList; import static org.hamcrest.CoreMatchers.hasItem; import static org.junit.Assert.*; package me.atam.atam4j; public class AcceptanceTestsRunnerTaskTest { AcceptanceTestsState acceptanceTestsState = new AcceptanceTestsState(); TestLogger logger = TestLoggerFactory.getTestLogger(LoggingListener.class); @Test public void testPassingTestsRun(){ assertTrue(runTestsAndGetResult(PassingTestWithNoCategory.class).wasSuccessful()); } @Test public void testFailingTestFailsAndErrorIsLogged(){
assertFalse(runTestsAndGetResult(FailingTest.class).wasSuccessful());
atam4j/atam4j
atam4j/src/test/java/me/atam/atam4j/AcceptanceTestsRunnerTaskTest.java
// Path: dummy-tests/src/test/java/me/atam/atam4j/dummytests/FailingTest.java // public class FailingTest { // // @Test // public void testThatFails(){ // Assert.assertTrue("Was expecting false to be true", false); // } // } // // Path: dummy-tests/src/test/java/me/atam/atam4j/dummytests/PassingTestWithNoCategory.java // @Monitor // public class PassingTestWithNoCategory { // // @Test // public void testThatPasses(){ // Assert.assertTrue(true); // } // } // // Path: dummy-tests/src/test/java/me/atam/atam4j/dummytests/TestThatFailsOnInitialisation.java // public class TestThatFailsOnInitialisation { // // @Before // public void setUp() throws Exception { // throw new RuntimeException("Nasty Exception on setUp()"); // } // // @Test // public void testThatWouldPassIfRun(){ // Assert.assertTrue(true); // } // } // // Path: atam4j/src/main/java/me/atam/atam4j/health/AcceptanceTestsState.java // public class AcceptanceTestsState { // // private Optional<Result> result = Optional.empty(); // // public Optional<Result> getResult() { // return result; // } // // public void setResult(Result result) { // this.result = Optional.of(result); // } // // } // // Path: atam4j/src/main/java/me/atam/atam4j/logging/LoggingListener.java // public class LoggingListener extends RunListener { // private static Logger LOGGER = LoggerFactory.getLogger(LoggingListener.class); // // @Override // public void testRunStarted(Description description) throws Exception { // LOGGER.info("Starting tests at {}", new Date()); // } // // @Override // public void testRunFinished(Result result) throws Exception { // LOGGER.info("Tests finishes at {}", new Date()); // LOGGER.info("Report :: total run = {}, failures = {}, in time = {} milliseconds", // result.getRunCount(), // result.getFailureCount(), // result.getRunTime() // ); // } // // @Override // public void testStarted(Description description) throws Exception { // LOGGER.debug("Starting {}", description.getDisplayName()); // } // // @Override // public void testFinished(Description description) throws Exception { // LOGGER.debug("Finished {}", description.getDisplayName()); // } // // @Override // public void testFailure(Failure failure) throws Exception { // LOGGER.error( // String.format("Test %s failed: %s", // failure.getTestHeader(), // failure.getDescription() // ), // failure.getException() // ); // } // // @Override // public void testAssumptionFailure(Failure failure) { // LOGGER.error( // String.format("Test %s assumption failed: %s", // failure.getTestHeader(), // failure.getDescription() // ), // failure.getException() // ); // } // // @Override // public void testIgnored(Description description) throws Exception { // LOGGER.debug("Test {} ignored: ", description.getDisplayName()); // } // }
import me.atam.atam4j.dummytests.FailingTest; import me.atam.atam4j.dummytests.PassingTestWithNoCategory; import me.atam.atam4j.dummytests.TestThatFailsOnInitialisation; import me.atam.atam4j.health.AcceptanceTestsState; import me.atam.atam4j.logging.LoggingListener; import org.junit.Test; import org.junit.runner.Result; import uk.org.lidalia.slf4jtest.TestLogger; import uk.org.lidalia.slf4jtest.TestLoggerFactory; import static java.util.Arrays.asList; import static org.hamcrest.CoreMatchers.hasItem; import static org.junit.Assert.*;
package me.atam.atam4j; public class AcceptanceTestsRunnerTaskTest { AcceptanceTestsState acceptanceTestsState = new AcceptanceTestsState(); TestLogger logger = TestLoggerFactory.getTestLogger(LoggingListener.class); @Test public void testPassingTestsRun(){ assertTrue(runTestsAndGetResult(PassingTestWithNoCategory.class).wasSuccessful()); } @Test public void testFailingTestFailsAndErrorIsLogged(){ assertFalse(runTestsAndGetResult(FailingTest.class).wasSuccessful()); assertThat(logger.getLoggingEvents(), hasItem(LoggingEventWithThrowableMatcher.hasThrowableThatContainsString("Was expecting false to be true"))); } @Test public void testPassingAndFailingTestReportsFailure() { assertFalse(runTestsAndGetResult(FailingTest.class, PassingTestWithNoCategory.class).wasSuccessful()); } @Test public void testThatExceptionFromTestsGetsLogged() {
// Path: dummy-tests/src/test/java/me/atam/atam4j/dummytests/FailingTest.java // public class FailingTest { // // @Test // public void testThatFails(){ // Assert.assertTrue("Was expecting false to be true", false); // } // } // // Path: dummy-tests/src/test/java/me/atam/atam4j/dummytests/PassingTestWithNoCategory.java // @Monitor // public class PassingTestWithNoCategory { // // @Test // public void testThatPasses(){ // Assert.assertTrue(true); // } // } // // Path: dummy-tests/src/test/java/me/atam/atam4j/dummytests/TestThatFailsOnInitialisation.java // public class TestThatFailsOnInitialisation { // // @Before // public void setUp() throws Exception { // throw new RuntimeException("Nasty Exception on setUp()"); // } // // @Test // public void testThatWouldPassIfRun(){ // Assert.assertTrue(true); // } // } // // Path: atam4j/src/main/java/me/atam/atam4j/health/AcceptanceTestsState.java // public class AcceptanceTestsState { // // private Optional<Result> result = Optional.empty(); // // public Optional<Result> getResult() { // return result; // } // // public void setResult(Result result) { // this.result = Optional.of(result); // } // // } // // Path: atam4j/src/main/java/me/atam/atam4j/logging/LoggingListener.java // public class LoggingListener extends RunListener { // private static Logger LOGGER = LoggerFactory.getLogger(LoggingListener.class); // // @Override // public void testRunStarted(Description description) throws Exception { // LOGGER.info("Starting tests at {}", new Date()); // } // // @Override // public void testRunFinished(Result result) throws Exception { // LOGGER.info("Tests finishes at {}", new Date()); // LOGGER.info("Report :: total run = {}, failures = {}, in time = {} milliseconds", // result.getRunCount(), // result.getFailureCount(), // result.getRunTime() // ); // } // // @Override // public void testStarted(Description description) throws Exception { // LOGGER.debug("Starting {}", description.getDisplayName()); // } // // @Override // public void testFinished(Description description) throws Exception { // LOGGER.debug("Finished {}", description.getDisplayName()); // } // // @Override // public void testFailure(Failure failure) throws Exception { // LOGGER.error( // String.format("Test %s failed: %s", // failure.getTestHeader(), // failure.getDescription() // ), // failure.getException() // ); // } // // @Override // public void testAssumptionFailure(Failure failure) { // LOGGER.error( // String.format("Test %s assumption failed: %s", // failure.getTestHeader(), // failure.getDescription() // ), // failure.getException() // ); // } // // @Override // public void testIgnored(Description description) throws Exception { // LOGGER.debug("Test {} ignored: ", description.getDisplayName()); // } // } // Path: atam4j/src/test/java/me/atam/atam4j/AcceptanceTestsRunnerTaskTest.java import me.atam.atam4j.dummytests.FailingTest; import me.atam.atam4j.dummytests.PassingTestWithNoCategory; import me.atam.atam4j.dummytests.TestThatFailsOnInitialisation; import me.atam.atam4j.health.AcceptanceTestsState; import me.atam.atam4j.logging.LoggingListener; import org.junit.Test; import org.junit.runner.Result; import uk.org.lidalia.slf4jtest.TestLogger; import uk.org.lidalia.slf4jtest.TestLoggerFactory; import static java.util.Arrays.asList; import static org.hamcrest.CoreMatchers.hasItem; import static org.junit.Assert.*; package me.atam.atam4j; public class AcceptanceTestsRunnerTaskTest { AcceptanceTestsState acceptanceTestsState = new AcceptanceTestsState(); TestLogger logger = TestLoggerFactory.getTestLogger(LoggingListener.class); @Test public void testPassingTestsRun(){ assertTrue(runTestsAndGetResult(PassingTestWithNoCategory.class).wasSuccessful()); } @Test public void testFailingTestFailsAndErrorIsLogged(){ assertFalse(runTestsAndGetResult(FailingTest.class).wasSuccessful()); assertThat(logger.getLoggingEvents(), hasItem(LoggingEventWithThrowableMatcher.hasThrowableThatContainsString("Was expecting false to be true"))); } @Test public void testPassingAndFailingTestReportsFailure() { assertFalse(runTestsAndGetResult(FailingTest.class, PassingTestWithNoCategory.class).wasSuccessful()); } @Test public void testThatExceptionFromTestsGetsLogged() {
assertFalse(runTestsAndGetResult(TestThatFailsOnInitialisation.class).wasSuccessful());
atam4j/atam4j
acceptance-tests/src/main/java/me/atam/atam4jsampleapp/Atam4jTestApplication.java
// Path: atam4j/src/main/java/me/atam/atam4j/Atam4j.java // public class Atam4j implements Managed { // // private final AcceptanceTestsState acceptanceTestsState = new AcceptanceTestsState(); // private final AcceptanceTestsRunnerTaskScheduler acceptanceTestsRunnerTaskScheduler; // private final TestRunListener testRunListener; // private final JerseyEnvironment jerseyEnvironment; // // public Atam4j(JerseyEnvironment jerseyEnvironment, // TestRunListener testRunListener, // AcceptanceTestsRunnerTaskScheduler acceptanceTestsRunnerTaskScheduler) { // // this.jerseyEnvironment = jerseyEnvironment; // this.testRunListener = testRunListener; // this.acceptanceTestsRunnerTaskScheduler = acceptanceTestsRunnerTaskScheduler; // } // // // @Override // public void start() { // acceptanceTestsRunnerTaskScheduler.scheduleAcceptanceTestsRunnerTask(acceptanceTestsState); // jerseyEnvironment.register(new TestStatusResource(testRunListener)); // } // // @Override // public void stop() { // acceptanceTestsRunnerTaskScheduler.stop(); // } // // public static class Atam4jBuilder { // // private Optional<Class[]> testClasses = Optional.empty(); // private long initialDelay = 60; // private long period = 300; // private TimeUnit unit = TimeUnit.SECONDS; // private JerseyEnvironment jerseyEnvironment; // private final List<RunListener> runListeners = new ArrayList<>(); // // public Atam4jBuilder(JerseyEnvironment jerseyEnvironment) { // this.jerseyEnvironment = jerseyEnvironment; // } // // public Atam4jBuilder withTestClasses(Class... testClasses) { // this.testClasses = Optional.of(testClasses); // return this; // } // // public Atam4jBuilder withInitialDelay(long initialDelay) { // this.initialDelay = initialDelay; // return this; // } // // public Atam4jBuilder withPeriod(long period) { // this.period = period; // return this; // } // // public Atam4jBuilder withUnit(TimeUnit unit) { // this.unit = unit; // return this; // } // // public Atam4jBuilder withListener(RunListener listener) { // this.runListeners.add(listener); // return this; // } // // public Atam4j build() { // TestRunListener testRunListener = new TestRunListener(); // List<RunListener> runListenersWithAtam4jListener = new ArrayList<>(); // runListenersWithAtam4jListener.add(testRunListener); // runListenersWithAtam4jListener.addAll(this.runListeners); // return new Atam4j(jerseyEnvironment, testRunListener, // new AcceptanceTestsRunnerTaskScheduler( // findTestClasses(), // initialDelay, // period, // unit, // runListenersWithAtam4jListener)); // } // // private Class[] findTestClasses() { // final Class[] classes = testClasses.orElseGet(() -> // new Reflections(new ConfigurationBuilder() // .setUrls(ClasspathHelper.forJavaClassPath()) // .setScanners(new SubTypesScanner(), new TypeAnnotationsScanner())) // .getTypesAnnotatedWith(Monitor.class) // .stream() // .toArray(Class[]::new)); // if(classes.length == 0) { // throw new NoTestClassFoundException("Could not find any annotated test classes and no classes were provided via the Atam4jBuilder."); // } // return classes; // } // } // } // // Path: acceptance-tests/src/main/java/me/atam/atam4jsampleapp/resources/CustomListenerStatusResource.java // @Path("/customlistenerstatus") // @Produces("application/json") // public class CustomListenerStatusResource { // private final CustomListenerStatus customListenerStatus; // // public CustomListenerStatusResource(CustomListenerStatus customListenerStatus) { this.customListenerStatus = customListenerStatus; } // // @GET // public CustomListenerStatus getAcceptanceTestRunListenerStatus() { return customListenerStatus; } // }
import com.google.common.io.Resources; import io.dropwizard.Application; import io.dropwizard.setup.Environment; import me.atam.atam4j.Atam4j; import me.atam.atam4jsampleapp.resources.CustomListenerStatusResource; import java.io.File; import java.util.concurrent.TimeUnit;
package me.atam.atam4jsampleapp; public class Atam4jTestApplication extends Application<ApplicationConfiguration> { public static void main(String[] args) throws Exception { if (args == null || args.length == 0) { args = new String[]{"server", new File(Resources.getResource("atam4j-config.yml").toURI()).getAbsolutePath()}; } new Atam4jTestApplication().run(args); } @Override public void run(final ApplicationConfiguration configuration, final Environment environment) throws Exception { CustomListenerStatus customListenerStatus = new CustomListenerStatus();
// Path: atam4j/src/main/java/me/atam/atam4j/Atam4j.java // public class Atam4j implements Managed { // // private final AcceptanceTestsState acceptanceTestsState = new AcceptanceTestsState(); // private final AcceptanceTestsRunnerTaskScheduler acceptanceTestsRunnerTaskScheduler; // private final TestRunListener testRunListener; // private final JerseyEnvironment jerseyEnvironment; // // public Atam4j(JerseyEnvironment jerseyEnvironment, // TestRunListener testRunListener, // AcceptanceTestsRunnerTaskScheduler acceptanceTestsRunnerTaskScheduler) { // // this.jerseyEnvironment = jerseyEnvironment; // this.testRunListener = testRunListener; // this.acceptanceTestsRunnerTaskScheduler = acceptanceTestsRunnerTaskScheduler; // } // // // @Override // public void start() { // acceptanceTestsRunnerTaskScheduler.scheduleAcceptanceTestsRunnerTask(acceptanceTestsState); // jerseyEnvironment.register(new TestStatusResource(testRunListener)); // } // // @Override // public void stop() { // acceptanceTestsRunnerTaskScheduler.stop(); // } // // public static class Atam4jBuilder { // // private Optional<Class[]> testClasses = Optional.empty(); // private long initialDelay = 60; // private long period = 300; // private TimeUnit unit = TimeUnit.SECONDS; // private JerseyEnvironment jerseyEnvironment; // private final List<RunListener> runListeners = new ArrayList<>(); // // public Atam4jBuilder(JerseyEnvironment jerseyEnvironment) { // this.jerseyEnvironment = jerseyEnvironment; // } // // public Atam4jBuilder withTestClasses(Class... testClasses) { // this.testClasses = Optional.of(testClasses); // return this; // } // // public Atam4jBuilder withInitialDelay(long initialDelay) { // this.initialDelay = initialDelay; // return this; // } // // public Atam4jBuilder withPeriod(long period) { // this.period = period; // return this; // } // // public Atam4jBuilder withUnit(TimeUnit unit) { // this.unit = unit; // return this; // } // // public Atam4jBuilder withListener(RunListener listener) { // this.runListeners.add(listener); // return this; // } // // public Atam4j build() { // TestRunListener testRunListener = new TestRunListener(); // List<RunListener> runListenersWithAtam4jListener = new ArrayList<>(); // runListenersWithAtam4jListener.add(testRunListener); // runListenersWithAtam4jListener.addAll(this.runListeners); // return new Atam4j(jerseyEnvironment, testRunListener, // new AcceptanceTestsRunnerTaskScheduler( // findTestClasses(), // initialDelay, // period, // unit, // runListenersWithAtam4jListener)); // } // // private Class[] findTestClasses() { // final Class[] classes = testClasses.orElseGet(() -> // new Reflections(new ConfigurationBuilder() // .setUrls(ClasspathHelper.forJavaClassPath()) // .setScanners(new SubTypesScanner(), new TypeAnnotationsScanner())) // .getTypesAnnotatedWith(Monitor.class) // .stream() // .toArray(Class[]::new)); // if(classes.length == 0) { // throw new NoTestClassFoundException("Could not find any annotated test classes and no classes were provided via the Atam4jBuilder."); // } // return classes; // } // } // } // // Path: acceptance-tests/src/main/java/me/atam/atam4jsampleapp/resources/CustomListenerStatusResource.java // @Path("/customlistenerstatus") // @Produces("application/json") // public class CustomListenerStatusResource { // private final CustomListenerStatus customListenerStatus; // // public CustomListenerStatusResource(CustomListenerStatus customListenerStatus) { this.customListenerStatus = customListenerStatus; } // // @GET // public CustomListenerStatus getAcceptanceTestRunListenerStatus() { return customListenerStatus; } // } // Path: acceptance-tests/src/main/java/me/atam/atam4jsampleapp/Atam4jTestApplication.java import com.google.common.io.Resources; import io.dropwizard.Application; import io.dropwizard.setup.Environment; import me.atam.atam4j.Atam4j; import me.atam.atam4jsampleapp.resources.CustomListenerStatusResource; import java.io.File; import java.util.concurrent.TimeUnit; package me.atam.atam4jsampleapp; public class Atam4jTestApplication extends Application<ApplicationConfiguration> { public static void main(String[] args) throws Exception { if (args == null || args.length == 0) { args = new String[]{"server", new File(Resources.getResource("atam4j-config.yml").toURI()).getAbsolutePath()}; } new Atam4jTestApplication().run(args); } @Override public void run(final ApplicationConfiguration configuration, final Environment environment) throws Exception { CustomListenerStatus customListenerStatus = new CustomListenerStatus();
Atam4j atam4j = new Atam4j.Atam4jBuilder(environment.jersey())
atam4j/atam4j
acceptance-tests/src/main/java/me/atam/atam4jsampleapp/Atam4jTestApplication.java
// Path: atam4j/src/main/java/me/atam/atam4j/Atam4j.java // public class Atam4j implements Managed { // // private final AcceptanceTestsState acceptanceTestsState = new AcceptanceTestsState(); // private final AcceptanceTestsRunnerTaskScheduler acceptanceTestsRunnerTaskScheduler; // private final TestRunListener testRunListener; // private final JerseyEnvironment jerseyEnvironment; // // public Atam4j(JerseyEnvironment jerseyEnvironment, // TestRunListener testRunListener, // AcceptanceTestsRunnerTaskScheduler acceptanceTestsRunnerTaskScheduler) { // // this.jerseyEnvironment = jerseyEnvironment; // this.testRunListener = testRunListener; // this.acceptanceTestsRunnerTaskScheduler = acceptanceTestsRunnerTaskScheduler; // } // // // @Override // public void start() { // acceptanceTestsRunnerTaskScheduler.scheduleAcceptanceTestsRunnerTask(acceptanceTestsState); // jerseyEnvironment.register(new TestStatusResource(testRunListener)); // } // // @Override // public void stop() { // acceptanceTestsRunnerTaskScheduler.stop(); // } // // public static class Atam4jBuilder { // // private Optional<Class[]> testClasses = Optional.empty(); // private long initialDelay = 60; // private long period = 300; // private TimeUnit unit = TimeUnit.SECONDS; // private JerseyEnvironment jerseyEnvironment; // private final List<RunListener> runListeners = new ArrayList<>(); // // public Atam4jBuilder(JerseyEnvironment jerseyEnvironment) { // this.jerseyEnvironment = jerseyEnvironment; // } // // public Atam4jBuilder withTestClasses(Class... testClasses) { // this.testClasses = Optional.of(testClasses); // return this; // } // // public Atam4jBuilder withInitialDelay(long initialDelay) { // this.initialDelay = initialDelay; // return this; // } // // public Atam4jBuilder withPeriod(long period) { // this.period = period; // return this; // } // // public Atam4jBuilder withUnit(TimeUnit unit) { // this.unit = unit; // return this; // } // // public Atam4jBuilder withListener(RunListener listener) { // this.runListeners.add(listener); // return this; // } // // public Atam4j build() { // TestRunListener testRunListener = new TestRunListener(); // List<RunListener> runListenersWithAtam4jListener = new ArrayList<>(); // runListenersWithAtam4jListener.add(testRunListener); // runListenersWithAtam4jListener.addAll(this.runListeners); // return new Atam4j(jerseyEnvironment, testRunListener, // new AcceptanceTestsRunnerTaskScheduler( // findTestClasses(), // initialDelay, // period, // unit, // runListenersWithAtam4jListener)); // } // // private Class[] findTestClasses() { // final Class[] classes = testClasses.orElseGet(() -> // new Reflections(new ConfigurationBuilder() // .setUrls(ClasspathHelper.forJavaClassPath()) // .setScanners(new SubTypesScanner(), new TypeAnnotationsScanner())) // .getTypesAnnotatedWith(Monitor.class) // .stream() // .toArray(Class[]::new)); // if(classes.length == 0) { // throw new NoTestClassFoundException("Could not find any annotated test classes and no classes were provided via the Atam4jBuilder."); // } // return classes; // } // } // } // // Path: acceptance-tests/src/main/java/me/atam/atam4jsampleapp/resources/CustomListenerStatusResource.java // @Path("/customlistenerstatus") // @Produces("application/json") // public class CustomListenerStatusResource { // private final CustomListenerStatus customListenerStatus; // // public CustomListenerStatusResource(CustomListenerStatus customListenerStatus) { this.customListenerStatus = customListenerStatus; } // // @GET // public CustomListenerStatus getAcceptanceTestRunListenerStatus() { return customListenerStatus; } // }
import com.google.common.io.Resources; import io.dropwizard.Application; import io.dropwizard.setup.Environment; import me.atam.atam4j.Atam4j; import me.atam.atam4jsampleapp.resources.CustomListenerStatusResource; import java.io.File; import java.util.concurrent.TimeUnit;
package me.atam.atam4jsampleapp; public class Atam4jTestApplication extends Application<ApplicationConfiguration> { public static void main(String[] args) throws Exception { if (args == null || args.length == 0) { args = new String[]{"server", new File(Resources.getResource("atam4j-config.yml").toURI()).getAbsolutePath()}; } new Atam4jTestApplication().run(args); } @Override public void run(final ApplicationConfiguration configuration, final Environment environment) throws Exception { CustomListenerStatus customListenerStatus = new CustomListenerStatus(); Atam4j atam4j = new Atam4j.Atam4jBuilder(environment.jersey()) .withUnit(TimeUnit.MILLISECONDS) .withInitialDelay(configuration.getInitialDelayInMillis()) .withPeriod(configuration.getPeriodInMillis()) .withTestClasses(configuration.getTestClasses()) .withListener(new CustomListener(customListenerStatus)) .build(); environment.lifecycle().manage(atam4j);
// Path: atam4j/src/main/java/me/atam/atam4j/Atam4j.java // public class Atam4j implements Managed { // // private final AcceptanceTestsState acceptanceTestsState = new AcceptanceTestsState(); // private final AcceptanceTestsRunnerTaskScheduler acceptanceTestsRunnerTaskScheduler; // private final TestRunListener testRunListener; // private final JerseyEnvironment jerseyEnvironment; // // public Atam4j(JerseyEnvironment jerseyEnvironment, // TestRunListener testRunListener, // AcceptanceTestsRunnerTaskScheduler acceptanceTestsRunnerTaskScheduler) { // // this.jerseyEnvironment = jerseyEnvironment; // this.testRunListener = testRunListener; // this.acceptanceTestsRunnerTaskScheduler = acceptanceTestsRunnerTaskScheduler; // } // // // @Override // public void start() { // acceptanceTestsRunnerTaskScheduler.scheduleAcceptanceTestsRunnerTask(acceptanceTestsState); // jerseyEnvironment.register(new TestStatusResource(testRunListener)); // } // // @Override // public void stop() { // acceptanceTestsRunnerTaskScheduler.stop(); // } // // public static class Atam4jBuilder { // // private Optional<Class[]> testClasses = Optional.empty(); // private long initialDelay = 60; // private long period = 300; // private TimeUnit unit = TimeUnit.SECONDS; // private JerseyEnvironment jerseyEnvironment; // private final List<RunListener> runListeners = new ArrayList<>(); // // public Atam4jBuilder(JerseyEnvironment jerseyEnvironment) { // this.jerseyEnvironment = jerseyEnvironment; // } // // public Atam4jBuilder withTestClasses(Class... testClasses) { // this.testClasses = Optional.of(testClasses); // return this; // } // // public Atam4jBuilder withInitialDelay(long initialDelay) { // this.initialDelay = initialDelay; // return this; // } // // public Atam4jBuilder withPeriod(long period) { // this.period = period; // return this; // } // // public Atam4jBuilder withUnit(TimeUnit unit) { // this.unit = unit; // return this; // } // // public Atam4jBuilder withListener(RunListener listener) { // this.runListeners.add(listener); // return this; // } // // public Atam4j build() { // TestRunListener testRunListener = new TestRunListener(); // List<RunListener> runListenersWithAtam4jListener = new ArrayList<>(); // runListenersWithAtam4jListener.add(testRunListener); // runListenersWithAtam4jListener.addAll(this.runListeners); // return new Atam4j(jerseyEnvironment, testRunListener, // new AcceptanceTestsRunnerTaskScheduler( // findTestClasses(), // initialDelay, // period, // unit, // runListenersWithAtam4jListener)); // } // // private Class[] findTestClasses() { // final Class[] classes = testClasses.orElseGet(() -> // new Reflections(new ConfigurationBuilder() // .setUrls(ClasspathHelper.forJavaClassPath()) // .setScanners(new SubTypesScanner(), new TypeAnnotationsScanner())) // .getTypesAnnotatedWith(Monitor.class) // .stream() // .toArray(Class[]::new)); // if(classes.length == 0) { // throw new NoTestClassFoundException("Could not find any annotated test classes and no classes were provided via the Atam4jBuilder."); // } // return classes; // } // } // } // // Path: acceptance-tests/src/main/java/me/atam/atam4jsampleapp/resources/CustomListenerStatusResource.java // @Path("/customlistenerstatus") // @Produces("application/json") // public class CustomListenerStatusResource { // private final CustomListenerStatus customListenerStatus; // // public CustomListenerStatusResource(CustomListenerStatus customListenerStatus) { this.customListenerStatus = customListenerStatus; } // // @GET // public CustomListenerStatus getAcceptanceTestRunListenerStatus() { return customListenerStatus; } // } // Path: acceptance-tests/src/main/java/me/atam/atam4jsampleapp/Atam4jTestApplication.java import com.google.common.io.Resources; import io.dropwizard.Application; import io.dropwizard.setup.Environment; import me.atam.atam4j.Atam4j; import me.atam.atam4jsampleapp.resources.CustomListenerStatusResource; import java.io.File; import java.util.concurrent.TimeUnit; package me.atam.atam4jsampleapp; public class Atam4jTestApplication extends Application<ApplicationConfiguration> { public static void main(String[] args) throws Exception { if (args == null || args.length == 0) { args = new String[]{"server", new File(Resources.getResource("atam4j-config.yml").toURI()).getAbsolutePath()}; } new Atam4jTestApplication().run(args); } @Override public void run(final ApplicationConfiguration configuration, final Environment environment) throws Exception { CustomListenerStatus customListenerStatus = new CustomListenerStatus(); Atam4j atam4j = new Atam4j.Atam4jBuilder(environment.jersey()) .withUnit(TimeUnit.MILLISECONDS) .withInitialDelay(configuration.getInitialDelayInMillis()) .withPeriod(configuration.getPeriodInMillis()) .withTestClasses(configuration.getTestClasses()) .withListener(new CustomListener(customListenerStatus)) .build(); environment.lifecycle().manage(atam4j);
environment.jersey().register(new CustomListenerStatusResource(customListenerStatus));
atam4j/atam4j
atam4j/src/main/java/me/atam/atam4j/AcceptanceTestsRunnerTask.java
// Path: atam4j/src/main/java/me/atam/atam4j/health/AcceptanceTestsState.java // public class AcceptanceTestsState { // // private Optional<Result> result = Optional.empty(); // // public Optional<Result> getResult() { // return result; // } // // public void setResult(Result result) { // this.result = Optional.of(result); // } // // } // // Path: atam4j/src/main/java/me/atam/atam4j/logging/LoggingListener.java // public class LoggingListener extends RunListener { // private static Logger LOGGER = LoggerFactory.getLogger(LoggingListener.class); // // @Override // public void testRunStarted(Description description) throws Exception { // LOGGER.info("Starting tests at {}", new Date()); // } // // @Override // public void testRunFinished(Result result) throws Exception { // LOGGER.info("Tests finishes at {}", new Date()); // LOGGER.info("Report :: total run = {}, failures = {}, in time = {} milliseconds", // result.getRunCount(), // result.getFailureCount(), // result.getRunTime() // ); // } // // @Override // public void testStarted(Description description) throws Exception { // LOGGER.debug("Starting {}", description.getDisplayName()); // } // // @Override // public void testFinished(Description description) throws Exception { // LOGGER.debug("Finished {}", description.getDisplayName()); // } // // @Override // public void testFailure(Failure failure) throws Exception { // LOGGER.error( // String.format("Test %s failed: %s", // failure.getTestHeader(), // failure.getDescription() // ), // failure.getException() // ); // } // // @Override // public void testAssumptionFailure(Failure failure) { // LOGGER.error( // String.format("Test %s assumption failed: %s", // failure.getTestHeader(), // failure.getDescription() // ), // failure.getException() // ); // } // // @Override // public void testIgnored(Description description) throws Exception { // LOGGER.debug("Test {} ignored: ", description.getDisplayName()); // } // }
import me.atam.atam4j.health.AcceptanceTestsState; import me.atam.atam4j.logging.LoggingListener; import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runner.notification.RunListener; import java.util.List;
package me.atam.atam4j; public class AcceptanceTestsRunnerTask implements Runnable { private final AcceptanceTestsState testsState; private final Class[] testClasses; private List<RunListener> runListeners; AcceptanceTestsRunnerTask(final AcceptanceTestsState testsState, final List<RunListener> runListeners, final Class... testClasses) { this.testsState = testsState; this.testClasses = testClasses; this.runListeners = runListeners; } @Override public void run() { JUnitCore jUnitCore = new JUnitCore();
// Path: atam4j/src/main/java/me/atam/atam4j/health/AcceptanceTestsState.java // public class AcceptanceTestsState { // // private Optional<Result> result = Optional.empty(); // // public Optional<Result> getResult() { // return result; // } // // public void setResult(Result result) { // this.result = Optional.of(result); // } // // } // // Path: atam4j/src/main/java/me/atam/atam4j/logging/LoggingListener.java // public class LoggingListener extends RunListener { // private static Logger LOGGER = LoggerFactory.getLogger(LoggingListener.class); // // @Override // public void testRunStarted(Description description) throws Exception { // LOGGER.info("Starting tests at {}", new Date()); // } // // @Override // public void testRunFinished(Result result) throws Exception { // LOGGER.info("Tests finishes at {}", new Date()); // LOGGER.info("Report :: total run = {}, failures = {}, in time = {} milliseconds", // result.getRunCount(), // result.getFailureCount(), // result.getRunTime() // ); // } // // @Override // public void testStarted(Description description) throws Exception { // LOGGER.debug("Starting {}", description.getDisplayName()); // } // // @Override // public void testFinished(Description description) throws Exception { // LOGGER.debug("Finished {}", description.getDisplayName()); // } // // @Override // public void testFailure(Failure failure) throws Exception { // LOGGER.error( // String.format("Test %s failed: %s", // failure.getTestHeader(), // failure.getDescription() // ), // failure.getException() // ); // } // // @Override // public void testAssumptionFailure(Failure failure) { // LOGGER.error( // String.format("Test %s assumption failed: %s", // failure.getTestHeader(), // failure.getDescription() // ), // failure.getException() // ); // } // // @Override // public void testIgnored(Description description) throws Exception { // LOGGER.debug("Test {} ignored: ", description.getDisplayName()); // } // } // Path: atam4j/src/main/java/me/atam/atam4j/AcceptanceTestsRunnerTask.java import me.atam.atam4j.health.AcceptanceTestsState; import me.atam.atam4j.logging.LoggingListener; import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.runner.notification.RunListener; import java.util.List; package me.atam.atam4j; public class AcceptanceTestsRunnerTask implements Runnable { private final AcceptanceTestsState testsState; private final Class[] testClasses; private List<RunListener> runListeners; AcceptanceTestsRunnerTask(final AcceptanceTestsState testsState, final List<RunListener> runListeners, final Class... testClasses) { this.testsState = testsState; this.testClasses = testClasses; this.runListeners = runListeners; } @Override public void run() { JUnitCore jUnitCore = new JUnitCore();
jUnitCore.addListener(new LoggingListener());
atam4j/atam4j
acceptance-tests/src/main/java/me/atam/atam4jsampleapp/resources/CustomListenerStatusResource.java
// Path: acceptance-tests/src/main/java/me/atam/atam4jsampleapp/CustomListenerStatus.java // public class CustomListenerStatus { // private boolean started; // // public boolean isStarted() { // return started; // } // // public void setStarted(boolean started) { // this.started = started; // } // // public CustomListenerStatus() { // this.started = false; // } // }
import me.atam.atam4jsampleapp.CustomListenerStatus; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces;
package me.atam.atam4jsampleapp.resources; @Path("/customlistenerstatus") @Produces("application/json") public class CustomListenerStatusResource {
// Path: acceptance-tests/src/main/java/me/atam/atam4jsampleapp/CustomListenerStatus.java // public class CustomListenerStatus { // private boolean started; // // public boolean isStarted() { // return started; // } // // public void setStarted(boolean started) { // this.started = started; // } // // public CustomListenerStatus() { // this.started = false; // } // } // Path: acceptance-tests/src/main/java/me/atam/atam4jsampleapp/resources/CustomListenerStatusResource.java import me.atam.atam4jsampleapp.CustomListenerStatus; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; package me.atam.atam4jsampleapp.resources; @Path("/customlistenerstatus") @Produces("application/json") public class CustomListenerStatusResource {
private final CustomListenerStatus customListenerStatus;
atam4j/atam4j
atam4j/src/main/java/me/atam/atam4j/AcceptanceTestsRunnerTaskScheduler.java
// Path: atam4j/src/main/java/me/atam/atam4j/health/AcceptanceTestsState.java // public class AcceptanceTestsState { // // private Optional<Result> result = Optional.empty(); // // public Optional<Result> getResult() { // return result; // } // // public void setResult(Result result) { // this.result = Optional.of(result); // } // // }
import com.google.common.util.concurrent.ThreadFactoryBuilder; import me.atam.atam4j.health.AcceptanceTestsState; import org.junit.runner.notification.RunListener; import java.util.List; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit;
package me.atam.atam4j; public class AcceptanceTestsRunnerTaskScheduler { private final Class[] testClasses; private final long initialDelay; private final long period; private final TimeUnit unit; private final ScheduledExecutorService scheduler; private final List<RunListener> runListeners; public AcceptanceTestsRunnerTaskScheduler(final Class[] testClasses, final long initialDelay, final long period, final TimeUnit unit, final List<RunListener> runListeners) { this.testClasses = testClasses; this.initialDelay = initialDelay; this.period = period; this.unit = unit; this.runListeners = runListeners; this.scheduler = Executors.newSingleThreadScheduledExecutor( new ThreadFactoryBuilder() .setNameFormat("acceptance-tests-runner") .setDaemon(false) .build()); }
// Path: atam4j/src/main/java/me/atam/atam4j/health/AcceptanceTestsState.java // public class AcceptanceTestsState { // // private Optional<Result> result = Optional.empty(); // // public Optional<Result> getResult() { // return result; // } // // public void setResult(Result result) { // this.result = Optional.of(result); // } // // } // Path: atam4j/src/main/java/me/atam/atam4j/AcceptanceTestsRunnerTaskScheduler.java import com.google.common.util.concurrent.ThreadFactoryBuilder; import me.atam.atam4j.health.AcceptanceTestsState; import org.junit.runner.notification.RunListener; import java.util.List; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; package me.atam.atam4j; public class AcceptanceTestsRunnerTaskScheduler { private final Class[] testClasses; private final long initialDelay; private final long period; private final TimeUnit unit; private final ScheduledExecutorService scheduler; private final List<RunListener> runListeners; public AcceptanceTestsRunnerTaskScheduler(final Class[] testClasses, final long initialDelay, final long period, final TimeUnit unit, final List<RunListener> runListeners) { this.testClasses = testClasses; this.initialDelay = initialDelay; this.period = period; this.unit = unit; this.runListeners = runListeners; this.scheduler = Executors.newSingleThreadScheduledExecutor( new ThreadFactoryBuilder() .setNameFormat("acceptance-tests-runner") .setDaemon(false) .build()); }
public void scheduleAcceptanceTestsRunnerTask(final AcceptanceTestsState acceptanceTestsState) {
atam4j/atam4j
acceptance-tests/src/test/java/me/atam/atam4jsampleapp/CustomListenerTest.java
// Path: dummy-tests/src/test/java/me/atam/atam4j/dummytests/PassingTestWithNoCategory.java // @Monitor // public class PassingTestWithNoCategory { // // @Test // public void testThatPasses(){ // Assert.assertTrue(true); // } // } // // Path: acceptance-tests/src/test/java/me/atam/atam4jsampleapp/testsupport/AcceptanceTest.java // public abstract class AcceptanceTest { // // protected DropwizardTestSupport<ApplicationConfiguration> dropwizardTestSupportAppConfig; // // @After // public void stopApplication() { // dropwizardTestSupportAppConfig.after(); // } // // public Response getTestRunResultFromServer(String testsURI){ // return new JerseyClientBuilder().build().target( // testsURI) // .request() // .get(); // } // // public String getTestsURI() { // return String.format("http://localhost:%d/tests", dropwizardTestSupportAppConfig.getLocalPort()); // } // // public Response getResponseFromTestsWithCategoryOnceTestRunHasCompleted(String category) { // waitUntilTestRunHasCompleted(); // return getTestRunResultFromServer(getTestsURI() + "/" + category); // } // // public Response getResponseFromTestsEndpointOnceTestsRunHasCompleted() { // waitUntilTestRunHasCompleted(); // return getTestRunResultFromServer(getTestsURI()); // } // // public Response getCustomListenerStatusOnceTestsRunHasCompleted() { // waitUntilTestRunHasCompleted(); // return getTestRunResultFromServer(getCustomListenerStatusURI()); // } // // public String getCustomListenerStatusURI() { // return String.format("http://localhost:%d/customlistenerstatus", dropwizardTestSupportAppConfig.getLocalPort()); // } // // private void waitUntilTestRunHasCompleted() { // PollingPredicate<Response> responsePollingPredicate = new PollingPredicate<>( // MAX_ATTEMPTS, // RETRY_POLL_INTERVAL, // response -> !response.readEntity(TestsRunResult.class).getStatus().equals(TestsRunResult.Status.TOO_EARLY), // () -> getTestRunResultFromServer(getTestsURI())); // // assertTrue(responsePollingPredicate.pollUntilPassedOrMaxAttemptsExceeded()); // } // // } // // Path: acceptance-tests/src/test/java/me/atam/atam4jsampleapp/testsupport/Atam4jApplicationStarter.java // public class Atam4jApplicationStarter { // // public static DropwizardTestSupport<ApplicationConfiguration> startApplicationWith( // int initialDelayInMillis, Class testClass, int periodInMillis) { // // ConfigOverride[] configOverrides = { // ConfigOverride.config("testClasses", testClass.getName()), // ConfigOverride.config("initialDelayInMillis", String.valueOf(initialDelayInMillis)), // ConfigOverride.config("periodInMillis", String.valueOf(periodInMillis)) // }; // // DropwizardTestSupport<ApplicationConfiguration> applicationConfigurationDropwizardTestSupport = // new DropwizardTestSupport<>(Atam4jTestApplication.class, // ResourceHelpers.resourceFilePath("atam4j-config.yml"), // configOverrides); // // applicationConfigurationDropwizardTestSupport.before(); // return applicationConfigurationDropwizardTestSupport; // } // } // // Path: acceptance-tests/src/test/java/me/atam/atam4jsampleapp/testsupport/AcceptanceTestTimeouts.java // public static final int TEN_SECONDS_IN_MILLIS = 10000;
import me.atam.atam4j.dummytests.PassingTestWithNoCategory; import me.atam.atam4jsampleapp.testsupport.AcceptanceTest; import me.atam.atam4jsampleapp.testsupport.Atam4jApplicationStarter; import org.junit.Test; import javax.ws.rs.core.Response; import static me.atam.atam4jsampleapp.testsupport.AcceptanceTestTimeouts.TEN_SECONDS_IN_MILLIS; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat;
package me.atam.atam4jsampleapp; public class CustomListenerTest extends AcceptanceTest { @Test public void givenAConfiguredCustomLister_whenTestsAreRun_thenListenerCallbacksWillBeCalled() { //given
// Path: dummy-tests/src/test/java/me/atam/atam4j/dummytests/PassingTestWithNoCategory.java // @Monitor // public class PassingTestWithNoCategory { // // @Test // public void testThatPasses(){ // Assert.assertTrue(true); // } // } // // Path: acceptance-tests/src/test/java/me/atam/atam4jsampleapp/testsupport/AcceptanceTest.java // public abstract class AcceptanceTest { // // protected DropwizardTestSupport<ApplicationConfiguration> dropwizardTestSupportAppConfig; // // @After // public void stopApplication() { // dropwizardTestSupportAppConfig.after(); // } // // public Response getTestRunResultFromServer(String testsURI){ // return new JerseyClientBuilder().build().target( // testsURI) // .request() // .get(); // } // // public String getTestsURI() { // return String.format("http://localhost:%d/tests", dropwizardTestSupportAppConfig.getLocalPort()); // } // // public Response getResponseFromTestsWithCategoryOnceTestRunHasCompleted(String category) { // waitUntilTestRunHasCompleted(); // return getTestRunResultFromServer(getTestsURI() + "/" + category); // } // // public Response getResponseFromTestsEndpointOnceTestsRunHasCompleted() { // waitUntilTestRunHasCompleted(); // return getTestRunResultFromServer(getTestsURI()); // } // // public Response getCustomListenerStatusOnceTestsRunHasCompleted() { // waitUntilTestRunHasCompleted(); // return getTestRunResultFromServer(getCustomListenerStatusURI()); // } // // public String getCustomListenerStatusURI() { // return String.format("http://localhost:%d/customlistenerstatus", dropwizardTestSupportAppConfig.getLocalPort()); // } // // private void waitUntilTestRunHasCompleted() { // PollingPredicate<Response> responsePollingPredicate = new PollingPredicate<>( // MAX_ATTEMPTS, // RETRY_POLL_INTERVAL, // response -> !response.readEntity(TestsRunResult.class).getStatus().equals(TestsRunResult.Status.TOO_EARLY), // () -> getTestRunResultFromServer(getTestsURI())); // // assertTrue(responsePollingPredicate.pollUntilPassedOrMaxAttemptsExceeded()); // } // // } // // Path: acceptance-tests/src/test/java/me/atam/atam4jsampleapp/testsupport/Atam4jApplicationStarter.java // public class Atam4jApplicationStarter { // // public static DropwizardTestSupport<ApplicationConfiguration> startApplicationWith( // int initialDelayInMillis, Class testClass, int periodInMillis) { // // ConfigOverride[] configOverrides = { // ConfigOverride.config("testClasses", testClass.getName()), // ConfigOverride.config("initialDelayInMillis", String.valueOf(initialDelayInMillis)), // ConfigOverride.config("periodInMillis", String.valueOf(periodInMillis)) // }; // // DropwizardTestSupport<ApplicationConfiguration> applicationConfigurationDropwizardTestSupport = // new DropwizardTestSupport<>(Atam4jTestApplication.class, // ResourceHelpers.resourceFilePath("atam4j-config.yml"), // configOverrides); // // applicationConfigurationDropwizardTestSupport.before(); // return applicationConfigurationDropwizardTestSupport; // } // } // // Path: acceptance-tests/src/test/java/me/atam/atam4jsampleapp/testsupport/AcceptanceTestTimeouts.java // public static final int TEN_SECONDS_IN_MILLIS = 10000; // Path: acceptance-tests/src/test/java/me/atam/atam4jsampleapp/CustomListenerTest.java import me.atam.atam4j.dummytests.PassingTestWithNoCategory; import me.atam.atam4jsampleapp.testsupport.AcceptanceTest; import me.atam.atam4jsampleapp.testsupport.Atam4jApplicationStarter; import org.junit.Test; import javax.ws.rs.core.Response; import static me.atam.atam4jsampleapp.testsupport.AcceptanceTestTimeouts.TEN_SECONDS_IN_MILLIS; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; package me.atam.atam4jsampleapp; public class CustomListenerTest extends AcceptanceTest { @Test public void givenAConfiguredCustomLister_whenTestsAreRun_thenListenerCallbacksWillBeCalled() { //given
dropwizardTestSupportAppConfig = Atam4jApplicationStarter
atam4j/atam4j
acceptance-tests/src/test/java/me/atam/atam4jsampleapp/CustomListenerTest.java
// Path: dummy-tests/src/test/java/me/atam/atam4j/dummytests/PassingTestWithNoCategory.java // @Monitor // public class PassingTestWithNoCategory { // // @Test // public void testThatPasses(){ // Assert.assertTrue(true); // } // } // // Path: acceptance-tests/src/test/java/me/atam/atam4jsampleapp/testsupport/AcceptanceTest.java // public abstract class AcceptanceTest { // // protected DropwizardTestSupport<ApplicationConfiguration> dropwizardTestSupportAppConfig; // // @After // public void stopApplication() { // dropwizardTestSupportAppConfig.after(); // } // // public Response getTestRunResultFromServer(String testsURI){ // return new JerseyClientBuilder().build().target( // testsURI) // .request() // .get(); // } // // public String getTestsURI() { // return String.format("http://localhost:%d/tests", dropwizardTestSupportAppConfig.getLocalPort()); // } // // public Response getResponseFromTestsWithCategoryOnceTestRunHasCompleted(String category) { // waitUntilTestRunHasCompleted(); // return getTestRunResultFromServer(getTestsURI() + "/" + category); // } // // public Response getResponseFromTestsEndpointOnceTestsRunHasCompleted() { // waitUntilTestRunHasCompleted(); // return getTestRunResultFromServer(getTestsURI()); // } // // public Response getCustomListenerStatusOnceTestsRunHasCompleted() { // waitUntilTestRunHasCompleted(); // return getTestRunResultFromServer(getCustomListenerStatusURI()); // } // // public String getCustomListenerStatusURI() { // return String.format("http://localhost:%d/customlistenerstatus", dropwizardTestSupportAppConfig.getLocalPort()); // } // // private void waitUntilTestRunHasCompleted() { // PollingPredicate<Response> responsePollingPredicate = new PollingPredicate<>( // MAX_ATTEMPTS, // RETRY_POLL_INTERVAL, // response -> !response.readEntity(TestsRunResult.class).getStatus().equals(TestsRunResult.Status.TOO_EARLY), // () -> getTestRunResultFromServer(getTestsURI())); // // assertTrue(responsePollingPredicate.pollUntilPassedOrMaxAttemptsExceeded()); // } // // } // // Path: acceptance-tests/src/test/java/me/atam/atam4jsampleapp/testsupport/Atam4jApplicationStarter.java // public class Atam4jApplicationStarter { // // public static DropwizardTestSupport<ApplicationConfiguration> startApplicationWith( // int initialDelayInMillis, Class testClass, int periodInMillis) { // // ConfigOverride[] configOverrides = { // ConfigOverride.config("testClasses", testClass.getName()), // ConfigOverride.config("initialDelayInMillis", String.valueOf(initialDelayInMillis)), // ConfigOverride.config("periodInMillis", String.valueOf(periodInMillis)) // }; // // DropwizardTestSupport<ApplicationConfiguration> applicationConfigurationDropwizardTestSupport = // new DropwizardTestSupport<>(Atam4jTestApplication.class, // ResourceHelpers.resourceFilePath("atam4j-config.yml"), // configOverrides); // // applicationConfigurationDropwizardTestSupport.before(); // return applicationConfigurationDropwizardTestSupport; // } // } // // Path: acceptance-tests/src/test/java/me/atam/atam4jsampleapp/testsupport/AcceptanceTestTimeouts.java // public static final int TEN_SECONDS_IN_MILLIS = 10000;
import me.atam.atam4j.dummytests.PassingTestWithNoCategory; import me.atam.atam4jsampleapp.testsupport.AcceptanceTest; import me.atam.atam4jsampleapp.testsupport.Atam4jApplicationStarter; import org.junit.Test; import javax.ws.rs.core.Response; import static me.atam.atam4jsampleapp.testsupport.AcceptanceTestTimeouts.TEN_SECONDS_IN_MILLIS; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat;
package me.atam.atam4jsampleapp; public class CustomListenerTest extends AcceptanceTest { @Test public void givenAConfiguredCustomLister_whenTestsAreRun_thenListenerCallbacksWillBeCalled() { //given dropwizardTestSupportAppConfig = Atam4jApplicationStarter
// Path: dummy-tests/src/test/java/me/atam/atam4j/dummytests/PassingTestWithNoCategory.java // @Monitor // public class PassingTestWithNoCategory { // // @Test // public void testThatPasses(){ // Assert.assertTrue(true); // } // } // // Path: acceptance-tests/src/test/java/me/atam/atam4jsampleapp/testsupport/AcceptanceTest.java // public abstract class AcceptanceTest { // // protected DropwizardTestSupport<ApplicationConfiguration> dropwizardTestSupportAppConfig; // // @After // public void stopApplication() { // dropwizardTestSupportAppConfig.after(); // } // // public Response getTestRunResultFromServer(String testsURI){ // return new JerseyClientBuilder().build().target( // testsURI) // .request() // .get(); // } // // public String getTestsURI() { // return String.format("http://localhost:%d/tests", dropwizardTestSupportAppConfig.getLocalPort()); // } // // public Response getResponseFromTestsWithCategoryOnceTestRunHasCompleted(String category) { // waitUntilTestRunHasCompleted(); // return getTestRunResultFromServer(getTestsURI() + "/" + category); // } // // public Response getResponseFromTestsEndpointOnceTestsRunHasCompleted() { // waitUntilTestRunHasCompleted(); // return getTestRunResultFromServer(getTestsURI()); // } // // public Response getCustomListenerStatusOnceTestsRunHasCompleted() { // waitUntilTestRunHasCompleted(); // return getTestRunResultFromServer(getCustomListenerStatusURI()); // } // // public String getCustomListenerStatusURI() { // return String.format("http://localhost:%d/customlistenerstatus", dropwizardTestSupportAppConfig.getLocalPort()); // } // // private void waitUntilTestRunHasCompleted() { // PollingPredicate<Response> responsePollingPredicate = new PollingPredicate<>( // MAX_ATTEMPTS, // RETRY_POLL_INTERVAL, // response -> !response.readEntity(TestsRunResult.class).getStatus().equals(TestsRunResult.Status.TOO_EARLY), // () -> getTestRunResultFromServer(getTestsURI())); // // assertTrue(responsePollingPredicate.pollUntilPassedOrMaxAttemptsExceeded()); // } // // } // // Path: acceptance-tests/src/test/java/me/atam/atam4jsampleapp/testsupport/Atam4jApplicationStarter.java // public class Atam4jApplicationStarter { // // public static DropwizardTestSupport<ApplicationConfiguration> startApplicationWith( // int initialDelayInMillis, Class testClass, int periodInMillis) { // // ConfigOverride[] configOverrides = { // ConfigOverride.config("testClasses", testClass.getName()), // ConfigOverride.config("initialDelayInMillis", String.valueOf(initialDelayInMillis)), // ConfigOverride.config("periodInMillis", String.valueOf(periodInMillis)) // }; // // DropwizardTestSupport<ApplicationConfiguration> applicationConfigurationDropwizardTestSupport = // new DropwizardTestSupport<>(Atam4jTestApplication.class, // ResourceHelpers.resourceFilePath("atam4j-config.yml"), // configOverrides); // // applicationConfigurationDropwizardTestSupport.before(); // return applicationConfigurationDropwizardTestSupport; // } // } // // Path: acceptance-tests/src/test/java/me/atam/atam4jsampleapp/testsupport/AcceptanceTestTimeouts.java // public static final int TEN_SECONDS_IN_MILLIS = 10000; // Path: acceptance-tests/src/test/java/me/atam/atam4jsampleapp/CustomListenerTest.java import me.atam.atam4j.dummytests.PassingTestWithNoCategory; import me.atam.atam4jsampleapp.testsupport.AcceptanceTest; import me.atam.atam4jsampleapp.testsupport.Atam4jApplicationStarter; import org.junit.Test; import javax.ws.rs.core.Response; import static me.atam.atam4jsampleapp.testsupport.AcceptanceTestTimeouts.TEN_SECONDS_IN_MILLIS; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; package me.atam.atam4jsampleapp; public class CustomListenerTest extends AcceptanceTest { @Test public void givenAConfiguredCustomLister_whenTestsAreRun_thenListenerCallbacksWillBeCalled() { //given dropwizardTestSupportAppConfig = Atam4jApplicationStarter
.startApplicationWith(TEN_SECONDS_IN_MILLIS, PassingTestWithNoCategory.class, 1);
atam4j/atam4j
acceptance-tests/src/test/java/me/atam/atam4jsampleapp/CustomListenerTest.java
// Path: dummy-tests/src/test/java/me/atam/atam4j/dummytests/PassingTestWithNoCategory.java // @Monitor // public class PassingTestWithNoCategory { // // @Test // public void testThatPasses(){ // Assert.assertTrue(true); // } // } // // Path: acceptance-tests/src/test/java/me/atam/atam4jsampleapp/testsupport/AcceptanceTest.java // public abstract class AcceptanceTest { // // protected DropwizardTestSupport<ApplicationConfiguration> dropwizardTestSupportAppConfig; // // @After // public void stopApplication() { // dropwizardTestSupportAppConfig.after(); // } // // public Response getTestRunResultFromServer(String testsURI){ // return new JerseyClientBuilder().build().target( // testsURI) // .request() // .get(); // } // // public String getTestsURI() { // return String.format("http://localhost:%d/tests", dropwizardTestSupportAppConfig.getLocalPort()); // } // // public Response getResponseFromTestsWithCategoryOnceTestRunHasCompleted(String category) { // waitUntilTestRunHasCompleted(); // return getTestRunResultFromServer(getTestsURI() + "/" + category); // } // // public Response getResponseFromTestsEndpointOnceTestsRunHasCompleted() { // waitUntilTestRunHasCompleted(); // return getTestRunResultFromServer(getTestsURI()); // } // // public Response getCustomListenerStatusOnceTestsRunHasCompleted() { // waitUntilTestRunHasCompleted(); // return getTestRunResultFromServer(getCustomListenerStatusURI()); // } // // public String getCustomListenerStatusURI() { // return String.format("http://localhost:%d/customlistenerstatus", dropwizardTestSupportAppConfig.getLocalPort()); // } // // private void waitUntilTestRunHasCompleted() { // PollingPredicate<Response> responsePollingPredicate = new PollingPredicate<>( // MAX_ATTEMPTS, // RETRY_POLL_INTERVAL, // response -> !response.readEntity(TestsRunResult.class).getStatus().equals(TestsRunResult.Status.TOO_EARLY), // () -> getTestRunResultFromServer(getTestsURI())); // // assertTrue(responsePollingPredicate.pollUntilPassedOrMaxAttemptsExceeded()); // } // // } // // Path: acceptance-tests/src/test/java/me/atam/atam4jsampleapp/testsupport/Atam4jApplicationStarter.java // public class Atam4jApplicationStarter { // // public static DropwizardTestSupport<ApplicationConfiguration> startApplicationWith( // int initialDelayInMillis, Class testClass, int periodInMillis) { // // ConfigOverride[] configOverrides = { // ConfigOverride.config("testClasses", testClass.getName()), // ConfigOverride.config("initialDelayInMillis", String.valueOf(initialDelayInMillis)), // ConfigOverride.config("periodInMillis", String.valueOf(periodInMillis)) // }; // // DropwizardTestSupport<ApplicationConfiguration> applicationConfigurationDropwizardTestSupport = // new DropwizardTestSupport<>(Atam4jTestApplication.class, // ResourceHelpers.resourceFilePath("atam4j-config.yml"), // configOverrides); // // applicationConfigurationDropwizardTestSupport.before(); // return applicationConfigurationDropwizardTestSupport; // } // } // // Path: acceptance-tests/src/test/java/me/atam/atam4jsampleapp/testsupport/AcceptanceTestTimeouts.java // public static final int TEN_SECONDS_IN_MILLIS = 10000;
import me.atam.atam4j.dummytests.PassingTestWithNoCategory; import me.atam.atam4jsampleapp.testsupport.AcceptanceTest; import me.atam.atam4jsampleapp.testsupport.Atam4jApplicationStarter; import org.junit.Test; import javax.ws.rs.core.Response; import static me.atam.atam4jsampleapp.testsupport.AcceptanceTestTimeouts.TEN_SECONDS_IN_MILLIS; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat;
package me.atam.atam4jsampleapp; public class CustomListenerTest extends AcceptanceTest { @Test public void givenAConfiguredCustomLister_whenTestsAreRun_thenListenerCallbacksWillBeCalled() { //given dropwizardTestSupportAppConfig = Atam4jApplicationStarter
// Path: dummy-tests/src/test/java/me/atam/atam4j/dummytests/PassingTestWithNoCategory.java // @Monitor // public class PassingTestWithNoCategory { // // @Test // public void testThatPasses(){ // Assert.assertTrue(true); // } // } // // Path: acceptance-tests/src/test/java/me/atam/atam4jsampleapp/testsupport/AcceptanceTest.java // public abstract class AcceptanceTest { // // protected DropwizardTestSupport<ApplicationConfiguration> dropwizardTestSupportAppConfig; // // @After // public void stopApplication() { // dropwizardTestSupportAppConfig.after(); // } // // public Response getTestRunResultFromServer(String testsURI){ // return new JerseyClientBuilder().build().target( // testsURI) // .request() // .get(); // } // // public String getTestsURI() { // return String.format("http://localhost:%d/tests", dropwizardTestSupportAppConfig.getLocalPort()); // } // // public Response getResponseFromTestsWithCategoryOnceTestRunHasCompleted(String category) { // waitUntilTestRunHasCompleted(); // return getTestRunResultFromServer(getTestsURI() + "/" + category); // } // // public Response getResponseFromTestsEndpointOnceTestsRunHasCompleted() { // waitUntilTestRunHasCompleted(); // return getTestRunResultFromServer(getTestsURI()); // } // // public Response getCustomListenerStatusOnceTestsRunHasCompleted() { // waitUntilTestRunHasCompleted(); // return getTestRunResultFromServer(getCustomListenerStatusURI()); // } // // public String getCustomListenerStatusURI() { // return String.format("http://localhost:%d/customlistenerstatus", dropwizardTestSupportAppConfig.getLocalPort()); // } // // private void waitUntilTestRunHasCompleted() { // PollingPredicate<Response> responsePollingPredicate = new PollingPredicate<>( // MAX_ATTEMPTS, // RETRY_POLL_INTERVAL, // response -> !response.readEntity(TestsRunResult.class).getStatus().equals(TestsRunResult.Status.TOO_EARLY), // () -> getTestRunResultFromServer(getTestsURI())); // // assertTrue(responsePollingPredicate.pollUntilPassedOrMaxAttemptsExceeded()); // } // // } // // Path: acceptance-tests/src/test/java/me/atam/atam4jsampleapp/testsupport/Atam4jApplicationStarter.java // public class Atam4jApplicationStarter { // // public static DropwizardTestSupport<ApplicationConfiguration> startApplicationWith( // int initialDelayInMillis, Class testClass, int periodInMillis) { // // ConfigOverride[] configOverrides = { // ConfigOverride.config("testClasses", testClass.getName()), // ConfigOverride.config("initialDelayInMillis", String.valueOf(initialDelayInMillis)), // ConfigOverride.config("periodInMillis", String.valueOf(periodInMillis)) // }; // // DropwizardTestSupport<ApplicationConfiguration> applicationConfigurationDropwizardTestSupport = // new DropwizardTestSupport<>(Atam4jTestApplication.class, // ResourceHelpers.resourceFilePath("atam4j-config.yml"), // configOverrides); // // applicationConfigurationDropwizardTestSupport.before(); // return applicationConfigurationDropwizardTestSupport; // } // } // // Path: acceptance-tests/src/test/java/me/atam/atam4jsampleapp/testsupport/AcceptanceTestTimeouts.java // public static final int TEN_SECONDS_IN_MILLIS = 10000; // Path: acceptance-tests/src/test/java/me/atam/atam4jsampleapp/CustomListenerTest.java import me.atam.atam4j.dummytests.PassingTestWithNoCategory; import me.atam.atam4jsampleapp.testsupport.AcceptanceTest; import me.atam.atam4jsampleapp.testsupport.Atam4jApplicationStarter; import org.junit.Test; import javax.ws.rs.core.Response; import static me.atam.atam4jsampleapp.testsupport.AcceptanceTestTimeouts.TEN_SECONDS_IN_MILLIS; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; package me.atam.atam4jsampleapp; public class CustomListenerTest extends AcceptanceTest { @Test public void givenAConfiguredCustomLister_whenTestsAreRun_thenListenerCallbacksWillBeCalled() { //given dropwizardTestSupportAppConfig = Atam4jApplicationStarter
.startApplicationWith(TEN_SECONDS_IN_MILLIS, PassingTestWithNoCategory.class, 1);
atam4j/atam4j
atam4j/src/main/java/me/atam/atam4j/Atam4j.java
// Path: atam4j/src/main/java/me/atam/atam4j/exceptions/NoTestClassFoundException.java // public class NoTestClassFoundException extends RuntimeException { // // public NoTestClassFoundException(String message) { // super(message); // } // } // // Path: atam4j/src/main/java/me/atam/atam4j/health/AcceptanceTestsState.java // public class AcceptanceTestsState { // // private Optional<Result> result = Optional.empty(); // // public Optional<Result> getResult() { // return result; // } // // public void setResult(Result result) { // this.result = Optional.of(result); // } // // } // // Path: atam4j/src/main/java/me/atam/atam4j/resources/TestStatusResource.java // @Path("/tests") // @Produces("application/json") // public class TestStatusResource { // // private final TestRunListener testRunListener; // // public TestStatusResource(TestRunListener testRunListener) { // this.testRunListener = testRunListener; // } // // @GET // public Response getTestStatus(){ // return buildResponse(testRunListener.getTestsRunResult()); // } // // @GET // @Path("{category}") // public Response getTestStatusForACategory(@PathParam("category") String category) { // return buildResponse(testRunListener.getTestsRunResult(category)); // } // // private Response buildResponse(TestsRunResult testRunResult) { // if (testRunResult.getStatus().equals(TestsRunResult.Status.FAILURES)) { // return Response.status(Response.Status.INTERNAL_SERVER_ERROR) // .entity(testRunResult) // .build(); // } else if (testRunResult.getStatus().equals(TestsRunResult.Status.CATEGORY_NOT_FOUND)) { // return Response.status(Response.Status.NOT_FOUND) // .build(); // } else { // return Response.status(Response.Status.OK) // .entity(testRunResult) // .build(); // } // } // }
import io.dropwizard.jersey.setup.JerseyEnvironment; import io.dropwizard.lifecycle.Managed; import me.atam.atam4j.exceptions.NoTestClassFoundException; import me.atam.atam4j.health.AcceptanceTestsState; import me.atam.atam4j.resources.TestStatusResource; import org.junit.runner.notification.RunListener; import org.reflections.Reflections; import org.reflections.scanners.SubTypesScanner; import org.reflections.scanners.TypeAnnotationsScanner; import org.reflections.util.ClasspathHelper; import org.reflections.util.ConfigurationBuilder; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.concurrent.TimeUnit;
package me.atam.atam4j; public class Atam4j implements Managed { private final AcceptanceTestsState acceptanceTestsState = new AcceptanceTestsState(); private final AcceptanceTestsRunnerTaskScheduler acceptanceTestsRunnerTaskScheduler; private final TestRunListener testRunListener; private final JerseyEnvironment jerseyEnvironment; public Atam4j(JerseyEnvironment jerseyEnvironment, TestRunListener testRunListener, AcceptanceTestsRunnerTaskScheduler acceptanceTestsRunnerTaskScheduler) { this.jerseyEnvironment = jerseyEnvironment; this.testRunListener = testRunListener; this.acceptanceTestsRunnerTaskScheduler = acceptanceTestsRunnerTaskScheduler; } @Override public void start() { acceptanceTestsRunnerTaskScheduler.scheduleAcceptanceTestsRunnerTask(acceptanceTestsState);
// Path: atam4j/src/main/java/me/atam/atam4j/exceptions/NoTestClassFoundException.java // public class NoTestClassFoundException extends RuntimeException { // // public NoTestClassFoundException(String message) { // super(message); // } // } // // Path: atam4j/src/main/java/me/atam/atam4j/health/AcceptanceTestsState.java // public class AcceptanceTestsState { // // private Optional<Result> result = Optional.empty(); // // public Optional<Result> getResult() { // return result; // } // // public void setResult(Result result) { // this.result = Optional.of(result); // } // // } // // Path: atam4j/src/main/java/me/atam/atam4j/resources/TestStatusResource.java // @Path("/tests") // @Produces("application/json") // public class TestStatusResource { // // private final TestRunListener testRunListener; // // public TestStatusResource(TestRunListener testRunListener) { // this.testRunListener = testRunListener; // } // // @GET // public Response getTestStatus(){ // return buildResponse(testRunListener.getTestsRunResult()); // } // // @GET // @Path("{category}") // public Response getTestStatusForACategory(@PathParam("category") String category) { // return buildResponse(testRunListener.getTestsRunResult(category)); // } // // private Response buildResponse(TestsRunResult testRunResult) { // if (testRunResult.getStatus().equals(TestsRunResult.Status.FAILURES)) { // return Response.status(Response.Status.INTERNAL_SERVER_ERROR) // .entity(testRunResult) // .build(); // } else if (testRunResult.getStatus().equals(TestsRunResult.Status.CATEGORY_NOT_FOUND)) { // return Response.status(Response.Status.NOT_FOUND) // .build(); // } else { // return Response.status(Response.Status.OK) // .entity(testRunResult) // .build(); // } // } // } // Path: atam4j/src/main/java/me/atam/atam4j/Atam4j.java import io.dropwizard.jersey.setup.JerseyEnvironment; import io.dropwizard.lifecycle.Managed; import me.atam.atam4j.exceptions.NoTestClassFoundException; import me.atam.atam4j.health.AcceptanceTestsState; import me.atam.atam4j.resources.TestStatusResource; import org.junit.runner.notification.RunListener; import org.reflections.Reflections; import org.reflections.scanners.SubTypesScanner; import org.reflections.scanners.TypeAnnotationsScanner; import org.reflections.util.ClasspathHelper; import org.reflections.util.ConfigurationBuilder; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.concurrent.TimeUnit; package me.atam.atam4j; public class Atam4j implements Managed { private final AcceptanceTestsState acceptanceTestsState = new AcceptanceTestsState(); private final AcceptanceTestsRunnerTaskScheduler acceptanceTestsRunnerTaskScheduler; private final TestRunListener testRunListener; private final JerseyEnvironment jerseyEnvironment; public Atam4j(JerseyEnvironment jerseyEnvironment, TestRunListener testRunListener, AcceptanceTestsRunnerTaskScheduler acceptanceTestsRunnerTaskScheduler) { this.jerseyEnvironment = jerseyEnvironment; this.testRunListener = testRunListener; this.acceptanceTestsRunnerTaskScheduler = acceptanceTestsRunnerTaskScheduler; } @Override public void start() { acceptanceTestsRunnerTaskScheduler.scheduleAcceptanceTestsRunnerTask(acceptanceTestsState);
jerseyEnvironment.register(new TestStatusResource(testRunListener));
atam4j/atam4j
atam4j/src/main/java/me/atam/atam4j/Atam4j.java
// Path: atam4j/src/main/java/me/atam/atam4j/exceptions/NoTestClassFoundException.java // public class NoTestClassFoundException extends RuntimeException { // // public NoTestClassFoundException(String message) { // super(message); // } // } // // Path: atam4j/src/main/java/me/atam/atam4j/health/AcceptanceTestsState.java // public class AcceptanceTestsState { // // private Optional<Result> result = Optional.empty(); // // public Optional<Result> getResult() { // return result; // } // // public void setResult(Result result) { // this.result = Optional.of(result); // } // // } // // Path: atam4j/src/main/java/me/atam/atam4j/resources/TestStatusResource.java // @Path("/tests") // @Produces("application/json") // public class TestStatusResource { // // private final TestRunListener testRunListener; // // public TestStatusResource(TestRunListener testRunListener) { // this.testRunListener = testRunListener; // } // // @GET // public Response getTestStatus(){ // return buildResponse(testRunListener.getTestsRunResult()); // } // // @GET // @Path("{category}") // public Response getTestStatusForACategory(@PathParam("category") String category) { // return buildResponse(testRunListener.getTestsRunResult(category)); // } // // private Response buildResponse(TestsRunResult testRunResult) { // if (testRunResult.getStatus().equals(TestsRunResult.Status.FAILURES)) { // return Response.status(Response.Status.INTERNAL_SERVER_ERROR) // .entity(testRunResult) // .build(); // } else if (testRunResult.getStatus().equals(TestsRunResult.Status.CATEGORY_NOT_FOUND)) { // return Response.status(Response.Status.NOT_FOUND) // .build(); // } else { // return Response.status(Response.Status.OK) // .entity(testRunResult) // .build(); // } // } // }
import io.dropwizard.jersey.setup.JerseyEnvironment; import io.dropwizard.lifecycle.Managed; import me.atam.atam4j.exceptions.NoTestClassFoundException; import me.atam.atam4j.health.AcceptanceTestsState; import me.atam.atam4j.resources.TestStatusResource; import org.junit.runner.notification.RunListener; import org.reflections.Reflections; import org.reflections.scanners.SubTypesScanner; import org.reflections.scanners.TypeAnnotationsScanner; import org.reflections.util.ClasspathHelper; import org.reflections.util.ConfigurationBuilder; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.concurrent.TimeUnit;
} public Atam4jBuilder withListener(RunListener listener) { this.runListeners.add(listener); return this; } public Atam4j build() { TestRunListener testRunListener = new TestRunListener(); List<RunListener> runListenersWithAtam4jListener = new ArrayList<>(); runListenersWithAtam4jListener.add(testRunListener); runListenersWithAtam4jListener.addAll(this.runListeners); return new Atam4j(jerseyEnvironment, testRunListener, new AcceptanceTestsRunnerTaskScheduler( findTestClasses(), initialDelay, period, unit, runListenersWithAtam4jListener)); } private Class[] findTestClasses() { final Class[] classes = testClasses.orElseGet(() -> new Reflections(new ConfigurationBuilder() .setUrls(ClasspathHelper.forJavaClassPath()) .setScanners(new SubTypesScanner(), new TypeAnnotationsScanner())) .getTypesAnnotatedWith(Monitor.class) .stream() .toArray(Class[]::new)); if(classes.length == 0) {
// Path: atam4j/src/main/java/me/atam/atam4j/exceptions/NoTestClassFoundException.java // public class NoTestClassFoundException extends RuntimeException { // // public NoTestClassFoundException(String message) { // super(message); // } // } // // Path: atam4j/src/main/java/me/atam/atam4j/health/AcceptanceTestsState.java // public class AcceptanceTestsState { // // private Optional<Result> result = Optional.empty(); // // public Optional<Result> getResult() { // return result; // } // // public void setResult(Result result) { // this.result = Optional.of(result); // } // // } // // Path: atam4j/src/main/java/me/atam/atam4j/resources/TestStatusResource.java // @Path("/tests") // @Produces("application/json") // public class TestStatusResource { // // private final TestRunListener testRunListener; // // public TestStatusResource(TestRunListener testRunListener) { // this.testRunListener = testRunListener; // } // // @GET // public Response getTestStatus(){ // return buildResponse(testRunListener.getTestsRunResult()); // } // // @GET // @Path("{category}") // public Response getTestStatusForACategory(@PathParam("category") String category) { // return buildResponse(testRunListener.getTestsRunResult(category)); // } // // private Response buildResponse(TestsRunResult testRunResult) { // if (testRunResult.getStatus().equals(TestsRunResult.Status.FAILURES)) { // return Response.status(Response.Status.INTERNAL_SERVER_ERROR) // .entity(testRunResult) // .build(); // } else if (testRunResult.getStatus().equals(TestsRunResult.Status.CATEGORY_NOT_FOUND)) { // return Response.status(Response.Status.NOT_FOUND) // .build(); // } else { // return Response.status(Response.Status.OK) // .entity(testRunResult) // .build(); // } // } // } // Path: atam4j/src/main/java/me/atam/atam4j/Atam4j.java import io.dropwizard.jersey.setup.JerseyEnvironment; import io.dropwizard.lifecycle.Managed; import me.atam.atam4j.exceptions.NoTestClassFoundException; import me.atam.atam4j.health.AcceptanceTestsState; import me.atam.atam4j.resources.TestStatusResource; import org.junit.runner.notification.RunListener; import org.reflections.Reflections; import org.reflections.scanners.SubTypesScanner; import org.reflections.scanners.TypeAnnotationsScanner; import org.reflections.util.ClasspathHelper; import org.reflections.util.ConfigurationBuilder; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.concurrent.TimeUnit; } public Atam4jBuilder withListener(RunListener listener) { this.runListeners.add(listener); return this; } public Atam4j build() { TestRunListener testRunListener = new TestRunListener(); List<RunListener> runListenersWithAtam4jListener = new ArrayList<>(); runListenersWithAtam4jListener.add(testRunListener); runListenersWithAtam4jListener.addAll(this.runListeners); return new Atam4j(jerseyEnvironment, testRunListener, new AcceptanceTestsRunnerTaskScheduler( findTestClasses(), initialDelay, period, unit, runListenersWithAtam4jListener)); } private Class[] findTestClasses() { final Class[] classes = testClasses.orElseGet(() -> new Reflections(new ConfigurationBuilder() .setUrls(ClasspathHelper.forJavaClassPath()) .setScanners(new SubTypesScanner(), new TypeAnnotationsScanner())) .getTypesAnnotatedWith(Monitor.class) .stream() .toArray(Class[]::new)); if(classes.length == 0) {
throw new NoTestClassFoundException("Could not find any annotated test classes and no classes were provided via the Atam4jBuilder.");
atam4j/atam4j
atam4j/src/test/java/me/atam/atam4j/TestRunListenerTest.java
// Path: atam4j-domain/src/main/java/me/atam/atam4jdomain/TestsRunResult.java // public final class TestsRunResult { // // private final Collection<IndividualTestResult> tests; // private final Status status; // // public TestsRunResult(final @JsonProperty("tests") Collection<IndividualTestResult> tests, // final @JsonProperty("status") Status status) { // this.tests = tests; // this.status = status; // // } // // public TestsRunResult(final Collection<IndividualTestResult> tests) { // this.tests = tests; // this.status = buildStatus(tests); // } // // public Collection<IndividualTestResult> getTests() { // return tests; // } // // // // // public Status getStatus() { // return status; // } // // private Status buildStatus(final Collection<IndividualTestResult> testResults) { // if (testResults.isEmpty()) { // return Status.CATEGORY_NOT_FOUND; // } // return testResults.stream() // .filter(testReport -> !testReport.isPassed()) // .findAny() // .map(failures -> Status.FAILURES) // .orElse(Status.ALL_OK); // } // // public Optional<IndividualTestResult> getTestByClassAndName(String className, String testName) { // return tests.stream().filter(t -> t.getTestClass().equals(className)).filter(t -> t.getTestName().equals(testName)).findFirst(); // } // // public enum Status { // TOO_EARLY("Too early to tell - tests not complete yet"), // CATEGORY_NOT_FOUND("This category does not exist"), // ALL_OK("All is A OK!"), // FAILURES("Failures"); // // private final String message; // // Status(String message) { // this.message = message; // } // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // TestsRunResult that = (TestsRunResult) o; // // if (tests != null ? !tests.equals(that.tests) : that.tests != null) return false; // return status == that.status; // // } // // @Override // public int hashCode() { // int result = tests != null ? tests.hashCode() : 0; // result = 31 * result + (status != null ? status.hashCode() : 0); // return result; // } // // @Override // public String toString() { // return "TestsRunResult{" + // "tests=" + tests + // ", status=" + status + // '}'; // } // }
import me.atam.atam4jdomain.TestsRunResult; import org.hamcrest.CoreMatchers; import org.junit.Test; import org.junit.runner.Description; import org.junit.runner.notification.Failure; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when;
package me.atam.atam4j; public class TestRunListenerTest { private TestRunListener testRunListener = new TestRunListener(); @Test public void givenTestRunNotFinished_whenGetTestRunResultCalled_thenStatusIsTooEarly() throws Exception {
// Path: atam4j-domain/src/main/java/me/atam/atam4jdomain/TestsRunResult.java // public final class TestsRunResult { // // private final Collection<IndividualTestResult> tests; // private final Status status; // // public TestsRunResult(final @JsonProperty("tests") Collection<IndividualTestResult> tests, // final @JsonProperty("status") Status status) { // this.tests = tests; // this.status = status; // // } // // public TestsRunResult(final Collection<IndividualTestResult> tests) { // this.tests = tests; // this.status = buildStatus(tests); // } // // public Collection<IndividualTestResult> getTests() { // return tests; // } // // // // // public Status getStatus() { // return status; // } // // private Status buildStatus(final Collection<IndividualTestResult> testResults) { // if (testResults.isEmpty()) { // return Status.CATEGORY_NOT_FOUND; // } // return testResults.stream() // .filter(testReport -> !testReport.isPassed()) // .findAny() // .map(failures -> Status.FAILURES) // .orElse(Status.ALL_OK); // } // // public Optional<IndividualTestResult> getTestByClassAndName(String className, String testName) { // return tests.stream().filter(t -> t.getTestClass().equals(className)).filter(t -> t.getTestName().equals(testName)).findFirst(); // } // // public enum Status { // TOO_EARLY("Too early to tell - tests not complete yet"), // CATEGORY_NOT_FOUND("This category does not exist"), // ALL_OK("All is A OK!"), // FAILURES("Failures"); // // private final String message; // // Status(String message) { // this.message = message; // } // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // TestsRunResult that = (TestsRunResult) o; // // if (tests != null ? !tests.equals(that.tests) : that.tests != null) return false; // return status == that.status; // // } // // @Override // public int hashCode() { // int result = tests != null ? tests.hashCode() : 0; // result = 31 * result + (status != null ? status.hashCode() : 0); // return result; // } // // @Override // public String toString() { // return "TestsRunResult{" + // "tests=" + tests + // ", status=" + status + // '}'; // } // } // Path: atam4j/src/test/java/me/atam/atam4j/TestRunListenerTest.java import me.atam.atam4jdomain.TestsRunResult; import org.hamcrest.CoreMatchers; import org.junit.Test; import org.junit.runner.Description; import org.junit.runner.notification.Failure; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; package me.atam.atam4j; public class TestRunListenerTest { private TestRunListener testRunListener = new TestRunListener(); @Test public void givenTestRunNotFinished_whenGetTestRunResultCalled_thenStatusIsTooEarly() throws Exception {
assertThat(testRunListener.getTestsRunResult().getStatus(), CoreMatchers.is(TestsRunResult.Status.TOO_EARLY));
atam4j/atam4j
atam4j/src/test/java/me/atam/atam4j/Atam4jBuilderTest.java
// Path: dummy-tests/src/test/java/me/atam/atam4j/dummytests/PassingTestWithNoCategory.java // @Monitor // public class PassingTestWithNoCategory { // // @Test // public void testThatPasses(){ // Assert.assertTrue(true); // } // }
import io.dropwizard.jersey.setup.JerseyEnvironment; import me.atam.atam4j.dummytests.PassingTestWithNoCategory; import org.junit.Assert; import org.junit.Test;
package me.atam.atam4j; public class Atam4jBuilderTest { @Test public void givenBuilderConstructedWithHealthCheckRegistry_whenBuildCalled_thenManagerReturned() { Atam4j.Atam4jBuilder builder = new Atam4j.Atam4jBuilder(
// Path: dummy-tests/src/test/java/me/atam/atam4j/dummytests/PassingTestWithNoCategory.java // @Monitor // public class PassingTestWithNoCategory { // // @Test // public void testThatPasses(){ // Assert.assertTrue(true); // } // } // Path: atam4j/src/test/java/me/atam/atam4j/Atam4jBuilderTest.java import io.dropwizard.jersey.setup.JerseyEnvironment; import me.atam.atam4j.dummytests.PassingTestWithNoCategory; import org.junit.Assert; import org.junit.Test; package me.atam.atam4j; public class Atam4jBuilderTest { @Test public void givenBuilderConstructedWithHealthCheckRegistry_whenBuildCalled_thenManagerReturned() { Atam4j.Atam4jBuilder builder = new Atam4j.Atam4jBuilder(
new JerseyEnvironment(null,null)).withTestClasses(PassingTestWithNoCategory.class);
mscharhag/blog-examples
archunit/src/main/java/com/mscharhag/archunit/layers/repository/UserRepository.java
// Path: archunit/src/main/java/com/mscharhag/archunit/model/User.java // @Entity // public class User { // // private String name; // // public User(String name) { // this.name = name; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // }
import com.mscharhag.archunit.model.User; import javax.persistence.EntityManager;
package com.mscharhag.archunit.layers.repository; public class UserRepository { private EntityManager entityManager;
// Path: archunit/src/main/java/com/mscharhag/archunit/model/User.java // @Entity // public class User { // // private String name; // // public User(String name) { // this.name = name; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // } // Path: archunit/src/main/java/com/mscharhag/archunit/layers/repository/UserRepository.java import com.mscharhag.archunit.model.User; import javax.persistence.EntityManager; package com.mscharhag.archunit.layers.repository; public class UserRepository { private EntityManager entityManager;
public User loadUser() {
mscharhag/blog-examples
domain-injection/src/main/java/com/mscharhag/examples/domaininjection/Application.java
// Path: domain-injection/src/main/java/com/mscharhag/examples/domaininjection/domain/User.java // public class User { // private String firstName; // private String lastName; // // public User(String firstName, String lastName) { // this.firstName = firstName; // this.lastName = lastName; // } // // public String getFirstName() { // return firstName; // } // // public String getLastName() { // return lastName; // } // // @Override // public String toString() { // return "User{" + // "firstName='" + firstName + '\'' + // ", lastName='" + lastName + '\'' + // '}'; // } // }
import com.mscharhag.examples.domaininjection.annotation.LoggedInUser; import com.mscharhag.examples.domaininjection.annotation.SessionScopedBean; import com.mscharhag.examples.domaininjection.domain.User; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.*;
package com.mscharhag.examples.domaininjection; @Configuration @EnableAutoConfiguration @ComponentScan(basePackages = {"com.mscharhag.examples.domaininjection"}) public class Application { // @Bean // @Scope(value = WebApplicationContext.SCOPE_SESSION, proxyMode = ScopedProxyMode.TARGET_CLASS) @LoggedInUser @SessionScopedBean
// Path: domain-injection/src/main/java/com/mscharhag/examples/domaininjection/domain/User.java // public class User { // private String firstName; // private String lastName; // // public User(String firstName, String lastName) { // this.firstName = firstName; // this.lastName = lastName; // } // // public String getFirstName() { // return firstName; // } // // public String getLastName() { // return lastName; // } // // @Override // public String toString() { // return "User{" + // "firstName='" + firstName + '\'' + // ", lastName='" + lastName + '\'' + // '}'; // } // } // Path: domain-injection/src/main/java/com/mscharhag/examples/domaininjection/Application.java import com.mscharhag.examples.domaininjection.annotation.LoggedInUser; import com.mscharhag.examples.domaininjection.annotation.SessionScopedBean; import com.mscharhag.examples.domaininjection.domain.User; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.*; package com.mscharhag.examples.domaininjection; @Configuration @EnableAutoConfiguration @ComponentScan(basePackages = {"com.mscharhag.examples.domaininjection"}) public class Application { // @Bean // @Scope(value = WebApplicationContext.SCOPE_SESSION, proxyMode = ScopedProxyMode.TARGET_CLASS) @LoggedInUser @SessionScopedBean
public User getLoggedInUser() {
mscharhag/blog-examples
spring-error-handling/src/test/java/com/mscharhag/errorhandling/ArticleExceptionHandlerTest.java
// Path: spring-error-handling/src/main/java/com/mscharhag/errorhandling/article/ArticleId.java // public class ArticleId { // private String value; // // public ArticleId(String value) { // this.value = Objects.requireNonNull(value); // } // // public ArticleId() { // this(UUID.randomUUID().toString()); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // ArticleId articleId = (ArticleId) o; // return Objects.equals(value, articleId.value); // } // // @Override // public int hashCode() { // return Objects.hash(value); // } // // @Override // public String toString() { // return value; // } // } // // Path: spring-error-handling/src/main/java/com/mscharhag/errorhandling/article/ArticleRepository.java // @Component // public class ArticleRepository { // public Optional<Article> findById(ArticleId id) { // return Optional.empty(); // } // }
import com.mscharhag.errorhandling.article.ArticleId; import com.mscharhag.errorhandling.article.ArticleRepository; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.ResultMatcher; import org.springframework.test.web.servlet.result.MockMvcResultHandlers; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import java.util.Optional; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
package com.mscharhag.errorhandling; @SpringBootTest @AutoConfigureMockMvc public class ArticleExceptionHandlerTest { @Autowired private MockMvc mvc; @MockBean
// Path: spring-error-handling/src/main/java/com/mscharhag/errorhandling/article/ArticleId.java // public class ArticleId { // private String value; // // public ArticleId(String value) { // this.value = Objects.requireNonNull(value); // } // // public ArticleId() { // this(UUID.randomUUID().toString()); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // ArticleId articleId = (ArticleId) o; // return Objects.equals(value, articleId.value); // } // // @Override // public int hashCode() { // return Objects.hash(value); // } // // @Override // public String toString() { // return value; // } // } // // Path: spring-error-handling/src/main/java/com/mscharhag/errorhandling/article/ArticleRepository.java // @Component // public class ArticleRepository { // public Optional<Article> findById(ArticleId id) { // return Optional.empty(); // } // } // Path: spring-error-handling/src/test/java/com/mscharhag/errorhandling/ArticleExceptionHandlerTest.java import com.mscharhag.errorhandling.article.ArticleId; import com.mscharhag.errorhandling.article.ArticleRepository; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.ResultMatcher; import org.springframework.test.web.servlet.result.MockMvcResultHandlers; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import java.util.Optional; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; package com.mscharhag.errorhandling; @SpringBootTest @AutoConfigureMockMvc public class ArticleExceptionHandlerTest { @Autowired private MockMvc mvc; @MockBean
private ArticleRepository articleRepository;
mscharhag/blog-examples
spring-error-handling/src/test/java/com/mscharhag/errorhandling/ArticleExceptionHandlerTest.java
// Path: spring-error-handling/src/main/java/com/mscharhag/errorhandling/article/ArticleId.java // public class ArticleId { // private String value; // // public ArticleId(String value) { // this.value = Objects.requireNonNull(value); // } // // public ArticleId() { // this(UUID.randomUUID().toString()); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // ArticleId articleId = (ArticleId) o; // return Objects.equals(value, articleId.value); // } // // @Override // public int hashCode() { // return Objects.hash(value); // } // // @Override // public String toString() { // return value; // } // } // // Path: spring-error-handling/src/main/java/com/mscharhag/errorhandling/article/ArticleRepository.java // @Component // public class ArticleRepository { // public Optional<Article> findById(ArticleId id) { // return Optional.empty(); // } // }
import com.mscharhag.errorhandling.article.ArticleId; import com.mscharhag.errorhandling.article.ArticleRepository; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.ResultMatcher; import org.springframework.test.web.servlet.result.MockMvcResultHandlers; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import java.util.Optional; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
package com.mscharhag.errorhandling; @SpringBootTest @AutoConfigureMockMvc public class ArticleExceptionHandlerTest { @Autowired private MockMvc mvc; @MockBean private ArticleRepository articleRepository; @Test public void articleNotFound() throws Exception {
// Path: spring-error-handling/src/main/java/com/mscharhag/errorhandling/article/ArticleId.java // public class ArticleId { // private String value; // // public ArticleId(String value) { // this.value = Objects.requireNonNull(value); // } // // public ArticleId() { // this(UUID.randomUUID().toString()); // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // ArticleId articleId = (ArticleId) o; // return Objects.equals(value, articleId.value); // } // // @Override // public int hashCode() { // return Objects.hash(value); // } // // @Override // public String toString() { // return value; // } // } // // Path: spring-error-handling/src/main/java/com/mscharhag/errorhandling/article/ArticleRepository.java // @Component // public class ArticleRepository { // public Optional<Article> findById(ArticleId id) { // return Optional.empty(); // } // } // Path: spring-error-handling/src/test/java/com/mscharhag/errorhandling/ArticleExceptionHandlerTest.java import com.mscharhag.errorhandling.article.ArticleId; import com.mscharhag.errorhandling.article.ArticleRepository; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.ResultMatcher; import org.springframework.test.web.servlet.result.MockMvcResultHandlers; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import java.util.Optional; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; package com.mscharhag.errorhandling; @SpringBootTest @AutoConfigureMockMvc public class ArticleExceptionHandlerTest { @Autowired private MockMvc mvc; @MockBean private ArticleRepository articleRepository; @Test public void articleNotFound() throws Exception {
when(articleRepository.findById(new ArticleId("123"))).thenReturn(Optional.empty());
mscharhag/blog-examples
exception-translation/src/main/java/com/mscharhag/exceptiontranslation/aspect/ExceptionTranslationAspect.java
// Path: exception-translation/src/main/java/com/mscharhag/exceptiontranslation/exception/DataAccessException.java // public class DataAccessException extends RuntimeException { // public DataAccessException(Throwable cause) { // super(cause); // } // }
import com.mscharhag.exceptiontranslation.exception.DataAccessException; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.hibernate.HibernateException;
package com.mscharhag.exceptiontranslation.aspect; @Aspect public class ExceptionTranslationAspect { @Around("execution(* com.mscharhag.exceptiontranslation.repository..*(..))") public Object translateToDataAccessException(ProceedingJoinPoint pjp) throws Throwable { try { return pjp.proceed(); } catch (HibernateException e) {
// Path: exception-translation/src/main/java/com/mscharhag/exceptiontranslation/exception/DataAccessException.java // public class DataAccessException extends RuntimeException { // public DataAccessException(Throwable cause) { // super(cause); // } // } // Path: exception-translation/src/main/java/com/mscharhag/exceptiontranslation/aspect/ExceptionTranslationAspect.java import com.mscharhag.exceptiontranslation.exception.DataAccessException; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.hibernate.HibernateException; package com.mscharhag.exceptiontranslation.aspect; @Aspect public class ExceptionTranslationAspect { @Around("execution(* com.mscharhag.exceptiontranslation.repository..*(..))") public Object translateToDataAccessException(ProceedingJoinPoint pjp) throws Throwable { try { return pjp.proceed(); } catch (HibernateException e) {
throw new DataAccessException(e);
mscharhag/blog-examples
archunit/src/main/java/com/mscharhag/archunit/layers/controller/UserController.java
// Path: archunit/src/main/java/com/mscharhag/archunit/layers/service/UserService.java // public interface UserService { // User getUser(); // } // // Path: archunit/src/main/java/com/mscharhag/archunit/model/User.java // @Entity // public class User { // // private String name; // // public User(String name) { // this.name = name; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // }
import com.mscharhag.archunit.layers.service.UserService; import com.mscharhag.archunit.model.User;
package com.mscharhag.archunit.layers.controller; public class UserController { private final UserService service; public UserController(UserService service) { this.service = service; }
// Path: archunit/src/main/java/com/mscharhag/archunit/layers/service/UserService.java // public interface UserService { // User getUser(); // } // // Path: archunit/src/main/java/com/mscharhag/archunit/model/User.java // @Entity // public class User { // // private String name; // // public User(String name) { // this.name = name; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // } // Path: archunit/src/main/java/com/mscharhag/archunit/layers/controller/UserController.java import com.mscharhag.archunit.layers.service.UserService; import com.mscharhag.archunit.model.User; package com.mscharhag.archunit.layers.controller; public class UserController { private final UserService service; public UserController(UserService service) { this.service = service; }
public User getUser() {
mscharhag/blog-examples
spring-data-jooq/src/test/java/com/mscharhag/repository/UserRepositoryTest.java
// Path: spring-data-jooq/src/main/java/com/mscharhag/springjooq/Application.java // @Configuration // @EnableAutoConfiguration // @ComponentScan // public class Application { // // @Bean // public DataSource dataSource() { // BasicDataSource dataSource = new BasicDataSource(); // dataSource.setDriverClassName("com.mysql.jdbc.Driver"); // dataSource.setUrl("jdbc:mysql://localhost:3306/jooq"); // dataSource.setUsername("spring-data-jooq"); // dataSource.setPassword("spring-data-jooq"); // return dataSource; // // // EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder(); // // return builder.setType(EmbeddedDatabaseType.H2).build(); // } // // @Bean // public EntityManagerFactory entityManagerFactory() throws SQLException { // HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); // vendorAdapter.setGenerateDdl(true); // LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean(); // factory.setJpaVendorAdapter(vendorAdapter); // factory.setPackagesToScan("com.mscharhag.springjooq.entity"); // factory.setDataSource(dataSource()); // factory.afterPropertiesSet(); // return factory.getObject(); // } // // @Bean // public TransactionAwareDataSourceProxy transactionAwareDataSource() { // return new TransactionAwareDataSourceProxy(dataSource()); // } // // @Bean // public DataSourceConnectionProvider connectionProvider() { // return new DataSourceConnectionProvider(transactionAwareDataSource()); // } // // // @Bean // public DefaultConfiguration configuration() { // DefaultConfiguration jooqConfiguration = new DefaultConfiguration(); // // jooqConfiguration.set(connectionProvider()); // jooqConfiguration.set(SQLDialect.MYSQL); // jooqConfiguration.set( // new RecordMapperProvider() { // @Override // public <R extends Record, E> RecordMapper<R, E> provide(RecordType<R> recordType, Class<? extends E> type) { // // if (type == Product.class) { // // return new RecordMapper<R, E>() { // // @Override // // public E map(R record) { // // Object name = record.getValue("name"); // // Object price = record.getValue("price"); // // return (E) record.getValue("ID"); // // } // // }; // // } // // return new DefaultRecordMapper(recordType, type); // } // } // ); // return jooqConfiguration; // } // // @Bean // public DefaultDSLContext dsl() { // return new DefaultDSLContext(configuration()); // } // // @Bean(autowire = Autowire.BY_TYPE) // public JpaRepositoryFactoryBean<UserRepository, User, Long> jpaRepositoryFactoryBean() { // JpaRepositoryFactoryBean factory = new JooqRepositoryBean<UserRepository, User, Long>(); // factory.setRepositoryInterface(UserRepository.class); // return factory; // } // // public static void main(String[] args) throws Exception { // SpringApplication.run(Application.class, args); // } // // } // // Path: spring-data-jooq/src/main/java/com/mscharhag/springjooq/entity/User.java // @Entity // public class User { // // @Id // @GeneratedValue // private Long id; // // private String name; // private String email; // // @OneToMany // private List<Order> orders; // // public String getName() { // return name; // } // // @Column(name = "name") // public void setName(String name) { // this.name = name; // } // // public String getEmail() { // return email; // } // // @Column(name = "email") // public void setEmail(String email) { // this.email = email; // } // // public Long getId() { // return id; // } // @Column(name = "id") // public void setId(Long id) { // this.id = id; // } // // @Override // public String toString() { // return "User{" + // "id=" + id + // ", name='" + name + '\'' + // ", email='" + email + '\'' + // '}'; // } // } // // Path: spring-data-jooq/src/main/java/com/mscharhag/springjooq/repository/UserRepository.java // @Repository // public interface UserRepository extends JpaRepository<User, Long>, JooqQueryExecutor<User> { // // User findUserByName(String name); // }
import com.mscharhag.springjooq.Application; import com.mscharhag.springjooq.entity.User; import com.mscharhag.springjooq.generated.tables.Product; import com.mscharhag.springjooq.repository.UserRepository; import org.jooq.DSLContext; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.data.domain.PageRequest; import org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.transaction.TransactionConfiguration; import org.springframework.transaction.annotation.Transactional; import static com.mscharhag.springjooq.generated.tables.User.USER;
package com.mscharhag.repository; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = Application.class) //@Transactional //@TransactionConfiguration(defaultRollback = true) public class UserRepositoryTest { @Autowired DSLContext jooq; @Autowired
// Path: spring-data-jooq/src/main/java/com/mscharhag/springjooq/Application.java // @Configuration // @EnableAutoConfiguration // @ComponentScan // public class Application { // // @Bean // public DataSource dataSource() { // BasicDataSource dataSource = new BasicDataSource(); // dataSource.setDriverClassName("com.mysql.jdbc.Driver"); // dataSource.setUrl("jdbc:mysql://localhost:3306/jooq"); // dataSource.setUsername("spring-data-jooq"); // dataSource.setPassword("spring-data-jooq"); // return dataSource; // // // EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder(); // // return builder.setType(EmbeddedDatabaseType.H2).build(); // } // // @Bean // public EntityManagerFactory entityManagerFactory() throws SQLException { // HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); // vendorAdapter.setGenerateDdl(true); // LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean(); // factory.setJpaVendorAdapter(vendorAdapter); // factory.setPackagesToScan("com.mscharhag.springjooq.entity"); // factory.setDataSource(dataSource()); // factory.afterPropertiesSet(); // return factory.getObject(); // } // // @Bean // public TransactionAwareDataSourceProxy transactionAwareDataSource() { // return new TransactionAwareDataSourceProxy(dataSource()); // } // // @Bean // public DataSourceConnectionProvider connectionProvider() { // return new DataSourceConnectionProvider(transactionAwareDataSource()); // } // // // @Bean // public DefaultConfiguration configuration() { // DefaultConfiguration jooqConfiguration = new DefaultConfiguration(); // // jooqConfiguration.set(connectionProvider()); // jooqConfiguration.set(SQLDialect.MYSQL); // jooqConfiguration.set( // new RecordMapperProvider() { // @Override // public <R extends Record, E> RecordMapper<R, E> provide(RecordType<R> recordType, Class<? extends E> type) { // // if (type == Product.class) { // // return new RecordMapper<R, E>() { // // @Override // // public E map(R record) { // // Object name = record.getValue("name"); // // Object price = record.getValue("price"); // // return (E) record.getValue("ID"); // // } // // }; // // } // // return new DefaultRecordMapper(recordType, type); // } // } // ); // return jooqConfiguration; // } // // @Bean // public DefaultDSLContext dsl() { // return new DefaultDSLContext(configuration()); // } // // @Bean(autowire = Autowire.BY_TYPE) // public JpaRepositoryFactoryBean<UserRepository, User, Long> jpaRepositoryFactoryBean() { // JpaRepositoryFactoryBean factory = new JooqRepositoryBean<UserRepository, User, Long>(); // factory.setRepositoryInterface(UserRepository.class); // return factory; // } // // public static void main(String[] args) throws Exception { // SpringApplication.run(Application.class, args); // } // // } // // Path: spring-data-jooq/src/main/java/com/mscharhag/springjooq/entity/User.java // @Entity // public class User { // // @Id // @GeneratedValue // private Long id; // // private String name; // private String email; // // @OneToMany // private List<Order> orders; // // public String getName() { // return name; // } // // @Column(name = "name") // public void setName(String name) { // this.name = name; // } // // public String getEmail() { // return email; // } // // @Column(name = "email") // public void setEmail(String email) { // this.email = email; // } // // public Long getId() { // return id; // } // @Column(name = "id") // public void setId(Long id) { // this.id = id; // } // // @Override // public String toString() { // return "User{" + // "id=" + id + // ", name='" + name + '\'' + // ", email='" + email + '\'' + // '}'; // } // } // // Path: spring-data-jooq/src/main/java/com/mscharhag/springjooq/repository/UserRepository.java // @Repository // public interface UserRepository extends JpaRepository<User, Long>, JooqQueryExecutor<User> { // // User findUserByName(String name); // } // Path: spring-data-jooq/src/test/java/com/mscharhag/repository/UserRepositoryTest.java import com.mscharhag.springjooq.Application; import com.mscharhag.springjooq.entity.User; import com.mscharhag.springjooq.generated.tables.Product; import com.mscharhag.springjooq.repository.UserRepository; import org.jooq.DSLContext; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import org.springframework.data.domain.PageRequest; import org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.transaction.TransactionConfiguration; import org.springframework.transaction.annotation.Transactional; import static com.mscharhag.springjooq.generated.tables.User.USER; package com.mscharhag.repository; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = Application.class) //@Transactional //@TransactionConfiguration(defaultRollback = true) public class UserRepositoryTest { @Autowired DSLContext jooq; @Autowired
private UserRepository userRepository;
mscharhag/blog-examples
spring-validation/src/main/java/com/mscharhag/validation/Address.java
// Path: spring-validation/src/main/java/com/mscharhag/validation/ValidationHelper.java // public static <T> void validate(T object, Class<?>... groups) { // Set<ConstraintViolation<T>> violations = validator.validate(object, groups); // if (!violations.isEmpty()) { // throw new ConstraintViolationException(violations); // } // }
import javax.validation.constraints.NotBlank; import javax.validation.constraints.Size; import static com.mscharhag.validation.ValidationHelper.validate;
package com.mscharhag.validation; public class Address { @NotBlank @Size(max = 50) private String street; @NotBlank @Size(max = 50) private String city; @NotBlank @Size(max = 10) private String zipCode; @NotBlank private String country; public Address() {} public Address(String street, String city, String zipCode, String country) { this.street = street; this.city = city; this.zipCode = zipCode; this.country = country;
// Path: spring-validation/src/main/java/com/mscharhag/validation/ValidationHelper.java // public static <T> void validate(T object, Class<?>... groups) { // Set<ConstraintViolation<T>> violations = validator.validate(object, groups); // if (!violations.isEmpty()) { // throw new ConstraintViolationException(violations); // } // } // Path: spring-validation/src/main/java/com/mscharhag/validation/Address.java import javax.validation.constraints.NotBlank; import javax.validation.constraints.Size; import static com.mscharhag.validation.ValidationHelper.validate; package com.mscharhag.validation; public class Address { @NotBlank @Size(max = 50) private String street; @NotBlank @Size(max = 50) private String city; @NotBlank @Size(max = 10) private String zipCode; @NotBlank private String country; public Address() {} public Address(String street, String city, String zipCode, String country) { this.street = street; this.city = city; this.zipCode = zipCode; this.country = country;
validate(this);
mscharhag/blog-examples
spring-data-jooq/src/main/java/com/mscharhag/springjooq/Application.java
// Path: spring-data-jooq/src/main/java/com/mscharhag/springjooq/entity/User.java // @Entity // public class User { // // @Id // @GeneratedValue // private Long id; // // private String name; // private String email; // // @OneToMany // private List<Order> orders; // // public String getName() { // return name; // } // // @Column(name = "name") // public void setName(String name) { // this.name = name; // } // // public String getEmail() { // return email; // } // // @Column(name = "email") // public void setEmail(String email) { // this.email = email; // } // // public Long getId() { // return id; // } // @Column(name = "id") // public void setId(Long id) { // this.id = id; // } // // @Override // public String toString() { // return "User{" + // "id=" + id + // ", name='" + name + '\'' + // ", email='" + email + '\'' + // '}'; // } // } // // Path: spring-data-jooq/src/main/java/com/mscharhag/springjooq/jooq/JooqRepositoryBean.java // public class JooqRepositoryBean<T extends Repository<S, ID>, S, ID extends Serializable> // extends JpaRepositoryFactoryBean<T, S, ID> { // // @Autowired // private DSLContext jooq; // // protected RepositoryFactorySupport createRepositoryFactory(EntityManager entityManager) { // return new JooqJpaRepositoryFactory(entityManager, jooq); // } // } // // Path: spring-data-jooq/src/main/java/com/mscharhag/springjooq/repository/UserRepository.java // @Repository // public interface UserRepository extends JpaRepository<User, Long>, JooqQueryExecutor<User> { // // User findUserByName(String name); // }
import com.mscharhag.springjooq.entity.User; import com.mscharhag.springjooq.jooq.JooqRepositoryBean; import com.mscharhag.springjooq.repository.UserRepository; import org.apache.commons.dbcp.BasicDataSource; import org.jooq.*; import org.jooq.impl.*; import org.springframework.beans.factory.annotation.Autowire; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean; import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; import javax.persistence.EntityManagerFactory; import javax.sql.DataSource; import java.sql.SQLException;
jooqConfiguration.set(connectionProvider()); jooqConfiguration.set(SQLDialect.MYSQL); jooqConfiguration.set( new RecordMapperProvider() { @Override public <R extends Record, E> RecordMapper<R, E> provide(RecordType<R> recordType, Class<? extends E> type) { // if (type == Product.class) { // return new RecordMapper<R, E>() { // @Override // public E map(R record) { // Object name = record.getValue("name"); // Object price = record.getValue("price"); // return (E) record.getValue("ID"); // } // }; // } return new DefaultRecordMapper(recordType, type); } } ); return jooqConfiguration; } @Bean public DefaultDSLContext dsl() { return new DefaultDSLContext(configuration()); } @Bean(autowire = Autowire.BY_TYPE)
// Path: spring-data-jooq/src/main/java/com/mscharhag/springjooq/entity/User.java // @Entity // public class User { // // @Id // @GeneratedValue // private Long id; // // private String name; // private String email; // // @OneToMany // private List<Order> orders; // // public String getName() { // return name; // } // // @Column(name = "name") // public void setName(String name) { // this.name = name; // } // // public String getEmail() { // return email; // } // // @Column(name = "email") // public void setEmail(String email) { // this.email = email; // } // // public Long getId() { // return id; // } // @Column(name = "id") // public void setId(Long id) { // this.id = id; // } // // @Override // public String toString() { // return "User{" + // "id=" + id + // ", name='" + name + '\'' + // ", email='" + email + '\'' + // '}'; // } // } // // Path: spring-data-jooq/src/main/java/com/mscharhag/springjooq/jooq/JooqRepositoryBean.java // public class JooqRepositoryBean<T extends Repository<S, ID>, S, ID extends Serializable> // extends JpaRepositoryFactoryBean<T, S, ID> { // // @Autowired // private DSLContext jooq; // // protected RepositoryFactorySupport createRepositoryFactory(EntityManager entityManager) { // return new JooqJpaRepositoryFactory(entityManager, jooq); // } // } // // Path: spring-data-jooq/src/main/java/com/mscharhag/springjooq/repository/UserRepository.java // @Repository // public interface UserRepository extends JpaRepository<User, Long>, JooqQueryExecutor<User> { // // User findUserByName(String name); // } // Path: spring-data-jooq/src/main/java/com/mscharhag/springjooq/Application.java import com.mscharhag.springjooq.entity.User; import com.mscharhag.springjooq.jooq.JooqRepositoryBean; import com.mscharhag.springjooq.repository.UserRepository; import org.apache.commons.dbcp.BasicDataSource; import org.jooq.*; import org.jooq.impl.*; import org.springframework.beans.factory.annotation.Autowire; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean; import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; import javax.persistence.EntityManagerFactory; import javax.sql.DataSource; import java.sql.SQLException; jooqConfiguration.set(connectionProvider()); jooqConfiguration.set(SQLDialect.MYSQL); jooqConfiguration.set( new RecordMapperProvider() { @Override public <R extends Record, E> RecordMapper<R, E> provide(RecordType<R> recordType, Class<? extends E> type) { // if (type == Product.class) { // return new RecordMapper<R, E>() { // @Override // public E map(R record) { // Object name = record.getValue("name"); // Object price = record.getValue("price"); // return (E) record.getValue("ID"); // } // }; // } return new DefaultRecordMapper(recordType, type); } } ); return jooqConfiguration; } @Bean public DefaultDSLContext dsl() { return new DefaultDSLContext(configuration()); } @Bean(autowire = Autowire.BY_TYPE)
public JpaRepositoryFactoryBean<UserRepository, User, Long> jpaRepositoryFactoryBean() {
mscharhag/blog-examples
spring-data-jooq/src/main/java/com/mscharhag/springjooq/Application.java
// Path: spring-data-jooq/src/main/java/com/mscharhag/springjooq/entity/User.java // @Entity // public class User { // // @Id // @GeneratedValue // private Long id; // // private String name; // private String email; // // @OneToMany // private List<Order> orders; // // public String getName() { // return name; // } // // @Column(name = "name") // public void setName(String name) { // this.name = name; // } // // public String getEmail() { // return email; // } // // @Column(name = "email") // public void setEmail(String email) { // this.email = email; // } // // public Long getId() { // return id; // } // @Column(name = "id") // public void setId(Long id) { // this.id = id; // } // // @Override // public String toString() { // return "User{" + // "id=" + id + // ", name='" + name + '\'' + // ", email='" + email + '\'' + // '}'; // } // } // // Path: spring-data-jooq/src/main/java/com/mscharhag/springjooq/jooq/JooqRepositoryBean.java // public class JooqRepositoryBean<T extends Repository<S, ID>, S, ID extends Serializable> // extends JpaRepositoryFactoryBean<T, S, ID> { // // @Autowired // private DSLContext jooq; // // protected RepositoryFactorySupport createRepositoryFactory(EntityManager entityManager) { // return new JooqJpaRepositoryFactory(entityManager, jooq); // } // } // // Path: spring-data-jooq/src/main/java/com/mscharhag/springjooq/repository/UserRepository.java // @Repository // public interface UserRepository extends JpaRepository<User, Long>, JooqQueryExecutor<User> { // // User findUserByName(String name); // }
import com.mscharhag.springjooq.entity.User; import com.mscharhag.springjooq.jooq.JooqRepositoryBean; import com.mscharhag.springjooq.repository.UserRepository; import org.apache.commons.dbcp.BasicDataSource; import org.jooq.*; import org.jooq.impl.*; import org.springframework.beans.factory.annotation.Autowire; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean; import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; import javax.persistence.EntityManagerFactory; import javax.sql.DataSource; import java.sql.SQLException;
jooqConfiguration.set(connectionProvider()); jooqConfiguration.set(SQLDialect.MYSQL); jooqConfiguration.set( new RecordMapperProvider() { @Override public <R extends Record, E> RecordMapper<R, E> provide(RecordType<R> recordType, Class<? extends E> type) { // if (type == Product.class) { // return new RecordMapper<R, E>() { // @Override // public E map(R record) { // Object name = record.getValue("name"); // Object price = record.getValue("price"); // return (E) record.getValue("ID"); // } // }; // } return new DefaultRecordMapper(recordType, type); } } ); return jooqConfiguration; } @Bean public DefaultDSLContext dsl() { return new DefaultDSLContext(configuration()); } @Bean(autowire = Autowire.BY_TYPE)
// Path: spring-data-jooq/src/main/java/com/mscharhag/springjooq/entity/User.java // @Entity // public class User { // // @Id // @GeneratedValue // private Long id; // // private String name; // private String email; // // @OneToMany // private List<Order> orders; // // public String getName() { // return name; // } // // @Column(name = "name") // public void setName(String name) { // this.name = name; // } // // public String getEmail() { // return email; // } // // @Column(name = "email") // public void setEmail(String email) { // this.email = email; // } // // public Long getId() { // return id; // } // @Column(name = "id") // public void setId(Long id) { // this.id = id; // } // // @Override // public String toString() { // return "User{" + // "id=" + id + // ", name='" + name + '\'' + // ", email='" + email + '\'' + // '}'; // } // } // // Path: spring-data-jooq/src/main/java/com/mscharhag/springjooq/jooq/JooqRepositoryBean.java // public class JooqRepositoryBean<T extends Repository<S, ID>, S, ID extends Serializable> // extends JpaRepositoryFactoryBean<T, S, ID> { // // @Autowired // private DSLContext jooq; // // protected RepositoryFactorySupport createRepositoryFactory(EntityManager entityManager) { // return new JooqJpaRepositoryFactory(entityManager, jooq); // } // } // // Path: spring-data-jooq/src/main/java/com/mscharhag/springjooq/repository/UserRepository.java // @Repository // public interface UserRepository extends JpaRepository<User, Long>, JooqQueryExecutor<User> { // // User findUserByName(String name); // } // Path: spring-data-jooq/src/main/java/com/mscharhag/springjooq/Application.java import com.mscharhag.springjooq.entity.User; import com.mscharhag.springjooq.jooq.JooqRepositoryBean; import com.mscharhag.springjooq.repository.UserRepository; import org.apache.commons.dbcp.BasicDataSource; import org.jooq.*; import org.jooq.impl.*; import org.springframework.beans.factory.annotation.Autowire; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean; import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; import javax.persistence.EntityManagerFactory; import javax.sql.DataSource; import java.sql.SQLException; jooqConfiguration.set(connectionProvider()); jooqConfiguration.set(SQLDialect.MYSQL); jooqConfiguration.set( new RecordMapperProvider() { @Override public <R extends Record, E> RecordMapper<R, E> provide(RecordType<R> recordType, Class<? extends E> type) { // if (type == Product.class) { // return new RecordMapper<R, E>() { // @Override // public E map(R record) { // Object name = record.getValue("name"); // Object price = record.getValue("price"); // return (E) record.getValue("ID"); // } // }; // } return new DefaultRecordMapper(recordType, type); } } ); return jooqConfiguration; } @Bean public DefaultDSLContext dsl() { return new DefaultDSLContext(configuration()); } @Bean(autowire = Autowire.BY_TYPE)
public JpaRepositoryFactoryBean<UserRepository, User, Long> jpaRepositoryFactoryBean() {
mscharhag/blog-examples
spring-data-jooq/src/main/java/com/mscharhag/springjooq/Application.java
// Path: spring-data-jooq/src/main/java/com/mscharhag/springjooq/entity/User.java // @Entity // public class User { // // @Id // @GeneratedValue // private Long id; // // private String name; // private String email; // // @OneToMany // private List<Order> orders; // // public String getName() { // return name; // } // // @Column(name = "name") // public void setName(String name) { // this.name = name; // } // // public String getEmail() { // return email; // } // // @Column(name = "email") // public void setEmail(String email) { // this.email = email; // } // // public Long getId() { // return id; // } // @Column(name = "id") // public void setId(Long id) { // this.id = id; // } // // @Override // public String toString() { // return "User{" + // "id=" + id + // ", name='" + name + '\'' + // ", email='" + email + '\'' + // '}'; // } // } // // Path: spring-data-jooq/src/main/java/com/mscharhag/springjooq/jooq/JooqRepositoryBean.java // public class JooqRepositoryBean<T extends Repository<S, ID>, S, ID extends Serializable> // extends JpaRepositoryFactoryBean<T, S, ID> { // // @Autowired // private DSLContext jooq; // // protected RepositoryFactorySupport createRepositoryFactory(EntityManager entityManager) { // return new JooqJpaRepositoryFactory(entityManager, jooq); // } // } // // Path: spring-data-jooq/src/main/java/com/mscharhag/springjooq/repository/UserRepository.java // @Repository // public interface UserRepository extends JpaRepository<User, Long>, JooqQueryExecutor<User> { // // User findUserByName(String name); // }
import com.mscharhag.springjooq.entity.User; import com.mscharhag.springjooq.jooq.JooqRepositoryBean; import com.mscharhag.springjooq.repository.UserRepository; import org.apache.commons.dbcp.BasicDataSource; import org.jooq.*; import org.jooq.impl.*; import org.springframework.beans.factory.annotation.Autowire; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean; import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; import javax.persistence.EntityManagerFactory; import javax.sql.DataSource; import java.sql.SQLException;
jooqConfiguration.set(SQLDialect.MYSQL); jooqConfiguration.set( new RecordMapperProvider() { @Override public <R extends Record, E> RecordMapper<R, E> provide(RecordType<R> recordType, Class<? extends E> type) { // if (type == Product.class) { // return new RecordMapper<R, E>() { // @Override // public E map(R record) { // Object name = record.getValue("name"); // Object price = record.getValue("price"); // return (E) record.getValue("ID"); // } // }; // } return new DefaultRecordMapper(recordType, type); } } ); return jooqConfiguration; } @Bean public DefaultDSLContext dsl() { return new DefaultDSLContext(configuration()); } @Bean(autowire = Autowire.BY_TYPE) public JpaRepositoryFactoryBean<UserRepository, User, Long> jpaRepositoryFactoryBean() {
// Path: spring-data-jooq/src/main/java/com/mscharhag/springjooq/entity/User.java // @Entity // public class User { // // @Id // @GeneratedValue // private Long id; // // private String name; // private String email; // // @OneToMany // private List<Order> orders; // // public String getName() { // return name; // } // // @Column(name = "name") // public void setName(String name) { // this.name = name; // } // // public String getEmail() { // return email; // } // // @Column(name = "email") // public void setEmail(String email) { // this.email = email; // } // // public Long getId() { // return id; // } // @Column(name = "id") // public void setId(Long id) { // this.id = id; // } // // @Override // public String toString() { // return "User{" + // "id=" + id + // ", name='" + name + '\'' + // ", email='" + email + '\'' + // '}'; // } // } // // Path: spring-data-jooq/src/main/java/com/mscharhag/springjooq/jooq/JooqRepositoryBean.java // public class JooqRepositoryBean<T extends Repository<S, ID>, S, ID extends Serializable> // extends JpaRepositoryFactoryBean<T, S, ID> { // // @Autowired // private DSLContext jooq; // // protected RepositoryFactorySupport createRepositoryFactory(EntityManager entityManager) { // return new JooqJpaRepositoryFactory(entityManager, jooq); // } // } // // Path: spring-data-jooq/src/main/java/com/mscharhag/springjooq/repository/UserRepository.java // @Repository // public interface UserRepository extends JpaRepository<User, Long>, JooqQueryExecutor<User> { // // User findUserByName(String name); // } // Path: spring-data-jooq/src/main/java/com/mscharhag/springjooq/Application.java import com.mscharhag.springjooq.entity.User; import com.mscharhag.springjooq.jooq.JooqRepositoryBean; import com.mscharhag.springjooq.repository.UserRepository; import org.apache.commons.dbcp.BasicDataSource; import org.jooq.*; import org.jooq.impl.*; import org.springframework.beans.factory.annotation.Autowire; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean; import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; import javax.persistence.EntityManagerFactory; import javax.sql.DataSource; import java.sql.SQLException; jooqConfiguration.set(SQLDialect.MYSQL); jooqConfiguration.set( new RecordMapperProvider() { @Override public <R extends Record, E> RecordMapper<R, E> provide(RecordType<R> recordType, Class<? extends E> type) { // if (type == Product.class) { // return new RecordMapper<R, E>() { // @Override // public E map(R record) { // Object name = record.getValue("name"); // Object price = record.getValue("price"); // return (E) record.getValue("ID"); // } // }; // } return new DefaultRecordMapper(recordType, type); } } ); return jooqConfiguration; } @Bean public DefaultDSLContext dsl() { return new DefaultDSLContext(configuration()); } @Bean(autowire = Autowire.BY_TYPE) public JpaRepositoryFactoryBean<UserRepository, User, Long> jpaRepositoryFactoryBean() {
JpaRepositoryFactoryBean factory = new JooqRepositoryBean<UserRepository, User, Long>();
mscharhag/blog-examples
exception-translation/src/test/java/com/mscharhag/exceptiontranslation/MyRepositoryTest.java
// Path: exception-translation/src/main/java/com/mscharhag/exceptiontranslation/exception/DataAccessException.java // public class DataAccessException extends RuntimeException { // public DataAccessException(Throwable cause) { // super(cause); // } // } // // Path: exception-translation/src/main/java/com/mscharhag/exceptiontranslation/repository/MyRepository.java // public class MyRepository { // // public Object getSomeData() { // // simulate hibernate error // throw new JDBCException("Error", null); // } // }
import com.mscharhag.exceptiontranslation.exception.DataAccessException; import com.mscharhag.exceptiontranslation.repository.MyRepository; import org.junit.Test;
package com.mscharhag.exceptiontranslation; public class MyRepositoryTest { private MyRepository repository = new MyRepository();
// Path: exception-translation/src/main/java/com/mscharhag/exceptiontranslation/exception/DataAccessException.java // public class DataAccessException extends RuntimeException { // public DataAccessException(Throwable cause) { // super(cause); // } // } // // Path: exception-translation/src/main/java/com/mscharhag/exceptiontranslation/repository/MyRepository.java // public class MyRepository { // // public Object getSomeData() { // // simulate hibernate error // throw new JDBCException("Error", null); // } // } // Path: exception-translation/src/test/java/com/mscharhag/exceptiontranslation/MyRepositoryTest.java import com.mscharhag.exceptiontranslation.exception.DataAccessException; import com.mscharhag.exceptiontranslation.repository.MyRepository; import org.junit.Test; package com.mscharhag.exceptiontranslation; public class MyRepositoryTest { private MyRepository repository = new MyRepository();
@Test(expected = DataAccessException.class)
mscharhag/blog-examples
archunit/src/main/java/com/mscharhag/archunit/layers/service/impl/UserServiceImpl.java
// Path: archunit/src/main/java/com/mscharhag/archunit/layers/repository/UserRepository.java // public class UserRepository { // // private EntityManager entityManager; // // public User loadUser() { // return new User("John Doe"); // } // } // // Path: archunit/src/main/java/com/mscharhag/archunit/layers/service/UserService.java // public interface UserService { // User getUser(); // } // // Path: archunit/src/main/java/com/mscharhag/archunit/model/User.java // @Entity // public class User { // // private String name; // // public User(String name) { // this.name = name; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // }
import com.mscharhag.archunit.layers.repository.UserRepository; import com.mscharhag.archunit.layers.service.UserService; import com.mscharhag.archunit.model.User; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
package com.mscharhag.archunit.layers.service.impl; public class UserServiceImpl implements UserService { private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);
// Path: archunit/src/main/java/com/mscharhag/archunit/layers/repository/UserRepository.java // public class UserRepository { // // private EntityManager entityManager; // // public User loadUser() { // return new User("John Doe"); // } // } // // Path: archunit/src/main/java/com/mscharhag/archunit/layers/service/UserService.java // public interface UserService { // User getUser(); // } // // Path: archunit/src/main/java/com/mscharhag/archunit/model/User.java // @Entity // public class User { // // private String name; // // public User(String name) { // this.name = name; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // } // Path: archunit/src/main/java/com/mscharhag/archunit/layers/service/impl/UserServiceImpl.java import com.mscharhag.archunit.layers.repository.UserRepository; import com.mscharhag.archunit.layers.service.UserService; import com.mscharhag.archunit.model.User; import org.slf4j.Logger; import org.slf4j.LoggerFactory; package com.mscharhag.archunit.layers.service.impl; public class UserServiceImpl implements UserService { private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);
private final UserRepository repository;
mscharhag/blog-examples
archunit/src/main/java/com/mscharhag/archunit/layers/service/impl/UserServiceImpl.java
// Path: archunit/src/main/java/com/mscharhag/archunit/layers/repository/UserRepository.java // public class UserRepository { // // private EntityManager entityManager; // // public User loadUser() { // return new User("John Doe"); // } // } // // Path: archunit/src/main/java/com/mscharhag/archunit/layers/service/UserService.java // public interface UserService { // User getUser(); // } // // Path: archunit/src/main/java/com/mscharhag/archunit/model/User.java // @Entity // public class User { // // private String name; // // public User(String name) { // this.name = name; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // }
import com.mscharhag.archunit.layers.repository.UserRepository; import com.mscharhag.archunit.layers.service.UserService; import com.mscharhag.archunit.model.User; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
package com.mscharhag.archunit.layers.service.impl; public class UserServiceImpl implements UserService { private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class); private final UserRepository repository; public UserServiceImpl(UserRepository repository) { this.repository = repository; }
// Path: archunit/src/main/java/com/mscharhag/archunit/layers/repository/UserRepository.java // public class UserRepository { // // private EntityManager entityManager; // // public User loadUser() { // return new User("John Doe"); // } // } // // Path: archunit/src/main/java/com/mscharhag/archunit/layers/service/UserService.java // public interface UserService { // User getUser(); // } // // Path: archunit/src/main/java/com/mscharhag/archunit/model/User.java // @Entity // public class User { // // private String name; // // public User(String name) { // this.name = name; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // } // Path: archunit/src/main/java/com/mscharhag/archunit/layers/service/impl/UserServiceImpl.java import com.mscharhag.archunit.layers.repository.UserRepository; import com.mscharhag.archunit.layers.service.UserService; import com.mscharhag.archunit.model.User; import org.slf4j.Logger; import org.slf4j.LoggerFactory; package com.mscharhag.archunit.layers.service.impl; public class UserServiceImpl implements UserService { private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class); private final UserRepository repository; public UserServiceImpl(UserRepository repository) { this.repository = repository; }
public User getUser() {
mscharhag/blog-examples
domain-injection/src/main/java/com/mscharhag/examples/domaininjection/controller/TestController.java
// Path: domain-injection/src/main/java/com/mscharhag/examples/domaininjection/domain/User.java // public class User { // private String firstName; // private String lastName; // // public User(String firstName, String lastName) { // this.firstName = firstName; // this.lastName = lastName; // } // // public String getFirstName() { // return firstName; // } // // public String getLastName() { // return lastName; // } // // @Override // public String toString() { // return "User{" + // "firstName='" + firstName + '\'' + // ", lastName='" + lastName + '\'' + // '}'; // } // }
import com.mscharhag.examples.domaininjection.annotation.LoggedInUser; import com.mscharhag.examples.domaininjection.domain.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController;
package com.mscharhag.examples.domaininjection.controller; @RestController public class TestController { @Autowired @LoggedInUser
// Path: domain-injection/src/main/java/com/mscharhag/examples/domaininjection/domain/User.java // public class User { // private String firstName; // private String lastName; // // public User(String firstName, String lastName) { // this.firstName = firstName; // this.lastName = lastName; // } // // public String getFirstName() { // return firstName; // } // // public String getLastName() { // return lastName; // } // // @Override // public String toString() { // return "User{" + // "firstName='" + firstName + '\'' + // ", lastName='" + lastName + '\'' + // '}'; // } // } // Path: domain-injection/src/main/java/com/mscharhag/examples/domaininjection/controller/TestController.java import com.mscharhag.examples.domaininjection.annotation.LoggedInUser; import com.mscharhag.examples.domaininjection.domain.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; package com.mscharhag.examples.domaininjection.controller; @RestController public class TestController { @Autowired @LoggedInUser
private User loggedInUser;
mscharhag/blog-examples
spring-error-handling/src/main/java/com/mscharhag/errorhandling/article/ArticleExceptionHandler.java
// Path: spring-error-handling/src/main/java/com/mscharhag/errorhandling/ErrorResponse.java // public class ErrorResponse { // private final String code; // private final String message; // // public ErrorResponse(String code, String message) { // this.code = code; // this.message = message; // } // // public String getMessage() { // return message; // } // // public String getCode() { // return code; // } // }
import com.mscharhag.errorhandling.ErrorResponse; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler;
package com.mscharhag.errorhandling.article; @ControllerAdvice public class ArticleExceptionHandler { @ExceptionHandler(ArticleNotFoundException.class)
// Path: spring-error-handling/src/main/java/com/mscharhag/errorhandling/ErrorResponse.java // public class ErrorResponse { // private final String code; // private final String message; // // public ErrorResponse(String code, String message) { // this.code = code; // this.message = message; // } // // public String getMessage() { // return message; // } // // public String getCode() { // return code; // } // } // Path: spring-error-handling/src/main/java/com/mscharhag/errorhandling/article/ArticleExceptionHandler.java import com.mscharhag.errorhandling.ErrorResponse; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; package com.mscharhag.errorhandling.article; @ControllerAdvice public class ArticleExceptionHandler { @ExceptionHandler(ArticleNotFoundException.class)
public ResponseEntity<ErrorResponse> onArticleNotFoundException(ArticleNotFoundException e) {
kousen/GradleRecipesForAndroid
ch04/HelloWorldICNDB/app/src/main/java/com/kousenit/helloworldicndb/WelcomeActivity.java
// Path: ch04/HelloWorldICNDB/icndb/src/main/java/com/kousenit/icndb/JokeFinder.java // public class JokeFinder { // private TextView jokeView; // private Retrofit retrofit; // private AsyncTask<String, Void, String> task; // // interface ICNDB { // @GET("/jokes/random") // Call<IcndbJoke> getJoke(@Query("firstName") String firstName, // @Query("lastName") String lastName, // @Query("limitTo") String limitTo); // } // // public JokeFinder() { // retrofit = new Retrofit.Builder() // .baseUrl("http://api.icndb.com") // .addConverterFactory(GsonConverterFactory.create()) // .build(); // } // // public void getJoke(TextView textView, String first, String last) { // this.jokeView = textView; // // ICNDB icndb = retrofit.create(ICNDB.class); // icndb.getJoke(first, last, "[nerdy]").enqueue(new Callback<IcndbJoke>() { // @Override // public void onResponse(Call<IcndbJoke> call, Response<IcndbJoke> response) { // if (!response.isSuccessful()) { // System.out.println(call.request().url() + " failed: " + response.code()); // return; // } // // jokeView.setText(response.body().getJoke()); // } // // @Override // public void onFailure(Call<IcndbJoke> call, Throwable t) { // System.out.println(call.request().url() + " failed: " + t); // } // }); // } // }
import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import androidx.appcompat.app.AppCompatActivity; import android.view.Menu; import android.view.MenuItem; import android.widget.TextView; import com.kousenit.icndb.JokeFinder;
package com.kousenit.helloworldicndb; public class WelcomeActivity extends AppCompatActivity { private TextView greetingText; private TextView jokeText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_welcome); if (getActionBar() != null) { getActionBar().setDisplayHomeAsUpEnabled(true); } String name = getIntent().getStringExtra("name"); greetingText = findViewById(R.id.greeting_text); jokeText = findViewById(R.id.joke_text); final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
// Path: ch04/HelloWorldICNDB/icndb/src/main/java/com/kousenit/icndb/JokeFinder.java // public class JokeFinder { // private TextView jokeView; // private Retrofit retrofit; // private AsyncTask<String, Void, String> task; // // interface ICNDB { // @GET("/jokes/random") // Call<IcndbJoke> getJoke(@Query("firstName") String firstName, // @Query("lastName") String lastName, // @Query("limitTo") String limitTo); // } // // public JokeFinder() { // retrofit = new Retrofit.Builder() // .baseUrl("http://api.icndb.com") // .addConverterFactory(GsonConverterFactory.create()) // .build(); // } // // public void getJoke(TextView textView, String first, String last) { // this.jokeView = textView; // // ICNDB icndb = retrofit.create(ICNDB.class); // icndb.getJoke(first, last, "[nerdy]").enqueue(new Callback<IcndbJoke>() { // @Override // public void onResponse(Call<IcndbJoke> call, Response<IcndbJoke> response) { // if (!response.isSuccessful()) { // System.out.println(call.request().url() + " failed: " + response.code()); // return; // } // // jokeView.setText(response.body().getJoke()); // } // // @Override // public void onFailure(Call<IcndbJoke> call, Throwable t) { // System.out.println(call.request().url() + " failed: " + t); // } // }); // } // } // Path: ch04/HelloWorldICNDB/app/src/main/java/com/kousenit/helloworldicndb/WelcomeActivity.java import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import androidx.appcompat.app.AppCompatActivity; import android.view.Menu; import android.view.MenuItem; import android.widget.TextView; import com.kousenit.icndb.JokeFinder; package com.kousenit.helloworldicndb; public class WelcomeActivity extends AppCompatActivity { private TextView greetingText; private TextView jokeText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_welcome); if (getActionBar() != null) { getActionBar().setDisplayHomeAsUpEnabled(true); } String name = getIntent().getStringExtra("name"); greetingText = findViewById(R.id.greeting_text); jokeText = findViewById(R.id.joke_text); final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
new JokeFinder().getJoke(jokeText,
GoogleCloudPlatform/getting-started-java
bookshelf/1-cloud-run/src/main/java/com/example/getstarted/basicactions/DeleteBookServlet.java
// Path: bookshelf-standard/5-logging/src/main/java/com/example/getstarted/daos/BookDao.java // public interface BookDao { // Long createBook(Book book) throws SQLException; // // Book readBook(Long bookId) throws SQLException; // // void updateBook(Book book) throws SQLException; // // void deleteBook(Long bookId) throws SQLException; // // Result<Book> listBooks(String startCursor) throws SQLException; // // Result<Book> listBooksByUser(String userId, String startCursor) throws SQLException; // }
import com.example.getstarted.daos.BookDao; import java.io.IOException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;
/* Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.example.getstarted.basicactions; // [START bookshelf_delete_servlet] @SuppressWarnings("serial") @WebServlet( name = "delete", urlPatterns = {"/delete"}) public class DeleteBookServlet extends HttpServlet { @Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { String id = req.getParameter("id");
// Path: bookshelf-standard/5-logging/src/main/java/com/example/getstarted/daos/BookDao.java // public interface BookDao { // Long createBook(Book book) throws SQLException; // // Book readBook(Long bookId) throws SQLException; // // void updateBook(Book book) throws SQLException; // // void deleteBook(Long bookId) throws SQLException; // // Result<Book> listBooks(String startCursor) throws SQLException; // // Result<Book> listBooksByUser(String userId, String startCursor) throws SQLException; // } // Path: bookshelf/1-cloud-run/src/main/java/com/example/getstarted/basicactions/DeleteBookServlet.java import com.example.getstarted.daos.BookDao; import java.io.IOException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /* Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.example.getstarted.basicactions; // [START bookshelf_delete_servlet] @SuppressWarnings("serial") @WebServlet( name = "delete", urlPatterns = {"/delete"}) public class DeleteBookServlet extends HttpServlet { @Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { String id = req.getParameter("id");
BookDao dao = (BookDao) this.getServletContext().getAttribute("dao");
GoogleCloudPlatform/getting-started-java
bookshelf-standard/5-logging/src/main/java/com/example/getstarted/daos/BookDao.java
// Path: bookshelf/1-cloud-run/src/main/java/com/example/getstarted/objects/Book.java // public class Book { // private String title; // private String author; // private String createdBy; // private String createdById; // private String publishedDate; // private String description; // private String id; // private String imageUrl; // public static final String AUTHOR = "author"; // public static final String CREATED_BY = "createdBy"; // public static final String CREATED_BY_ID = "createdById"; // public static final String DESCRIPTION = "description"; // public static final String ID = "id"; // public static final String PUBLISHED_DATE = "publishedDate"; // public static final String TITLE = "title"; // public static final String IMAGE_URL = "imageUrl"; // // // We use a Builder pattern here to simplify and standardize construction of // // Book objects. // private Book(Builder builder) { // this.title = builder.title; // this.author = builder.author; // this.createdBy = builder.createdBy; // this.createdById = builder.createdById; // this.publishedDate = builder.publishedDate; // this.description = builder.description; // this.id = builder.id; // this.imageUrl = builder.imageUrl; // } // // public static class Builder { // private String title; // private String author; // private String createdBy; // private String createdById; // private String publishedDate; // private String description; // private String id; // private String imageUrl; // // public Builder title(String title) { // this.title = title; // return this; // } // // public Builder author(String author) { // this.author = author; // return this; // } // // public Builder createdBy(String createdBy) { // this.createdBy = createdBy; // return this; // } // // public Builder createdById(String createdById) { // this.createdById = createdById; // return this; // } // // public Builder publishedDate(String publishedDate) { // this.publishedDate = publishedDate; // return this; // } // // public Builder description(String description) { // this.description = description; // return this; // } // // public Builder id(String id) { // this.id = id; // return this; // } // // public Builder imageUrl(String imageUrl) { // this.imageUrl = imageUrl; // return this; // } // // public Book build() { // return new Book(this); // } // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String author) { // this.author = author; // } // // public String getCreatedBy() { // return createdBy; // } // // public void setCreatedBy(String createdBy) { // this.createdBy = createdBy; // } // // public String getCreatedById() { // return createdById; // } // // public void setCreatedById(String createdById) { // this.createdById = createdById; // } // // public String getPublishedDate() { // return publishedDate; // } // // public void setPublishedDate(String publishedDate) { // this.publishedDate = publishedDate; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getImageUrl() { // return imageUrl; // } // // public void setImageUrl(String imageUrl) { // this.imageUrl = imageUrl; // } // // @Override // public String toString() { // return "Title: " // + title // + ", Author: " // + author // + ", Published date: " // + publishedDate // + ", Added by: " // + createdBy; // } // } // // Path: bookshelf/1-cloud-run/src/main/java/com/example/getstarted/objects/Result.java // public class Result<K> { // private String cursor; // private List<K> result; // // public String getCursor() { // return cursor; // } // // public void setCursor(String cursor) { // this.cursor = cursor; // } // // public List<K> getResult() { // return result; // } // // public void setResult(List<K> result) { // this.result = result; // } // // public Result(List<K> result, String cursor) { // this.result = result; // this.cursor = cursor; // } // // public Result(List<K> result) { // this.result = result; // this.cursor = null; // } // }
import com.example.getstarted.objects.Book; import com.example.getstarted.objects.Result; import java.sql.SQLException;
/* Copyright 2016 Google 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.example.getstarted.daos; // [START example] public interface BookDao { Long createBook(Book book) throws SQLException; Book readBook(Long bookId) throws SQLException; void updateBook(Book book) throws SQLException; void deleteBook(Long bookId) throws SQLException;
// Path: bookshelf/1-cloud-run/src/main/java/com/example/getstarted/objects/Book.java // public class Book { // private String title; // private String author; // private String createdBy; // private String createdById; // private String publishedDate; // private String description; // private String id; // private String imageUrl; // public static final String AUTHOR = "author"; // public static final String CREATED_BY = "createdBy"; // public static final String CREATED_BY_ID = "createdById"; // public static final String DESCRIPTION = "description"; // public static final String ID = "id"; // public static final String PUBLISHED_DATE = "publishedDate"; // public static final String TITLE = "title"; // public static final String IMAGE_URL = "imageUrl"; // // // We use a Builder pattern here to simplify and standardize construction of // // Book objects. // private Book(Builder builder) { // this.title = builder.title; // this.author = builder.author; // this.createdBy = builder.createdBy; // this.createdById = builder.createdById; // this.publishedDate = builder.publishedDate; // this.description = builder.description; // this.id = builder.id; // this.imageUrl = builder.imageUrl; // } // // public static class Builder { // private String title; // private String author; // private String createdBy; // private String createdById; // private String publishedDate; // private String description; // private String id; // private String imageUrl; // // public Builder title(String title) { // this.title = title; // return this; // } // // public Builder author(String author) { // this.author = author; // return this; // } // // public Builder createdBy(String createdBy) { // this.createdBy = createdBy; // return this; // } // // public Builder createdById(String createdById) { // this.createdById = createdById; // return this; // } // // public Builder publishedDate(String publishedDate) { // this.publishedDate = publishedDate; // return this; // } // // public Builder description(String description) { // this.description = description; // return this; // } // // public Builder id(String id) { // this.id = id; // return this; // } // // public Builder imageUrl(String imageUrl) { // this.imageUrl = imageUrl; // return this; // } // // public Book build() { // return new Book(this); // } // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String author) { // this.author = author; // } // // public String getCreatedBy() { // return createdBy; // } // // public void setCreatedBy(String createdBy) { // this.createdBy = createdBy; // } // // public String getCreatedById() { // return createdById; // } // // public void setCreatedById(String createdById) { // this.createdById = createdById; // } // // public String getPublishedDate() { // return publishedDate; // } // // public void setPublishedDate(String publishedDate) { // this.publishedDate = publishedDate; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getImageUrl() { // return imageUrl; // } // // public void setImageUrl(String imageUrl) { // this.imageUrl = imageUrl; // } // // @Override // public String toString() { // return "Title: " // + title // + ", Author: " // + author // + ", Published date: " // + publishedDate // + ", Added by: " // + createdBy; // } // } // // Path: bookshelf/1-cloud-run/src/main/java/com/example/getstarted/objects/Result.java // public class Result<K> { // private String cursor; // private List<K> result; // // public String getCursor() { // return cursor; // } // // public void setCursor(String cursor) { // this.cursor = cursor; // } // // public List<K> getResult() { // return result; // } // // public void setResult(List<K> result) { // this.result = result; // } // // public Result(List<K> result, String cursor) { // this.result = result; // this.cursor = cursor; // } // // public Result(List<K> result) { // this.result = result; // this.cursor = null; // } // } // Path: bookshelf-standard/5-logging/src/main/java/com/example/getstarted/daos/BookDao.java import com.example.getstarted.objects.Book; import com.example.getstarted.objects.Result; import java.sql.SQLException; /* Copyright 2016 Google 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.example.getstarted.daos; // [START example] public interface BookDao { Long createBook(Book book) throws SQLException; Book readBook(Long bookId) throws SQLException; void updateBook(Book book) throws SQLException; void deleteBook(Long bookId) throws SQLException;
Result<Book> listBooks(String startCursor) throws SQLException;
GoogleCloudPlatform/getting-started-java
bookshelf-standard/5-logging/src/main/java/com/example/getstarted/basicactions/ReadBookServlet.java
// Path: bookshelf-standard/5-logging/src/main/java/com/example/getstarted/daos/BookDao.java // public interface BookDao { // Long createBook(Book book) throws SQLException; // // Book readBook(Long bookId) throws SQLException; // // void updateBook(Book book) throws SQLException; // // void deleteBook(Long bookId) throws SQLException; // // Result<Book> listBooks(String startCursor) throws SQLException; // // Result<Book> listBooksByUser(String userId, String startCursor) throws SQLException; // } // // Path: bookshelf/1-cloud-run/src/main/java/com/example/getstarted/objects/Book.java // public class Book { // private String title; // private String author; // private String createdBy; // private String createdById; // private String publishedDate; // private String description; // private String id; // private String imageUrl; // public static final String AUTHOR = "author"; // public static final String CREATED_BY = "createdBy"; // public static final String CREATED_BY_ID = "createdById"; // public static final String DESCRIPTION = "description"; // public static final String ID = "id"; // public static final String PUBLISHED_DATE = "publishedDate"; // public static final String TITLE = "title"; // public static final String IMAGE_URL = "imageUrl"; // // // We use a Builder pattern here to simplify and standardize construction of // // Book objects. // private Book(Builder builder) { // this.title = builder.title; // this.author = builder.author; // this.createdBy = builder.createdBy; // this.createdById = builder.createdById; // this.publishedDate = builder.publishedDate; // this.description = builder.description; // this.id = builder.id; // this.imageUrl = builder.imageUrl; // } // // public static class Builder { // private String title; // private String author; // private String createdBy; // private String createdById; // private String publishedDate; // private String description; // private String id; // private String imageUrl; // // public Builder title(String title) { // this.title = title; // return this; // } // // public Builder author(String author) { // this.author = author; // return this; // } // // public Builder createdBy(String createdBy) { // this.createdBy = createdBy; // return this; // } // // public Builder createdById(String createdById) { // this.createdById = createdById; // return this; // } // // public Builder publishedDate(String publishedDate) { // this.publishedDate = publishedDate; // return this; // } // // public Builder description(String description) { // this.description = description; // return this; // } // // public Builder id(String id) { // this.id = id; // return this; // } // // public Builder imageUrl(String imageUrl) { // this.imageUrl = imageUrl; // return this; // } // // public Book build() { // return new Book(this); // } // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String author) { // this.author = author; // } // // public String getCreatedBy() { // return createdBy; // } // // public void setCreatedBy(String createdBy) { // this.createdBy = createdBy; // } // // public String getCreatedById() { // return createdById; // } // // public void setCreatedById(String createdById) { // this.createdById = createdById; // } // // public String getPublishedDate() { // return publishedDate; // } // // public void setPublishedDate(String publishedDate) { // this.publishedDate = publishedDate; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getImageUrl() { // return imageUrl; // } // // public void setImageUrl(String imageUrl) { // this.imageUrl = imageUrl; // } // // @Override // public String toString() { // return "Title: " // + title // + ", Author: " // + author // + ", Published date: " // + publishedDate // + ", Added by: " // + createdBy; // } // }
import com.example.getstarted.daos.BookDao; import com.example.getstarted.objects.Book; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;
/* Copyright 2016 Google 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.example.getstarted.basicactions; // [START example] @SuppressWarnings("serial") public class ReadBookServlet extends HttpServlet { // [START init] private final Logger logger = Logger.getLogger(ReadBookServlet.class.getName()); // [END init] @Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { Long id = Long.decode(req.getParameter("id"));
// Path: bookshelf-standard/5-logging/src/main/java/com/example/getstarted/daos/BookDao.java // public interface BookDao { // Long createBook(Book book) throws SQLException; // // Book readBook(Long bookId) throws SQLException; // // void updateBook(Book book) throws SQLException; // // void deleteBook(Long bookId) throws SQLException; // // Result<Book> listBooks(String startCursor) throws SQLException; // // Result<Book> listBooksByUser(String userId, String startCursor) throws SQLException; // } // // Path: bookshelf/1-cloud-run/src/main/java/com/example/getstarted/objects/Book.java // public class Book { // private String title; // private String author; // private String createdBy; // private String createdById; // private String publishedDate; // private String description; // private String id; // private String imageUrl; // public static final String AUTHOR = "author"; // public static final String CREATED_BY = "createdBy"; // public static final String CREATED_BY_ID = "createdById"; // public static final String DESCRIPTION = "description"; // public static final String ID = "id"; // public static final String PUBLISHED_DATE = "publishedDate"; // public static final String TITLE = "title"; // public static final String IMAGE_URL = "imageUrl"; // // // We use a Builder pattern here to simplify and standardize construction of // // Book objects. // private Book(Builder builder) { // this.title = builder.title; // this.author = builder.author; // this.createdBy = builder.createdBy; // this.createdById = builder.createdById; // this.publishedDate = builder.publishedDate; // this.description = builder.description; // this.id = builder.id; // this.imageUrl = builder.imageUrl; // } // // public static class Builder { // private String title; // private String author; // private String createdBy; // private String createdById; // private String publishedDate; // private String description; // private String id; // private String imageUrl; // // public Builder title(String title) { // this.title = title; // return this; // } // // public Builder author(String author) { // this.author = author; // return this; // } // // public Builder createdBy(String createdBy) { // this.createdBy = createdBy; // return this; // } // // public Builder createdById(String createdById) { // this.createdById = createdById; // return this; // } // // public Builder publishedDate(String publishedDate) { // this.publishedDate = publishedDate; // return this; // } // // public Builder description(String description) { // this.description = description; // return this; // } // // public Builder id(String id) { // this.id = id; // return this; // } // // public Builder imageUrl(String imageUrl) { // this.imageUrl = imageUrl; // return this; // } // // public Book build() { // return new Book(this); // } // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String author) { // this.author = author; // } // // public String getCreatedBy() { // return createdBy; // } // // public void setCreatedBy(String createdBy) { // this.createdBy = createdBy; // } // // public String getCreatedById() { // return createdById; // } // // public void setCreatedById(String createdById) { // this.createdById = createdById; // } // // public String getPublishedDate() { // return publishedDate; // } // // public void setPublishedDate(String publishedDate) { // this.publishedDate = publishedDate; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getImageUrl() { // return imageUrl; // } // // public void setImageUrl(String imageUrl) { // this.imageUrl = imageUrl; // } // // @Override // public String toString() { // return "Title: " // + title // + ", Author: " // + author // + ", Published date: " // + publishedDate // + ", Added by: " // + createdBy; // } // } // Path: bookshelf-standard/5-logging/src/main/java/com/example/getstarted/basicactions/ReadBookServlet.java import com.example.getstarted.daos.BookDao; import com.example.getstarted.objects.Book; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /* Copyright 2016 Google 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.example.getstarted.basicactions; // [START example] @SuppressWarnings("serial") public class ReadBookServlet extends HttpServlet { // [START init] private final Logger logger = Logger.getLogger(ReadBookServlet.class.getName()); // [END init] @Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { Long id = Long.decode(req.getParameter("id"));
BookDao dao = (BookDao) this.getServletContext().getAttribute("dao");
GoogleCloudPlatform/getting-started-java
bookshelf-standard/5-logging/src/main/java/com/example/getstarted/basicactions/ReadBookServlet.java
// Path: bookshelf-standard/5-logging/src/main/java/com/example/getstarted/daos/BookDao.java // public interface BookDao { // Long createBook(Book book) throws SQLException; // // Book readBook(Long bookId) throws SQLException; // // void updateBook(Book book) throws SQLException; // // void deleteBook(Long bookId) throws SQLException; // // Result<Book> listBooks(String startCursor) throws SQLException; // // Result<Book> listBooksByUser(String userId, String startCursor) throws SQLException; // } // // Path: bookshelf/1-cloud-run/src/main/java/com/example/getstarted/objects/Book.java // public class Book { // private String title; // private String author; // private String createdBy; // private String createdById; // private String publishedDate; // private String description; // private String id; // private String imageUrl; // public static final String AUTHOR = "author"; // public static final String CREATED_BY = "createdBy"; // public static final String CREATED_BY_ID = "createdById"; // public static final String DESCRIPTION = "description"; // public static final String ID = "id"; // public static final String PUBLISHED_DATE = "publishedDate"; // public static final String TITLE = "title"; // public static final String IMAGE_URL = "imageUrl"; // // // We use a Builder pattern here to simplify and standardize construction of // // Book objects. // private Book(Builder builder) { // this.title = builder.title; // this.author = builder.author; // this.createdBy = builder.createdBy; // this.createdById = builder.createdById; // this.publishedDate = builder.publishedDate; // this.description = builder.description; // this.id = builder.id; // this.imageUrl = builder.imageUrl; // } // // public static class Builder { // private String title; // private String author; // private String createdBy; // private String createdById; // private String publishedDate; // private String description; // private String id; // private String imageUrl; // // public Builder title(String title) { // this.title = title; // return this; // } // // public Builder author(String author) { // this.author = author; // return this; // } // // public Builder createdBy(String createdBy) { // this.createdBy = createdBy; // return this; // } // // public Builder createdById(String createdById) { // this.createdById = createdById; // return this; // } // // public Builder publishedDate(String publishedDate) { // this.publishedDate = publishedDate; // return this; // } // // public Builder description(String description) { // this.description = description; // return this; // } // // public Builder id(String id) { // this.id = id; // return this; // } // // public Builder imageUrl(String imageUrl) { // this.imageUrl = imageUrl; // return this; // } // // public Book build() { // return new Book(this); // } // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String author) { // this.author = author; // } // // public String getCreatedBy() { // return createdBy; // } // // public void setCreatedBy(String createdBy) { // this.createdBy = createdBy; // } // // public String getCreatedById() { // return createdById; // } // // public void setCreatedById(String createdById) { // this.createdById = createdById; // } // // public String getPublishedDate() { // return publishedDate; // } // // public void setPublishedDate(String publishedDate) { // this.publishedDate = publishedDate; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getImageUrl() { // return imageUrl; // } // // public void setImageUrl(String imageUrl) { // this.imageUrl = imageUrl; // } // // @Override // public String toString() { // return "Title: " // + title // + ", Author: " // + author // + ", Published date: " // + publishedDate // + ", Added by: " // + createdBy; // } // }
import com.example.getstarted.daos.BookDao; import com.example.getstarted.objects.Book; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;
/* Copyright 2016 Google 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.example.getstarted.basicactions; // [START example] @SuppressWarnings("serial") public class ReadBookServlet extends HttpServlet { // [START init] private final Logger logger = Logger.getLogger(ReadBookServlet.class.getName()); // [END init] @Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { Long id = Long.decode(req.getParameter("id")); BookDao dao = (BookDao) this.getServletContext().getAttribute("dao"); try {
// Path: bookshelf-standard/5-logging/src/main/java/com/example/getstarted/daos/BookDao.java // public interface BookDao { // Long createBook(Book book) throws SQLException; // // Book readBook(Long bookId) throws SQLException; // // void updateBook(Book book) throws SQLException; // // void deleteBook(Long bookId) throws SQLException; // // Result<Book> listBooks(String startCursor) throws SQLException; // // Result<Book> listBooksByUser(String userId, String startCursor) throws SQLException; // } // // Path: bookshelf/1-cloud-run/src/main/java/com/example/getstarted/objects/Book.java // public class Book { // private String title; // private String author; // private String createdBy; // private String createdById; // private String publishedDate; // private String description; // private String id; // private String imageUrl; // public static final String AUTHOR = "author"; // public static final String CREATED_BY = "createdBy"; // public static final String CREATED_BY_ID = "createdById"; // public static final String DESCRIPTION = "description"; // public static final String ID = "id"; // public static final String PUBLISHED_DATE = "publishedDate"; // public static final String TITLE = "title"; // public static final String IMAGE_URL = "imageUrl"; // // // We use a Builder pattern here to simplify and standardize construction of // // Book objects. // private Book(Builder builder) { // this.title = builder.title; // this.author = builder.author; // this.createdBy = builder.createdBy; // this.createdById = builder.createdById; // this.publishedDate = builder.publishedDate; // this.description = builder.description; // this.id = builder.id; // this.imageUrl = builder.imageUrl; // } // // public static class Builder { // private String title; // private String author; // private String createdBy; // private String createdById; // private String publishedDate; // private String description; // private String id; // private String imageUrl; // // public Builder title(String title) { // this.title = title; // return this; // } // // public Builder author(String author) { // this.author = author; // return this; // } // // public Builder createdBy(String createdBy) { // this.createdBy = createdBy; // return this; // } // // public Builder createdById(String createdById) { // this.createdById = createdById; // return this; // } // // public Builder publishedDate(String publishedDate) { // this.publishedDate = publishedDate; // return this; // } // // public Builder description(String description) { // this.description = description; // return this; // } // // public Builder id(String id) { // this.id = id; // return this; // } // // public Builder imageUrl(String imageUrl) { // this.imageUrl = imageUrl; // return this; // } // // public Book build() { // return new Book(this); // } // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String author) { // this.author = author; // } // // public String getCreatedBy() { // return createdBy; // } // // public void setCreatedBy(String createdBy) { // this.createdBy = createdBy; // } // // public String getCreatedById() { // return createdById; // } // // public void setCreatedById(String createdById) { // this.createdById = createdById; // } // // public String getPublishedDate() { // return publishedDate; // } // // public void setPublishedDate(String publishedDate) { // this.publishedDate = publishedDate; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getImageUrl() { // return imageUrl; // } // // public void setImageUrl(String imageUrl) { // this.imageUrl = imageUrl; // } // // @Override // public String toString() { // return "Title: " // + title // + ", Author: " // + author // + ", Published date: " // + publishedDate // + ", Added by: " // + createdBy; // } // } // Path: bookshelf-standard/5-logging/src/main/java/com/example/getstarted/basicactions/ReadBookServlet.java import com.example.getstarted.daos.BookDao; import com.example.getstarted.objects.Book; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /* Copyright 2016 Google 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.example.getstarted.basicactions; // [START example] @SuppressWarnings("serial") public class ReadBookServlet extends HttpServlet { // [START init] private final Logger logger = Logger.getLogger(ReadBookServlet.class.getName()); // [END init] @Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { Long id = Long.decode(req.getParameter("id")); BookDao dao = (BookDao) this.getServletContext().getAttribute("dao"); try {
Book book = dao.readBook(id);
GoogleCloudPlatform/getting-started-java
bookshelf-standard/5-logging/src/main/java/com/example/getstarted/basicactions/DeleteBookServlet.java
// Path: bookshelf-standard/5-logging/src/main/java/com/example/getstarted/daos/BookDao.java // public interface BookDao { // Long createBook(Book book) throws SQLException; // // Book readBook(Long bookId) throws SQLException; // // void updateBook(Book book) throws SQLException; // // void deleteBook(Long bookId) throws SQLException; // // Result<Book> listBooks(String startCursor) throws SQLException; // // Result<Book> listBooksByUser(String userId, String startCursor) throws SQLException; // }
import com.example.getstarted.daos.BookDao; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;
/* Copyright 2016 Google 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.example.getstarted.basicactions; // [START example] @SuppressWarnings("serial") public class DeleteBookServlet extends HttpServlet { @Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Long id = Long.decode(req.getParameter("id"));
// Path: bookshelf-standard/5-logging/src/main/java/com/example/getstarted/daos/BookDao.java // public interface BookDao { // Long createBook(Book book) throws SQLException; // // Book readBook(Long bookId) throws SQLException; // // void updateBook(Book book) throws SQLException; // // void deleteBook(Long bookId) throws SQLException; // // Result<Book> listBooks(String startCursor) throws SQLException; // // Result<Book> listBooksByUser(String userId, String startCursor) throws SQLException; // } // Path: bookshelf-standard/5-logging/src/main/java/com/example/getstarted/basicactions/DeleteBookServlet.java import com.example.getstarted.daos.BookDao; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /* Copyright 2016 Google 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.example.getstarted.basicactions; // [START example] @SuppressWarnings("serial") public class DeleteBookServlet extends HttpServlet { @Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Long id = Long.decode(req.getParameter("id"));
BookDao dao = (BookDao) this.getServletContext().getAttribute("dao");
GoogleCloudPlatform/getting-started-java
background/src/main/java/com/getstarted/background/functions/TranslateServlet.java
// Path: background/src/main/java/com/getstarted/background/objects/PubSubMessage.java // public class PubSubMessage { // private TranslateMessage message; // private String subscription; // // public TranslateMessage getMessage() { // return message; // } // // public void setMessage(TranslateMessage message) { // this.message = message; // } // // public String getSubscription() { // return subscription; // } // // public void setSubscription(String subscription) { // this.subscription = subscription; // } // } // // Path: background/src/main/java/com/getstarted/background/objects/TranslateMessage.java // public class TranslateMessage { // public String data; // public TranslateAttributes attributes; // public String messageId; // public String publishTime; // public String translatedText; // public String sourceLang = "en"; // public String targetLang = "en"; // // public String getData() { // return data; // } // // public void setData(String data) { // this.data = data; // } // // public TranslateAttributes getAttributes() { // return attributes; // } // // public void setAttributes(TranslateAttributes attributes) { // this.attributes = attributes; // } // // public String getMessageId() { // return messageId; // } // // public void setMessageId(String messageId) { // this.messageId = messageId; // } // // public String getPublishTime() { // return publishTime; // } // // public void setPublishTime(String publishTime) { // this.publishTime = publishTime; // } // // public String getTranslatedText() { // return translatedText; // } // // public void setTranslatedText(String translatedText) { // this.translatedText = translatedText; // } // // public String getSourceLang() { // return sourceLang; // } // // public void setSourceLang(String sourceLang) { // this.sourceLang = sourceLang; // } // // public String getTargetLang() { // return targetLang; // } // // public void setTargetLang(String targetLang) { // this.targetLang = targetLang; // } // }
import com.getstarted.background.objects.PubSubMessage; import com.getstarted.background.objects.TranslateMessage; import com.google.api.core.ApiFuture; import com.google.cloud.firestore.CollectionReference; import com.google.cloud.firestore.DocumentSnapshot; import com.google.cloud.firestore.Firestore; import com.google.cloud.firestore.QueryDocumentSnapshot; import com.google.cloud.firestore.QuerySnapshot; import com.google.cloud.firestore.SetOptions; import com.google.cloud.firestore.WriteResult; import com.google.cloud.translate.Translate; import com.google.cloud.translate.Translation; import com.google.common.collect.Lists; import com.google.gson.Gson; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.Base64; import java.util.Comparator; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.stream.Collectors; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;
/* Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.getstarted.background.functions; @WebServlet( name = "translate", urlPatterns = {"/", "/translate"}) public class TranslateServlet extends HttpServlet { private static final Gson gson = new Gson(); private static final String PUBSUB_VERIFICATION_TOKEN = System.getenv("PUBSUB_VERIFICATION_TOKEN"); // [START getting_started_background_app_list] @Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Firestore firestore = (Firestore) this.getServletContext().getAttribute("firestore"); CollectionReference translations = firestore.collection("translations"); QuerySnapshot snapshot; try { snapshot = translations.limit(10).get().get(); } catch (InterruptedException | ExecutionException e) { throw new ServletException("Exception retrieving documents from Firestore.", e); }
// Path: background/src/main/java/com/getstarted/background/objects/PubSubMessage.java // public class PubSubMessage { // private TranslateMessage message; // private String subscription; // // public TranslateMessage getMessage() { // return message; // } // // public void setMessage(TranslateMessage message) { // this.message = message; // } // // public String getSubscription() { // return subscription; // } // // public void setSubscription(String subscription) { // this.subscription = subscription; // } // } // // Path: background/src/main/java/com/getstarted/background/objects/TranslateMessage.java // public class TranslateMessage { // public String data; // public TranslateAttributes attributes; // public String messageId; // public String publishTime; // public String translatedText; // public String sourceLang = "en"; // public String targetLang = "en"; // // public String getData() { // return data; // } // // public void setData(String data) { // this.data = data; // } // // public TranslateAttributes getAttributes() { // return attributes; // } // // public void setAttributes(TranslateAttributes attributes) { // this.attributes = attributes; // } // // public String getMessageId() { // return messageId; // } // // public void setMessageId(String messageId) { // this.messageId = messageId; // } // // public String getPublishTime() { // return publishTime; // } // // public void setPublishTime(String publishTime) { // this.publishTime = publishTime; // } // // public String getTranslatedText() { // return translatedText; // } // // public void setTranslatedText(String translatedText) { // this.translatedText = translatedText; // } // // public String getSourceLang() { // return sourceLang; // } // // public void setSourceLang(String sourceLang) { // this.sourceLang = sourceLang; // } // // public String getTargetLang() { // return targetLang; // } // // public void setTargetLang(String targetLang) { // this.targetLang = targetLang; // } // } // Path: background/src/main/java/com/getstarted/background/functions/TranslateServlet.java import com.getstarted.background.objects.PubSubMessage; import com.getstarted.background.objects.TranslateMessage; import com.google.api.core.ApiFuture; import com.google.cloud.firestore.CollectionReference; import com.google.cloud.firestore.DocumentSnapshot; import com.google.cloud.firestore.Firestore; import com.google.cloud.firestore.QueryDocumentSnapshot; import com.google.cloud.firestore.QuerySnapshot; import com.google.cloud.firestore.SetOptions; import com.google.cloud.firestore.WriteResult; import com.google.cloud.translate.Translate; import com.google.cloud.translate.Translation; import com.google.common.collect.Lists; import com.google.gson.Gson; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.Base64; import java.util.Comparator; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.stream.Collectors; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /* Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.getstarted.background.functions; @WebServlet( name = "translate", urlPatterns = {"/", "/translate"}) public class TranslateServlet extends HttpServlet { private static final Gson gson = new Gson(); private static final String PUBSUB_VERIFICATION_TOKEN = System.getenv("PUBSUB_VERIFICATION_TOKEN"); // [START getting_started_background_app_list] @Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Firestore firestore = (Firestore) this.getServletContext().getAttribute("firestore"); CollectionReference translations = firestore.collection("translations"); QuerySnapshot snapshot; try { snapshot = translations.limit(10).get().get(); } catch (InterruptedException | ExecutionException e) { throw new ServletException("Exception retrieving documents from Firestore.", e); }
List<TranslateMessage> translateMessages = Lists.newArrayList();
GoogleCloudPlatform/getting-started-java
background/src/main/java/com/getstarted/background/functions/TranslateServlet.java
// Path: background/src/main/java/com/getstarted/background/objects/PubSubMessage.java // public class PubSubMessage { // private TranslateMessage message; // private String subscription; // // public TranslateMessage getMessage() { // return message; // } // // public void setMessage(TranslateMessage message) { // this.message = message; // } // // public String getSubscription() { // return subscription; // } // // public void setSubscription(String subscription) { // this.subscription = subscription; // } // } // // Path: background/src/main/java/com/getstarted/background/objects/TranslateMessage.java // public class TranslateMessage { // public String data; // public TranslateAttributes attributes; // public String messageId; // public String publishTime; // public String translatedText; // public String sourceLang = "en"; // public String targetLang = "en"; // // public String getData() { // return data; // } // // public void setData(String data) { // this.data = data; // } // // public TranslateAttributes getAttributes() { // return attributes; // } // // public void setAttributes(TranslateAttributes attributes) { // this.attributes = attributes; // } // // public String getMessageId() { // return messageId; // } // // public void setMessageId(String messageId) { // this.messageId = messageId; // } // // public String getPublishTime() { // return publishTime; // } // // public void setPublishTime(String publishTime) { // this.publishTime = publishTime; // } // // public String getTranslatedText() { // return translatedText; // } // // public void setTranslatedText(String translatedText) { // this.translatedText = translatedText; // } // // public String getSourceLang() { // return sourceLang; // } // // public void setSourceLang(String sourceLang) { // this.sourceLang = sourceLang; // } // // public String getTargetLang() { // return targetLang; // } // // public void setTargetLang(String targetLang) { // this.targetLang = targetLang; // } // }
import com.getstarted.background.objects.PubSubMessage; import com.getstarted.background.objects.TranslateMessage; import com.google.api.core.ApiFuture; import com.google.cloud.firestore.CollectionReference; import com.google.cloud.firestore.DocumentSnapshot; import com.google.cloud.firestore.Firestore; import com.google.cloud.firestore.QueryDocumentSnapshot; import com.google.cloud.firestore.QuerySnapshot; import com.google.cloud.firestore.SetOptions; import com.google.cloud.firestore.WriteResult; import com.google.cloud.translate.Translate; import com.google.cloud.translate.Translation; import com.google.common.collect.Lists; import com.google.gson.Gson; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.Base64; import java.util.Comparator; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.stream.Collectors; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;
TranslateMessage message = gson.fromJson(encoded, TranslateMessage.class); message.setData(decode(message.getData())); translateMessages.add(message); } req.setAttribute("messages", translateMessages); req.setAttribute("page", "list"); req.getRequestDispatcher("/base.jsp").forward(req, resp); } // [END getting_started_background_app_list] /** * Handle a posted message from Pubsub. * * @param req The message Pubsub posts to this process. * @param resp Not used. */ @Override public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { // Block requests that don't contain the proper verification token. String pubsubVerificationToken = PUBSUB_VERIFICATION_TOKEN; if (req.getParameter("token").compareTo(pubsubVerificationToken) != 0) { resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); return; } // [START getting_started_background_translate_string] String body = req.getReader().lines().collect(Collectors.joining(System.lineSeparator()));
// Path: background/src/main/java/com/getstarted/background/objects/PubSubMessage.java // public class PubSubMessage { // private TranslateMessage message; // private String subscription; // // public TranslateMessage getMessage() { // return message; // } // // public void setMessage(TranslateMessage message) { // this.message = message; // } // // public String getSubscription() { // return subscription; // } // // public void setSubscription(String subscription) { // this.subscription = subscription; // } // } // // Path: background/src/main/java/com/getstarted/background/objects/TranslateMessage.java // public class TranslateMessage { // public String data; // public TranslateAttributes attributes; // public String messageId; // public String publishTime; // public String translatedText; // public String sourceLang = "en"; // public String targetLang = "en"; // // public String getData() { // return data; // } // // public void setData(String data) { // this.data = data; // } // // public TranslateAttributes getAttributes() { // return attributes; // } // // public void setAttributes(TranslateAttributes attributes) { // this.attributes = attributes; // } // // public String getMessageId() { // return messageId; // } // // public void setMessageId(String messageId) { // this.messageId = messageId; // } // // public String getPublishTime() { // return publishTime; // } // // public void setPublishTime(String publishTime) { // this.publishTime = publishTime; // } // // public String getTranslatedText() { // return translatedText; // } // // public void setTranslatedText(String translatedText) { // this.translatedText = translatedText; // } // // public String getSourceLang() { // return sourceLang; // } // // public void setSourceLang(String sourceLang) { // this.sourceLang = sourceLang; // } // // public String getTargetLang() { // return targetLang; // } // // public void setTargetLang(String targetLang) { // this.targetLang = targetLang; // } // } // Path: background/src/main/java/com/getstarted/background/functions/TranslateServlet.java import com.getstarted.background.objects.PubSubMessage; import com.getstarted.background.objects.TranslateMessage; import com.google.api.core.ApiFuture; import com.google.cloud.firestore.CollectionReference; import com.google.cloud.firestore.DocumentSnapshot; import com.google.cloud.firestore.Firestore; import com.google.cloud.firestore.QueryDocumentSnapshot; import com.google.cloud.firestore.QuerySnapshot; import com.google.cloud.firestore.SetOptions; import com.google.cloud.firestore.WriteResult; import com.google.cloud.translate.Translate; import com.google.cloud.translate.Translation; import com.google.common.collect.Lists; import com.google.gson.Gson; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.Base64; import java.util.Comparator; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.stream.Collectors; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; TranslateMessage message = gson.fromJson(encoded, TranslateMessage.class); message.setData(decode(message.getData())); translateMessages.add(message); } req.setAttribute("messages", translateMessages); req.setAttribute("page", "list"); req.getRequestDispatcher("/base.jsp").forward(req, resp); } // [END getting_started_background_app_list] /** * Handle a posted message from Pubsub. * * @param req The message Pubsub posts to this process. * @param resp Not used. */ @Override public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { // Block requests that don't contain the proper verification token. String pubsubVerificationToken = PUBSUB_VERIFICATION_TOKEN; if (req.getParameter("token").compareTo(pubsubVerificationToken) != 0) { resp.setStatus(HttpServletResponse.SC_BAD_REQUEST); return; } // [START getting_started_background_translate_string] String body = req.getReader().lines().collect(Collectors.joining(System.lineSeparator()));
PubSubMessage pubsubMessage = gson.fromJson(body, PubSubMessage.class);
GoogleCloudPlatform/getting-started-java
bookshelf-standard/2-structured-data/src/main/java/com/example/getstarted/basicactions/UpdateBookServlet.java
// Path: bookshelf-standard/5-logging/src/main/java/com/example/getstarted/daos/BookDao.java // public interface BookDao { // Long createBook(Book book) throws SQLException; // // Book readBook(Long bookId) throws SQLException; // // void updateBook(Book book) throws SQLException; // // void deleteBook(Long bookId) throws SQLException; // // Result<Book> listBooks(String startCursor) throws SQLException; // // Result<Book> listBooksByUser(String userId, String startCursor) throws SQLException; // } // // Path: bookshelf/1-cloud-run/src/main/java/com/example/getstarted/objects/Book.java // public class Book { // private String title; // private String author; // private String createdBy; // private String createdById; // private String publishedDate; // private String description; // private String id; // private String imageUrl; // public static final String AUTHOR = "author"; // public static final String CREATED_BY = "createdBy"; // public static final String CREATED_BY_ID = "createdById"; // public static final String DESCRIPTION = "description"; // public static final String ID = "id"; // public static final String PUBLISHED_DATE = "publishedDate"; // public static final String TITLE = "title"; // public static final String IMAGE_URL = "imageUrl"; // // // We use a Builder pattern here to simplify and standardize construction of // // Book objects. // private Book(Builder builder) { // this.title = builder.title; // this.author = builder.author; // this.createdBy = builder.createdBy; // this.createdById = builder.createdById; // this.publishedDate = builder.publishedDate; // this.description = builder.description; // this.id = builder.id; // this.imageUrl = builder.imageUrl; // } // // public static class Builder { // private String title; // private String author; // private String createdBy; // private String createdById; // private String publishedDate; // private String description; // private String id; // private String imageUrl; // // public Builder title(String title) { // this.title = title; // return this; // } // // public Builder author(String author) { // this.author = author; // return this; // } // // public Builder createdBy(String createdBy) { // this.createdBy = createdBy; // return this; // } // // public Builder createdById(String createdById) { // this.createdById = createdById; // return this; // } // // public Builder publishedDate(String publishedDate) { // this.publishedDate = publishedDate; // return this; // } // // public Builder description(String description) { // this.description = description; // return this; // } // // public Builder id(String id) { // this.id = id; // return this; // } // // public Builder imageUrl(String imageUrl) { // this.imageUrl = imageUrl; // return this; // } // // public Book build() { // return new Book(this); // } // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String author) { // this.author = author; // } // // public String getCreatedBy() { // return createdBy; // } // // public void setCreatedBy(String createdBy) { // this.createdBy = createdBy; // } // // public String getCreatedById() { // return createdById; // } // // public void setCreatedById(String createdById) { // this.createdById = createdById; // } // // public String getPublishedDate() { // return publishedDate; // } // // public void setPublishedDate(String publishedDate) { // this.publishedDate = publishedDate; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getImageUrl() { // return imageUrl; // } // // public void setImageUrl(String imageUrl) { // this.imageUrl = imageUrl; // } // // @Override // public String toString() { // return "Title: " // + title // + ", Author: " // + author // + ", Published date: " // + publishedDate // + ", Added by: " // + createdBy; // } // }
import com.example.getstarted.daos.BookDao; import com.example.getstarted.objects.Book; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;
/* Copyright 2016 Google 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.example.getstarted.basicactions; // [START example] @SuppressWarnings("serial") public class UpdateBookServlet extends HttpServlet { @Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// Path: bookshelf-standard/5-logging/src/main/java/com/example/getstarted/daos/BookDao.java // public interface BookDao { // Long createBook(Book book) throws SQLException; // // Book readBook(Long bookId) throws SQLException; // // void updateBook(Book book) throws SQLException; // // void deleteBook(Long bookId) throws SQLException; // // Result<Book> listBooks(String startCursor) throws SQLException; // // Result<Book> listBooksByUser(String userId, String startCursor) throws SQLException; // } // // Path: bookshelf/1-cloud-run/src/main/java/com/example/getstarted/objects/Book.java // public class Book { // private String title; // private String author; // private String createdBy; // private String createdById; // private String publishedDate; // private String description; // private String id; // private String imageUrl; // public static final String AUTHOR = "author"; // public static final String CREATED_BY = "createdBy"; // public static final String CREATED_BY_ID = "createdById"; // public static final String DESCRIPTION = "description"; // public static final String ID = "id"; // public static final String PUBLISHED_DATE = "publishedDate"; // public static final String TITLE = "title"; // public static final String IMAGE_URL = "imageUrl"; // // // We use a Builder pattern here to simplify and standardize construction of // // Book objects. // private Book(Builder builder) { // this.title = builder.title; // this.author = builder.author; // this.createdBy = builder.createdBy; // this.createdById = builder.createdById; // this.publishedDate = builder.publishedDate; // this.description = builder.description; // this.id = builder.id; // this.imageUrl = builder.imageUrl; // } // // public static class Builder { // private String title; // private String author; // private String createdBy; // private String createdById; // private String publishedDate; // private String description; // private String id; // private String imageUrl; // // public Builder title(String title) { // this.title = title; // return this; // } // // public Builder author(String author) { // this.author = author; // return this; // } // // public Builder createdBy(String createdBy) { // this.createdBy = createdBy; // return this; // } // // public Builder createdById(String createdById) { // this.createdById = createdById; // return this; // } // // public Builder publishedDate(String publishedDate) { // this.publishedDate = publishedDate; // return this; // } // // public Builder description(String description) { // this.description = description; // return this; // } // // public Builder id(String id) { // this.id = id; // return this; // } // // public Builder imageUrl(String imageUrl) { // this.imageUrl = imageUrl; // return this; // } // // public Book build() { // return new Book(this); // } // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String author) { // this.author = author; // } // // public String getCreatedBy() { // return createdBy; // } // // public void setCreatedBy(String createdBy) { // this.createdBy = createdBy; // } // // public String getCreatedById() { // return createdById; // } // // public void setCreatedById(String createdById) { // this.createdById = createdById; // } // // public String getPublishedDate() { // return publishedDate; // } // // public void setPublishedDate(String publishedDate) { // this.publishedDate = publishedDate; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getImageUrl() { // return imageUrl; // } // // public void setImageUrl(String imageUrl) { // this.imageUrl = imageUrl; // } // // @Override // public String toString() { // return "Title: " // + title // + ", Author: " // + author // + ", Published date: " // + publishedDate // + ", Added by: " // + createdBy; // } // } // Path: bookshelf-standard/2-structured-data/src/main/java/com/example/getstarted/basicactions/UpdateBookServlet.java import com.example.getstarted.daos.BookDao; import com.example.getstarted.objects.Book; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /* Copyright 2016 Google 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.example.getstarted.basicactions; // [START example] @SuppressWarnings("serial") public class UpdateBookServlet extends HttpServlet { @Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
BookDao dao = (BookDao) this.getServletContext().getAttribute("dao");
GoogleCloudPlatform/getting-started-java
bookshelf-standard/2-structured-data/src/main/java/com/example/getstarted/basicactions/UpdateBookServlet.java
// Path: bookshelf-standard/5-logging/src/main/java/com/example/getstarted/daos/BookDao.java // public interface BookDao { // Long createBook(Book book) throws SQLException; // // Book readBook(Long bookId) throws SQLException; // // void updateBook(Book book) throws SQLException; // // void deleteBook(Long bookId) throws SQLException; // // Result<Book> listBooks(String startCursor) throws SQLException; // // Result<Book> listBooksByUser(String userId, String startCursor) throws SQLException; // } // // Path: bookshelf/1-cloud-run/src/main/java/com/example/getstarted/objects/Book.java // public class Book { // private String title; // private String author; // private String createdBy; // private String createdById; // private String publishedDate; // private String description; // private String id; // private String imageUrl; // public static final String AUTHOR = "author"; // public static final String CREATED_BY = "createdBy"; // public static final String CREATED_BY_ID = "createdById"; // public static final String DESCRIPTION = "description"; // public static final String ID = "id"; // public static final String PUBLISHED_DATE = "publishedDate"; // public static final String TITLE = "title"; // public static final String IMAGE_URL = "imageUrl"; // // // We use a Builder pattern here to simplify and standardize construction of // // Book objects. // private Book(Builder builder) { // this.title = builder.title; // this.author = builder.author; // this.createdBy = builder.createdBy; // this.createdById = builder.createdById; // this.publishedDate = builder.publishedDate; // this.description = builder.description; // this.id = builder.id; // this.imageUrl = builder.imageUrl; // } // // public static class Builder { // private String title; // private String author; // private String createdBy; // private String createdById; // private String publishedDate; // private String description; // private String id; // private String imageUrl; // // public Builder title(String title) { // this.title = title; // return this; // } // // public Builder author(String author) { // this.author = author; // return this; // } // // public Builder createdBy(String createdBy) { // this.createdBy = createdBy; // return this; // } // // public Builder createdById(String createdById) { // this.createdById = createdById; // return this; // } // // public Builder publishedDate(String publishedDate) { // this.publishedDate = publishedDate; // return this; // } // // public Builder description(String description) { // this.description = description; // return this; // } // // public Builder id(String id) { // this.id = id; // return this; // } // // public Builder imageUrl(String imageUrl) { // this.imageUrl = imageUrl; // return this; // } // // public Book build() { // return new Book(this); // } // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String author) { // this.author = author; // } // // public String getCreatedBy() { // return createdBy; // } // // public void setCreatedBy(String createdBy) { // this.createdBy = createdBy; // } // // public String getCreatedById() { // return createdById; // } // // public void setCreatedById(String createdById) { // this.createdById = createdById; // } // // public String getPublishedDate() { // return publishedDate; // } // // public void setPublishedDate(String publishedDate) { // this.publishedDate = publishedDate; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getImageUrl() { // return imageUrl; // } // // public void setImageUrl(String imageUrl) { // this.imageUrl = imageUrl; // } // // @Override // public String toString() { // return "Title: " // + title // + ", Author: " // + author // + ", Published date: " // + publishedDate // + ", Added by: " // + createdBy; // } // }
import com.example.getstarted.daos.BookDao; import com.example.getstarted.objects.Book; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;
/* Copyright 2016 Google 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.example.getstarted.basicactions; // [START example] @SuppressWarnings("serial") public class UpdateBookServlet extends HttpServlet { @Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { BookDao dao = (BookDao) this.getServletContext().getAttribute("dao"); try {
// Path: bookshelf-standard/5-logging/src/main/java/com/example/getstarted/daos/BookDao.java // public interface BookDao { // Long createBook(Book book) throws SQLException; // // Book readBook(Long bookId) throws SQLException; // // void updateBook(Book book) throws SQLException; // // void deleteBook(Long bookId) throws SQLException; // // Result<Book> listBooks(String startCursor) throws SQLException; // // Result<Book> listBooksByUser(String userId, String startCursor) throws SQLException; // } // // Path: bookshelf/1-cloud-run/src/main/java/com/example/getstarted/objects/Book.java // public class Book { // private String title; // private String author; // private String createdBy; // private String createdById; // private String publishedDate; // private String description; // private String id; // private String imageUrl; // public static final String AUTHOR = "author"; // public static final String CREATED_BY = "createdBy"; // public static final String CREATED_BY_ID = "createdById"; // public static final String DESCRIPTION = "description"; // public static final String ID = "id"; // public static final String PUBLISHED_DATE = "publishedDate"; // public static final String TITLE = "title"; // public static final String IMAGE_URL = "imageUrl"; // // // We use a Builder pattern here to simplify and standardize construction of // // Book objects. // private Book(Builder builder) { // this.title = builder.title; // this.author = builder.author; // this.createdBy = builder.createdBy; // this.createdById = builder.createdById; // this.publishedDate = builder.publishedDate; // this.description = builder.description; // this.id = builder.id; // this.imageUrl = builder.imageUrl; // } // // public static class Builder { // private String title; // private String author; // private String createdBy; // private String createdById; // private String publishedDate; // private String description; // private String id; // private String imageUrl; // // public Builder title(String title) { // this.title = title; // return this; // } // // public Builder author(String author) { // this.author = author; // return this; // } // // public Builder createdBy(String createdBy) { // this.createdBy = createdBy; // return this; // } // // public Builder createdById(String createdById) { // this.createdById = createdById; // return this; // } // // public Builder publishedDate(String publishedDate) { // this.publishedDate = publishedDate; // return this; // } // // public Builder description(String description) { // this.description = description; // return this; // } // // public Builder id(String id) { // this.id = id; // return this; // } // // public Builder imageUrl(String imageUrl) { // this.imageUrl = imageUrl; // return this; // } // // public Book build() { // return new Book(this); // } // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String author) { // this.author = author; // } // // public String getCreatedBy() { // return createdBy; // } // // public void setCreatedBy(String createdBy) { // this.createdBy = createdBy; // } // // public String getCreatedById() { // return createdById; // } // // public void setCreatedById(String createdById) { // this.createdById = createdById; // } // // public String getPublishedDate() { // return publishedDate; // } // // public void setPublishedDate(String publishedDate) { // this.publishedDate = publishedDate; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getImageUrl() { // return imageUrl; // } // // public void setImageUrl(String imageUrl) { // this.imageUrl = imageUrl; // } // // @Override // public String toString() { // return "Title: " // + title // + ", Author: " // + author // + ", Published date: " // + publishedDate // + ", Added by: " // + createdBy; // } // } // Path: bookshelf-standard/2-structured-data/src/main/java/com/example/getstarted/basicactions/UpdateBookServlet.java import com.example.getstarted.daos.BookDao; import com.example.getstarted.objects.Book; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /* Copyright 2016 Google 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.example.getstarted.basicactions; // [START example] @SuppressWarnings("serial") public class UpdateBookServlet extends HttpServlet { @Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { BookDao dao = (BookDao) this.getServletContext().getAttribute("dao"); try {
Book book = dao.readBook(Long.decode(req.getParameter("id")));
GoogleCloudPlatform/getting-started-java
bookshelf/1-cloud-run/src/main/java/com/example/getstarted/daos/BookDao.java
// Path: bookshelf/1-cloud-run/src/main/java/com/example/getstarted/objects/Book.java // public class Book { // private String title; // private String author; // private String createdBy; // private String createdById; // private String publishedDate; // private String description; // private String id; // private String imageUrl; // public static final String AUTHOR = "author"; // public static final String CREATED_BY = "createdBy"; // public static final String CREATED_BY_ID = "createdById"; // public static final String DESCRIPTION = "description"; // public static final String ID = "id"; // public static final String PUBLISHED_DATE = "publishedDate"; // public static final String TITLE = "title"; // public static final String IMAGE_URL = "imageUrl"; // // // We use a Builder pattern here to simplify and standardize construction of // // Book objects. // private Book(Builder builder) { // this.title = builder.title; // this.author = builder.author; // this.createdBy = builder.createdBy; // this.createdById = builder.createdById; // this.publishedDate = builder.publishedDate; // this.description = builder.description; // this.id = builder.id; // this.imageUrl = builder.imageUrl; // } // // public static class Builder { // private String title; // private String author; // private String createdBy; // private String createdById; // private String publishedDate; // private String description; // private String id; // private String imageUrl; // // public Builder title(String title) { // this.title = title; // return this; // } // // public Builder author(String author) { // this.author = author; // return this; // } // // public Builder createdBy(String createdBy) { // this.createdBy = createdBy; // return this; // } // // public Builder createdById(String createdById) { // this.createdById = createdById; // return this; // } // // public Builder publishedDate(String publishedDate) { // this.publishedDate = publishedDate; // return this; // } // // public Builder description(String description) { // this.description = description; // return this; // } // // public Builder id(String id) { // this.id = id; // return this; // } // // public Builder imageUrl(String imageUrl) { // this.imageUrl = imageUrl; // return this; // } // // public Book build() { // return new Book(this); // } // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String author) { // this.author = author; // } // // public String getCreatedBy() { // return createdBy; // } // // public void setCreatedBy(String createdBy) { // this.createdBy = createdBy; // } // // public String getCreatedById() { // return createdById; // } // // public void setCreatedById(String createdById) { // this.createdById = createdById; // } // // public String getPublishedDate() { // return publishedDate; // } // // public void setPublishedDate(String publishedDate) { // this.publishedDate = publishedDate; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getImageUrl() { // return imageUrl; // } // // public void setImageUrl(String imageUrl) { // this.imageUrl = imageUrl; // } // // @Override // public String toString() { // return "Title: " // + title // + ", Author: " // + author // + ", Published date: " // + publishedDate // + ", Added by: " // + createdBy; // } // } // // Path: bookshelf/1-cloud-run/src/main/java/com/example/getstarted/objects/Result.java // public class Result<K> { // private String cursor; // private List<K> result; // // public String getCursor() { // return cursor; // } // // public void setCursor(String cursor) { // this.cursor = cursor; // } // // public List<K> getResult() { // return result; // } // // public void setResult(List<K> result) { // this.result = result; // } // // public Result(List<K> result, String cursor) { // this.result = result; // this.cursor = cursor; // } // // public Result(List<K> result) { // this.result = result; // this.cursor = null; // } // }
import com.example.getstarted.objects.Book; import com.example.getstarted.objects.Result;
/* Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.example.getstarted.daos; // [START bookshelf_base_dao] public interface BookDao { String createBook(Book book); Book readBook(String bookId); void updateBook(Book book); void deleteBook(String bookId);
// Path: bookshelf/1-cloud-run/src/main/java/com/example/getstarted/objects/Book.java // public class Book { // private String title; // private String author; // private String createdBy; // private String createdById; // private String publishedDate; // private String description; // private String id; // private String imageUrl; // public static final String AUTHOR = "author"; // public static final String CREATED_BY = "createdBy"; // public static final String CREATED_BY_ID = "createdById"; // public static final String DESCRIPTION = "description"; // public static final String ID = "id"; // public static final String PUBLISHED_DATE = "publishedDate"; // public static final String TITLE = "title"; // public static final String IMAGE_URL = "imageUrl"; // // // We use a Builder pattern here to simplify and standardize construction of // // Book objects. // private Book(Builder builder) { // this.title = builder.title; // this.author = builder.author; // this.createdBy = builder.createdBy; // this.createdById = builder.createdById; // this.publishedDate = builder.publishedDate; // this.description = builder.description; // this.id = builder.id; // this.imageUrl = builder.imageUrl; // } // // public static class Builder { // private String title; // private String author; // private String createdBy; // private String createdById; // private String publishedDate; // private String description; // private String id; // private String imageUrl; // // public Builder title(String title) { // this.title = title; // return this; // } // // public Builder author(String author) { // this.author = author; // return this; // } // // public Builder createdBy(String createdBy) { // this.createdBy = createdBy; // return this; // } // // public Builder createdById(String createdById) { // this.createdById = createdById; // return this; // } // // public Builder publishedDate(String publishedDate) { // this.publishedDate = publishedDate; // return this; // } // // public Builder description(String description) { // this.description = description; // return this; // } // // public Builder id(String id) { // this.id = id; // return this; // } // // public Builder imageUrl(String imageUrl) { // this.imageUrl = imageUrl; // return this; // } // // public Book build() { // return new Book(this); // } // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String author) { // this.author = author; // } // // public String getCreatedBy() { // return createdBy; // } // // public void setCreatedBy(String createdBy) { // this.createdBy = createdBy; // } // // public String getCreatedById() { // return createdById; // } // // public void setCreatedById(String createdById) { // this.createdById = createdById; // } // // public String getPublishedDate() { // return publishedDate; // } // // public void setPublishedDate(String publishedDate) { // this.publishedDate = publishedDate; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getImageUrl() { // return imageUrl; // } // // public void setImageUrl(String imageUrl) { // this.imageUrl = imageUrl; // } // // @Override // public String toString() { // return "Title: " // + title // + ", Author: " // + author // + ", Published date: " // + publishedDate // + ", Added by: " // + createdBy; // } // } // // Path: bookshelf/1-cloud-run/src/main/java/com/example/getstarted/objects/Result.java // public class Result<K> { // private String cursor; // private List<K> result; // // public String getCursor() { // return cursor; // } // // public void setCursor(String cursor) { // this.cursor = cursor; // } // // public List<K> getResult() { // return result; // } // // public void setResult(List<K> result) { // this.result = result; // } // // public Result(List<K> result, String cursor) { // this.result = result; // this.cursor = cursor; // } // // public Result(List<K> result) { // this.result = result; // this.cursor = null; // } // } // Path: bookshelf/1-cloud-run/src/main/java/com/example/getstarted/daos/BookDao.java import com.example.getstarted.objects.Book; import com.example.getstarted.objects.Result; /* Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.example.getstarted.daos; // [START bookshelf_base_dao] public interface BookDao { String createBook(Book book); Book readBook(String bookId); void updateBook(Book book); void deleteBook(String bookId);
Result<Book> listBooks(String startCursor);
GoogleCloudPlatform/getting-started-java
bookshelf/1-cloud-run/src/main/java/com/example/getstarted/basicactions/ReadBookServlet.java
// Path: bookshelf-standard/5-logging/src/main/java/com/example/getstarted/daos/BookDao.java // public interface BookDao { // Long createBook(Book book) throws SQLException; // // Book readBook(Long bookId) throws SQLException; // // void updateBook(Book book) throws SQLException; // // void deleteBook(Long bookId) throws SQLException; // // Result<Book> listBooks(String startCursor) throws SQLException; // // Result<Book> listBooksByUser(String userId, String startCursor) throws SQLException; // } // // Path: bookshelf/1-cloud-run/src/main/java/com/example/getstarted/objects/Book.java // public class Book { // private String title; // private String author; // private String createdBy; // private String createdById; // private String publishedDate; // private String description; // private String id; // private String imageUrl; // public static final String AUTHOR = "author"; // public static final String CREATED_BY = "createdBy"; // public static final String CREATED_BY_ID = "createdById"; // public static final String DESCRIPTION = "description"; // public static final String ID = "id"; // public static final String PUBLISHED_DATE = "publishedDate"; // public static final String TITLE = "title"; // public static final String IMAGE_URL = "imageUrl"; // // // We use a Builder pattern here to simplify and standardize construction of // // Book objects. // private Book(Builder builder) { // this.title = builder.title; // this.author = builder.author; // this.createdBy = builder.createdBy; // this.createdById = builder.createdById; // this.publishedDate = builder.publishedDate; // this.description = builder.description; // this.id = builder.id; // this.imageUrl = builder.imageUrl; // } // // public static class Builder { // private String title; // private String author; // private String createdBy; // private String createdById; // private String publishedDate; // private String description; // private String id; // private String imageUrl; // // public Builder title(String title) { // this.title = title; // return this; // } // // public Builder author(String author) { // this.author = author; // return this; // } // // public Builder createdBy(String createdBy) { // this.createdBy = createdBy; // return this; // } // // public Builder createdById(String createdById) { // this.createdById = createdById; // return this; // } // // public Builder publishedDate(String publishedDate) { // this.publishedDate = publishedDate; // return this; // } // // public Builder description(String description) { // this.description = description; // return this; // } // // public Builder id(String id) { // this.id = id; // return this; // } // // public Builder imageUrl(String imageUrl) { // this.imageUrl = imageUrl; // return this; // } // // public Book build() { // return new Book(this); // } // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String author) { // this.author = author; // } // // public String getCreatedBy() { // return createdBy; // } // // public void setCreatedBy(String createdBy) { // this.createdBy = createdBy; // } // // public String getCreatedById() { // return createdById; // } // // public void setCreatedById(String createdById) { // this.createdById = createdById; // } // // public String getPublishedDate() { // return publishedDate; // } // // public void setPublishedDate(String publishedDate) { // this.publishedDate = publishedDate; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getImageUrl() { // return imageUrl; // } // // public void setImageUrl(String imageUrl) { // this.imageUrl = imageUrl; // } // // @Override // public String toString() { // return "Title: " // + title // + ", Author: " // + author // + ", Published date: " // + publishedDate // + ", Added by: " // + createdBy; // } // }
import com.example.getstarted.daos.BookDao; import com.example.getstarted.objects.Book; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;
/* Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.example.getstarted.basicactions; // [START bookshelf_read_servlet] @SuppressWarnings("serial") @WebServlet( name = "read", urlPatterns = {"/read"}) public class ReadBookServlet extends HttpServlet { private final Logger logger = Logger.getLogger(ReadBookServlet.class.getName()); @Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String id = req.getParameter("id");
// Path: bookshelf-standard/5-logging/src/main/java/com/example/getstarted/daos/BookDao.java // public interface BookDao { // Long createBook(Book book) throws SQLException; // // Book readBook(Long bookId) throws SQLException; // // void updateBook(Book book) throws SQLException; // // void deleteBook(Long bookId) throws SQLException; // // Result<Book> listBooks(String startCursor) throws SQLException; // // Result<Book> listBooksByUser(String userId, String startCursor) throws SQLException; // } // // Path: bookshelf/1-cloud-run/src/main/java/com/example/getstarted/objects/Book.java // public class Book { // private String title; // private String author; // private String createdBy; // private String createdById; // private String publishedDate; // private String description; // private String id; // private String imageUrl; // public static final String AUTHOR = "author"; // public static final String CREATED_BY = "createdBy"; // public static final String CREATED_BY_ID = "createdById"; // public static final String DESCRIPTION = "description"; // public static final String ID = "id"; // public static final String PUBLISHED_DATE = "publishedDate"; // public static final String TITLE = "title"; // public static final String IMAGE_URL = "imageUrl"; // // // We use a Builder pattern here to simplify and standardize construction of // // Book objects. // private Book(Builder builder) { // this.title = builder.title; // this.author = builder.author; // this.createdBy = builder.createdBy; // this.createdById = builder.createdById; // this.publishedDate = builder.publishedDate; // this.description = builder.description; // this.id = builder.id; // this.imageUrl = builder.imageUrl; // } // // public static class Builder { // private String title; // private String author; // private String createdBy; // private String createdById; // private String publishedDate; // private String description; // private String id; // private String imageUrl; // // public Builder title(String title) { // this.title = title; // return this; // } // // public Builder author(String author) { // this.author = author; // return this; // } // // public Builder createdBy(String createdBy) { // this.createdBy = createdBy; // return this; // } // // public Builder createdById(String createdById) { // this.createdById = createdById; // return this; // } // // public Builder publishedDate(String publishedDate) { // this.publishedDate = publishedDate; // return this; // } // // public Builder description(String description) { // this.description = description; // return this; // } // // public Builder id(String id) { // this.id = id; // return this; // } // // public Builder imageUrl(String imageUrl) { // this.imageUrl = imageUrl; // return this; // } // // public Book build() { // return new Book(this); // } // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String author) { // this.author = author; // } // // public String getCreatedBy() { // return createdBy; // } // // public void setCreatedBy(String createdBy) { // this.createdBy = createdBy; // } // // public String getCreatedById() { // return createdById; // } // // public void setCreatedById(String createdById) { // this.createdById = createdById; // } // // public String getPublishedDate() { // return publishedDate; // } // // public void setPublishedDate(String publishedDate) { // this.publishedDate = publishedDate; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getImageUrl() { // return imageUrl; // } // // public void setImageUrl(String imageUrl) { // this.imageUrl = imageUrl; // } // // @Override // public String toString() { // return "Title: " // + title // + ", Author: " // + author // + ", Published date: " // + publishedDate // + ", Added by: " // + createdBy; // } // } // Path: bookshelf/1-cloud-run/src/main/java/com/example/getstarted/basicactions/ReadBookServlet.java import com.example.getstarted.daos.BookDao; import com.example.getstarted.objects.Book; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /* Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.example.getstarted.basicactions; // [START bookshelf_read_servlet] @SuppressWarnings("serial") @WebServlet( name = "read", urlPatterns = {"/read"}) public class ReadBookServlet extends HttpServlet { private final Logger logger = Logger.getLogger(ReadBookServlet.class.getName()); @Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String id = req.getParameter("id");
BookDao dao = (BookDao) this.getServletContext().getAttribute("dao");
GoogleCloudPlatform/getting-started-java
bookshelf/1-cloud-run/src/main/java/com/example/getstarted/basicactions/ReadBookServlet.java
// Path: bookshelf-standard/5-logging/src/main/java/com/example/getstarted/daos/BookDao.java // public interface BookDao { // Long createBook(Book book) throws SQLException; // // Book readBook(Long bookId) throws SQLException; // // void updateBook(Book book) throws SQLException; // // void deleteBook(Long bookId) throws SQLException; // // Result<Book> listBooks(String startCursor) throws SQLException; // // Result<Book> listBooksByUser(String userId, String startCursor) throws SQLException; // } // // Path: bookshelf/1-cloud-run/src/main/java/com/example/getstarted/objects/Book.java // public class Book { // private String title; // private String author; // private String createdBy; // private String createdById; // private String publishedDate; // private String description; // private String id; // private String imageUrl; // public static final String AUTHOR = "author"; // public static final String CREATED_BY = "createdBy"; // public static final String CREATED_BY_ID = "createdById"; // public static final String DESCRIPTION = "description"; // public static final String ID = "id"; // public static final String PUBLISHED_DATE = "publishedDate"; // public static final String TITLE = "title"; // public static final String IMAGE_URL = "imageUrl"; // // // We use a Builder pattern here to simplify and standardize construction of // // Book objects. // private Book(Builder builder) { // this.title = builder.title; // this.author = builder.author; // this.createdBy = builder.createdBy; // this.createdById = builder.createdById; // this.publishedDate = builder.publishedDate; // this.description = builder.description; // this.id = builder.id; // this.imageUrl = builder.imageUrl; // } // // public static class Builder { // private String title; // private String author; // private String createdBy; // private String createdById; // private String publishedDate; // private String description; // private String id; // private String imageUrl; // // public Builder title(String title) { // this.title = title; // return this; // } // // public Builder author(String author) { // this.author = author; // return this; // } // // public Builder createdBy(String createdBy) { // this.createdBy = createdBy; // return this; // } // // public Builder createdById(String createdById) { // this.createdById = createdById; // return this; // } // // public Builder publishedDate(String publishedDate) { // this.publishedDate = publishedDate; // return this; // } // // public Builder description(String description) { // this.description = description; // return this; // } // // public Builder id(String id) { // this.id = id; // return this; // } // // public Builder imageUrl(String imageUrl) { // this.imageUrl = imageUrl; // return this; // } // // public Book build() { // return new Book(this); // } // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String author) { // this.author = author; // } // // public String getCreatedBy() { // return createdBy; // } // // public void setCreatedBy(String createdBy) { // this.createdBy = createdBy; // } // // public String getCreatedById() { // return createdById; // } // // public void setCreatedById(String createdById) { // this.createdById = createdById; // } // // public String getPublishedDate() { // return publishedDate; // } // // public void setPublishedDate(String publishedDate) { // this.publishedDate = publishedDate; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getImageUrl() { // return imageUrl; // } // // public void setImageUrl(String imageUrl) { // this.imageUrl = imageUrl; // } // // @Override // public String toString() { // return "Title: " // + title // + ", Author: " // + author // + ", Published date: " // + publishedDate // + ", Added by: " // + createdBy; // } // }
import com.example.getstarted.daos.BookDao; import com.example.getstarted.objects.Book; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;
/* Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.example.getstarted.basicactions; // [START bookshelf_read_servlet] @SuppressWarnings("serial") @WebServlet( name = "read", urlPatterns = {"/read"}) public class ReadBookServlet extends HttpServlet { private final Logger logger = Logger.getLogger(ReadBookServlet.class.getName()); @Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String id = req.getParameter("id"); BookDao dao = (BookDao) this.getServletContext().getAttribute("dao");
// Path: bookshelf-standard/5-logging/src/main/java/com/example/getstarted/daos/BookDao.java // public interface BookDao { // Long createBook(Book book) throws SQLException; // // Book readBook(Long bookId) throws SQLException; // // void updateBook(Book book) throws SQLException; // // void deleteBook(Long bookId) throws SQLException; // // Result<Book> listBooks(String startCursor) throws SQLException; // // Result<Book> listBooksByUser(String userId, String startCursor) throws SQLException; // } // // Path: bookshelf/1-cloud-run/src/main/java/com/example/getstarted/objects/Book.java // public class Book { // private String title; // private String author; // private String createdBy; // private String createdById; // private String publishedDate; // private String description; // private String id; // private String imageUrl; // public static final String AUTHOR = "author"; // public static final String CREATED_BY = "createdBy"; // public static final String CREATED_BY_ID = "createdById"; // public static final String DESCRIPTION = "description"; // public static final String ID = "id"; // public static final String PUBLISHED_DATE = "publishedDate"; // public static final String TITLE = "title"; // public static final String IMAGE_URL = "imageUrl"; // // // We use a Builder pattern here to simplify and standardize construction of // // Book objects. // private Book(Builder builder) { // this.title = builder.title; // this.author = builder.author; // this.createdBy = builder.createdBy; // this.createdById = builder.createdById; // this.publishedDate = builder.publishedDate; // this.description = builder.description; // this.id = builder.id; // this.imageUrl = builder.imageUrl; // } // // public static class Builder { // private String title; // private String author; // private String createdBy; // private String createdById; // private String publishedDate; // private String description; // private String id; // private String imageUrl; // // public Builder title(String title) { // this.title = title; // return this; // } // // public Builder author(String author) { // this.author = author; // return this; // } // // public Builder createdBy(String createdBy) { // this.createdBy = createdBy; // return this; // } // // public Builder createdById(String createdById) { // this.createdById = createdById; // return this; // } // // public Builder publishedDate(String publishedDate) { // this.publishedDate = publishedDate; // return this; // } // // public Builder description(String description) { // this.description = description; // return this; // } // // public Builder id(String id) { // this.id = id; // return this; // } // // public Builder imageUrl(String imageUrl) { // this.imageUrl = imageUrl; // return this; // } // // public Book build() { // return new Book(this); // } // } // // public String getTitle() { // return title; // } // // public void setTitle(String title) { // this.title = title; // } // // public String getAuthor() { // return author; // } // // public void setAuthor(String author) { // this.author = author; // } // // public String getCreatedBy() { // return createdBy; // } // // public void setCreatedBy(String createdBy) { // this.createdBy = createdBy; // } // // public String getCreatedById() { // return createdById; // } // // public void setCreatedById(String createdById) { // this.createdById = createdById; // } // // public String getPublishedDate() { // return publishedDate; // } // // public void setPublishedDate(String publishedDate) { // this.publishedDate = publishedDate; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getImageUrl() { // return imageUrl; // } // // public void setImageUrl(String imageUrl) { // this.imageUrl = imageUrl; // } // // @Override // public String toString() { // return "Title: " // + title // + ", Author: " // + author // + ", Published date: " // + publishedDate // + ", Added by: " // + createdBy; // } // } // Path: bookshelf/1-cloud-run/src/main/java/com/example/getstarted/basicactions/ReadBookServlet.java import com.example.getstarted.daos.BookDao; import com.example.getstarted.objects.Book; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /* Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.example.getstarted.basicactions; // [START bookshelf_read_servlet] @SuppressWarnings("serial") @WebServlet( name = "read", urlPatterns = {"/read"}) public class ReadBookServlet extends HttpServlet { private final Logger logger = Logger.getLogger(ReadBookServlet.class.getName()); @Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String id = req.getParameter("id"); BookDao dao = (BookDao) this.getServletContext().getAttribute("dao");
Book book = dao.readBook(id);
sayembd/java-examples
jpa-example/src/test/java/com/codesod/example/jpa/nplusone/service/PurchasingServiceIT.java
// Path: jpa-example/src/main/java/com/codesod/example/jpa/nplusone/dto/PurchaseOrderDTO.java // public class PurchaseOrderDTO { // private final String id; // private final OffsetDateTime orderDate; // // public PurchaseOrderDTO(String id, OffsetDateTime orderDate) { // this.id = id; // this.orderDate = orderDate; // } // // public String getId() { // return id; // } // // public OffsetDateTime getOrderDate() { // return orderDate; // } // } // // Path: jpa-example/src/main/java/com/codesod/example/jpa/nplusone/entity/PurchaseOrder.java // @Entity // public class PurchaseOrder { // // @Id // private String id; // private String customerId; // // @OneToMany(cascade = ALL, fetch = EAGER) // @JoinColumn(name = "purchase_order_id") // private List<PurchaseOrderItem> purchaseOrderItems = new ArrayList<>(); // // private OffsetDateTime orderDate; // // public PurchaseOrder(String id, String customerId) { // this.id = id; // this.customerId = customerId; // this.orderDate = OffsetDateTime.now(); // } // // public PurchaseOrder addOrderItem(PurchaseOrderItem purchaseOrderItem) { // purchaseOrderItems.add(purchaseOrderItem); // return this; // } // // private PurchaseOrder() {} // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getCustomerId() { // return customerId; // } // // public void setCustomerId(String customerId) { // this.customerId = customerId; // } // // public List<PurchaseOrderItem> getPurchaseOrderItems() { // return purchaseOrderItems; // } // // public void setPurchaseOrderItems(List<PurchaseOrderItem> purchaseOrderItems) { // this.purchaseOrderItems = purchaseOrderItems; // } // // public OffsetDateTime getOrderDate() { // return orderDate; // } // // public void setOrderDate(OffsetDateTime orderDate) { // this.orderDate = orderDate; // } // } // // Path: jpa-example/src/main/java/com/codesod/example/jpa/nplusone/repository/PurchaseOrderRepository.java // @Repository // public interface PurchaseOrderRepository extends JpaRepository<PurchaseOrder, String>, // JpaSpecificationExecutor<PurchaseOrder> { // // List<PurchaseOrder> findByCustomerId(String customerId); // }
import java.util.List; import static org.assertj.core.api.Assertions.assertThat; import com.codesod.example.jpa.nplusone.dto.PurchaseOrderDTO; import com.codesod.example.jpa.nplusone.entity.PurchaseOrder; import com.codesod.example.jpa.nplusone.repository.PurchaseOrderRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import org.junit.Test; import org.junit.runner.RunWith; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.TypedQuery; import java.util.Arrays;
/* * Copyright 2018 MD Sayem Ahmed * * 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.codesod.example.jpa.nplusone.service; /** * @author MD Sayem Ahmed */ @SpringBootTest @RunWith(SpringRunner.class) public class PurchasingServiceIT { @Autowired private PurchasingService purchasingService; @PersistenceContext private EntityManager entityManager; @Test public void fetches_data_with_n_plus_1_queries() { // Given purchasingService.createOrder("Sayem", Arrays.asList("Harry Potter 1", "Harry Potter 2")); purchasingService.createOrder("Sayem", Arrays.asList("Harry Potter 3", "Harry Potter 4")); // When
// Path: jpa-example/src/main/java/com/codesod/example/jpa/nplusone/dto/PurchaseOrderDTO.java // public class PurchaseOrderDTO { // private final String id; // private final OffsetDateTime orderDate; // // public PurchaseOrderDTO(String id, OffsetDateTime orderDate) { // this.id = id; // this.orderDate = orderDate; // } // // public String getId() { // return id; // } // // public OffsetDateTime getOrderDate() { // return orderDate; // } // } // // Path: jpa-example/src/main/java/com/codesod/example/jpa/nplusone/entity/PurchaseOrder.java // @Entity // public class PurchaseOrder { // // @Id // private String id; // private String customerId; // // @OneToMany(cascade = ALL, fetch = EAGER) // @JoinColumn(name = "purchase_order_id") // private List<PurchaseOrderItem> purchaseOrderItems = new ArrayList<>(); // // private OffsetDateTime orderDate; // // public PurchaseOrder(String id, String customerId) { // this.id = id; // this.customerId = customerId; // this.orderDate = OffsetDateTime.now(); // } // // public PurchaseOrder addOrderItem(PurchaseOrderItem purchaseOrderItem) { // purchaseOrderItems.add(purchaseOrderItem); // return this; // } // // private PurchaseOrder() {} // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getCustomerId() { // return customerId; // } // // public void setCustomerId(String customerId) { // this.customerId = customerId; // } // // public List<PurchaseOrderItem> getPurchaseOrderItems() { // return purchaseOrderItems; // } // // public void setPurchaseOrderItems(List<PurchaseOrderItem> purchaseOrderItems) { // this.purchaseOrderItems = purchaseOrderItems; // } // // public OffsetDateTime getOrderDate() { // return orderDate; // } // // public void setOrderDate(OffsetDateTime orderDate) { // this.orderDate = orderDate; // } // } // // Path: jpa-example/src/main/java/com/codesod/example/jpa/nplusone/repository/PurchaseOrderRepository.java // @Repository // public interface PurchaseOrderRepository extends JpaRepository<PurchaseOrder, String>, // JpaSpecificationExecutor<PurchaseOrder> { // // List<PurchaseOrder> findByCustomerId(String customerId); // } // Path: jpa-example/src/test/java/com/codesod/example/jpa/nplusone/service/PurchasingServiceIT.java import java.util.List; import static org.assertj.core.api.Assertions.assertThat; import com.codesod.example.jpa.nplusone.dto.PurchaseOrderDTO; import com.codesod.example.jpa.nplusone.entity.PurchaseOrder; import com.codesod.example.jpa.nplusone.repository.PurchaseOrderRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import org.junit.Test; import org.junit.runner.RunWith; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.TypedQuery; import java.util.Arrays; /* * Copyright 2018 MD Sayem Ahmed * * 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.codesod.example.jpa.nplusone.service; /** * @author MD Sayem Ahmed */ @SpringBootTest @RunWith(SpringRunner.class) public class PurchasingServiceIT { @Autowired private PurchasingService purchasingService; @PersistenceContext private EntityManager entityManager; @Test public void fetches_data_with_n_plus_1_queries() { // Given purchasingService.createOrder("Sayem", Arrays.asList("Harry Potter 1", "Harry Potter 2")); purchasingService.createOrder("Sayem", Arrays.asList("Harry Potter 3", "Harry Potter 4")); // When
List<PurchaseOrder> ordersOfCustomer = purchasingService.findOrdersOfCustomer("Sayem");
sayembd/java-examples
jpa-example/src/test/java/com/codesod/example/jpa/nplusone/service/PurchasingServiceIT.java
// Path: jpa-example/src/main/java/com/codesod/example/jpa/nplusone/dto/PurchaseOrderDTO.java // public class PurchaseOrderDTO { // private final String id; // private final OffsetDateTime orderDate; // // public PurchaseOrderDTO(String id, OffsetDateTime orderDate) { // this.id = id; // this.orderDate = orderDate; // } // // public String getId() { // return id; // } // // public OffsetDateTime getOrderDate() { // return orderDate; // } // } // // Path: jpa-example/src/main/java/com/codesod/example/jpa/nplusone/entity/PurchaseOrder.java // @Entity // public class PurchaseOrder { // // @Id // private String id; // private String customerId; // // @OneToMany(cascade = ALL, fetch = EAGER) // @JoinColumn(name = "purchase_order_id") // private List<PurchaseOrderItem> purchaseOrderItems = new ArrayList<>(); // // private OffsetDateTime orderDate; // // public PurchaseOrder(String id, String customerId) { // this.id = id; // this.customerId = customerId; // this.orderDate = OffsetDateTime.now(); // } // // public PurchaseOrder addOrderItem(PurchaseOrderItem purchaseOrderItem) { // purchaseOrderItems.add(purchaseOrderItem); // return this; // } // // private PurchaseOrder() {} // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getCustomerId() { // return customerId; // } // // public void setCustomerId(String customerId) { // this.customerId = customerId; // } // // public List<PurchaseOrderItem> getPurchaseOrderItems() { // return purchaseOrderItems; // } // // public void setPurchaseOrderItems(List<PurchaseOrderItem> purchaseOrderItems) { // this.purchaseOrderItems = purchaseOrderItems; // } // // public OffsetDateTime getOrderDate() { // return orderDate; // } // // public void setOrderDate(OffsetDateTime orderDate) { // this.orderDate = orderDate; // } // } // // Path: jpa-example/src/main/java/com/codesod/example/jpa/nplusone/repository/PurchaseOrderRepository.java // @Repository // public interface PurchaseOrderRepository extends JpaRepository<PurchaseOrder, String>, // JpaSpecificationExecutor<PurchaseOrder> { // // List<PurchaseOrder> findByCustomerId(String customerId); // }
import java.util.List; import static org.assertj.core.api.Assertions.assertThat; import com.codesod.example.jpa.nplusone.dto.PurchaseOrderDTO; import com.codesod.example.jpa.nplusone.entity.PurchaseOrder; import com.codesod.example.jpa.nplusone.repository.PurchaseOrderRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import org.junit.Test; import org.junit.runner.RunWith; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.TypedQuery; import java.util.Arrays;
/* * Copyright 2018 MD Sayem Ahmed * * 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.codesod.example.jpa.nplusone.service; /** * @author MD Sayem Ahmed */ @SpringBootTest @RunWith(SpringRunner.class) public class PurchasingServiceIT { @Autowired private PurchasingService purchasingService; @PersistenceContext private EntityManager entityManager; @Test public void fetches_data_with_n_plus_1_queries() { // Given purchasingService.createOrder("Sayem", Arrays.asList("Harry Potter 1", "Harry Potter 2")); purchasingService.createOrder("Sayem", Arrays.asList("Harry Potter 3", "Harry Potter 4")); // When List<PurchaseOrder> ordersOfCustomer = purchasingService.findOrdersOfCustomer("Sayem"); //Then assertThat(ordersOfCustomer).hasSize(2); } @Test public void fetches_a_tuple() { // Given purchasingService.createOrder("Sayem", Arrays.asList("Tin Goyenda", "Rupali Makorsha")); purchasingService.createOrder("Sayem", Arrays.asList("Roktochokhkhhu", "Kalo Beral")); // When
// Path: jpa-example/src/main/java/com/codesod/example/jpa/nplusone/dto/PurchaseOrderDTO.java // public class PurchaseOrderDTO { // private final String id; // private final OffsetDateTime orderDate; // // public PurchaseOrderDTO(String id, OffsetDateTime orderDate) { // this.id = id; // this.orderDate = orderDate; // } // // public String getId() { // return id; // } // // public OffsetDateTime getOrderDate() { // return orderDate; // } // } // // Path: jpa-example/src/main/java/com/codesod/example/jpa/nplusone/entity/PurchaseOrder.java // @Entity // public class PurchaseOrder { // // @Id // private String id; // private String customerId; // // @OneToMany(cascade = ALL, fetch = EAGER) // @JoinColumn(name = "purchase_order_id") // private List<PurchaseOrderItem> purchaseOrderItems = new ArrayList<>(); // // private OffsetDateTime orderDate; // // public PurchaseOrder(String id, String customerId) { // this.id = id; // this.customerId = customerId; // this.orderDate = OffsetDateTime.now(); // } // // public PurchaseOrder addOrderItem(PurchaseOrderItem purchaseOrderItem) { // purchaseOrderItems.add(purchaseOrderItem); // return this; // } // // private PurchaseOrder() {} // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getCustomerId() { // return customerId; // } // // public void setCustomerId(String customerId) { // this.customerId = customerId; // } // // public List<PurchaseOrderItem> getPurchaseOrderItems() { // return purchaseOrderItems; // } // // public void setPurchaseOrderItems(List<PurchaseOrderItem> purchaseOrderItems) { // this.purchaseOrderItems = purchaseOrderItems; // } // // public OffsetDateTime getOrderDate() { // return orderDate; // } // // public void setOrderDate(OffsetDateTime orderDate) { // this.orderDate = orderDate; // } // } // // Path: jpa-example/src/main/java/com/codesod/example/jpa/nplusone/repository/PurchaseOrderRepository.java // @Repository // public interface PurchaseOrderRepository extends JpaRepository<PurchaseOrder, String>, // JpaSpecificationExecutor<PurchaseOrder> { // // List<PurchaseOrder> findByCustomerId(String customerId); // } // Path: jpa-example/src/test/java/com/codesod/example/jpa/nplusone/service/PurchasingServiceIT.java import java.util.List; import static org.assertj.core.api.Assertions.assertThat; import com.codesod.example.jpa.nplusone.dto.PurchaseOrderDTO; import com.codesod.example.jpa.nplusone.entity.PurchaseOrder; import com.codesod.example.jpa.nplusone.repository.PurchaseOrderRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import org.junit.Test; import org.junit.runner.RunWith; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.TypedQuery; import java.util.Arrays; /* * Copyright 2018 MD Sayem Ahmed * * 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.codesod.example.jpa.nplusone.service; /** * @author MD Sayem Ahmed */ @SpringBootTest @RunWith(SpringRunner.class) public class PurchasingServiceIT { @Autowired private PurchasingService purchasingService; @PersistenceContext private EntityManager entityManager; @Test public void fetches_data_with_n_plus_1_queries() { // Given purchasingService.createOrder("Sayem", Arrays.asList("Harry Potter 1", "Harry Potter 2")); purchasingService.createOrder("Sayem", Arrays.asList("Harry Potter 3", "Harry Potter 4")); // When List<PurchaseOrder> ordersOfCustomer = purchasingService.findOrdersOfCustomer("Sayem"); //Then assertThat(ordersOfCustomer).hasSize(2); } @Test public void fetches_a_tuple() { // Given purchasingService.createOrder("Sayem", Arrays.asList("Tin Goyenda", "Rupali Makorsha")); purchasingService.createOrder("Sayem", Arrays.asList("Roktochokhkhhu", "Kalo Beral")); // When
TypedQuery<PurchaseOrderDTO> jpaQuery = entityManager.createQuery(
sayembd/java-examples
java-core/src/main/java/com/sayemahmed/example/validation/rule/OrderItemValidatorComposite.java
// Path: java-core/src/main/java/com/sayemahmed/example/validation/OrderDTO.java // @Getter // @Setter // @ToString // public static class OrderItem { // private String menuId; // private String description; // private String price; // private Integer quantity; // }
import com.sayemahmed.example.validation.OrderDTO.OrderItem; import java.util.List; import lombok.RequiredArgsConstructor;
/* * Copyright 2017 MD Sayem Ahmed * * 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.sayemahmed.example.validation.rule; @RequiredArgsConstructor class OrderItemValidatorComposite implements OrderItemValidator { private final List<OrderItemValidator> validators; @Override
// Path: java-core/src/main/java/com/sayemahmed/example/validation/OrderDTO.java // @Getter // @Setter // @ToString // public static class OrderItem { // private String menuId; // private String description; // private String price; // private Integer quantity; // } // Path: java-core/src/main/java/com/sayemahmed/example/validation/rule/OrderItemValidatorComposite.java import com.sayemahmed.example.validation.OrderDTO.OrderItem; import java.util.List; import lombok.RequiredArgsConstructor; /* * Copyright 2017 MD Sayem Ahmed * * 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.sayemahmed.example.validation.rule; @RequiredArgsConstructor class OrderItemValidatorComposite implements OrderItemValidator { private final List<OrderItemValidator> validators; @Override
public ErrorNotification validate(OrderItem orderItem) {
sayembd/java-examples
java-core/src/main/java/com/sayemahmed/example/validation/OrderService.java
// Path: java-core/src/main/java/com/sayemahmed/example/validation/rule/ErrorNotification.java // public class ErrorNotification { // private List<String> errors = new ArrayList<>(); // // public void addAll(ErrorNotification errorNotification) { // this.errors.addAll(errorNotification.errors); // } // // public boolean hasError() { // return !errors.isEmpty(); // } // // public String getAllErrors() { // return String.join(", ", errors); // } // // void addError(String message) { // this.errors.add(message); // } // } // // Path: java-core/src/main/java/com/sayemahmed/example/validation/rule/OrderItemValidator.java // public interface OrderItemValidator { // ErrorNotification validate(OrderDTO.OrderItem orderItem); // }
import com.sayemahmed.example.validation.rule.ErrorNotification; import com.sayemahmed.example.validation.rule.OrderItemValidator; import org.springframework.stereotype.Service; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j;
/* * Copyright 2017 MD Sayem Ahmed * * 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.sayemahmed.example.validation; @Service @Slf4j @RequiredArgsConstructor class OrderService {
// Path: java-core/src/main/java/com/sayemahmed/example/validation/rule/ErrorNotification.java // public class ErrorNotification { // private List<String> errors = new ArrayList<>(); // // public void addAll(ErrorNotification errorNotification) { // this.errors.addAll(errorNotification.errors); // } // // public boolean hasError() { // return !errors.isEmpty(); // } // // public String getAllErrors() { // return String.join(", ", errors); // } // // void addError(String message) { // this.errors.add(message); // } // } // // Path: java-core/src/main/java/com/sayemahmed/example/validation/rule/OrderItemValidator.java // public interface OrderItemValidator { // ErrorNotification validate(OrderDTO.OrderItem orderItem); // } // Path: java-core/src/main/java/com/sayemahmed/example/validation/OrderService.java import com.sayemahmed.example.validation.rule.ErrorNotification; import com.sayemahmed.example.validation.rule.OrderItemValidator; import org.springframework.stereotype.Service; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; /* * Copyright 2017 MD Sayem Ahmed * * 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.sayemahmed.example.validation; @Service @Slf4j @RequiredArgsConstructor class OrderService {
private final OrderItemValidator validator;
sayembd/java-examples
java-core/src/main/java/com/sayemahmed/example/validation/OrderService.java
// Path: java-core/src/main/java/com/sayemahmed/example/validation/rule/ErrorNotification.java // public class ErrorNotification { // private List<String> errors = new ArrayList<>(); // // public void addAll(ErrorNotification errorNotification) { // this.errors.addAll(errorNotification.errors); // } // // public boolean hasError() { // return !errors.isEmpty(); // } // // public String getAllErrors() { // return String.join(", ", errors); // } // // void addError(String message) { // this.errors.add(message); // } // } // // Path: java-core/src/main/java/com/sayemahmed/example/validation/rule/OrderItemValidator.java // public interface OrderItemValidator { // ErrorNotification validate(OrderDTO.OrderItem orderItem); // }
import com.sayemahmed.example.validation.rule.ErrorNotification; import com.sayemahmed.example.validation.rule.OrderItemValidator; import org.springframework.stereotype.Service; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j;
/* * Copyright 2017 MD Sayem Ahmed * * 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.sayemahmed.example.validation; @Service @Slf4j @RequiredArgsConstructor class OrderService { private final OrderItemValidator validator; void createOrder(OrderDTO orderDTO) {
// Path: java-core/src/main/java/com/sayemahmed/example/validation/rule/ErrorNotification.java // public class ErrorNotification { // private List<String> errors = new ArrayList<>(); // // public void addAll(ErrorNotification errorNotification) { // this.errors.addAll(errorNotification.errors); // } // // public boolean hasError() { // return !errors.isEmpty(); // } // // public String getAllErrors() { // return String.join(", ", errors); // } // // void addError(String message) { // this.errors.add(message); // } // } // // Path: java-core/src/main/java/com/sayemahmed/example/validation/rule/OrderItemValidator.java // public interface OrderItemValidator { // ErrorNotification validate(OrderDTO.OrderItem orderItem); // } // Path: java-core/src/main/java/com/sayemahmed/example/validation/OrderService.java import com.sayemahmed.example.validation.rule.ErrorNotification; import com.sayemahmed.example.validation.rule.OrderItemValidator; import org.springframework.stereotype.Service; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; /* * Copyright 2017 MD Sayem Ahmed * * 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.sayemahmed.example.validation; @Service @Slf4j @RequiredArgsConstructor class OrderService { private final OrderItemValidator validator; void createOrder(OrderDTO orderDTO) {
ErrorNotification errorNotification = new ErrorNotification();
sayembd/java-examples
jpa-example/src/main/java/com/codesod/example/jpa/nplusone/service/PurchasingService.java
// Path: jpa-example/src/main/java/com/codesod/example/jpa/nplusone/entity/PurchaseOrder.java // @Entity // public class PurchaseOrder { // // @Id // private String id; // private String customerId; // // @OneToMany(cascade = ALL, fetch = EAGER) // @JoinColumn(name = "purchase_order_id") // private List<PurchaseOrderItem> purchaseOrderItems = new ArrayList<>(); // // private OffsetDateTime orderDate; // // public PurchaseOrder(String id, String customerId) { // this.id = id; // this.customerId = customerId; // this.orderDate = OffsetDateTime.now(); // } // // public PurchaseOrder addOrderItem(PurchaseOrderItem purchaseOrderItem) { // purchaseOrderItems.add(purchaseOrderItem); // return this; // } // // private PurchaseOrder() {} // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getCustomerId() { // return customerId; // } // // public void setCustomerId(String customerId) { // this.customerId = customerId; // } // // public List<PurchaseOrderItem> getPurchaseOrderItems() { // return purchaseOrderItems; // } // // public void setPurchaseOrderItems(List<PurchaseOrderItem> purchaseOrderItems) { // this.purchaseOrderItems = purchaseOrderItems; // } // // public OffsetDateTime getOrderDate() { // return orderDate; // } // // public void setOrderDate(OffsetDateTime orderDate) { // this.orderDate = orderDate; // } // } // // Path: jpa-example/src/main/java/com/codesod/example/jpa/nplusone/entity/PurchaseOrderItem.java // @Entity // public class PurchaseOrderItem { // // @Id // private String id; // // private String bookId; // // public PurchaseOrderItem(String id, String bookId) { // this.id = id; // this.bookId = bookId; // } // // private PurchaseOrderItem() {} // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getBookId() { // return bookId; // } // // public void setBookId(String bookId) { // this.bookId = bookId; // } // } // // Path: jpa-example/src/main/java/com/codesod/example/jpa/nplusone/repository/PurchaseOrderRepository.java // @Repository // public interface PurchaseOrderRepository extends JpaRepository<PurchaseOrder, String>, // JpaSpecificationExecutor<PurchaseOrder> { // // List<PurchaseOrder> findByCustomerId(String customerId); // }
import com.codesod.example.jpa.nplusone.entity.PurchaseOrder; import com.codesod.example.jpa.nplusone.entity.PurchaseOrderItem; import com.codesod.example.jpa.nplusone.repository.PurchaseOrderRepository; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; import java.util.UUID;
/* * Copyright 2018 MD Sayem Ahmed * * 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.codesod.example.jpa.nplusone.service; /** * @author MD Sayem Ahmed */ @Service public class PurchasingService {
// Path: jpa-example/src/main/java/com/codesod/example/jpa/nplusone/entity/PurchaseOrder.java // @Entity // public class PurchaseOrder { // // @Id // private String id; // private String customerId; // // @OneToMany(cascade = ALL, fetch = EAGER) // @JoinColumn(name = "purchase_order_id") // private List<PurchaseOrderItem> purchaseOrderItems = new ArrayList<>(); // // private OffsetDateTime orderDate; // // public PurchaseOrder(String id, String customerId) { // this.id = id; // this.customerId = customerId; // this.orderDate = OffsetDateTime.now(); // } // // public PurchaseOrder addOrderItem(PurchaseOrderItem purchaseOrderItem) { // purchaseOrderItems.add(purchaseOrderItem); // return this; // } // // private PurchaseOrder() {} // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getCustomerId() { // return customerId; // } // // public void setCustomerId(String customerId) { // this.customerId = customerId; // } // // public List<PurchaseOrderItem> getPurchaseOrderItems() { // return purchaseOrderItems; // } // // public void setPurchaseOrderItems(List<PurchaseOrderItem> purchaseOrderItems) { // this.purchaseOrderItems = purchaseOrderItems; // } // // public OffsetDateTime getOrderDate() { // return orderDate; // } // // public void setOrderDate(OffsetDateTime orderDate) { // this.orderDate = orderDate; // } // } // // Path: jpa-example/src/main/java/com/codesod/example/jpa/nplusone/entity/PurchaseOrderItem.java // @Entity // public class PurchaseOrderItem { // // @Id // private String id; // // private String bookId; // // public PurchaseOrderItem(String id, String bookId) { // this.id = id; // this.bookId = bookId; // } // // private PurchaseOrderItem() {} // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getBookId() { // return bookId; // } // // public void setBookId(String bookId) { // this.bookId = bookId; // } // } // // Path: jpa-example/src/main/java/com/codesod/example/jpa/nplusone/repository/PurchaseOrderRepository.java // @Repository // public interface PurchaseOrderRepository extends JpaRepository<PurchaseOrder, String>, // JpaSpecificationExecutor<PurchaseOrder> { // // List<PurchaseOrder> findByCustomerId(String customerId); // } // Path: jpa-example/src/main/java/com/codesod/example/jpa/nplusone/service/PurchasingService.java import com.codesod.example.jpa.nplusone.entity.PurchaseOrder; import com.codesod.example.jpa.nplusone.entity.PurchaseOrderItem; import com.codesod.example.jpa.nplusone.repository.PurchaseOrderRepository; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; import java.util.UUID; /* * Copyright 2018 MD Sayem Ahmed * * 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.codesod.example.jpa.nplusone.service; /** * @author MD Sayem Ahmed */ @Service public class PurchasingService {
private final PurchaseOrderRepository purchaseOrderRepository;
sayembd/java-examples
jpa-example/src/main/java/com/codesod/example/jpa/nplusone/service/PurchasingService.java
// Path: jpa-example/src/main/java/com/codesod/example/jpa/nplusone/entity/PurchaseOrder.java // @Entity // public class PurchaseOrder { // // @Id // private String id; // private String customerId; // // @OneToMany(cascade = ALL, fetch = EAGER) // @JoinColumn(name = "purchase_order_id") // private List<PurchaseOrderItem> purchaseOrderItems = new ArrayList<>(); // // private OffsetDateTime orderDate; // // public PurchaseOrder(String id, String customerId) { // this.id = id; // this.customerId = customerId; // this.orderDate = OffsetDateTime.now(); // } // // public PurchaseOrder addOrderItem(PurchaseOrderItem purchaseOrderItem) { // purchaseOrderItems.add(purchaseOrderItem); // return this; // } // // private PurchaseOrder() {} // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getCustomerId() { // return customerId; // } // // public void setCustomerId(String customerId) { // this.customerId = customerId; // } // // public List<PurchaseOrderItem> getPurchaseOrderItems() { // return purchaseOrderItems; // } // // public void setPurchaseOrderItems(List<PurchaseOrderItem> purchaseOrderItems) { // this.purchaseOrderItems = purchaseOrderItems; // } // // public OffsetDateTime getOrderDate() { // return orderDate; // } // // public void setOrderDate(OffsetDateTime orderDate) { // this.orderDate = orderDate; // } // } // // Path: jpa-example/src/main/java/com/codesod/example/jpa/nplusone/entity/PurchaseOrderItem.java // @Entity // public class PurchaseOrderItem { // // @Id // private String id; // // private String bookId; // // public PurchaseOrderItem(String id, String bookId) { // this.id = id; // this.bookId = bookId; // } // // private PurchaseOrderItem() {} // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getBookId() { // return bookId; // } // // public void setBookId(String bookId) { // this.bookId = bookId; // } // } // // Path: jpa-example/src/main/java/com/codesod/example/jpa/nplusone/repository/PurchaseOrderRepository.java // @Repository // public interface PurchaseOrderRepository extends JpaRepository<PurchaseOrder, String>, // JpaSpecificationExecutor<PurchaseOrder> { // // List<PurchaseOrder> findByCustomerId(String customerId); // }
import com.codesod.example.jpa.nplusone.entity.PurchaseOrder; import com.codesod.example.jpa.nplusone.entity.PurchaseOrderItem; import com.codesod.example.jpa.nplusone.repository.PurchaseOrderRepository; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; import java.util.UUID;
/* * Copyright 2018 MD Sayem Ahmed * * 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.codesod.example.jpa.nplusone.service; /** * @author MD Sayem Ahmed */ @Service public class PurchasingService { private final PurchaseOrderRepository purchaseOrderRepository; public PurchasingService(PurchaseOrderRepository purchaseOrderRepository) { this.purchaseOrderRepository = purchaseOrderRepository; } @Transactional public void createOrder(String customerId, List<String> bookIds) {
// Path: jpa-example/src/main/java/com/codesod/example/jpa/nplusone/entity/PurchaseOrder.java // @Entity // public class PurchaseOrder { // // @Id // private String id; // private String customerId; // // @OneToMany(cascade = ALL, fetch = EAGER) // @JoinColumn(name = "purchase_order_id") // private List<PurchaseOrderItem> purchaseOrderItems = new ArrayList<>(); // // private OffsetDateTime orderDate; // // public PurchaseOrder(String id, String customerId) { // this.id = id; // this.customerId = customerId; // this.orderDate = OffsetDateTime.now(); // } // // public PurchaseOrder addOrderItem(PurchaseOrderItem purchaseOrderItem) { // purchaseOrderItems.add(purchaseOrderItem); // return this; // } // // private PurchaseOrder() {} // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getCustomerId() { // return customerId; // } // // public void setCustomerId(String customerId) { // this.customerId = customerId; // } // // public List<PurchaseOrderItem> getPurchaseOrderItems() { // return purchaseOrderItems; // } // // public void setPurchaseOrderItems(List<PurchaseOrderItem> purchaseOrderItems) { // this.purchaseOrderItems = purchaseOrderItems; // } // // public OffsetDateTime getOrderDate() { // return orderDate; // } // // public void setOrderDate(OffsetDateTime orderDate) { // this.orderDate = orderDate; // } // } // // Path: jpa-example/src/main/java/com/codesod/example/jpa/nplusone/entity/PurchaseOrderItem.java // @Entity // public class PurchaseOrderItem { // // @Id // private String id; // // private String bookId; // // public PurchaseOrderItem(String id, String bookId) { // this.id = id; // this.bookId = bookId; // } // // private PurchaseOrderItem() {} // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getBookId() { // return bookId; // } // // public void setBookId(String bookId) { // this.bookId = bookId; // } // } // // Path: jpa-example/src/main/java/com/codesod/example/jpa/nplusone/repository/PurchaseOrderRepository.java // @Repository // public interface PurchaseOrderRepository extends JpaRepository<PurchaseOrder, String>, // JpaSpecificationExecutor<PurchaseOrder> { // // List<PurchaseOrder> findByCustomerId(String customerId); // } // Path: jpa-example/src/main/java/com/codesod/example/jpa/nplusone/service/PurchasingService.java import com.codesod.example.jpa.nplusone.entity.PurchaseOrder; import com.codesod.example.jpa.nplusone.entity.PurchaseOrderItem; import com.codesod.example.jpa.nplusone.repository.PurchaseOrderRepository; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; import java.util.UUID; /* * Copyright 2018 MD Sayem Ahmed * * 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.codesod.example.jpa.nplusone.service; /** * @author MD Sayem Ahmed */ @Service public class PurchasingService { private final PurchaseOrderRepository purchaseOrderRepository; public PurchasingService(PurchaseOrderRepository purchaseOrderRepository) { this.purchaseOrderRepository = purchaseOrderRepository; } @Transactional public void createOrder(String customerId, List<String> bookIds) {
PurchaseOrder purchaseOrder = new PurchaseOrder(UUID.randomUUID().toString(), customerId);
sayembd/java-examples
jpa-example/src/main/java/com/codesod/example/jpa/nplusone/service/PurchasingService.java
// Path: jpa-example/src/main/java/com/codesod/example/jpa/nplusone/entity/PurchaseOrder.java // @Entity // public class PurchaseOrder { // // @Id // private String id; // private String customerId; // // @OneToMany(cascade = ALL, fetch = EAGER) // @JoinColumn(name = "purchase_order_id") // private List<PurchaseOrderItem> purchaseOrderItems = new ArrayList<>(); // // private OffsetDateTime orderDate; // // public PurchaseOrder(String id, String customerId) { // this.id = id; // this.customerId = customerId; // this.orderDate = OffsetDateTime.now(); // } // // public PurchaseOrder addOrderItem(PurchaseOrderItem purchaseOrderItem) { // purchaseOrderItems.add(purchaseOrderItem); // return this; // } // // private PurchaseOrder() {} // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getCustomerId() { // return customerId; // } // // public void setCustomerId(String customerId) { // this.customerId = customerId; // } // // public List<PurchaseOrderItem> getPurchaseOrderItems() { // return purchaseOrderItems; // } // // public void setPurchaseOrderItems(List<PurchaseOrderItem> purchaseOrderItems) { // this.purchaseOrderItems = purchaseOrderItems; // } // // public OffsetDateTime getOrderDate() { // return orderDate; // } // // public void setOrderDate(OffsetDateTime orderDate) { // this.orderDate = orderDate; // } // } // // Path: jpa-example/src/main/java/com/codesod/example/jpa/nplusone/entity/PurchaseOrderItem.java // @Entity // public class PurchaseOrderItem { // // @Id // private String id; // // private String bookId; // // public PurchaseOrderItem(String id, String bookId) { // this.id = id; // this.bookId = bookId; // } // // private PurchaseOrderItem() {} // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getBookId() { // return bookId; // } // // public void setBookId(String bookId) { // this.bookId = bookId; // } // } // // Path: jpa-example/src/main/java/com/codesod/example/jpa/nplusone/repository/PurchaseOrderRepository.java // @Repository // public interface PurchaseOrderRepository extends JpaRepository<PurchaseOrder, String>, // JpaSpecificationExecutor<PurchaseOrder> { // // List<PurchaseOrder> findByCustomerId(String customerId); // }
import com.codesod.example.jpa.nplusone.entity.PurchaseOrder; import com.codesod.example.jpa.nplusone.entity.PurchaseOrderItem; import com.codesod.example.jpa.nplusone.repository.PurchaseOrderRepository; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; import java.util.UUID;
/* * Copyright 2018 MD Sayem Ahmed * * 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.codesod.example.jpa.nplusone.service; /** * @author MD Sayem Ahmed */ @Service public class PurchasingService { private final PurchaseOrderRepository purchaseOrderRepository; public PurchasingService(PurchaseOrderRepository purchaseOrderRepository) { this.purchaseOrderRepository = purchaseOrderRepository; } @Transactional public void createOrder(String customerId, List<String> bookIds) { PurchaseOrder purchaseOrder = new PurchaseOrder(UUID.randomUUID().toString(), customerId); bookIds.stream()
// Path: jpa-example/src/main/java/com/codesod/example/jpa/nplusone/entity/PurchaseOrder.java // @Entity // public class PurchaseOrder { // // @Id // private String id; // private String customerId; // // @OneToMany(cascade = ALL, fetch = EAGER) // @JoinColumn(name = "purchase_order_id") // private List<PurchaseOrderItem> purchaseOrderItems = new ArrayList<>(); // // private OffsetDateTime orderDate; // // public PurchaseOrder(String id, String customerId) { // this.id = id; // this.customerId = customerId; // this.orderDate = OffsetDateTime.now(); // } // // public PurchaseOrder addOrderItem(PurchaseOrderItem purchaseOrderItem) { // purchaseOrderItems.add(purchaseOrderItem); // return this; // } // // private PurchaseOrder() {} // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getCustomerId() { // return customerId; // } // // public void setCustomerId(String customerId) { // this.customerId = customerId; // } // // public List<PurchaseOrderItem> getPurchaseOrderItems() { // return purchaseOrderItems; // } // // public void setPurchaseOrderItems(List<PurchaseOrderItem> purchaseOrderItems) { // this.purchaseOrderItems = purchaseOrderItems; // } // // public OffsetDateTime getOrderDate() { // return orderDate; // } // // public void setOrderDate(OffsetDateTime orderDate) { // this.orderDate = orderDate; // } // } // // Path: jpa-example/src/main/java/com/codesod/example/jpa/nplusone/entity/PurchaseOrderItem.java // @Entity // public class PurchaseOrderItem { // // @Id // private String id; // // private String bookId; // // public PurchaseOrderItem(String id, String bookId) { // this.id = id; // this.bookId = bookId; // } // // private PurchaseOrderItem() {} // // public String getId() { // return id; // } // // public void setId(String id) { // this.id = id; // } // // public String getBookId() { // return bookId; // } // // public void setBookId(String bookId) { // this.bookId = bookId; // } // } // // Path: jpa-example/src/main/java/com/codesod/example/jpa/nplusone/repository/PurchaseOrderRepository.java // @Repository // public interface PurchaseOrderRepository extends JpaRepository<PurchaseOrder, String>, // JpaSpecificationExecutor<PurchaseOrder> { // // List<PurchaseOrder> findByCustomerId(String customerId); // } // Path: jpa-example/src/main/java/com/codesod/example/jpa/nplusone/service/PurchasingService.java import com.codesod.example.jpa.nplusone.entity.PurchaseOrder; import com.codesod.example.jpa.nplusone.entity.PurchaseOrderItem; import com.codesod.example.jpa.nplusone.repository.PurchaseOrderRepository; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; import java.util.UUID; /* * Copyright 2018 MD Sayem Ahmed * * 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.codesod.example.jpa.nplusone.service; /** * @author MD Sayem Ahmed */ @Service public class PurchasingService { private final PurchaseOrderRepository purchaseOrderRepository; public PurchasingService(PurchaseOrderRepository purchaseOrderRepository) { this.purchaseOrderRepository = purchaseOrderRepository; } @Transactional public void createOrder(String customerId, List<String> bookIds) { PurchaseOrder purchaseOrder = new PurchaseOrder(UUID.randomUUID().toString(), customerId); bookIds.stream()
.map(bookId -> new PurchaseOrderItem(UUID.randomUUID().toString(), bookId))
sayembd/java-examples
java-core/src/test/java/com/sayemahmed/example/validation/rule/QuantityValidatorTest.java
// Path: java-core/src/main/java/com/sayemahmed/example/validation/OrderDTO.java // @Getter // @Setter // @ToString // public class OrderDTO { // // @NotNull // private String customerId; // // @NotNull // @Size(min = 1) // private List<OrderItem> orderItems; // // @Getter // @Setter // @ToString // public static class OrderItem { // private String menuId; // private String description; // private String price; // private Integer quantity; // } // }
import com.sayemahmed.example.validation.OrderDTO; import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test;
/* * Copyright 2017 MD Sayem Ahmed * * 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.sayemahmed.example.validation.rule; public class QuantityValidatorTest { @Test public void validate_quantityIsNull_invalid() { QuantityValidator validator = new QuantityValidator();
// Path: java-core/src/main/java/com/sayemahmed/example/validation/OrderDTO.java // @Getter // @Setter // @ToString // public class OrderDTO { // // @NotNull // private String customerId; // // @NotNull // @Size(min = 1) // private List<OrderItem> orderItems; // // @Getter // @Setter // @ToString // public static class OrderItem { // private String menuId; // private String description; // private String price; // private Integer quantity; // } // } // Path: java-core/src/test/java/com/sayemahmed/example/validation/rule/QuantityValidatorTest.java import com.sayemahmed.example.validation.OrderDTO; import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; /* * Copyright 2017 MD Sayem Ahmed * * 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.sayemahmed.example.validation.rule; public class QuantityValidatorTest { @Test public void validate_quantityIsNull_invalid() { QuantityValidator validator = new QuantityValidator();
ErrorNotification errorNotification = validator.validate(new OrderDTO.OrderItem());
sayembd/java-examples
java-core/src/main/java/com/sayemahmed/example/validation/rule/ItemDescriptionValidator.java
// Path: java-core/src/main/java/com/sayemahmed/example/validation/OrderDTO.java // @Getter // @Setter // @ToString // public class OrderDTO { // // @NotNull // private String customerId; // // @NotNull // @Size(min = 1) // private List<OrderItem> orderItems; // // @Getter // @Setter // @ToString // public static class OrderItem { // private String menuId; // private String description; // private String price; // private Integer quantity; // } // }
import com.sayemahmed.example.validation.OrderDTO; import java.util.Optional;
/* * Copyright 2017 MD Sayem Ahmed * * 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.sayemahmed.example.validation.rule; class ItemDescriptionValidator implements OrderItemValidator { static final String MISSING_ITEM_DESCRIPTION = "Item description should be provided"; @Override
// Path: java-core/src/main/java/com/sayemahmed/example/validation/OrderDTO.java // @Getter // @Setter // @ToString // public class OrderDTO { // // @NotNull // private String customerId; // // @NotNull // @Size(min = 1) // private List<OrderItem> orderItems; // // @Getter // @Setter // @ToString // public static class OrderItem { // private String menuId; // private String description; // private String price; // private Integer quantity; // } // } // Path: java-core/src/main/java/com/sayemahmed/example/validation/rule/ItemDescriptionValidator.java import com.sayemahmed.example.validation.OrderDTO; import java.util.Optional; /* * Copyright 2017 MD Sayem Ahmed * * 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.sayemahmed.example.validation.rule; class ItemDescriptionValidator implements OrderItemValidator { static final String MISSING_ITEM_DESCRIPTION = "Item description should be provided"; @Override
public ErrorNotification validate(OrderDTO.OrderItem orderItem) {
sayembd/java-examples
java-core/src/main/java/com/sayemahmed/example/executor/MonitoredThreadPoolExecutor.java
// Path: java-core/src/main/java/com/sayemahmed/example/executor/MonitoredThreadPoolExecutor.java // static final String activeThreads = "activeThreads"; // // Path: java-core/src/main/java/com/sayemahmed/example/executor/MonitoredThreadPoolExecutor.java // static final String failedTasks = "failed-tasks"; // // Path: java-core/src/main/java/com/sayemahmed/example/executor/MonitoredThreadPoolExecutor.java // static final String maxPoolSize = "maxPoolSize"; // // Path: java-core/src/main/java/com/sayemahmed/example/executor/MonitoredThreadPoolExecutor.java // static final String queueSize = "queueSize"; // // Path: java-core/src/main/java/com/sayemahmed/example/executor/MonitoredThreadPoolExecutor.java // static final String successfulTasks = "successful-tasks"; // // Path: java-core/src/main/java/com/sayemahmed/example/executor/MonitoredThreadPoolExecutor.java // static final String taskExecution = "task-execution";
import com.codahale.metrics.Counter; import com.codahale.metrics.Gauge; import com.codahale.metrics.MetricRegistry; import com.codahale.metrics.Timer; import lombok.extern.slf4j.Slf4j; import java.util.concurrent.BlockingQueue; import java.util.concurrent.CancellationException; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.RejectedExecutionHandler; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import static com.sayemahmed.example.executor.MonitoredThreadPoolExecutor.MonitoringKey.activeThreads; import static com.sayemahmed.example.executor.MonitoredThreadPoolExecutor.MonitoringKey.failedTasks; import static com.sayemahmed.example.executor.MonitoredThreadPoolExecutor.MonitoringKey.maxPoolSize; import static com.sayemahmed.example.executor.MonitoredThreadPoolExecutor.MonitoringKey.queueSize; import static com.sayemahmed.example.executor.MonitoredThreadPoolExecutor.MonitoringKey.successfulTasks; import static com.sayemahmed.example.executor.MonitoredThreadPoolExecutor.MonitoringKey.taskExecution;
RejectedExecutionHandler handler, MetricRegistry metricRegistry, String poolName ) { super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, handler); this.metricRegistry = metricRegistry; this.metricsPrefix = MetricRegistry.name(getClass(), poolName); registerGauges(); } public MonitoredThreadPoolExecutor( int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler, MetricRegistry metricRegistry, String poolName ) { super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler); this.metricRegistry = metricRegistry; this.metricsPrefix = MetricRegistry.name(getClass(), poolName); registerGauges(); } @Override protected void beforeExecute(Thread thread, Runnable task) { super.beforeExecute(thread, task);
// Path: java-core/src/main/java/com/sayemahmed/example/executor/MonitoredThreadPoolExecutor.java // static final String activeThreads = "activeThreads"; // // Path: java-core/src/main/java/com/sayemahmed/example/executor/MonitoredThreadPoolExecutor.java // static final String failedTasks = "failed-tasks"; // // Path: java-core/src/main/java/com/sayemahmed/example/executor/MonitoredThreadPoolExecutor.java // static final String maxPoolSize = "maxPoolSize"; // // Path: java-core/src/main/java/com/sayemahmed/example/executor/MonitoredThreadPoolExecutor.java // static final String queueSize = "queueSize"; // // Path: java-core/src/main/java/com/sayemahmed/example/executor/MonitoredThreadPoolExecutor.java // static final String successfulTasks = "successful-tasks"; // // Path: java-core/src/main/java/com/sayemahmed/example/executor/MonitoredThreadPoolExecutor.java // static final String taskExecution = "task-execution"; // Path: java-core/src/main/java/com/sayemahmed/example/executor/MonitoredThreadPoolExecutor.java import com.codahale.metrics.Counter; import com.codahale.metrics.Gauge; import com.codahale.metrics.MetricRegistry; import com.codahale.metrics.Timer; import lombok.extern.slf4j.Slf4j; import java.util.concurrent.BlockingQueue; import java.util.concurrent.CancellationException; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.RejectedExecutionHandler; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import static com.sayemahmed.example.executor.MonitoredThreadPoolExecutor.MonitoringKey.activeThreads; import static com.sayemahmed.example.executor.MonitoredThreadPoolExecutor.MonitoringKey.failedTasks; import static com.sayemahmed.example.executor.MonitoredThreadPoolExecutor.MonitoringKey.maxPoolSize; import static com.sayemahmed.example.executor.MonitoredThreadPoolExecutor.MonitoringKey.queueSize; import static com.sayemahmed.example.executor.MonitoredThreadPoolExecutor.MonitoringKey.successfulTasks; import static com.sayemahmed.example.executor.MonitoredThreadPoolExecutor.MonitoringKey.taskExecution; RejectedExecutionHandler handler, MetricRegistry metricRegistry, String poolName ) { super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, handler); this.metricRegistry = metricRegistry; this.metricsPrefix = MetricRegistry.name(getClass(), poolName); registerGauges(); } public MonitoredThreadPoolExecutor( int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler, MetricRegistry metricRegistry, String poolName ) { super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler); this.metricRegistry = metricRegistry; this.metricsPrefix = MetricRegistry.name(getClass(), poolName); registerGauges(); } @Override protected void beforeExecute(Thread thread, Runnable task) { super.beforeExecute(thread, task);
Timer timer = metricRegistry.timer(MetricRegistry.name(metricsPrefix, taskExecution));
sayembd/java-examples
java-core/src/main/java/com/sayemahmed/example/executor/MonitoredThreadPoolExecutor.java
// Path: java-core/src/main/java/com/sayemahmed/example/executor/MonitoredThreadPoolExecutor.java // static final String activeThreads = "activeThreads"; // // Path: java-core/src/main/java/com/sayemahmed/example/executor/MonitoredThreadPoolExecutor.java // static final String failedTasks = "failed-tasks"; // // Path: java-core/src/main/java/com/sayemahmed/example/executor/MonitoredThreadPoolExecutor.java // static final String maxPoolSize = "maxPoolSize"; // // Path: java-core/src/main/java/com/sayemahmed/example/executor/MonitoredThreadPoolExecutor.java // static final String queueSize = "queueSize"; // // Path: java-core/src/main/java/com/sayemahmed/example/executor/MonitoredThreadPoolExecutor.java // static final String successfulTasks = "successful-tasks"; // // Path: java-core/src/main/java/com/sayemahmed/example/executor/MonitoredThreadPoolExecutor.java // static final String taskExecution = "task-execution";
import com.codahale.metrics.Counter; import com.codahale.metrics.Gauge; import com.codahale.metrics.MetricRegistry; import com.codahale.metrics.Timer; import lombok.extern.slf4j.Slf4j; import java.util.concurrent.BlockingQueue; import java.util.concurrent.CancellationException; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.RejectedExecutionHandler; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import static com.sayemahmed.example.executor.MonitoredThreadPoolExecutor.MonitoringKey.activeThreads; import static com.sayemahmed.example.executor.MonitoredThreadPoolExecutor.MonitoringKey.failedTasks; import static com.sayemahmed.example.executor.MonitoredThreadPoolExecutor.MonitoringKey.maxPoolSize; import static com.sayemahmed.example.executor.MonitoredThreadPoolExecutor.MonitoringKey.queueSize; import static com.sayemahmed.example.executor.MonitoredThreadPoolExecutor.MonitoringKey.successfulTasks; import static com.sayemahmed.example.executor.MonitoredThreadPoolExecutor.MonitoringKey.taskExecution;
this.metricRegistry = metricRegistry; this.metricsPrefix = MetricRegistry.name(getClass(), poolName); registerGauges(); } @Override protected void beforeExecute(Thread thread, Runnable task) { super.beforeExecute(thread, task); Timer timer = metricRegistry.timer(MetricRegistry.name(metricsPrefix, taskExecution)); taskExecutionTimer.set(timer.time()); } @Override protected void afterExecute(Runnable task, Throwable throwable) { Timer.Context context = taskExecutionTimer.get(); context.stop(); super.afterExecute(task, throwable); if (throwable == null && task instanceof Future<?> && ((Future<?>) task).isDone()) { try { ((Future<?>) task).get(); } catch (CancellationException ce) { throwable = ce; } catch (ExecutionException ee) { throwable = ee.getCause(); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); } } if (throwable != null) {
// Path: java-core/src/main/java/com/sayemahmed/example/executor/MonitoredThreadPoolExecutor.java // static final String activeThreads = "activeThreads"; // // Path: java-core/src/main/java/com/sayemahmed/example/executor/MonitoredThreadPoolExecutor.java // static final String failedTasks = "failed-tasks"; // // Path: java-core/src/main/java/com/sayemahmed/example/executor/MonitoredThreadPoolExecutor.java // static final String maxPoolSize = "maxPoolSize"; // // Path: java-core/src/main/java/com/sayemahmed/example/executor/MonitoredThreadPoolExecutor.java // static final String queueSize = "queueSize"; // // Path: java-core/src/main/java/com/sayemahmed/example/executor/MonitoredThreadPoolExecutor.java // static final String successfulTasks = "successful-tasks"; // // Path: java-core/src/main/java/com/sayemahmed/example/executor/MonitoredThreadPoolExecutor.java // static final String taskExecution = "task-execution"; // Path: java-core/src/main/java/com/sayemahmed/example/executor/MonitoredThreadPoolExecutor.java import com.codahale.metrics.Counter; import com.codahale.metrics.Gauge; import com.codahale.metrics.MetricRegistry; import com.codahale.metrics.Timer; import lombok.extern.slf4j.Slf4j; import java.util.concurrent.BlockingQueue; import java.util.concurrent.CancellationException; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.RejectedExecutionHandler; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import static com.sayemahmed.example.executor.MonitoredThreadPoolExecutor.MonitoringKey.activeThreads; import static com.sayemahmed.example.executor.MonitoredThreadPoolExecutor.MonitoringKey.failedTasks; import static com.sayemahmed.example.executor.MonitoredThreadPoolExecutor.MonitoringKey.maxPoolSize; import static com.sayemahmed.example.executor.MonitoredThreadPoolExecutor.MonitoringKey.queueSize; import static com.sayemahmed.example.executor.MonitoredThreadPoolExecutor.MonitoringKey.successfulTasks; import static com.sayemahmed.example.executor.MonitoredThreadPoolExecutor.MonitoringKey.taskExecution; this.metricRegistry = metricRegistry; this.metricsPrefix = MetricRegistry.name(getClass(), poolName); registerGauges(); } @Override protected void beforeExecute(Thread thread, Runnable task) { super.beforeExecute(thread, task); Timer timer = metricRegistry.timer(MetricRegistry.name(metricsPrefix, taskExecution)); taskExecutionTimer.set(timer.time()); } @Override protected void afterExecute(Runnable task, Throwable throwable) { Timer.Context context = taskExecutionTimer.get(); context.stop(); super.afterExecute(task, throwable); if (throwable == null && task instanceof Future<?> && ((Future<?>) task).isDone()) { try { ((Future<?>) task).get(); } catch (CancellationException ce) { throwable = ce; } catch (ExecutionException ee) { throwable = ee.getCause(); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); } } if (throwable != null) {
Counter failedTasksCounter = metricRegistry.counter(MetricRegistry.name(metricsPrefix, failedTasks));
sayembd/java-examples
java-core/src/main/java/com/sayemahmed/example/executor/MonitoredThreadPoolExecutor.java
// Path: java-core/src/main/java/com/sayemahmed/example/executor/MonitoredThreadPoolExecutor.java // static final String activeThreads = "activeThreads"; // // Path: java-core/src/main/java/com/sayemahmed/example/executor/MonitoredThreadPoolExecutor.java // static final String failedTasks = "failed-tasks"; // // Path: java-core/src/main/java/com/sayemahmed/example/executor/MonitoredThreadPoolExecutor.java // static final String maxPoolSize = "maxPoolSize"; // // Path: java-core/src/main/java/com/sayemahmed/example/executor/MonitoredThreadPoolExecutor.java // static final String queueSize = "queueSize"; // // Path: java-core/src/main/java/com/sayemahmed/example/executor/MonitoredThreadPoolExecutor.java // static final String successfulTasks = "successful-tasks"; // // Path: java-core/src/main/java/com/sayemahmed/example/executor/MonitoredThreadPoolExecutor.java // static final String taskExecution = "task-execution";
import com.codahale.metrics.Counter; import com.codahale.metrics.Gauge; import com.codahale.metrics.MetricRegistry; import com.codahale.metrics.Timer; import lombok.extern.slf4j.Slf4j; import java.util.concurrent.BlockingQueue; import java.util.concurrent.CancellationException; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.RejectedExecutionHandler; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import static com.sayemahmed.example.executor.MonitoredThreadPoolExecutor.MonitoringKey.activeThreads; import static com.sayemahmed.example.executor.MonitoredThreadPoolExecutor.MonitoringKey.failedTasks; import static com.sayemahmed.example.executor.MonitoredThreadPoolExecutor.MonitoringKey.maxPoolSize; import static com.sayemahmed.example.executor.MonitoredThreadPoolExecutor.MonitoringKey.queueSize; import static com.sayemahmed.example.executor.MonitoredThreadPoolExecutor.MonitoringKey.successfulTasks; import static com.sayemahmed.example.executor.MonitoredThreadPoolExecutor.MonitoringKey.taskExecution;
@Override protected void beforeExecute(Thread thread, Runnable task) { super.beforeExecute(thread, task); Timer timer = metricRegistry.timer(MetricRegistry.name(metricsPrefix, taskExecution)); taskExecutionTimer.set(timer.time()); } @Override protected void afterExecute(Runnable task, Throwable throwable) { Timer.Context context = taskExecutionTimer.get(); context.stop(); super.afterExecute(task, throwable); if (throwable == null && task instanceof Future<?> && ((Future<?>) task).isDone()) { try { ((Future<?>) task).get(); } catch (CancellationException ce) { throwable = ce; } catch (ExecutionException ee) { throwable = ee.getCause(); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); } } if (throwable != null) { Counter failedTasksCounter = metricRegistry.counter(MetricRegistry.name(metricsPrefix, failedTasks)); failedTasksCounter.inc(); } else { Counter successfulTasksCounter = metricRegistry.counter(
// Path: java-core/src/main/java/com/sayemahmed/example/executor/MonitoredThreadPoolExecutor.java // static final String activeThreads = "activeThreads"; // // Path: java-core/src/main/java/com/sayemahmed/example/executor/MonitoredThreadPoolExecutor.java // static final String failedTasks = "failed-tasks"; // // Path: java-core/src/main/java/com/sayemahmed/example/executor/MonitoredThreadPoolExecutor.java // static final String maxPoolSize = "maxPoolSize"; // // Path: java-core/src/main/java/com/sayemahmed/example/executor/MonitoredThreadPoolExecutor.java // static final String queueSize = "queueSize"; // // Path: java-core/src/main/java/com/sayemahmed/example/executor/MonitoredThreadPoolExecutor.java // static final String successfulTasks = "successful-tasks"; // // Path: java-core/src/main/java/com/sayemahmed/example/executor/MonitoredThreadPoolExecutor.java // static final String taskExecution = "task-execution"; // Path: java-core/src/main/java/com/sayemahmed/example/executor/MonitoredThreadPoolExecutor.java import com.codahale.metrics.Counter; import com.codahale.metrics.Gauge; import com.codahale.metrics.MetricRegistry; import com.codahale.metrics.Timer; import lombok.extern.slf4j.Slf4j; import java.util.concurrent.BlockingQueue; import java.util.concurrent.CancellationException; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.RejectedExecutionHandler; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import static com.sayemahmed.example.executor.MonitoredThreadPoolExecutor.MonitoringKey.activeThreads; import static com.sayemahmed.example.executor.MonitoredThreadPoolExecutor.MonitoringKey.failedTasks; import static com.sayemahmed.example.executor.MonitoredThreadPoolExecutor.MonitoringKey.maxPoolSize; import static com.sayemahmed.example.executor.MonitoredThreadPoolExecutor.MonitoringKey.queueSize; import static com.sayemahmed.example.executor.MonitoredThreadPoolExecutor.MonitoringKey.successfulTasks; import static com.sayemahmed.example.executor.MonitoredThreadPoolExecutor.MonitoringKey.taskExecution; @Override protected void beforeExecute(Thread thread, Runnable task) { super.beforeExecute(thread, task); Timer timer = metricRegistry.timer(MetricRegistry.name(metricsPrefix, taskExecution)); taskExecutionTimer.set(timer.time()); } @Override protected void afterExecute(Runnable task, Throwable throwable) { Timer.Context context = taskExecutionTimer.get(); context.stop(); super.afterExecute(task, throwable); if (throwable == null && task instanceof Future<?> && ((Future<?>) task).isDone()) { try { ((Future<?>) task).get(); } catch (CancellationException ce) { throwable = ce; } catch (ExecutionException ee) { throwable = ee.getCause(); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); } } if (throwable != null) { Counter failedTasksCounter = metricRegistry.counter(MetricRegistry.name(metricsPrefix, failedTasks)); failedTasksCounter.inc(); } else { Counter successfulTasksCounter = metricRegistry.counter(
MetricRegistry.name(metricsPrefix, successfulTasks));
sayembd/java-examples
java-core/src/main/java/com/sayemahmed/example/executor/MonitoredThreadPoolExecutor.java
// Path: java-core/src/main/java/com/sayemahmed/example/executor/MonitoredThreadPoolExecutor.java // static final String activeThreads = "activeThreads"; // // Path: java-core/src/main/java/com/sayemahmed/example/executor/MonitoredThreadPoolExecutor.java // static final String failedTasks = "failed-tasks"; // // Path: java-core/src/main/java/com/sayemahmed/example/executor/MonitoredThreadPoolExecutor.java // static final String maxPoolSize = "maxPoolSize"; // // Path: java-core/src/main/java/com/sayemahmed/example/executor/MonitoredThreadPoolExecutor.java // static final String queueSize = "queueSize"; // // Path: java-core/src/main/java/com/sayemahmed/example/executor/MonitoredThreadPoolExecutor.java // static final String successfulTasks = "successful-tasks"; // // Path: java-core/src/main/java/com/sayemahmed/example/executor/MonitoredThreadPoolExecutor.java // static final String taskExecution = "task-execution";
import com.codahale.metrics.Counter; import com.codahale.metrics.Gauge; import com.codahale.metrics.MetricRegistry; import com.codahale.metrics.Timer; import lombok.extern.slf4j.Slf4j; import java.util.concurrent.BlockingQueue; import java.util.concurrent.CancellationException; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.RejectedExecutionHandler; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import static com.sayemahmed.example.executor.MonitoredThreadPoolExecutor.MonitoringKey.activeThreads; import static com.sayemahmed.example.executor.MonitoredThreadPoolExecutor.MonitoringKey.failedTasks; import static com.sayemahmed.example.executor.MonitoredThreadPoolExecutor.MonitoringKey.maxPoolSize; import static com.sayemahmed.example.executor.MonitoredThreadPoolExecutor.MonitoringKey.queueSize; import static com.sayemahmed.example.executor.MonitoredThreadPoolExecutor.MonitoringKey.successfulTasks; import static com.sayemahmed.example.executor.MonitoredThreadPoolExecutor.MonitoringKey.taskExecution;
@Override protected void afterExecute(Runnable task, Throwable throwable) { Timer.Context context = taskExecutionTimer.get(); context.stop(); super.afterExecute(task, throwable); if (throwable == null && task instanceof Future<?> && ((Future<?>) task).isDone()) { try { ((Future<?>) task).get(); } catch (CancellationException ce) { throwable = ce; } catch (ExecutionException ee) { throwable = ee.getCause(); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); } } if (throwable != null) { Counter failedTasksCounter = metricRegistry.counter(MetricRegistry.name(metricsPrefix, failedTasks)); failedTasksCounter.inc(); } else { Counter successfulTasksCounter = metricRegistry.counter( MetricRegistry.name(metricsPrefix, successfulTasks)); successfulTasksCounter.inc(); } } private void registerGauges() { metricRegistry.register(MetricRegistry.name(metricsPrefix, MonitoringKey.corePoolSize), (Gauge<Integer>) this::getCorePoolSize);
// Path: java-core/src/main/java/com/sayemahmed/example/executor/MonitoredThreadPoolExecutor.java // static final String activeThreads = "activeThreads"; // // Path: java-core/src/main/java/com/sayemahmed/example/executor/MonitoredThreadPoolExecutor.java // static final String failedTasks = "failed-tasks"; // // Path: java-core/src/main/java/com/sayemahmed/example/executor/MonitoredThreadPoolExecutor.java // static final String maxPoolSize = "maxPoolSize"; // // Path: java-core/src/main/java/com/sayemahmed/example/executor/MonitoredThreadPoolExecutor.java // static final String queueSize = "queueSize"; // // Path: java-core/src/main/java/com/sayemahmed/example/executor/MonitoredThreadPoolExecutor.java // static final String successfulTasks = "successful-tasks"; // // Path: java-core/src/main/java/com/sayemahmed/example/executor/MonitoredThreadPoolExecutor.java // static final String taskExecution = "task-execution"; // Path: java-core/src/main/java/com/sayemahmed/example/executor/MonitoredThreadPoolExecutor.java import com.codahale.metrics.Counter; import com.codahale.metrics.Gauge; import com.codahale.metrics.MetricRegistry; import com.codahale.metrics.Timer; import lombok.extern.slf4j.Slf4j; import java.util.concurrent.BlockingQueue; import java.util.concurrent.CancellationException; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.RejectedExecutionHandler; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import static com.sayemahmed.example.executor.MonitoredThreadPoolExecutor.MonitoringKey.activeThreads; import static com.sayemahmed.example.executor.MonitoredThreadPoolExecutor.MonitoringKey.failedTasks; import static com.sayemahmed.example.executor.MonitoredThreadPoolExecutor.MonitoringKey.maxPoolSize; import static com.sayemahmed.example.executor.MonitoredThreadPoolExecutor.MonitoringKey.queueSize; import static com.sayemahmed.example.executor.MonitoredThreadPoolExecutor.MonitoringKey.successfulTasks; import static com.sayemahmed.example.executor.MonitoredThreadPoolExecutor.MonitoringKey.taskExecution; @Override protected void afterExecute(Runnable task, Throwable throwable) { Timer.Context context = taskExecutionTimer.get(); context.stop(); super.afterExecute(task, throwable); if (throwable == null && task instanceof Future<?> && ((Future<?>) task).isDone()) { try { ((Future<?>) task).get(); } catch (CancellationException ce) { throwable = ce; } catch (ExecutionException ee) { throwable = ee.getCause(); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); } } if (throwable != null) { Counter failedTasksCounter = metricRegistry.counter(MetricRegistry.name(metricsPrefix, failedTasks)); failedTasksCounter.inc(); } else { Counter successfulTasksCounter = metricRegistry.counter( MetricRegistry.name(metricsPrefix, successfulTasks)); successfulTasksCounter.inc(); } } private void registerGauges() { metricRegistry.register(MetricRegistry.name(metricsPrefix, MonitoringKey.corePoolSize), (Gauge<Integer>) this::getCorePoolSize);
metricRegistry.register(MetricRegistry.name(metricsPrefix, activeThreads),
sayembd/java-examples
java-core/src/main/java/com/sayemahmed/example/executor/MonitoredThreadPoolExecutor.java
// Path: java-core/src/main/java/com/sayemahmed/example/executor/MonitoredThreadPoolExecutor.java // static final String activeThreads = "activeThreads"; // // Path: java-core/src/main/java/com/sayemahmed/example/executor/MonitoredThreadPoolExecutor.java // static final String failedTasks = "failed-tasks"; // // Path: java-core/src/main/java/com/sayemahmed/example/executor/MonitoredThreadPoolExecutor.java // static final String maxPoolSize = "maxPoolSize"; // // Path: java-core/src/main/java/com/sayemahmed/example/executor/MonitoredThreadPoolExecutor.java // static final String queueSize = "queueSize"; // // Path: java-core/src/main/java/com/sayemahmed/example/executor/MonitoredThreadPoolExecutor.java // static final String successfulTasks = "successful-tasks"; // // Path: java-core/src/main/java/com/sayemahmed/example/executor/MonitoredThreadPoolExecutor.java // static final String taskExecution = "task-execution";
import com.codahale.metrics.Counter; import com.codahale.metrics.Gauge; import com.codahale.metrics.MetricRegistry; import com.codahale.metrics.Timer; import lombok.extern.slf4j.Slf4j; import java.util.concurrent.BlockingQueue; import java.util.concurrent.CancellationException; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.RejectedExecutionHandler; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import static com.sayemahmed.example.executor.MonitoredThreadPoolExecutor.MonitoringKey.activeThreads; import static com.sayemahmed.example.executor.MonitoredThreadPoolExecutor.MonitoringKey.failedTasks; import static com.sayemahmed.example.executor.MonitoredThreadPoolExecutor.MonitoringKey.maxPoolSize; import static com.sayemahmed.example.executor.MonitoredThreadPoolExecutor.MonitoringKey.queueSize; import static com.sayemahmed.example.executor.MonitoredThreadPoolExecutor.MonitoringKey.successfulTasks; import static com.sayemahmed.example.executor.MonitoredThreadPoolExecutor.MonitoringKey.taskExecution;
Timer.Context context = taskExecutionTimer.get(); context.stop(); super.afterExecute(task, throwable); if (throwable == null && task instanceof Future<?> && ((Future<?>) task).isDone()) { try { ((Future<?>) task).get(); } catch (CancellationException ce) { throwable = ce; } catch (ExecutionException ee) { throwable = ee.getCause(); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); } } if (throwable != null) { Counter failedTasksCounter = metricRegistry.counter(MetricRegistry.name(metricsPrefix, failedTasks)); failedTasksCounter.inc(); } else { Counter successfulTasksCounter = metricRegistry.counter( MetricRegistry.name(metricsPrefix, successfulTasks)); successfulTasksCounter.inc(); } } private void registerGauges() { metricRegistry.register(MetricRegistry.name(metricsPrefix, MonitoringKey.corePoolSize), (Gauge<Integer>) this::getCorePoolSize); metricRegistry.register(MetricRegistry.name(metricsPrefix, activeThreads), (Gauge<Integer>) this::getActiveCount);
// Path: java-core/src/main/java/com/sayemahmed/example/executor/MonitoredThreadPoolExecutor.java // static final String activeThreads = "activeThreads"; // // Path: java-core/src/main/java/com/sayemahmed/example/executor/MonitoredThreadPoolExecutor.java // static final String failedTasks = "failed-tasks"; // // Path: java-core/src/main/java/com/sayemahmed/example/executor/MonitoredThreadPoolExecutor.java // static final String maxPoolSize = "maxPoolSize"; // // Path: java-core/src/main/java/com/sayemahmed/example/executor/MonitoredThreadPoolExecutor.java // static final String queueSize = "queueSize"; // // Path: java-core/src/main/java/com/sayemahmed/example/executor/MonitoredThreadPoolExecutor.java // static final String successfulTasks = "successful-tasks"; // // Path: java-core/src/main/java/com/sayemahmed/example/executor/MonitoredThreadPoolExecutor.java // static final String taskExecution = "task-execution"; // Path: java-core/src/main/java/com/sayemahmed/example/executor/MonitoredThreadPoolExecutor.java import com.codahale.metrics.Counter; import com.codahale.metrics.Gauge; import com.codahale.metrics.MetricRegistry; import com.codahale.metrics.Timer; import lombok.extern.slf4j.Slf4j; import java.util.concurrent.BlockingQueue; import java.util.concurrent.CancellationException; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.RejectedExecutionHandler; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import static com.sayemahmed.example.executor.MonitoredThreadPoolExecutor.MonitoringKey.activeThreads; import static com.sayemahmed.example.executor.MonitoredThreadPoolExecutor.MonitoringKey.failedTasks; import static com.sayemahmed.example.executor.MonitoredThreadPoolExecutor.MonitoringKey.maxPoolSize; import static com.sayemahmed.example.executor.MonitoredThreadPoolExecutor.MonitoringKey.queueSize; import static com.sayemahmed.example.executor.MonitoredThreadPoolExecutor.MonitoringKey.successfulTasks; import static com.sayemahmed.example.executor.MonitoredThreadPoolExecutor.MonitoringKey.taskExecution; Timer.Context context = taskExecutionTimer.get(); context.stop(); super.afterExecute(task, throwable); if (throwable == null && task instanceof Future<?> && ((Future<?>) task).isDone()) { try { ((Future<?>) task).get(); } catch (CancellationException ce) { throwable = ce; } catch (ExecutionException ee) { throwable = ee.getCause(); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); } } if (throwable != null) { Counter failedTasksCounter = metricRegistry.counter(MetricRegistry.name(metricsPrefix, failedTasks)); failedTasksCounter.inc(); } else { Counter successfulTasksCounter = metricRegistry.counter( MetricRegistry.name(metricsPrefix, successfulTasks)); successfulTasksCounter.inc(); } } private void registerGauges() { metricRegistry.register(MetricRegistry.name(metricsPrefix, MonitoringKey.corePoolSize), (Gauge<Integer>) this::getCorePoolSize); metricRegistry.register(MetricRegistry.name(metricsPrefix, activeThreads), (Gauge<Integer>) this::getActiveCount);
metricRegistry.register(MetricRegistry.name(metricsPrefix, maxPoolSize),
sayembd/java-examples
java-core/src/main/java/com/sayemahmed/example/executor/MonitoredThreadPoolExecutor.java
// Path: java-core/src/main/java/com/sayemahmed/example/executor/MonitoredThreadPoolExecutor.java // static final String activeThreads = "activeThreads"; // // Path: java-core/src/main/java/com/sayemahmed/example/executor/MonitoredThreadPoolExecutor.java // static final String failedTasks = "failed-tasks"; // // Path: java-core/src/main/java/com/sayemahmed/example/executor/MonitoredThreadPoolExecutor.java // static final String maxPoolSize = "maxPoolSize"; // // Path: java-core/src/main/java/com/sayemahmed/example/executor/MonitoredThreadPoolExecutor.java // static final String queueSize = "queueSize"; // // Path: java-core/src/main/java/com/sayemahmed/example/executor/MonitoredThreadPoolExecutor.java // static final String successfulTasks = "successful-tasks"; // // Path: java-core/src/main/java/com/sayemahmed/example/executor/MonitoredThreadPoolExecutor.java // static final String taskExecution = "task-execution";
import com.codahale.metrics.Counter; import com.codahale.metrics.Gauge; import com.codahale.metrics.MetricRegistry; import com.codahale.metrics.Timer; import lombok.extern.slf4j.Slf4j; import java.util.concurrent.BlockingQueue; import java.util.concurrent.CancellationException; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.RejectedExecutionHandler; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import static com.sayemahmed.example.executor.MonitoredThreadPoolExecutor.MonitoringKey.activeThreads; import static com.sayemahmed.example.executor.MonitoredThreadPoolExecutor.MonitoringKey.failedTasks; import static com.sayemahmed.example.executor.MonitoredThreadPoolExecutor.MonitoringKey.maxPoolSize; import static com.sayemahmed.example.executor.MonitoredThreadPoolExecutor.MonitoringKey.queueSize; import static com.sayemahmed.example.executor.MonitoredThreadPoolExecutor.MonitoringKey.successfulTasks; import static com.sayemahmed.example.executor.MonitoredThreadPoolExecutor.MonitoringKey.taskExecution;
super.afterExecute(task, throwable); if (throwable == null && task instanceof Future<?> && ((Future<?>) task).isDone()) { try { ((Future<?>) task).get(); } catch (CancellationException ce) { throwable = ce; } catch (ExecutionException ee) { throwable = ee.getCause(); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); } } if (throwable != null) { Counter failedTasksCounter = metricRegistry.counter(MetricRegistry.name(metricsPrefix, failedTasks)); failedTasksCounter.inc(); } else { Counter successfulTasksCounter = metricRegistry.counter( MetricRegistry.name(metricsPrefix, successfulTasks)); successfulTasksCounter.inc(); } } private void registerGauges() { metricRegistry.register(MetricRegistry.name(metricsPrefix, MonitoringKey.corePoolSize), (Gauge<Integer>) this::getCorePoolSize); metricRegistry.register(MetricRegistry.name(metricsPrefix, activeThreads), (Gauge<Integer>) this::getActiveCount); metricRegistry.register(MetricRegistry.name(metricsPrefix, maxPoolSize), (Gauge<Integer>) this::getMaximumPoolSize);
// Path: java-core/src/main/java/com/sayemahmed/example/executor/MonitoredThreadPoolExecutor.java // static final String activeThreads = "activeThreads"; // // Path: java-core/src/main/java/com/sayemahmed/example/executor/MonitoredThreadPoolExecutor.java // static final String failedTasks = "failed-tasks"; // // Path: java-core/src/main/java/com/sayemahmed/example/executor/MonitoredThreadPoolExecutor.java // static final String maxPoolSize = "maxPoolSize"; // // Path: java-core/src/main/java/com/sayemahmed/example/executor/MonitoredThreadPoolExecutor.java // static final String queueSize = "queueSize"; // // Path: java-core/src/main/java/com/sayemahmed/example/executor/MonitoredThreadPoolExecutor.java // static final String successfulTasks = "successful-tasks"; // // Path: java-core/src/main/java/com/sayemahmed/example/executor/MonitoredThreadPoolExecutor.java // static final String taskExecution = "task-execution"; // Path: java-core/src/main/java/com/sayemahmed/example/executor/MonitoredThreadPoolExecutor.java import com.codahale.metrics.Counter; import com.codahale.metrics.Gauge; import com.codahale.metrics.MetricRegistry; import com.codahale.metrics.Timer; import lombok.extern.slf4j.Slf4j; import java.util.concurrent.BlockingQueue; import java.util.concurrent.CancellationException; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.RejectedExecutionHandler; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import static com.sayemahmed.example.executor.MonitoredThreadPoolExecutor.MonitoringKey.activeThreads; import static com.sayemahmed.example.executor.MonitoredThreadPoolExecutor.MonitoringKey.failedTasks; import static com.sayemahmed.example.executor.MonitoredThreadPoolExecutor.MonitoringKey.maxPoolSize; import static com.sayemahmed.example.executor.MonitoredThreadPoolExecutor.MonitoringKey.queueSize; import static com.sayemahmed.example.executor.MonitoredThreadPoolExecutor.MonitoringKey.successfulTasks; import static com.sayemahmed.example.executor.MonitoredThreadPoolExecutor.MonitoringKey.taskExecution; super.afterExecute(task, throwable); if (throwable == null && task instanceof Future<?> && ((Future<?>) task).isDone()) { try { ((Future<?>) task).get(); } catch (CancellationException ce) { throwable = ce; } catch (ExecutionException ee) { throwable = ee.getCause(); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); } } if (throwable != null) { Counter failedTasksCounter = metricRegistry.counter(MetricRegistry.name(metricsPrefix, failedTasks)); failedTasksCounter.inc(); } else { Counter successfulTasksCounter = metricRegistry.counter( MetricRegistry.name(metricsPrefix, successfulTasks)); successfulTasksCounter.inc(); } } private void registerGauges() { metricRegistry.register(MetricRegistry.name(metricsPrefix, MonitoringKey.corePoolSize), (Gauge<Integer>) this::getCorePoolSize); metricRegistry.register(MetricRegistry.name(metricsPrefix, activeThreads), (Gauge<Integer>) this::getActiveCount); metricRegistry.register(MetricRegistry.name(metricsPrefix, maxPoolSize), (Gauge<Integer>) this::getMaximumPoolSize);
metricRegistry.register(MetricRegistry.name(metricsPrefix, queueSize),
sayembd/java-examples
java-core/src/test/java/com/sayemahmed/example/validation/rule/PriceValidatorTest.java
// Path: java-core/src/main/java/com/sayemahmed/example/validation/OrderDTO.java // @Getter // @Setter // @ToString // public class OrderDTO { // // @NotNull // private String customerId; // // @NotNull // @Size(min = 1) // private List<OrderItem> orderItems; // // @Getter // @Setter // @ToString // public static class OrderItem { // private String menuId; // private String description; // private String price; // private Integer quantity; // } // }
import com.sayemahmed.example.validation.OrderDTO; import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test;
/* * Copyright 2017 MD Sayem Ahmed * * 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.sayemahmed.example.validation.rule; public class PriceValidatorTest { @Test public void validate_priceNull_invalid() { PriceValidator validator = new PriceValidator();
// Path: java-core/src/main/java/com/sayemahmed/example/validation/OrderDTO.java // @Getter // @Setter // @ToString // public class OrderDTO { // // @NotNull // private String customerId; // // @NotNull // @Size(min = 1) // private List<OrderItem> orderItems; // // @Getter // @Setter // @ToString // public static class OrderItem { // private String menuId; // private String description; // private String price; // private Integer quantity; // } // } // Path: java-core/src/test/java/com/sayemahmed/example/validation/rule/PriceValidatorTest.java import com.sayemahmed.example.validation.OrderDTO; import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; /* * Copyright 2017 MD Sayem Ahmed * * 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.sayemahmed.example.validation.rule; public class PriceValidatorTest { @Test public void validate_priceNull_invalid() { PriceValidator validator = new PriceValidator();
ErrorNotification errorNotification = validator.validate(new OrderDTO.OrderItem());
sayembd/java-examples
java-core/src/main/java/com/sayemahmed/example/validation/rule/PriceValidator.java
// Path: java-core/src/main/java/com/sayemahmed/example/validation/OrderDTO.java // @Getter // @Setter // @ToString // public class OrderDTO { // // @NotNull // private String customerId; // // @NotNull // @Size(min = 1) // private List<OrderItem> orderItems; // // @Getter // @Setter // @ToString // public static class OrderItem { // private String menuId; // private String description; // private String price; // private Integer quantity; // } // }
import com.sayemahmed.example.validation.OrderDTO; import java.math.BigDecimal; import java.util.Optional; import java.util.function.Consumer;
/* * Copyright 2017 MD Sayem Ahmed * * 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.sayemahmed.example.validation.rule; class PriceValidator implements OrderItemValidator { static final String PRICE_EMPTY_ERROR = "Price cannot be empty."; static final String PRICE_INVALID_ERROR_FORMAT = "Given price [%s] is not in valid format"; @Override
// Path: java-core/src/main/java/com/sayemahmed/example/validation/OrderDTO.java // @Getter // @Setter // @ToString // public class OrderDTO { // // @NotNull // private String customerId; // // @NotNull // @Size(min = 1) // private List<OrderItem> orderItems; // // @Getter // @Setter // @ToString // public static class OrderItem { // private String menuId; // private String description; // private String price; // private Integer quantity; // } // } // Path: java-core/src/main/java/com/sayemahmed/example/validation/rule/PriceValidator.java import com.sayemahmed.example.validation.OrderDTO; import java.math.BigDecimal; import java.util.Optional; import java.util.function.Consumer; /* * Copyright 2017 MD Sayem Ahmed * * 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.sayemahmed.example.validation.rule; class PriceValidator implements OrderItemValidator { static final String PRICE_EMPTY_ERROR = "Price cannot be empty."; static final String PRICE_INVALID_ERROR_FORMAT = "Given price [%s] is not in valid format"; @Override
public ErrorNotification validate(OrderDTO.OrderItem orderItem) {
sayembd/java-examples
executable-specification-example/src/test/java/com/sayemahmed/example/executablespecification/AddNewAccountServiceTest.java
// Path: executable-specification-example/src/main/java/com/sayemahmed/example/executablespecification/AddNewAccountService.java // @Builder // @Getter // static class AddNewAccountCommand { // private final String userId; // private final String accountName; // private final String initialBalance; // }
import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import com.sayemahmed.example.executablespecification.AddNewAccountService.AddNewAccountCommand; import java.math.BigDecimal; import org.assertj.core.api.BDDAssertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; import org.mockito.BDDMockito; import org.mockito.Captor;
/* * Copyright 2020 MD Sayem Ahmed * * 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.sayemahmed.example.executablespecification; @ExtendWith(MockitoExtension.class) class AddNewAccountServiceTest { @Mock private SaveAccountPort saveAccountPort; @Mock private FindAccountPort findAccountPort; @Nested @DisplayName("Given account does not exist") class AccountDoesNotExist { private AddNewAccountService accountService; @BeforeEach void setUp() { accountService = new AddNewAccountService(saveAccountPort, findAccountPort); } @Nested @DisplayName("When user adds a new account") class WhenUserAddsANewAccount { private static final String ACCOUNT_NAME = "test account"; private static final String INITIAL_BALANCE = "56.0"; private static final String USER_ID = "some id"; private Account savedAccount; @Captor private ArgumentCaptor<Account> accountArgumentCaptor; @BeforeEach void setUp() {
// Path: executable-specification-example/src/main/java/com/sayemahmed/example/executablespecification/AddNewAccountService.java // @Builder // @Getter // static class AddNewAccountCommand { // private final String userId; // private final String accountName; // private final String initialBalance; // } // Path: executable-specification-example/src/test/java/com/sayemahmed/example/executablespecification/AddNewAccountServiceTest.java import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import com.sayemahmed.example.executablespecification.AddNewAccountService.AddNewAccountCommand; import java.math.BigDecimal; import org.assertj.core.api.BDDAssertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; import org.mockito.BDDMockito; import org.mockito.Captor; /* * Copyright 2020 MD Sayem Ahmed * * 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.sayemahmed.example.executablespecification; @ExtendWith(MockitoExtension.class) class AddNewAccountServiceTest { @Mock private SaveAccountPort saveAccountPort; @Mock private FindAccountPort findAccountPort; @Nested @DisplayName("Given account does not exist") class AccountDoesNotExist { private AddNewAccountService accountService; @BeforeEach void setUp() { accountService = new AddNewAccountService(saveAccountPort, findAccountPort); } @Nested @DisplayName("When user adds a new account") class WhenUserAddsANewAccount { private static final String ACCOUNT_NAME = "test account"; private static final String INITIAL_BALANCE = "56.0"; private static final String USER_ID = "some id"; private Account savedAccount; @Captor private ArgumentCaptor<Account> accountArgumentCaptor; @BeforeEach void setUp() {
AddNewAccountCommand command = AddNewAccountCommand.builder()
sayembd/java-examples
java-core/src/main/java/com/sayemahmed/example/validation/rule/ValidatorConfiguration.java
// Path: java-core/src/main/java/com/sayemahmed/example/validation/MenuRepository.java // @Repository // @Slf4j // public class MenuRepository { // // public boolean menuExists(String menuId) { // log.info("Menu id {}.", menuId); // return true; // } // }
import com.sayemahmed.example.validation.MenuRepository; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.util.Arrays;
/* * Copyright 2017 MD Sayem Ahmed * * 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.sayemahmed.example.validation.rule; @Configuration class ValidatorConfiguration { @Bean
// Path: java-core/src/main/java/com/sayemahmed/example/validation/MenuRepository.java // @Repository // @Slf4j // public class MenuRepository { // // public boolean menuExists(String menuId) { // log.info("Menu id {}.", menuId); // return true; // } // } // Path: java-core/src/main/java/com/sayemahmed/example/validation/rule/ValidatorConfiguration.java import com.sayemahmed.example.validation.MenuRepository; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.util.Arrays; /* * Copyright 2017 MD Sayem Ahmed * * 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.sayemahmed.example.validation.rule; @Configuration class ValidatorConfiguration { @Bean
OrderItemValidator orderItemValidator(MenuRepository menuRepository) {
sayembd/java-examples
java-core/src/main/java/com/sayemahmed/example/validation/rule/MenuValidator.java
// Path: java-core/src/main/java/com/sayemahmed/example/validation/MenuRepository.java // @Repository // @Slf4j // public class MenuRepository { // // public boolean menuExists(String menuId) { // log.info("Menu id {}.", menuId); // return true; // } // } // // Path: java-core/src/main/java/com/sayemahmed/example/validation/OrderDTO.java // @Getter // @Setter // @ToString // public static class OrderItem { // private String menuId; // private String description; // private String price; // private Integer quantity; // }
import com.sayemahmed.example.validation.MenuRepository; import com.sayemahmed.example.validation.OrderDTO.OrderItem; import java.util.Optional; import java.util.function.Consumer; import lombok.RequiredArgsConstructor;
/* * Copyright 2017 MD Sayem Ahmed * * 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.sayemahmed.example.validation.rule; @RequiredArgsConstructor class MenuValidator implements OrderItemValidator {
// Path: java-core/src/main/java/com/sayemahmed/example/validation/MenuRepository.java // @Repository // @Slf4j // public class MenuRepository { // // public boolean menuExists(String menuId) { // log.info("Menu id {}.", menuId); // return true; // } // } // // Path: java-core/src/main/java/com/sayemahmed/example/validation/OrderDTO.java // @Getter // @Setter // @ToString // public static class OrderItem { // private String menuId; // private String description; // private String price; // private Integer quantity; // } // Path: java-core/src/main/java/com/sayemahmed/example/validation/rule/MenuValidator.java import com.sayemahmed.example.validation.MenuRepository; import com.sayemahmed.example.validation.OrderDTO.OrderItem; import java.util.Optional; import java.util.function.Consumer; import lombok.RequiredArgsConstructor; /* * Copyright 2017 MD Sayem Ahmed * * 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.sayemahmed.example.validation.rule; @RequiredArgsConstructor class MenuValidator implements OrderItemValidator {
private final MenuRepository menuRepository;
sayembd/java-examples
java-core/src/main/java/com/sayemahmed/example/validation/rule/MenuValidator.java
// Path: java-core/src/main/java/com/sayemahmed/example/validation/MenuRepository.java // @Repository // @Slf4j // public class MenuRepository { // // public boolean menuExists(String menuId) { // log.info("Menu id {}.", menuId); // return true; // } // } // // Path: java-core/src/main/java/com/sayemahmed/example/validation/OrderDTO.java // @Getter // @Setter // @ToString // public static class OrderItem { // private String menuId; // private String description; // private String price; // private Integer quantity; // }
import com.sayemahmed.example.validation.MenuRepository; import com.sayemahmed.example.validation.OrderDTO.OrderItem; import java.util.Optional; import java.util.function.Consumer; import lombok.RequiredArgsConstructor;
/* * Copyright 2017 MD Sayem Ahmed * * 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.sayemahmed.example.validation.rule; @RequiredArgsConstructor class MenuValidator implements OrderItemValidator { private final MenuRepository menuRepository; static final String MISSING_MENU_ERROR = "A menu item must be specified."; static final String INVALID_MENU_ERROR_FORMAT = "Given menu [%s] does not exist."; @Override
// Path: java-core/src/main/java/com/sayemahmed/example/validation/MenuRepository.java // @Repository // @Slf4j // public class MenuRepository { // // public boolean menuExists(String menuId) { // log.info("Menu id {}.", menuId); // return true; // } // } // // Path: java-core/src/main/java/com/sayemahmed/example/validation/OrderDTO.java // @Getter // @Setter // @ToString // public static class OrderItem { // private String menuId; // private String description; // private String price; // private Integer quantity; // } // Path: java-core/src/main/java/com/sayemahmed/example/validation/rule/MenuValidator.java import com.sayemahmed.example.validation.MenuRepository; import com.sayemahmed.example.validation.OrderDTO.OrderItem; import java.util.Optional; import java.util.function.Consumer; import lombok.RequiredArgsConstructor; /* * Copyright 2017 MD Sayem Ahmed * * 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.sayemahmed.example.validation.rule; @RequiredArgsConstructor class MenuValidator implements OrderItemValidator { private final MenuRepository menuRepository; static final String MISSING_MENU_ERROR = "A menu item must be specified."; static final String INVALID_MENU_ERROR_FORMAT = "Given menu [%s] does not exist."; @Override
public ErrorNotification validate(OrderItem orderItem) {
sayembd/java-examples
java-core/src/main/java/com/sayemahmed/example/validation/rule/QuantityValidator.java
// Path: java-core/src/main/java/com/sayemahmed/example/validation/OrderDTO.java // @Getter // @Setter // @ToString // public class OrderDTO { // // @NotNull // private String customerId; // // @NotNull // @Size(min = 1) // private List<OrderItem> orderItems; // // @Getter // @Setter // @ToString // public static class OrderItem { // private String menuId; // private String description; // private String price; // private Integer quantity; // } // }
import com.sayemahmed.example.validation.OrderDTO; import java.util.Optional; import java.util.function.Consumer;
/* * Copyright 2017 MD Sayem Ahmed * * 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.sayemahmed.example.validation.rule; class QuantityValidator implements OrderItemValidator { static final String MISSING_QUANTITY_ERROR = "Quantity must be given"; static final String INVALID_QUANTITY_ERROR = "Given quantity %s is not valid."; @Override
// Path: java-core/src/main/java/com/sayemahmed/example/validation/OrderDTO.java // @Getter // @Setter // @ToString // public class OrderDTO { // // @NotNull // private String customerId; // // @NotNull // @Size(min = 1) // private List<OrderItem> orderItems; // // @Getter // @Setter // @ToString // public static class OrderItem { // private String menuId; // private String description; // private String price; // private Integer quantity; // } // } // Path: java-core/src/main/java/com/sayemahmed/example/validation/rule/QuantityValidator.java import com.sayemahmed.example.validation.OrderDTO; import java.util.Optional; import java.util.function.Consumer; /* * Copyright 2017 MD Sayem Ahmed * * 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.sayemahmed.example.validation.rule; class QuantityValidator implements OrderItemValidator { static final String MISSING_QUANTITY_ERROR = "Quantity must be given"; static final String INVALID_QUANTITY_ERROR = "Given quantity %s is not valid."; @Override
public ErrorNotification validate(OrderDTO.OrderItem orderItem) {
sayembd/java-examples
java-core/src/test/java/com/sayemahmed/example/validation/rule/MenuValidatorTest.java
// Path: java-core/src/main/java/com/sayemahmed/example/validation/MenuRepository.java // @Repository // @Slf4j // public class MenuRepository { // // public boolean menuExists(String menuId) { // log.info("Menu id {}.", menuId); // return true; // } // } // // Path: java-core/src/main/java/com/sayemahmed/example/validation/OrderDTO.java // @Getter // @Setter // @ToString // public class OrderDTO { // // @NotNull // private String customerId; // // @NotNull // @Size(min = 1) // private List<OrderItem> orderItems; // // @Getter // @Setter // @ToString // public static class OrderItem { // private String menuId; // private String description; // private String price; // private Integer quantity; // } // }
import com.sayemahmed.example.validation.MenuRepository; import com.sayemahmed.example.validation.OrderDTO; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import org.junit.Test;
/* * Copyright 2017 MD Sayem Ahmed * * 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.sayemahmed.example.validation.rule; public class MenuValidatorTest { @Test public void validate_menuIdInvalid_invalid() {
// Path: java-core/src/main/java/com/sayemahmed/example/validation/MenuRepository.java // @Repository // @Slf4j // public class MenuRepository { // // public boolean menuExists(String menuId) { // log.info("Menu id {}.", menuId); // return true; // } // } // // Path: java-core/src/main/java/com/sayemahmed/example/validation/OrderDTO.java // @Getter // @Setter // @ToString // public class OrderDTO { // // @NotNull // private String customerId; // // @NotNull // @Size(min = 1) // private List<OrderItem> orderItems; // // @Getter // @Setter // @ToString // public static class OrderItem { // private String menuId; // private String description; // private String price; // private Integer quantity; // } // } // Path: java-core/src/test/java/com/sayemahmed/example/validation/rule/MenuValidatorTest.java import com.sayemahmed.example.validation.MenuRepository; import com.sayemahmed.example.validation.OrderDTO; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import org.junit.Test; /* * Copyright 2017 MD Sayem Ahmed * * 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.sayemahmed.example.validation.rule; public class MenuValidatorTest { @Test public void validate_menuIdInvalid_invalid() {
OrderDTO.OrderItem orderItem = new OrderDTO.OrderItem();
sayembd/java-examples
java-core/src/test/java/com/sayemahmed/example/validation/rule/MenuValidatorTest.java
// Path: java-core/src/main/java/com/sayemahmed/example/validation/MenuRepository.java // @Repository // @Slf4j // public class MenuRepository { // // public boolean menuExists(String menuId) { // log.info("Menu id {}.", menuId); // return true; // } // } // // Path: java-core/src/main/java/com/sayemahmed/example/validation/OrderDTO.java // @Getter // @Setter // @ToString // public class OrderDTO { // // @NotNull // private String customerId; // // @NotNull // @Size(min = 1) // private List<OrderItem> orderItems; // // @Getter // @Setter // @ToString // public static class OrderItem { // private String menuId; // private String description; // private String price; // private Integer quantity; // } // }
import com.sayemahmed.example.validation.MenuRepository; import com.sayemahmed.example.validation.OrderDTO; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import org.junit.Test;
/* * Copyright 2017 MD Sayem Ahmed * * 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.sayemahmed.example.validation.rule; public class MenuValidatorTest { @Test public void validate_menuIdInvalid_invalid() { OrderDTO.OrderItem orderItem = new OrderDTO.OrderItem(); String menuId = "some menu id"; orderItem.setMenuId(menuId);
// Path: java-core/src/main/java/com/sayemahmed/example/validation/MenuRepository.java // @Repository // @Slf4j // public class MenuRepository { // // public boolean menuExists(String menuId) { // log.info("Menu id {}.", menuId); // return true; // } // } // // Path: java-core/src/main/java/com/sayemahmed/example/validation/OrderDTO.java // @Getter // @Setter // @ToString // public class OrderDTO { // // @NotNull // private String customerId; // // @NotNull // @Size(min = 1) // private List<OrderItem> orderItems; // // @Getter // @Setter // @ToString // public static class OrderItem { // private String menuId; // private String description; // private String price; // private Integer quantity; // } // } // Path: java-core/src/test/java/com/sayemahmed/example/validation/rule/MenuValidatorTest.java import com.sayemahmed.example.validation.MenuRepository; import com.sayemahmed.example.validation.OrderDTO; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import org.junit.Test; /* * Copyright 2017 MD Sayem Ahmed * * 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.sayemahmed.example.validation.rule; public class MenuValidatorTest { @Test public void validate_menuIdInvalid_invalid() { OrderDTO.OrderItem orderItem = new OrderDTO.OrderItem(); String menuId = "some menu id"; orderItem.setMenuId(menuId);
MenuRepository menuRepository = mock(MenuRepository.class);
sayembd/java-examples
java-core/src/test/java/com/sayemahmed/example/validation/rule/ItemDescriptionValidatorTest.java
// Path: java-core/src/main/java/com/sayemahmed/example/validation/OrderDTO.java // @Getter // @Setter // @ToString // public class OrderDTO { // // @NotNull // private String customerId; // // @NotNull // @Size(min = 1) // private List<OrderItem> orderItems; // // @Getter // @Setter // @ToString // public static class OrderItem { // private String menuId; // private String description; // private String price; // private Integer quantity; // } // }
import com.sayemahmed.example.validation.OrderDTO; import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test;
/* * Copyright 2017 MD Sayem Ahmed * * 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.sayemahmed.example.validation.rule; public class ItemDescriptionValidatorTest { @Test public void validate_descriptionIsNull_invalid() { ItemDescriptionValidator validator = new ItemDescriptionValidator();
// Path: java-core/src/main/java/com/sayemahmed/example/validation/OrderDTO.java // @Getter // @Setter // @ToString // public class OrderDTO { // // @NotNull // private String customerId; // // @NotNull // @Size(min = 1) // private List<OrderItem> orderItems; // // @Getter // @Setter // @ToString // public static class OrderItem { // private String menuId; // private String description; // private String price; // private Integer quantity; // } // } // Path: java-core/src/test/java/com/sayemahmed/example/validation/rule/ItemDescriptionValidatorTest.java import com.sayemahmed.example.validation.OrderDTO; import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; /* * Copyright 2017 MD Sayem Ahmed * * 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.sayemahmed.example.validation.rule; public class ItemDescriptionValidatorTest { @Test public void validate_descriptionIsNull_invalid() { ItemDescriptionValidator validator = new ItemDescriptionValidator();
ErrorNotification errorNotification = validator.validate(new OrderDTO.OrderItem());
zhengshuheng/PatatiumAppUi
src/main/java/org/webdriver/patatiumappui/utils/TestBaseCase.java
// Path: src/main/java/org/webdriver/patatiumappui/utils/Log.java // public class Log // { // private final Class<?> clazz; // private Logger logger; // /** // * // * @param clazz 获取当前类 // */ // public Log(Class<?> clazz) // { // this.clazz=clazz; // //Logger.getLogger的方法是调用的是LogManager.getLogger()方法,所以这两个方法都是返回logger // this.logger=Logger.getLogger(this.clazz); // Log.initlog4j(); // // } // //初始化log4j,设置log4j的配置文件log4j.Properties // private static void initlog4j() // { // //创建Propderties对象 // Properties prop=new Properties(); // /*Log4j建议只使用四个级别,优先级从高到低分别是ERROR、WARN、INFO、DEBUG // 这里定义能显示到的最低级别,若定义到INFO级别,则看不到DEBUG级别的信息了~!级别后面是输出端*/ // prop.setProperty("log4j.rootLogger", "INFO,CONSOLE,E,F"); // prop.setProperty("log4j.appender.CONSOLE", "org.apache.log4j.ConsoleAppender"); // prop.setProperty("log4j.appender.CONSOLE.layout", "org.apache.log4j.PatternLayout"); // prop.setProperty("log4j.appender.CONSOLE.layout.ConversionPattern", "[%d{YYYY-MM-dd HH:mm:ss,SSS}] %-5p %c %m%n"); // // String src="test-output/log"; // //设置日期格式 // SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd"); // //获取当前日期 // String date=dateFormat.format(new Date()).toString(); // // File dir = new File(src+"/"+date); // if (!dir.exists()) // {dir.mkdirs();} // String filepath=dir.getAbsolutePath()+"/"+"log_"+date+".log"; // // prop.setProperty("log4j.appender.E","org.apache.log4j.FileAppender"); // prop.setProperty("log4j.appender.E.file",filepath); // prop.setProperty("log4j.appender.E.layout","org.apache.log4j.PatternLayout"); // prop.setProperty("log4j.appender.E.layout.ConversionPattern", "[%d{YYYY-MM-dd HH:mm:ss,SSS}] %-5p %c %m%n"); // // prop.setProperty("log4j.appender.F","org.apache.log4j.FileAppender"); // //String src="test-output/log"; // //设置日期格式 // //SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd"); // //获取当前日期 // //String date=dateFormat.format(new Date()).toString(); // //设置时间格式 // //SimpleDateFormat timeFormat=new SimpleDateFormat("yyyy-MM-dd HHmmss"); // //获取当前时间 // //String time=timeFormat.format(new Date()).toString(); // //File dir = new File(src+"/"+date); // // if (!dir.exists()) // // {dir.mkdirs();} // String filepathHtml=dir.getAbsolutePath()+"/"+"log_"+date+".html"; // prop.setProperty("log4j.appender.F.file",filepathHtml); // prop.setProperty("log4j.appender.F.layout","org.apache.log4j.HTMLLayout"); // //prop.setProperty("log4j.appender.F.layout.ConversionPattern", "[%d{YYYY-MM-dd HH:mm:ss,SSS}] %-5p %c %m%n"); // // PropertyConfigurator.configure(prop); // } // public void info(String message) // { // logger.info(message); // } // public void warn(String message) // { // logger.warn(message); // } // public void error(String message) // { // logger.error(message); // } // public void debug(String message) // { // logger.debug(message); // } // // }
import org.testng.annotations.*; import org.webdriver.patatiumappui.utils.Log; import org.openqa.selenium.Platform; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.firefox.FirefoxProfile; import org.openqa.selenium.htmlunit.HtmlUnitDriver; import org.openqa.selenium.ie.InternetExplorerDriver; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.remote.RemoteWebDriver; import io.appium.java_client.MobileElement; import io.appium.java_client.android.AndroidDriver; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.concurrent.TimeUnit;
package org.webdriver.patatiumappui.utils; public class TestBaseCase { public static AndroidDriver driver; //方法描述 public static String description;
// Path: src/main/java/org/webdriver/patatiumappui/utils/Log.java // public class Log // { // private final Class<?> clazz; // private Logger logger; // /** // * // * @param clazz 获取当前类 // */ // public Log(Class<?> clazz) // { // this.clazz=clazz; // //Logger.getLogger的方法是调用的是LogManager.getLogger()方法,所以这两个方法都是返回logger // this.logger=Logger.getLogger(this.clazz); // Log.initlog4j(); // // } // //初始化log4j,设置log4j的配置文件log4j.Properties // private static void initlog4j() // { // //创建Propderties对象 // Properties prop=new Properties(); // /*Log4j建议只使用四个级别,优先级从高到低分别是ERROR、WARN、INFO、DEBUG // 这里定义能显示到的最低级别,若定义到INFO级别,则看不到DEBUG级别的信息了~!级别后面是输出端*/ // prop.setProperty("log4j.rootLogger", "INFO,CONSOLE,E,F"); // prop.setProperty("log4j.appender.CONSOLE", "org.apache.log4j.ConsoleAppender"); // prop.setProperty("log4j.appender.CONSOLE.layout", "org.apache.log4j.PatternLayout"); // prop.setProperty("log4j.appender.CONSOLE.layout.ConversionPattern", "[%d{YYYY-MM-dd HH:mm:ss,SSS}] %-5p %c %m%n"); // // String src="test-output/log"; // //设置日期格式 // SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd"); // //获取当前日期 // String date=dateFormat.format(new Date()).toString(); // // File dir = new File(src+"/"+date); // if (!dir.exists()) // {dir.mkdirs();} // String filepath=dir.getAbsolutePath()+"/"+"log_"+date+".log"; // // prop.setProperty("log4j.appender.E","org.apache.log4j.FileAppender"); // prop.setProperty("log4j.appender.E.file",filepath); // prop.setProperty("log4j.appender.E.layout","org.apache.log4j.PatternLayout"); // prop.setProperty("log4j.appender.E.layout.ConversionPattern", "[%d{YYYY-MM-dd HH:mm:ss,SSS}] %-5p %c %m%n"); // // prop.setProperty("log4j.appender.F","org.apache.log4j.FileAppender"); // //String src="test-output/log"; // //设置日期格式 // //SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd"); // //获取当前日期 // //String date=dateFormat.format(new Date()).toString(); // //设置时间格式 // //SimpleDateFormat timeFormat=new SimpleDateFormat("yyyy-MM-dd HHmmss"); // //获取当前时间 // //String time=timeFormat.format(new Date()).toString(); // //File dir = new File(src+"/"+date); // // if (!dir.exists()) // // {dir.mkdirs();} // String filepathHtml=dir.getAbsolutePath()+"/"+"log_"+date+".html"; // prop.setProperty("log4j.appender.F.file",filepathHtml); // prop.setProperty("log4j.appender.F.layout","org.apache.log4j.HTMLLayout"); // //prop.setProperty("log4j.appender.F.layout.ConversionPattern", "[%d{YYYY-MM-dd HH:mm:ss,SSS}] %-5p %c %m%n"); // // PropertyConfigurator.configure(prop); // } // public void info(String message) // { // logger.info(message); // } // public void warn(String message) // { // logger.warn(message); // } // public void error(String message) // { // logger.error(message); // } // public void debug(String message) // { // logger.debug(message); // } // // } // Path: src/main/java/org/webdriver/patatiumappui/utils/TestBaseCase.java import org.testng.annotations.*; import org.webdriver.patatiumappui.utils.Log; import org.openqa.selenium.Platform; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.firefox.FirefoxProfile; import org.openqa.selenium.htmlunit.HtmlUnitDriver; import org.openqa.selenium.ie.InternetExplorerDriver; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.remote.RemoteWebDriver; import io.appium.java_client.MobileElement; import io.appium.java_client.android.AndroidDriver; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.concurrent.TimeUnit; package org.webdriver.patatiumappui.utils; public class TestBaseCase { public static AndroidDriver driver; //方法描述 public static String description;
public Log log=new Log(this.getClass().getSuperclass());
zhengshuheng/PatatiumAppUi
src/test/java/LoginTest.java
// Path: src/main/java/org/webdriver/patatiumappui/action/LoginAction.java // public class LoginAction extends TestBaseCase { // public LoginAction(String username,String password) throws IOException { // ElementAction action=new ElementAction(); // LoginPage loginPage=new LoginPage(); // action.click(loginPage.账号输入框()); // action.clear(loginPage.账号输入框()); // action.type(loginPage.账号输入框(),username); // action.click(loginPage.密码输入框()); // action.clear(loginPage.密码输入框()); // action.type(loginPage.密码输入框(),password); // action.sleep(1); // action.click(loginPage.登录按钮()); // } // } // // Path: src/main/java/org/webdriver/patatiumappui/pageObject/LoginPage.java // public class LoginPage extends BaseAction { // //用于eclipse工程内运行查找对象库文件路径 // private String path="src/main/java/org/webdriver/patatiumappui/pageObjectConfig/UILibrary.xml"; // public LoginPage() { // //工程内读取对象库文件 // setXmlObjectPath(path); // getLocatorMap(); // } // /*** // * 使用其他方式登录 // * @return // * @throws IOException // */ // public Locator 使用其他方式登录() throws IOException // { // Locator locator=getLocator("使用其他方式登录"); // return locator; // } // // /*** // * 账号 // * @return // * @throws IOException // */ // public Locator 账号输入框() throws IOException // { // Locator locator=getLocator("账号输入框"); // return locator; // } // // /*** // * 密码 // * @return // * @throws IOException // */ // public Locator 密码输入框() throws IOException // { // Locator locator=getLocator("密码输入框"); // return locator; // } // // /*** // * 登录 // * @return // * @throws IOException // */ // public Locator 登录按钮() throws IOException // { // Locator locator=getLocator("登录按钮"); // return locator; // } // // /*** // * 失败提示信息确认按钮 // * @return // * @throws IOException // */ // public Locator 登录失败提示信息() throws IOException // { // Locator locator=getLocator("登录失败提示信息"); // return locator; // } // // /*** // * 失败提示信息确认按钮 // * @return // * @throws IOException // */ // public Locator 登录失败确认按钮() throws IOException // { // Locator locator=getLocator("登录失败确认按钮"); // return locator; // } // } // // Path: src/main/java/org/webdriver/patatiumappui/pageObject/StartPage.java // public class StartPage extends BaseAction { // //用于eclipse工程内运行查找对象库文件路径 // private String path="src/main/java/org/webdriver/patatiumappui/pageObjectConfig/UILibrary.xml"; // public StartPage() { // //工程内读取对象库文件 // setXmlObjectPath(path); // getLocatorMap(); // } // /*** // * 登录 // * @return // * @throws IOException // */ // public Locator 登录() throws IOException // { // Locator locator=getLocator("登录"); // return locator; // } // // /*** // * 注册 // * @return // * @throws IOException // */ // public Locator 注册() throws IOException // { // Locator locator=getLocator("注册"); // return locator; // } // }
import org.dom4j.DocumentException; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.testng.annotations.*; import org.webdriver.patatiumappui.action.LoginAction; import org.webdriver.patatiumappui.pageObject.LoginPage; import org.webdriver.patatiumappui.pageObject.StartPage; import org.webdriver.patatiumappui.utils.*; import java.io.IOException;
/** * Created by zhengshuheng on 2016/9/2 0002. */ public class LoginTest extends TestBaseCase { ElementAction action=new ElementAction(); @BeforeClass public void beforeclass() throws IOException {
// Path: src/main/java/org/webdriver/patatiumappui/action/LoginAction.java // public class LoginAction extends TestBaseCase { // public LoginAction(String username,String password) throws IOException { // ElementAction action=new ElementAction(); // LoginPage loginPage=new LoginPage(); // action.click(loginPage.账号输入框()); // action.clear(loginPage.账号输入框()); // action.type(loginPage.账号输入框(),username); // action.click(loginPage.密码输入框()); // action.clear(loginPage.密码输入框()); // action.type(loginPage.密码输入框(),password); // action.sleep(1); // action.click(loginPage.登录按钮()); // } // } // // Path: src/main/java/org/webdriver/patatiumappui/pageObject/LoginPage.java // public class LoginPage extends BaseAction { // //用于eclipse工程内运行查找对象库文件路径 // private String path="src/main/java/org/webdriver/patatiumappui/pageObjectConfig/UILibrary.xml"; // public LoginPage() { // //工程内读取对象库文件 // setXmlObjectPath(path); // getLocatorMap(); // } // /*** // * 使用其他方式登录 // * @return // * @throws IOException // */ // public Locator 使用其他方式登录() throws IOException // { // Locator locator=getLocator("使用其他方式登录"); // return locator; // } // // /*** // * 账号 // * @return // * @throws IOException // */ // public Locator 账号输入框() throws IOException // { // Locator locator=getLocator("账号输入框"); // return locator; // } // // /*** // * 密码 // * @return // * @throws IOException // */ // public Locator 密码输入框() throws IOException // { // Locator locator=getLocator("密码输入框"); // return locator; // } // // /*** // * 登录 // * @return // * @throws IOException // */ // public Locator 登录按钮() throws IOException // { // Locator locator=getLocator("登录按钮"); // return locator; // } // // /*** // * 失败提示信息确认按钮 // * @return // * @throws IOException // */ // public Locator 登录失败提示信息() throws IOException // { // Locator locator=getLocator("登录失败提示信息"); // return locator; // } // // /*** // * 失败提示信息确认按钮 // * @return // * @throws IOException // */ // public Locator 登录失败确认按钮() throws IOException // { // Locator locator=getLocator("登录失败确认按钮"); // return locator; // } // } // // Path: src/main/java/org/webdriver/patatiumappui/pageObject/StartPage.java // public class StartPage extends BaseAction { // //用于eclipse工程内运行查找对象库文件路径 // private String path="src/main/java/org/webdriver/patatiumappui/pageObjectConfig/UILibrary.xml"; // public StartPage() { // //工程内读取对象库文件 // setXmlObjectPath(path); // getLocatorMap(); // } // /*** // * 登录 // * @return // * @throws IOException // */ // public Locator 登录() throws IOException // { // Locator locator=getLocator("登录"); // return locator; // } // // /*** // * 注册 // * @return // * @throws IOException // */ // public Locator 注册() throws IOException // { // Locator locator=getLocator("注册"); // return locator; // } // } // Path: src/test/java/LoginTest.java import org.dom4j.DocumentException; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.testng.annotations.*; import org.webdriver.patatiumappui.action.LoginAction; import org.webdriver.patatiumappui.pageObject.LoginPage; import org.webdriver.patatiumappui.pageObject.StartPage; import org.webdriver.patatiumappui.utils.*; import java.io.IOException; /** * Created by zhengshuheng on 2016/9/2 0002. */ public class LoginTest extends TestBaseCase { ElementAction action=new ElementAction(); @BeforeClass public void beforeclass() throws IOException {
StartPage startPage=new StartPage();
zhengshuheng/PatatiumAppUi
src/test/java/LoginTest.java
// Path: src/main/java/org/webdriver/patatiumappui/action/LoginAction.java // public class LoginAction extends TestBaseCase { // public LoginAction(String username,String password) throws IOException { // ElementAction action=new ElementAction(); // LoginPage loginPage=new LoginPage(); // action.click(loginPage.账号输入框()); // action.clear(loginPage.账号输入框()); // action.type(loginPage.账号输入框(),username); // action.click(loginPage.密码输入框()); // action.clear(loginPage.密码输入框()); // action.type(loginPage.密码输入框(),password); // action.sleep(1); // action.click(loginPage.登录按钮()); // } // } // // Path: src/main/java/org/webdriver/patatiumappui/pageObject/LoginPage.java // public class LoginPage extends BaseAction { // //用于eclipse工程内运行查找对象库文件路径 // private String path="src/main/java/org/webdriver/patatiumappui/pageObjectConfig/UILibrary.xml"; // public LoginPage() { // //工程内读取对象库文件 // setXmlObjectPath(path); // getLocatorMap(); // } // /*** // * 使用其他方式登录 // * @return // * @throws IOException // */ // public Locator 使用其他方式登录() throws IOException // { // Locator locator=getLocator("使用其他方式登录"); // return locator; // } // // /*** // * 账号 // * @return // * @throws IOException // */ // public Locator 账号输入框() throws IOException // { // Locator locator=getLocator("账号输入框"); // return locator; // } // // /*** // * 密码 // * @return // * @throws IOException // */ // public Locator 密码输入框() throws IOException // { // Locator locator=getLocator("密码输入框"); // return locator; // } // // /*** // * 登录 // * @return // * @throws IOException // */ // public Locator 登录按钮() throws IOException // { // Locator locator=getLocator("登录按钮"); // return locator; // } // // /*** // * 失败提示信息确认按钮 // * @return // * @throws IOException // */ // public Locator 登录失败提示信息() throws IOException // { // Locator locator=getLocator("登录失败提示信息"); // return locator; // } // // /*** // * 失败提示信息确认按钮 // * @return // * @throws IOException // */ // public Locator 登录失败确认按钮() throws IOException // { // Locator locator=getLocator("登录失败确认按钮"); // return locator; // } // } // // Path: src/main/java/org/webdriver/patatiumappui/pageObject/StartPage.java // public class StartPage extends BaseAction { // //用于eclipse工程内运行查找对象库文件路径 // private String path="src/main/java/org/webdriver/patatiumappui/pageObjectConfig/UILibrary.xml"; // public StartPage() { // //工程内读取对象库文件 // setXmlObjectPath(path); // getLocatorMap(); // } // /*** // * 登录 // * @return // * @throws IOException // */ // public Locator 登录() throws IOException // { // Locator locator=getLocator("登录"); // return locator; // } // // /*** // * 注册 // * @return // * @throws IOException // */ // public Locator 注册() throws IOException // { // Locator locator=getLocator("注册"); // return locator; // } // }
import org.dom4j.DocumentException; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.testng.annotations.*; import org.webdriver.patatiumappui.action.LoginAction; import org.webdriver.patatiumappui.pageObject.LoginPage; import org.webdriver.patatiumappui.pageObject.StartPage; import org.webdriver.patatiumappui.utils.*; import java.io.IOException;
/** * Created by zhengshuheng on 2016/9/2 0002. */ public class LoginTest extends TestBaseCase { ElementAction action=new ElementAction(); @BeforeClass public void beforeclass() throws IOException { StartPage startPage=new StartPage(); action.click(startPage.登录());
// Path: src/main/java/org/webdriver/patatiumappui/action/LoginAction.java // public class LoginAction extends TestBaseCase { // public LoginAction(String username,String password) throws IOException { // ElementAction action=new ElementAction(); // LoginPage loginPage=new LoginPage(); // action.click(loginPage.账号输入框()); // action.clear(loginPage.账号输入框()); // action.type(loginPage.账号输入框(),username); // action.click(loginPage.密码输入框()); // action.clear(loginPage.密码输入框()); // action.type(loginPage.密码输入框(),password); // action.sleep(1); // action.click(loginPage.登录按钮()); // } // } // // Path: src/main/java/org/webdriver/patatiumappui/pageObject/LoginPage.java // public class LoginPage extends BaseAction { // //用于eclipse工程内运行查找对象库文件路径 // private String path="src/main/java/org/webdriver/patatiumappui/pageObjectConfig/UILibrary.xml"; // public LoginPage() { // //工程内读取对象库文件 // setXmlObjectPath(path); // getLocatorMap(); // } // /*** // * 使用其他方式登录 // * @return // * @throws IOException // */ // public Locator 使用其他方式登录() throws IOException // { // Locator locator=getLocator("使用其他方式登录"); // return locator; // } // // /*** // * 账号 // * @return // * @throws IOException // */ // public Locator 账号输入框() throws IOException // { // Locator locator=getLocator("账号输入框"); // return locator; // } // // /*** // * 密码 // * @return // * @throws IOException // */ // public Locator 密码输入框() throws IOException // { // Locator locator=getLocator("密码输入框"); // return locator; // } // // /*** // * 登录 // * @return // * @throws IOException // */ // public Locator 登录按钮() throws IOException // { // Locator locator=getLocator("登录按钮"); // return locator; // } // // /*** // * 失败提示信息确认按钮 // * @return // * @throws IOException // */ // public Locator 登录失败提示信息() throws IOException // { // Locator locator=getLocator("登录失败提示信息"); // return locator; // } // // /*** // * 失败提示信息确认按钮 // * @return // * @throws IOException // */ // public Locator 登录失败确认按钮() throws IOException // { // Locator locator=getLocator("登录失败确认按钮"); // return locator; // } // } // // Path: src/main/java/org/webdriver/patatiumappui/pageObject/StartPage.java // public class StartPage extends BaseAction { // //用于eclipse工程内运行查找对象库文件路径 // private String path="src/main/java/org/webdriver/patatiumappui/pageObjectConfig/UILibrary.xml"; // public StartPage() { // //工程内读取对象库文件 // setXmlObjectPath(path); // getLocatorMap(); // } // /*** // * 登录 // * @return // * @throws IOException // */ // public Locator 登录() throws IOException // { // Locator locator=getLocator("登录"); // return locator; // } // // /*** // * 注册 // * @return // * @throws IOException // */ // public Locator 注册() throws IOException // { // Locator locator=getLocator("注册"); // return locator; // } // } // Path: src/test/java/LoginTest.java import org.dom4j.DocumentException; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.testng.annotations.*; import org.webdriver.patatiumappui.action.LoginAction; import org.webdriver.patatiumappui.pageObject.LoginPage; import org.webdriver.patatiumappui.pageObject.StartPage; import org.webdriver.patatiumappui.utils.*; import java.io.IOException; /** * Created by zhengshuheng on 2016/9/2 0002. */ public class LoginTest extends TestBaseCase { ElementAction action=new ElementAction(); @BeforeClass public void beforeclass() throws IOException { StartPage startPage=new StartPage(); action.click(startPage.登录());
LoginPage loginPage=new LoginPage();
zhengshuheng/PatatiumAppUi
src/test/java/LoginTest.java
// Path: src/main/java/org/webdriver/patatiumappui/action/LoginAction.java // public class LoginAction extends TestBaseCase { // public LoginAction(String username,String password) throws IOException { // ElementAction action=new ElementAction(); // LoginPage loginPage=new LoginPage(); // action.click(loginPage.账号输入框()); // action.clear(loginPage.账号输入框()); // action.type(loginPage.账号输入框(),username); // action.click(loginPage.密码输入框()); // action.clear(loginPage.密码输入框()); // action.type(loginPage.密码输入框(),password); // action.sleep(1); // action.click(loginPage.登录按钮()); // } // } // // Path: src/main/java/org/webdriver/patatiumappui/pageObject/LoginPage.java // public class LoginPage extends BaseAction { // //用于eclipse工程内运行查找对象库文件路径 // private String path="src/main/java/org/webdriver/patatiumappui/pageObjectConfig/UILibrary.xml"; // public LoginPage() { // //工程内读取对象库文件 // setXmlObjectPath(path); // getLocatorMap(); // } // /*** // * 使用其他方式登录 // * @return // * @throws IOException // */ // public Locator 使用其他方式登录() throws IOException // { // Locator locator=getLocator("使用其他方式登录"); // return locator; // } // // /*** // * 账号 // * @return // * @throws IOException // */ // public Locator 账号输入框() throws IOException // { // Locator locator=getLocator("账号输入框"); // return locator; // } // // /*** // * 密码 // * @return // * @throws IOException // */ // public Locator 密码输入框() throws IOException // { // Locator locator=getLocator("密码输入框"); // return locator; // } // // /*** // * 登录 // * @return // * @throws IOException // */ // public Locator 登录按钮() throws IOException // { // Locator locator=getLocator("登录按钮"); // return locator; // } // // /*** // * 失败提示信息确认按钮 // * @return // * @throws IOException // */ // public Locator 登录失败提示信息() throws IOException // { // Locator locator=getLocator("登录失败提示信息"); // return locator; // } // // /*** // * 失败提示信息确认按钮 // * @return // * @throws IOException // */ // public Locator 登录失败确认按钮() throws IOException // { // Locator locator=getLocator("登录失败确认按钮"); // return locator; // } // } // // Path: src/main/java/org/webdriver/patatiumappui/pageObject/StartPage.java // public class StartPage extends BaseAction { // //用于eclipse工程内运行查找对象库文件路径 // private String path="src/main/java/org/webdriver/patatiumappui/pageObjectConfig/UILibrary.xml"; // public StartPage() { // //工程内读取对象库文件 // setXmlObjectPath(path); // getLocatorMap(); // } // /*** // * 登录 // * @return // * @throws IOException // */ // public Locator 登录() throws IOException // { // Locator locator=getLocator("登录"); // return locator; // } // // /*** // * 注册 // * @return // * @throws IOException // */ // public Locator 注册() throws IOException // { // Locator locator=getLocator("注册"); // return locator; // } // }
import org.dom4j.DocumentException; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.testng.annotations.*; import org.webdriver.patatiumappui.action.LoginAction; import org.webdriver.patatiumappui.pageObject.LoginPage; import org.webdriver.patatiumappui.pageObject.StartPage; import org.webdriver.patatiumappui.utils.*; import java.io.IOException;
/** * Created by zhengshuheng on 2016/9/2 0002. */ public class LoginTest extends TestBaseCase { ElementAction action=new ElementAction(); @BeforeClass public void beforeclass() throws IOException { StartPage startPage=new StartPage(); action.click(startPage.登录()); LoginPage loginPage=new LoginPage(); action.sleep(2); action.click(loginPage.使用其他方式登录()); action.sleep(2); } @Test(description = "登录测试") public void login() throws IOException { //调用登录方法(需填写正确的用户名和密码)
// Path: src/main/java/org/webdriver/patatiumappui/action/LoginAction.java // public class LoginAction extends TestBaseCase { // public LoginAction(String username,String password) throws IOException { // ElementAction action=new ElementAction(); // LoginPage loginPage=new LoginPage(); // action.click(loginPage.账号输入框()); // action.clear(loginPage.账号输入框()); // action.type(loginPage.账号输入框(),username); // action.click(loginPage.密码输入框()); // action.clear(loginPage.密码输入框()); // action.type(loginPage.密码输入框(),password); // action.sleep(1); // action.click(loginPage.登录按钮()); // } // } // // Path: src/main/java/org/webdriver/patatiumappui/pageObject/LoginPage.java // public class LoginPage extends BaseAction { // //用于eclipse工程内运行查找对象库文件路径 // private String path="src/main/java/org/webdriver/patatiumappui/pageObjectConfig/UILibrary.xml"; // public LoginPage() { // //工程内读取对象库文件 // setXmlObjectPath(path); // getLocatorMap(); // } // /*** // * 使用其他方式登录 // * @return // * @throws IOException // */ // public Locator 使用其他方式登录() throws IOException // { // Locator locator=getLocator("使用其他方式登录"); // return locator; // } // // /*** // * 账号 // * @return // * @throws IOException // */ // public Locator 账号输入框() throws IOException // { // Locator locator=getLocator("账号输入框"); // return locator; // } // // /*** // * 密码 // * @return // * @throws IOException // */ // public Locator 密码输入框() throws IOException // { // Locator locator=getLocator("密码输入框"); // return locator; // } // // /*** // * 登录 // * @return // * @throws IOException // */ // public Locator 登录按钮() throws IOException // { // Locator locator=getLocator("登录按钮"); // return locator; // } // // /*** // * 失败提示信息确认按钮 // * @return // * @throws IOException // */ // public Locator 登录失败提示信息() throws IOException // { // Locator locator=getLocator("登录失败提示信息"); // return locator; // } // // /*** // * 失败提示信息确认按钮 // * @return // * @throws IOException // */ // public Locator 登录失败确认按钮() throws IOException // { // Locator locator=getLocator("登录失败确认按钮"); // return locator; // } // } // // Path: src/main/java/org/webdriver/patatiumappui/pageObject/StartPage.java // public class StartPage extends BaseAction { // //用于eclipse工程内运行查找对象库文件路径 // private String path="src/main/java/org/webdriver/patatiumappui/pageObjectConfig/UILibrary.xml"; // public StartPage() { // //工程内读取对象库文件 // setXmlObjectPath(path); // getLocatorMap(); // } // /*** // * 登录 // * @return // * @throws IOException // */ // public Locator 登录() throws IOException // { // Locator locator=getLocator("登录"); // return locator; // } // // /*** // * 注册 // * @return // * @throws IOException // */ // public Locator 注册() throws IOException // { // Locator locator=getLocator("注册"); // return locator; // } // } // Path: src/test/java/LoginTest.java import org.dom4j.DocumentException; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.testng.annotations.*; import org.webdriver.patatiumappui.action.LoginAction; import org.webdriver.patatiumappui.pageObject.LoginPage; import org.webdriver.patatiumappui.pageObject.StartPage; import org.webdriver.patatiumappui.utils.*; import java.io.IOException; /** * Created by zhengshuheng on 2016/9/2 0002. */ public class LoginTest extends TestBaseCase { ElementAction action=new ElementAction(); @BeforeClass public void beforeclass() throws IOException { StartPage startPage=new StartPage(); action.click(startPage.登录()); LoginPage loginPage=new LoginPage(); action.sleep(2); action.click(loginPage.使用其他方式登录()); action.sleep(2); } @Test(description = "登录测试") public void login() throws IOException { //调用登录方法(需填写正确的用户名和密码)
new LoginAction("609958331", "zheng@1597919");
zhengshuheng/PatatiumAppUi
src/main/java/org/webdriver/patatiumappui/utils/BaseAction.java
// Path: src/main/java/org/webdriver/patatiumappui/utils/Locator.java // public enum ByType { // xpath, id, linkText, name, className, cssSelector, partialLinkText, tagName // }
import org.openqa.selenium.By; import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.WebElement; import org.webdriver.patatiumappui.utils.Locator.ByType; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.concurrent.TimeUnit;
* 构造方法,创建创建BasePageOpera对象时,需要初始化的信息.传递相关参数 * this.getClass().getCanonicalName() 获取page类路径,也就是xml文档中的pageName * @throws Exception */ public BaseAction() { } public void getLocatorMap() { XmlReadUtil xmlReadUtil=new XmlReadUtil(); YamlReadUtil yamlReadUtil=new YamlReadUtil(); try { if((path==null||path.isEmpty())) {locatorMap = xmlReadUtil.readXMLDocument(path_inputStream_1, this.getClass().getCanonicalName());} else { if (path.contains(".xml")) { locatorMap = xmlReadUtil.readXMLDocument(path, this.getClass().getCanonicalName()); }else if (path.contains(".yaml")) { locatorMap=yamlReadUtil.getLocatorMap(path,this.getClass().getCanonicalName()); } } } catch (Exception e) { e.printStackTrace(); } }
// Path: src/main/java/org/webdriver/patatiumappui/utils/Locator.java // public enum ByType { // xpath, id, linkText, name, className, cssSelector, partialLinkText, tagName // } // Path: src/main/java/org/webdriver/patatiumappui/utils/BaseAction.java import org.openqa.selenium.By; import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.WebElement; import org.webdriver.patatiumappui.utils.Locator.ByType; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; import java.util.concurrent.TimeUnit; * 构造方法,创建创建BasePageOpera对象时,需要初始化的信息.传递相关参数 * this.getClass().getCanonicalName() 获取page类路径,也就是xml文档中的pageName * @throws Exception */ public BaseAction() { } public void getLocatorMap() { XmlReadUtil xmlReadUtil=new XmlReadUtil(); YamlReadUtil yamlReadUtil=new YamlReadUtil(); try { if((path==null||path.isEmpty())) {locatorMap = xmlReadUtil.readXMLDocument(path_inputStream_1, this.getClass().getCanonicalName());} else { if (path.contains(".xml")) { locatorMap = xmlReadUtil.readXMLDocument(path, this.getClass().getCanonicalName()); }else if (path.contains(".yaml")) { locatorMap=yamlReadUtil.getLocatorMap(path,this.getClass().getCanonicalName()); } } } catch (Exception e) { e.printStackTrace(); } }
static By getBy (ByType byType,Locator locator)
caoli5288/common
src/main/java/com/mengcraft/util/http/HTTPCall.java
// Path: src/main/java/com/mengcraft/util/http/HTTP.java // static boolean nil(Object i) { // return i == null; // }
import lombok.AccessLevel; import lombok.EqualsAndHashCode; import lombok.RequiredArgsConstructor; import lombok.SneakyThrows; import lombok.val; import java.io.IOException; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.concurrent.Callable; import java.util.regex.Pattern; import static com.mengcraft.util.http.HTTP.nil;
package com.mengcraft.util.http; /** * Created on 17-3-1. */ @EqualsAndHashCode(of = "request") @RequiredArgsConstructor(access = AccessLevel.PACKAGE) public class HTTPCall implements Callable<Integer> { private static final Pattern PROTOCOL = Pattern.compile("^http(s)?$"); private static final int TIMEOUT = 60000; private final HTTPRequest request; private final HTTP.Callback callback; private HttpURLConnection conn; private void valid(String protocol) throws IOException { if (!PROTOCOL.matcher(protocol).matches()) { throw new IOException(protocol); } } @SneakyThrows private int conn() { val link = new URL(request.getAddress()); valid(link.getProtocol()); conn = (HttpURLConnection) link.openConnection(); val method = request.getMethod(); conn.setRequestMethod(method.name()); val header = request.getHeader();
// Path: src/main/java/com/mengcraft/util/http/HTTP.java // static boolean nil(Object i) { // return i == null; // } // Path: src/main/java/com/mengcraft/util/http/HTTPCall.java import lombok.AccessLevel; import lombok.EqualsAndHashCode; import lombok.RequiredArgsConstructor; import lombok.SneakyThrows; import lombok.val; import java.io.IOException; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.concurrent.Callable; import java.util.regex.Pattern; import static com.mengcraft.util.http.HTTP.nil; package com.mengcraft.util.http; /** * Created on 17-3-1. */ @EqualsAndHashCode(of = "request") @RequiredArgsConstructor(access = AccessLevel.PACKAGE) public class HTTPCall implements Callable<Integer> { private static final Pattern PROTOCOL = Pattern.compile("^http(s)?$"); private static final int TIMEOUT = 60000; private final HTTPRequest request; private final HTTP.Callback callback; private HttpURLConnection conn; private void valid(String protocol) throws IOException { if (!PROTOCOL.matcher(protocol).matches()) { throw new IOException(protocol); } } @SneakyThrows private int conn() { val link = new URL(request.getAddress()); valid(link.getProtocol()); conn = (HttpURLConnection) link.openConnection(); val method = request.getMethod(); conn.setRequestMethod(method.name()); val header = request.getHeader();
if (!nil(header)) {