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
Nilhcem/droidconde-2016
app/src/main/java/com/nilhcem/droidconde/data/app/DataProviderCache.java
// Path: app/src/main/java/com/nilhcem/droidconde/data/app/model/Session.java // @Value // public class Session implements Parcelable { // // public static final Parcelable.Creator<Session> CREATOR = new Parcelable.Creator<Session>() { // public Session createFromParcel(Parcel source) { // return new Session(source); // } // // public Session[] newArray(int size) { // return new Session[size]; // } // }; // // int id; // String room; // List<Speaker> speakers; // String title; // String description; // LocalDateTime fromTime; // LocalDateTime toTime; // // public Session(int id, String room, List<Speaker> speakers, String title, String description, LocalDateTime fromTime, LocalDateTime toTime) { // this.id = id; // this.room = room; // this.speakers = speakers; // this.title = title; // this.description = description; // this.fromTime = fromTime; // this.toTime = toTime; // } // // protected Session(Parcel in) { // id = in.readInt(); // room = in.readString(); // speakers = in.createTypedArrayList(Speaker.CREATOR); // title = in.readString(); // description = in.readString(); // fromTime = (LocalDateTime) in.readSerializable(); // toTime = (LocalDateTime) in.readSerializable(); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(id); // dest.writeString(room); // dest.writeTypedList(speakers); // dest.writeString(title); // dest.writeString(description); // dest.writeSerializable(fromTime); // dest.writeSerializable(toTime); // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/data/app/model/Speaker.java // @Value // public class Speaker implements Parcelable { // // public static final Parcelable.Creator<Speaker> CREATOR = new Parcelable.Creator<Speaker>() { // public Speaker createFromParcel(Parcel source) { // return new Speaker(source); // } // // public Speaker[] newArray(int size) { // return new Speaker[size]; // } // }; // // int id; // String name; // String title; // String bio; // String website; // String twitter; // String github; // String photo; // // public Speaker(int id, String name, String title, String bio, String website, String twitter, String github, String photo) { // this.id = id; // this.name = name; // this.title = title; // this.bio = bio; // this.website = website; // this.twitter = twitter; // this.github = github; // this.photo = photo; // } // // protected Speaker(Parcel in) { // id = in.readInt(); // name = in.readString(); // title = in.readString(); // bio = in.readString(); // website = in.readString(); // twitter = in.readString(); // github = in.readString(); // photo = in.readString(); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(id); // dest.writeString(name); // dest.writeString(title); // dest.writeString(bio); // dest.writeString(website); // dest.writeString(twitter); // dest.writeString(github); // dest.writeString(photo); // } // }
import com.nilhcem.droidconde.data.app.model.Session; import com.nilhcem.droidconde.data.app.model.Speaker; import org.threeten.bp.LocalDateTime; import java.util.List; import timber.log.Timber;
package com.nilhcem.droidconde.data.app; public class DataProviderCache { private static final long CACHE_DURATION_MN = 10; List<Session> sessions; LocalDateTime sessionsFetchedTime;
// Path: app/src/main/java/com/nilhcem/droidconde/data/app/model/Session.java // @Value // public class Session implements Parcelable { // // public static final Parcelable.Creator<Session> CREATOR = new Parcelable.Creator<Session>() { // public Session createFromParcel(Parcel source) { // return new Session(source); // } // // public Session[] newArray(int size) { // return new Session[size]; // } // }; // // int id; // String room; // List<Speaker> speakers; // String title; // String description; // LocalDateTime fromTime; // LocalDateTime toTime; // // public Session(int id, String room, List<Speaker> speakers, String title, String description, LocalDateTime fromTime, LocalDateTime toTime) { // this.id = id; // this.room = room; // this.speakers = speakers; // this.title = title; // this.description = description; // this.fromTime = fromTime; // this.toTime = toTime; // } // // protected Session(Parcel in) { // id = in.readInt(); // room = in.readString(); // speakers = in.createTypedArrayList(Speaker.CREATOR); // title = in.readString(); // description = in.readString(); // fromTime = (LocalDateTime) in.readSerializable(); // toTime = (LocalDateTime) in.readSerializable(); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(id); // dest.writeString(room); // dest.writeTypedList(speakers); // dest.writeString(title); // dest.writeString(description); // dest.writeSerializable(fromTime); // dest.writeSerializable(toTime); // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/data/app/model/Speaker.java // @Value // public class Speaker implements Parcelable { // // public static final Parcelable.Creator<Speaker> CREATOR = new Parcelable.Creator<Speaker>() { // public Speaker createFromParcel(Parcel source) { // return new Speaker(source); // } // // public Speaker[] newArray(int size) { // return new Speaker[size]; // } // }; // // int id; // String name; // String title; // String bio; // String website; // String twitter; // String github; // String photo; // // public Speaker(int id, String name, String title, String bio, String website, String twitter, String github, String photo) { // this.id = id; // this.name = name; // this.title = title; // this.bio = bio; // this.website = website; // this.twitter = twitter; // this.github = github; // this.photo = photo; // } // // protected Speaker(Parcel in) { // id = in.readInt(); // name = in.readString(); // title = in.readString(); // bio = in.readString(); // website = in.readString(); // twitter = in.readString(); // github = in.readString(); // photo = in.readString(); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(id); // dest.writeString(name); // dest.writeString(title); // dest.writeString(bio); // dest.writeString(website); // dest.writeString(twitter); // dest.writeString(github); // dest.writeString(photo); // } // } // Path: app/src/main/java/com/nilhcem/droidconde/data/app/DataProviderCache.java import com.nilhcem.droidconde.data.app.model.Session; import com.nilhcem.droidconde.data.app.model.Speaker; import org.threeten.bp.LocalDateTime; import java.util.List; import timber.log.Timber; package com.nilhcem.droidconde.data.app; public class DataProviderCache { private static final long CACHE_DURATION_MN = 10; List<Session> sessions; LocalDateTime sessionsFetchedTime;
List<Speaker> speakers;
Nilhcem/droidconde-2016
app/src/main/java/com/nilhcem/droidconde/ui/settings/SettingsFragment.java
// Path: app/src/main/java/com/nilhcem/droidconde/DroidconApp.java // @DebugLog // public class DroidconApp extends Application { // // private AppComponent component; // // public static DroidconApp get(Context context) { // return (DroidconApp) context.getApplicationContext(); // } // // @Override // public void onCreate() { // super.onCreate(); // AndroidThreeTen.init(this); // initGraph(); // initLogger(); // } // // public AppComponent component() { // return component; // } // // private void initGraph() { // component = AppComponent.Initializer.init(this); // } // // private void initLogger() { // Timber.plant(new Timber.DebugTree()); // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/receiver/reminder/SessionsReminder.java // @Singleton // public class SessionsReminder { // // private final Context context; // private final SessionsDao sessionsDao; // private final SharedPreferences preferences; // private final AlarmManager alarmManager; // // @Inject // public SessionsReminder(Application app, SessionsDao sessionsDao, SharedPreferences preferences) { // this.context = app; // this.sessionsDao = sessionsDao; // this.preferences = preferences; // alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); // } // // public boolean isEnabled() { // return preferences.getBoolean(context.getString(R.string.settings_notify_key), false); // } // // public void enableSessionReminder() { // performOnSelectedSessions(this::addSessionReminder); // } // // public void disableSessionReminder() { // performOnSelectedSessions(this::removeSessionReminder); // } // // public void addSessionReminder(@NonNull Session session) { // if (!isEnabled()) { // Timber.d("SessionsReminder is not enable, skip adding session"); // return; // } // // PendingIntent intent = createSessionReminderIntent(session); // LocalDateTime now = LocalDateTime.now(); // LocalDateTime sessionStartTime = session.getFromTime().minusMinutes(3); // if (!sessionStartTime.isAfter(now)) { // Timber.w("Do not set reminder for passed session"); // return; // } // Timber.d("Setting reminder on %s", sessionStartTime); // App.setExactAlarm(alarmManager, sessionStartTime.atZone(ZoneOffset.systemDefault()).toInstant().toEpochMilli(), intent); // } // // public void removeSessionReminder(@NonNull Session session) { // Timber.d("Cancelling reminder on %s", session.getFromTime().minusMinutes(3)); // createSessionReminderIntent(session).cancel(); // } // // private PendingIntent createSessionReminderIntent(@NonNull Session session) { // Intent intent = new ReminderReceiverIntentBuilder(session).build(context); // return PendingIntent.getBroadcast(context, session.getId(), intent, PendingIntent.FLAG_UPDATE_CURRENT); // } // // private void performOnSelectedSessions(Action1<? super Session> onNext) { // sessionsDao.getSelectedSessions() // .flatMap(Observable::from) // .subscribeOn(Schedulers.io()) // .observeOn(Schedulers.computation()) // .subscribe(onNext, throwable -> Timber.e(throwable, "Error getting sessions")); // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/utils/Intents.java // public final class Intents { // // private Intents() { // throw new UnsupportedOperationException(); // } // // public static boolean startUri(@NonNull Context context, @NonNull String url) { // Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); // if (intent.resolveActivity(context.getPackageManager()) != null) { // context.startActivity(intent); // return true; // } // return false; // } // // public static void startExternalUrl(@NonNull Activity activity, @NonNull String url) { // CustomTabsIntent intent = new CustomTabsIntent.Builder() // .setShowTitle(true) // .setToolbarColor(ContextCompat.getColor(activity, R.color.primary)) // .build(); // intent.launchUrl(activity, Uri.parse(url)); // } // }
import android.os.Bundle; import android.support.annotation.StringRes; import android.support.v7.preference.CheckBoxPreference; import android.support.v7.preference.Preference; import android.support.v7.preference.PreferenceFragmentCompat; import com.nilhcem.droidconde.DroidconApp; import com.nilhcem.droidconde.R; import com.nilhcem.droidconde.receiver.reminder.SessionsReminder; import com.nilhcem.droidconde.utils.Intents; import javax.inject.Inject;
package com.nilhcem.droidconde.ui.settings; public class SettingsFragment extends PreferenceFragmentCompat implements SettingsMvp.View { @Inject SessionsReminder sessionsReminder; private SettingsPresenter presenter; private CheckBoxPreference notifySessions; private Preference appVersion; @Override public void onCreatePreferences(Bundle savedInstanceState, String rootKey) { initPreferences(); initPresenter(); notifySessions.setOnPreferenceChangeListener((preference, newValue) -> presenter.onNotifySessionsChange((Boolean) newValue)); } @Override public void setNotifySessionsCheckbox(boolean checked) { notifySessions.setChecked(checked); } @Override public void setAppVersion(CharSequence version) { appVersion.setSummary(version); } private void initPreferences() { addPreferencesFromResource(R.xml.settings); notifySessions = findPreference(R.string.settings_notify_key); appVersion = findPreference(R.string.settings_version_key); initPreferenceLink(R.string.settings_conf_key); initPreferenceLink(R.string.settings_github_key); initPreferenceLink(R.string.settings_developer_key); } private void initPresenter() {
// Path: app/src/main/java/com/nilhcem/droidconde/DroidconApp.java // @DebugLog // public class DroidconApp extends Application { // // private AppComponent component; // // public static DroidconApp get(Context context) { // return (DroidconApp) context.getApplicationContext(); // } // // @Override // public void onCreate() { // super.onCreate(); // AndroidThreeTen.init(this); // initGraph(); // initLogger(); // } // // public AppComponent component() { // return component; // } // // private void initGraph() { // component = AppComponent.Initializer.init(this); // } // // private void initLogger() { // Timber.plant(new Timber.DebugTree()); // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/receiver/reminder/SessionsReminder.java // @Singleton // public class SessionsReminder { // // private final Context context; // private final SessionsDao sessionsDao; // private final SharedPreferences preferences; // private final AlarmManager alarmManager; // // @Inject // public SessionsReminder(Application app, SessionsDao sessionsDao, SharedPreferences preferences) { // this.context = app; // this.sessionsDao = sessionsDao; // this.preferences = preferences; // alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); // } // // public boolean isEnabled() { // return preferences.getBoolean(context.getString(R.string.settings_notify_key), false); // } // // public void enableSessionReminder() { // performOnSelectedSessions(this::addSessionReminder); // } // // public void disableSessionReminder() { // performOnSelectedSessions(this::removeSessionReminder); // } // // public void addSessionReminder(@NonNull Session session) { // if (!isEnabled()) { // Timber.d("SessionsReminder is not enable, skip adding session"); // return; // } // // PendingIntent intent = createSessionReminderIntent(session); // LocalDateTime now = LocalDateTime.now(); // LocalDateTime sessionStartTime = session.getFromTime().minusMinutes(3); // if (!sessionStartTime.isAfter(now)) { // Timber.w("Do not set reminder for passed session"); // return; // } // Timber.d("Setting reminder on %s", sessionStartTime); // App.setExactAlarm(alarmManager, sessionStartTime.atZone(ZoneOffset.systemDefault()).toInstant().toEpochMilli(), intent); // } // // public void removeSessionReminder(@NonNull Session session) { // Timber.d("Cancelling reminder on %s", session.getFromTime().minusMinutes(3)); // createSessionReminderIntent(session).cancel(); // } // // private PendingIntent createSessionReminderIntent(@NonNull Session session) { // Intent intent = new ReminderReceiverIntentBuilder(session).build(context); // return PendingIntent.getBroadcast(context, session.getId(), intent, PendingIntent.FLAG_UPDATE_CURRENT); // } // // private void performOnSelectedSessions(Action1<? super Session> onNext) { // sessionsDao.getSelectedSessions() // .flatMap(Observable::from) // .subscribeOn(Schedulers.io()) // .observeOn(Schedulers.computation()) // .subscribe(onNext, throwable -> Timber.e(throwable, "Error getting sessions")); // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/utils/Intents.java // public final class Intents { // // private Intents() { // throw new UnsupportedOperationException(); // } // // public static boolean startUri(@NonNull Context context, @NonNull String url) { // Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); // if (intent.resolveActivity(context.getPackageManager()) != null) { // context.startActivity(intent); // return true; // } // return false; // } // // public static void startExternalUrl(@NonNull Activity activity, @NonNull String url) { // CustomTabsIntent intent = new CustomTabsIntent.Builder() // .setShowTitle(true) // .setToolbarColor(ContextCompat.getColor(activity, R.color.primary)) // .build(); // intent.launchUrl(activity, Uri.parse(url)); // } // } // Path: app/src/main/java/com/nilhcem/droidconde/ui/settings/SettingsFragment.java import android.os.Bundle; import android.support.annotation.StringRes; import android.support.v7.preference.CheckBoxPreference; import android.support.v7.preference.Preference; import android.support.v7.preference.PreferenceFragmentCompat; import com.nilhcem.droidconde.DroidconApp; import com.nilhcem.droidconde.R; import com.nilhcem.droidconde.receiver.reminder.SessionsReminder; import com.nilhcem.droidconde.utils.Intents; import javax.inject.Inject; package com.nilhcem.droidconde.ui.settings; public class SettingsFragment extends PreferenceFragmentCompat implements SettingsMvp.View { @Inject SessionsReminder sessionsReminder; private SettingsPresenter presenter; private CheckBoxPreference notifySessions; private Preference appVersion; @Override public void onCreatePreferences(Bundle savedInstanceState, String rootKey) { initPreferences(); initPresenter(); notifySessions.setOnPreferenceChangeListener((preference, newValue) -> presenter.onNotifySessionsChange((Boolean) newValue)); } @Override public void setNotifySessionsCheckbox(boolean checked) { notifySessions.setChecked(checked); } @Override public void setAppVersion(CharSequence version) { appVersion.setSummary(version); } private void initPreferences() { addPreferencesFromResource(R.xml.settings); notifySessions = findPreference(R.string.settings_notify_key); appVersion = findPreference(R.string.settings_version_key); initPreferenceLink(R.string.settings_conf_key); initPreferenceLink(R.string.settings_github_key); initPreferenceLink(R.string.settings_developer_key); } private void initPresenter() {
DroidconApp.get(getContext()).component().inject(this);
Nilhcem/droidconde-2016
app/src/main/java/com/nilhcem/droidconde/ui/settings/SettingsFragment.java
// Path: app/src/main/java/com/nilhcem/droidconde/DroidconApp.java // @DebugLog // public class DroidconApp extends Application { // // private AppComponent component; // // public static DroidconApp get(Context context) { // return (DroidconApp) context.getApplicationContext(); // } // // @Override // public void onCreate() { // super.onCreate(); // AndroidThreeTen.init(this); // initGraph(); // initLogger(); // } // // public AppComponent component() { // return component; // } // // private void initGraph() { // component = AppComponent.Initializer.init(this); // } // // private void initLogger() { // Timber.plant(new Timber.DebugTree()); // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/receiver/reminder/SessionsReminder.java // @Singleton // public class SessionsReminder { // // private final Context context; // private final SessionsDao sessionsDao; // private final SharedPreferences preferences; // private final AlarmManager alarmManager; // // @Inject // public SessionsReminder(Application app, SessionsDao sessionsDao, SharedPreferences preferences) { // this.context = app; // this.sessionsDao = sessionsDao; // this.preferences = preferences; // alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); // } // // public boolean isEnabled() { // return preferences.getBoolean(context.getString(R.string.settings_notify_key), false); // } // // public void enableSessionReminder() { // performOnSelectedSessions(this::addSessionReminder); // } // // public void disableSessionReminder() { // performOnSelectedSessions(this::removeSessionReminder); // } // // public void addSessionReminder(@NonNull Session session) { // if (!isEnabled()) { // Timber.d("SessionsReminder is not enable, skip adding session"); // return; // } // // PendingIntent intent = createSessionReminderIntent(session); // LocalDateTime now = LocalDateTime.now(); // LocalDateTime sessionStartTime = session.getFromTime().minusMinutes(3); // if (!sessionStartTime.isAfter(now)) { // Timber.w("Do not set reminder for passed session"); // return; // } // Timber.d("Setting reminder on %s", sessionStartTime); // App.setExactAlarm(alarmManager, sessionStartTime.atZone(ZoneOffset.systemDefault()).toInstant().toEpochMilli(), intent); // } // // public void removeSessionReminder(@NonNull Session session) { // Timber.d("Cancelling reminder on %s", session.getFromTime().minusMinutes(3)); // createSessionReminderIntent(session).cancel(); // } // // private PendingIntent createSessionReminderIntent(@NonNull Session session) { // Intent intent = new ReminderReceiverIntentBuilder(session).build(context); // return PendingIntent.getBroadcast(context, session.getId(), intent, PendingIntent.FLAG_UPDATE_CURRENT); // } // // private void performOnSelectedSessions(Action1<? super Session> onNext) { // sessionsDao.getSelectedSessions() // .flatMap(Observable::from) // .subscribeOn(Schedulers.io()) // .observeOn(Schedulers.computation()) // .subscribe(onNext, throwable -> Timber.e(throwable, "Error getting sessions")); // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/utils/Intents.java // public final class Intents { // // private Intents() { // throw new UnsupportedOperationException(); // } // // public static boolean startUri(@NonNull Context context, @NonNull String url) { // Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); // if (intent.resolveActivity(context.getPackageManager()) != null) { // context.startActivity(intent); // return true; // } // return false; // } // // public static void startExternalUrl(@NonNull Activity activity, @NonNull String url) { // CustomTabsIntent intent = new CustomTabsIntent.Builder() // .setShowTitle(true) // .setToolbarColor(ContextCompat.getColor(activity, R.color.primary)) // .build(); // intent.launchUrl(activity, Uri.parse(url)); // } // }
import android.os.Bundle; import android.support.annotation.StringRes; import android.support.v7.preference.CheckBoxPreference; import android.support.v7.preference.Preference; import android.support.v7.preference.PreferenceFragmentCompat; import com.nilhcem.droidconde.DroidconApp; import com.nilhcem.droidconde.R; import com.nilhcem.droidconde.receiver.reminder.SessionsReminder; import com.nilhcem.droidconde.utils.Intents; import javax.inject.Inject;
public void setNotifySessionsCheckbox(boolean checked) { notifySessions.setChecked(checked); } @Override public void setAppVersion(CharSequence version) { appVersion.setSummary(version); } private void initPreferences() { addPreferencesFromResource(R.xml.settings); notifySessions = findPreference(R.string.settings_notify_key); appVersion = findPreference(R.string.settings_version_key); initPreferenceLink(R.string.settings_conf_key); initPreferenceLink(R.string.settings_github_key); initPreferenceLink(R.string.settings_developer_key); } private void initPresenter() { DroidconApp.get(getContext()).component().inject(this); presenter = new SettingsPresenter(getContext(), this, sessionsReminder); presenter.onCreate(); } private <T extends Preference> T findPreference(@StringRes int resId) { return (T) findPreference(getString(resId)); } private void initPreferenceLink(@StringRes int resId) { findPreference(resId).setOnPreferenceClickListener(preference -> {
// Path: app/src/main/java/com/nilhcem/droidconde/DroidconApp.java // @DebugLog // public class DroidconApp extends Application { // // private AppComponent component; // // public static DroidconApp get(Context context) { // return (DroidconApp) context.getApplicationContext(); // } // // @Override // public void onCreate() { // super.onCreate(); // AndroidThreeTen.init(this); // initGraph(); // initLogger(); // } // // public AppComponent component() { // return component; // } // // private void initGraph() { // component = AppComponent.Initializer.init(this); // } // // private void initLogger() { // Timber.plant(new Timber.DebugTree()); // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/receiver/reminder/SessionsReminder.java // @Singleton // public class SessionsReminder { // // private final Context context; // private final SessionsDao sessionsDao; // private final SharedPreferences preferences; // private final AlarmManager alarmManager; // // @Inject // public SessionsReminder(Application app, SessionsDao sessionsDao, SharedPreferences preferences) { // this.context = app; // this.sessionsDao = sessionsDao; // this.preferences = preferences; // alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); // } // // public boolean isEnabled() { // return preferences.getBoolean(context.getString(R.string.settings_notify_key), false); // } // // public void enableSessionReminder() { // performOnSelectedSessions(this::addSessionReminder); // } // // public void disableSessionReminder() { // performOnSelectedSessions(this::removeSessionReminder); // } // // public void addSessionReminder(@NonNull Session session) { // if (!isEnabled()) { // Timber.d("SessionsReminder is not enable, skip adding session"); // return; // } // // PendingIntent intent = createSessionReminderIntent(session); // LocalDateTime now = LocalDateTime.now(); // LocalDateTime sessionStartTime = session.getFromTime().minusMinutes(3); // if (!sessionStartTime.isAfter(now)) { // Timber.w("Do not set reminder for passed session"); // return; // } // Timber.d("Setting reminder on %s", sessionStartTime); // App.setExactAlarm(alarmManager, sessionStartTime.atZone(ZoneOffset.systemDefault()).toInstant().toEpochMilli(), intent); // } // // public void removeSessionReminder(@NonNull Session session) { // Timber.d("Cancelling reminder on %s", session.getFromTime().minusMinutes(3)); // createSessionReminderIntent(session).cancel(); // } // // private PendingIntent createSessionReminderIntent(@NonNull Session session) { // Intent intent = new ReminderReceiverIntentBuilder(session).build(context); // return PendingIntent.getBroadcast(context, session.getId(), intent, PendingIntent.FLAG_UPDATE_CURRENT); // } // // private void performOnSelectedSessions(Action1<? super Session> onNext) { // sessionsDao.getSelectedSessions() // .flatMap(Observable::from) // .subscribeOn(Schedulers.io()) // .observeOn(Schedulers.computation()) // .subscribe(onNext, throwable -> Timber.e(throwable, "Error getting sessions")); // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/utils/Intents.java // public final class Intents { // // private Intents() { // throw new UnsupportedOperationException(); // } // // public static boolean startUri(@NonNull Context context, @NonNull String url) { // Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); // if (intent.resolveActivity(context.getPackageManager()) != null) { // context.startActivity(intent); // return true; // } // return false; // } // // public static void startExternalUrl(@NonNull Activity activity, @NonNull String url) { // CustomTabsIntent intent = new CustomTabsIntent.Builder() // .setShowTitle(true) // .setToolbarColor(ContextCompat.getColor(activity, R.color.primary)) // .build(); // intent.launchUrl(activity, Uri.parse(url)); // } // } // Path: app/src/main/java/com/nilhcem/droidconde/ui/settings/SettingsFragment.java import android.os.Bundle; import android.support.annotation.StringRes; import android.support.v7.preference.CheckBoxPreference; import android.support.v7.preference.Preference; import android.support.v7.preference.PreferenceFragmentCompat; import com.nilhcem.droidconde.DroidconApp; import com.nilhcem.droidconde.R; import com.nilhcem.droidconde.receiver.reminder.SessionsReminder; import com.nilhcem.droidconde.utils.Intents; import javax.inject.Inject; public void setNotifySessionsCheckbox(boolean checked) { notifySessions.setChecked(checked); } @Override public void setAppVersion(CharSequence version) { appVersion.setSummary(version); } private void initPreferences() { addPreferencesFromResource(R.xml.settings); notifySessions = findPreference(R.string.settings_notify_key); appVersion = findPreference(R.string.settings_version_key); initPreferenceLink(R.string.settings_conf_key); initPreferenceLink(R.string.settings_github_key); initPreferenceLink(R.string.settings_developer_key); } private void initPresenter() { DroidconApp.get(getContext()).component().inject(this); presenter = new SettingsPresenter(getContext(), this, sessionsReminder); presenter.onCreate(); } private <T extends Preference> T findPreference(@StringRes int resId) { return (T) findPreference(getString(resId)); } private void initPreferenceLink(@StringRes int resId) { findPreference(resId).setOnPreferenceClickListener(preference -> {
Intents.startExternalUrl(getActivity(), preference.getSummary().toString());
Nilhcem/droidconde-2016
app/src/main/java/com/nilhcem/droidconde/ui/schedule/day/ScheduleDayFragmentAdapterAllSessions.java
// Path: app/src/main/java/com/nilhcem/droidconde/data/app/SelectedSessionsMemory.java // @Singleton // public class SelectedSessionsMemory { // // private final Map<LocalDateTime, Integer> selectedSessions = new ConcurrentHashMap<>(); // // @Inject // public SelectedSessionsMemory() { // } // // public boolean isSelected(Session session) { // Integer sessionId = selectedSessions.get(session.getFromTime()); // return sessionId != null && session.getId() == sessionId; // } // // public void setSelectedSessions(Map<LocalDateTime, Integer> selectedSessions) { // this.selectedSessions.clear(); // this.selectedSessions.putAll(selectedSessions); // } // // public Integer get(LocalDateTime slotTime) { // return selectedSessions.get(slotTime); // } // // public void toggleSessionState(com.nilhcem.droidconde.data.app.model.Session session, boolean insert) { // selectedSessions.remove(session.getFromTime()); // if (insert) { // selectedSessions.put(session.getFromTime(), session.getId()); // } // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/data/app/model/Room.java // public enum Room { // // NONE(0, ""), // STAGE_1(1, "Stage 1"), // STAGE_2(2, "Stage 2"), // STAGE_3(3, "Stage 3"), // STAGE_4(4, "Stage 4"), // WORKSPACE(5, "Workspace"); // // public final int id; // public final String label; // // Room(int id, String label) { // this.id = id; // this.label = label; // } // // public static Room getFromId(int id) { // for (Room room : Room.values()) { // if (room.id == id) { // return room; // } // } // return NONE; // } // // public static Room getFromLabel(@NonNull String label) { // for (Room room : Room.values()) { // if (label.equals(room.label)) { // return room; // } // } // return NONE; // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/data/app/model/ScheduleSlot.java // @Value // public class ScheduleSlot implements Parcelable { // // public static final Parcelable.Creator<ScheduleSlot> CREATOR = new Parcelable.Creator<ScheduleSlot>() { // public ScheduleSlot createFromParcel(Parcel source) { // return new ScheduleSlot(source); // } // // public ScheduleSlot[] newArray(int size) { // return new ScheduleSlot[size]; // } // }; // // LocalDateTime time; // List<Session> sessions; // // public ScheduleSlot(LocalDateTime time, List<Session> sessions) { // this.time = time; // this.sessions = sessions; // } // // protected ScheduleSlot(Parcel in) { // time = (LocalDateTime) in.readSerializable(); // sessions = in.createTypedArrayList(Session.CREATOR); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeSerializable(time); // dest.writeTypedList(sessions); // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/data/app/model/Session.java // @Value // public class Session implements Parcelable { // // public static final Parcelable.Creator<Session> CREATOR = new Parcelable.Creator<Session>() { // public Session createFromParcel(Parcel source) { // return new Session(source); // } // // public Session[] newArray(int size) { // return new Session[size]; // } // }; // // int id; // String room; // List<Speaker> speakers; // String title; // String description; // LocalDateTime fromTime; // LocalDateTime toTime; // // public Session(int id, String room, List<Speaker> speakers, String title, String description, LocalDateTime fromTime, LocalDateTime toTime) { // this.id = id; // this.room = room; // this.speakers = speakers; // this.title = title; // this.description = description; // this.fromTime = fromTime; // this.toTime = toTime; // } // // protected Session(Parcel in) { // id = in.readInt(); // room = in.readString(); // speakers = in.createTypedArrayList(Speaker.CREATOR); // title = in.readString(); // description = in.readString(); // fromTime = (LocalDateTime) in.readSerializable(); // toTime = (LocalDateTime) in.readSerializable(); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(id); // dest.writeString(room); // dest.writeTypedList(speakers); // dest.writeString(title); // dest.writeString(description); // dest.writeSerializable(fromTime); // dest.writeSerializable(toTime); // } // }
import android.support.v4.util.Pair; import android.support.v7.widget.RecyclerView; import android.view.ViewGroup; import com.nilhcem.droidconde.data.app.SelectedSessionsMemory; import com.nilhcem.droidconde.data.app.model.Room; import com.nilhcem.droidconde.data.app.model.ScheduleSlot; import com.nilhcem.droidconde.data.app.model.Session; import com.squareup.picasso.Picasso; import java.util.List; import java8.util.stream.Collectors; import static java8.util.stream.StreamSupport.stream;
package com.nilhcem.droidconde.ui.schedule.day; public class ScheduleDayFragmentAdapterAllSessions extends RecyclerView.Adapter<ScheduleDayEntry> { private final List<Pair<Session, ScheduleSlot>> sessions; private final Picasso picasso;
// Path: app/src/main/java/com/nilhcem/droidconde/data/app/SelectedSessionsMemory.java // @Singleton // public class SelectedSessionsMemory { // // private final Map<LocalDateTime, Integer> selectedSessions = new ConcurrentHashMap<>(); // // @Inject // public SelectedSessionsMemory() { // } // // public boolean isSelected(Session session) { // Integer sessionId = selectedSessions.get(session.getFromTime()); // return sessionId != null && session.getId() == sessionId; // } // // public void setSelectedSessions(Map<LocalDateTime, Integer> selectedSessions) { // this.selectedSessions.clear(); // this.selectedSessions.putAll(selectedSessions); // } // // public Integer get(LocalDateTime slotTime) { // return selectedSessions.get(slotTime); // } // // public void toggleSessionState(com.nilhcem.droidconde.data.app.model.Session session, boolean insert) { // selectedSessions.remove(session.getFromTime()); // if (insert) { // selectedSessions.put(session.getFromTime(), session.getId()); // } // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/data/app/model/Room.java // public enum Room { // // NONE(0, ""), // STAGE_1(1, "Stage 1"), // STAGE_2(2, "Stage 2"), // STAGE_3(3, "Stage 3"), // STAGE_4(4, "Stage 4"), // WORKSPACE(5, "Workspace"); // // public final int id; // public final String label; // // Room(int id, String label) { // this.id = id; // this.label = label; // } // // public static Room getFromId(int id) { // for (Room room : Room.values()) { // if (room.id == id) { // return room; // } // } // return NONE; // } // // public static Room getFromLabel(@NonNull String label) { // for (Room room : Room.values()) { // if (label.equals(room.label)) { // return room; // } // } // return NONE; // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/data/app/model/ScheduleSlot.java // @Value // public class ScheduleSlot implements Parcelable { // // public static final Parcelable.Creator<ScheduleSlot> CREATOR = new Parcelable.Creator<ScheduleSlot>() { // public ScheduleSlot createFromParcel(Parcel source) { // return new ScheduleSlot(source); // } // // public ScheduleSlot[] newArray(int size) { // return new ScheduleSlot[size]; // } // }; // // LocalDateTime time; // List<Session> sessions; // // public ScheduleSlot(LocalDateTime time, List<Session> sessions) { // this.time = time; // this.sessions = sessions; // } // // protected ScheduleSlot(Parcel in) { // time = (LocalDateTime) in.readSerializable(); // sessions = in.createTypedArrayList(Session.CREATOR); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeSerializable(time); // dest.writeTypedList(sessions); // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/data/app/model/Session.java // @Value // public class Session implements Parcelable { // // public static final Parcelable.Creator<Session> CREATOR = new Parcelable.Creator<Session>() { // public Session createFromParcel(Parcel source) { // return new Session(source); // } // // public Session[] newArray(int size) { // return new Session[size]; // } // }; // // int id; // String room; // List<Speaker> speakers; // String title; // String description; // LocalDateTime fromTime; // LocalDateTime toTime; // // public Session(int id, String room, List<Speaker> speakers, String title, String description, LocalDateTime fromTime, LocalDateTime toTime) { // this.id = id; // this.room = room; // this.speakers = speakers; // this.title = title; // this.description = description; // this.fromTime = fromTime; // this.toTime = toTime; // } // // protected Session(Parcel in) { // id = in.readInt(); // room = in.readString(); // speakers = in.createTypedArrayList(Speaker.CREATOR); // title = in.readString(); // description = in.readString(); // fromTime = (LocalDateTime) in.readSerializable(); // toTime = (LocalDateTime) in.readSerializable(); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(id); // dest.writeString(room); // dest.writeTypedList(speakers); // dest.writeString(title); // dest.writeString(description); // dest.writeSerializable(fromTime); // dest.writeSerializable(toTime); // } // } // Path: app/src/main/java/com/nilhcem/droidconde/ui/schedule/day/ScheduleDayFragmentAdapterAllSessions.java import android.support.v4.util.Pair; import android.support.v7.widget.RecyclerView; import android.view.ViewGroup; import com.nilhcem.droidconde.data.app.SelectedSessionsMemory; import com.nilhcem.droidconde.data.app.model.Room; import com.nilhcem.droidconde.data.app.model.ScheduleSlot; import com.nilhcem.droidconde.data.app.model.Session; import com.squareup.picasso.Picasso; import java.util.List; import java8.util.stream.Collectors; import static java8.util.stream.StreamSupport.stream; package com.nilhcem.droidconde.ui.schedule.day; public class ScheduleDayFragmentAdapterAllSessions extends RecyclerView.Adapter<ScheduleDayEntry> { private final List<Pair<Session, ScheduleSlot>> sessions; private final Picasso picasso;
private final SelectedSessionsMemory selectedSessionsMemory;
Nilhcem/droidconde-2016
app/src/main/java/com/nilhcem/droidconde/ui/sessions/details/SessionDetailsSpeaker.java
// Path: app/src/main/java/com/nilhcem/droidconde/data/app/model/Speaker.java // @Value // public class Speaker implements Parcelable { // // public static final Parcelable.Creator<Speaker> CREATOR = new Parcelable.Creator<Speaker>() { // public Speaker createFromParcel(Parcel source) { // return new Speaker(source); // } // // public Speaker[] newArray(int size) { // return new Speaker[size]; // } // }; // // int id; // String name; // String title; // String bio; // String website; // String twitter; // String github; // String photo; // // public Speaker(int id, String name, String title, String bio, String website, String twitter, String github, String photo) { // this.id = id; // this.name = name; // this.title = title; // this.bio = bio; // this.website = website; // this.twitter = twitter; // this.github = github; // this.photo = photo; // } // // protected Speaker(Parcel in) { // id = in.readInt(); // name = in.readString(); // title = in.readString(); // bio = in.readString(); // website = in.readString(); // twitter = in.readString(); // github = in.readString(); // photo = in.readString(); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(id); // dest.writeString(name); // dest.writeString(title); // dest.writeString(bio); // dest.writeString(website); // dest.writeString(twitter); // dest.writeString(github); // dest.writeString(photo); // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/ui/core/picasso/CircleTransformation.java // public class CircleTransformation implements Transformation { // // @Override // public Bitmap transform(Bitmap source) { // int size = Math.min(source.getWidth(), source.getHeight()); // // int x = (source.getWidth() - size) / 2; // int y = (source.getHeight() - size) / 2; // // Bitmap squaredBitmap = Bitmap.createBitmap(source, x, y, size, size); // if (squaredBitmap != source) { // source.recycle(); // } // // Bitmap.Config config = source.getConfig() != null ? source.getConfig() : Bitmap.Config.ARGB_8888; // Bitmap bitmap = Bitmap.createBitmap(size, size, config); // // Canvas canvas = new Canvas(bitmap); // Paint paint = new Paint(); // BitmapShader shader = new BitmapShader(squaredBitmap, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP); // paint.setShader(shader); // paint.setAntiAlias(true); // // float r = size / 2f; // canvas.drawCircle(r, r, r, paint); // // squaredBitmap.recycle(); // return bitmap; // } // // @Override // public String key() { // return "circle"; // } // }
import android.content.Context; import android.content.res.TypedArray; import android.text.TextUtils; import android.view.LayoutInflater; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.TextView; import com.nilhcem.droidconde.R; import com.nilhcem.droidconde.data.app.model.Speaker; import com.nilhcem.droidconde.ui.core.picasso.CircleTransformation; import com.squareup.picasso.Picasso; import butterknife.BindView; import butterknife.ButterKnife;
package com.nilhcem.droidconde.ui.sessions.details; public class SessionDetailsSpeaker extends FrameLayout { @BindView(R.id.session_details_speaker_photo) ImageView photo; @BindView(R.id.session_details_speaker_name) TextView name; @BindView(R.id.session_details_speaker_title) TextView title;
// Path: app/src/main/java/com/nilhcem/droidconde/data/app/model/Speaker.java // @Value // public class Speaker implements Parcelable { // // public static final Parcelable.Creator<Speaker> CREATOR = new Parcelable.Creator<Speaker>() { // public Speaker createFromParcel(Parcel source) { // return new Speaker(source); // } // // public Speaker[] newArray(int size) { // return new Speaker[size]; // } // }; // // int id; // String name; // String title; // String bio; // String website; // String twitter; // String github; // String photo; // // public Speaker(int id, String name, String title, String bio, String website, String twitter, String github, String photo) { // this.id = id; // this.name = name; // this.title = title; // this.bio = bio; // this.website = website; // this.twitter = twitter; // this.github = github; // this.photo = photo; // } // // protected Speaker(Parcel in) { // id = in.readInt(); // name = in.readString(); // title = in.readString(); // bio = in.readString(); // website = in.readString(); // twitter = in.readString(); // github = in.readString(); // photo = in.readString(); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(id); // dest.writeString(name); // dest.writeString(title); // dest.writeString(bio); // dest.writeString(website); // dest.writeString(twitter); // dest.writeString(github); // dest.writeString(photo); // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/ui/core/picasso/CircleTransformation.java // public class CircleTransformation implements Transformation { // // @Override // public Bitmap transform(Bitmap source) { // int size = Math.min(source.getWidth(), source.getHeight()); // // int x = (source.getWidth() - size) / 2; // int y = (source.getHeight() - size) / 2; // // Bitmap squaredBitmap = Bitmap.createBitmap(source, x, y, size, size); // if (squaredBitmap != source) { // source.recycle(); // } // // Bitmap.Config config = source.getConfig() != null ? source.getConfig() : Bitmap.Config.ARGB_8888; // Bitmap bitmap = Bitmap.createBitmap(size, size, config); // // Canvas canvas = new Canvas(bitmap); // Paint paint = new Paint(); // BitmapShader shader = new BitmapShader(squaredBitmap, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP); // paint.setShader(shader); // paint.setAntiAlias(true); // // float r = size / 2f; // canvas.drawCircle(r, r, r, paint); // // squaredBitmap.recycle(); // return bitmap; // } // // @Override // public String key() { // return "circle"; // } // } // Path: app/src/main/java/com/nilhcem/droidconde/ui/sessions/details/SessionDetailsSpeaker.java import android.content.Context; import android.content.res.TypedArray; import android.text.TextUtils; import android.view.LayoutInflater; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.TextView; import com.nilhcem.droidconde.R; import com.nilhcem.droidconde.data.app.model.Speaker; import com.nilhcem.droidconde.ui.core.picasso.CircleTransformation; import com.squareup.picasso.Picasso; import butterknife.BindView; import butterknife.ButterKnife; package com.nilhcem.droidconde.ui.sessions.details; public class SessionDetailsSpeaker extends FrameLayout { @BindView(R.id.session_details_speaker_photo) ImageView photo; @BindView(R.id.session_details_speaker_name) TextView name; @BindView(R.id.session_details_speaker_title) TextView title;
public SessionDetailsSpeaker(Context context, Speaker speaker, Picasso picasso) {
Nilhcem/droidconde-2016
app/src/main/java/com/nilhcem/droidconde/ui/sessions/details/SessionDetailsSpeaker.java
// Path: app/src/main/java/com/nilhcem/droidconde/data/app/model/Speaker.java // @Value // public class Speaker implements Parcelable { // // public static final Parcelable.Creator<Speaker> CREATOR = new Parcelable.Creator<Speaker>() { // public Speaker createFromParcel(Parcel source) { // return new Speaker(source); // } // // public Speaker[] newArray(int size) { // return new Speaker[size]; // } // }; // // int id; // String name; // String title; // String bio; // String website; // String twitter; // String github; // String photo; // // public Speaker(int id, String name, String title, String bio, String website, String twitter, String github, String photo) { // this.id = id; // this.name = name; // this.title = title; // this.bio = bio; // this.website = website; // this.twitter = twitter; // this.github = github; // this.photo = photo; // } // // protected Speaker(Parcel in) { // id = in.readInt(); // name = in.readString(); // title = in.readString(); // bio = in.readString(); // website = in.readString(); // twitter = in.readString(); // github = in.readString(); // photo = in.readString(); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(id); // dest.writeString(name); // dest.writeString(title); // dest.writeString(bio); // dest.writeString(website); // dest.writeString(twitter); // dest.writeString(github); // dest.writeString(photo); // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/ui/core/picasso/CircleTransformation.java // public class CircleTransformation implements Transformation { // // @Override // public Bitmap transform(Bitmap source) { // int size = Math.min(source.getWidth(), source.getHeight()); // // int x = (source.getWidth() - size) / 2; // int y = (source.getHeight() - size) / 2; // // Bitmap squaredBitmap = Bitmap.createBitmap(source, x, y, size, size); // if (squaredBitmap != source) { // source.recycle(); // } // // Bitmap.Config config = source.getConfig() != null ? source.getConfig() : Bitmap.Config.ARGB_8888; // Bitmap bitmap = Bitmap.createBitmap(size, size, config); // // Canvas canvas = new Canvas(bitmap); // Paint paint = new Paint(); // BitmapShader shader = new BitmapShader(squaredBitmap, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP); // paint.setShader(shader); // paint.setAntiAlias(true); // // float r = size / 2f; // canvas.drawCircle(r, r, r, paint); // // squaredBitmap.recycle(); // return bitmap; // } // // @Override // public String key() { // return "circle"; // } // }
import android.content.Context; import android.content.res.TypedArray; import android.text.TextUtils; import android.view.LayoutInflater; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.TextView; import com.nilhcem.droidconde.R; import com.nilhcem.droidconde.data.app.model.Speaker; import com.nilhcem.droidconde.ui.core.picasso.CircleTransformation; import com.squareup.picasso.Picasso; import butterknife.BindView; import butterknife.ButterKnife;
package com.nilhcem.droidconde.ui.sessions.details; public class SessionDetailsSpeaker extends FrameLayout { @BindView(R.id.session_details_speaker_photo) ImageView photo; @BindView(R.id.session_details_speaker_name) TextView name; @BindView(R.id.session_details_speaker_title) TextView title; public SessionDetailsSpeaker(Context context, Speaker speaker, Picasso picasso) { super(context); int[] attrs = new int[]{android.R.attr.selectableItemBackground}; TypedArray ta = context.obtainStyledAttributes(attrs); setForeground(ta.getDrawable(0)); ta.recycle(); LayoutInflater.from(context).inflate(R.layout.session_details_speaker, this); ButterKnife.bind(this, this); bind(speaker, picasso); } private void bind(Speaker speaker, Picasso picasso) { String photoUrl = speaker.getPhoto(); if (!TextUtils.isEmpty(photoUrl)) {
// Path: app/src/main/java/com/nilhcem/droidconde/data/app/model/Speaker.java // @Value // public class Speaker implements Parcelable { // // public static final Parcelable.Creator<Speaker> CREATOR = new Parcelable.Creator<Speaker>() { // public Speaker createFromParcel(Parcel source) { // return new Speaker(source); // } // // public Speaker[] newArray(int size) { // return new Speaker[size]; // } // }; // // int id; // String name; // String title; // String bio; // String website; // String twitter; // String github; // String photo; // // public Speaker(int id, String name, String title, String bio, String website, String twitter, String github, String photo) { // this.id = id; // this.name = name; // this.title = title; // this.bio = bio; // this.website = website; // this.twitter = twitter; // this.github = github; // this.photo = photo; // } // // protected Speaker(Parcel in) { // id = in.readInt(); // name = in.readString(); // title = in.readString(); // bio = in.readString(); // website = in.readString(); // twitter = in.readString(); // github = in.readString(); // photo = in.readString(); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(id); // dest.writeString(name); // dest.writeString(title); // dest.writeString(bio); // dest.writeString(website); // dest.writeString(twitter); // dest.writeString(github); // dest.writeString(photo); // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/ui/core/picasso/CircleTransformation.java // public class CircleTransformation implements Transformation { // // @Override // public Bitmap transform(Bitmap source) { // int size = Math.min(source.getWidth(), source.getHeight()); // // int x = (source.getWidth() - size) / 2; // int y = (source.getHeight() - size) / 2; // // Bitmap squaredBitmap = Bitmap.createBitmap(source, x, y, size, size); // if (squaredBitmap != source) { // source.recycle(); // } // // Bitmap.Config config = source.getConfig() != null ? source.getConfig() : Bitmap.Config.ARGB_8888; // Bitmap bitmap = Bitmap.createBitmap(size, size, config); // // Canvas canvas = new Canvas(bitmap); // Paint paint = new Paint(); // BitmapShader shader = new BitmapShader(squaredBitmap, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP); // paint.setShader(shader); // paint.setAntiAlias(true); // // float r = size / 2f; // canvas.drawCircle(r, r, r, paint); // // squaredBitmap.recycle(); // return bitmap; // } // // @Override // public String key() { // return "circle"; // } // } // Path: app/src/main/java/com/nilhcem/droidconde/ui/sessions/details/SessionDetailsSpeaker.java import android.content.Context; import android.content.res.TypedArray; import android.text.TextUtils; import android.view.LayoutInflater; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.TextView; import com.nilhcem.droidconde.R; import com.nilhcem.droidconde.data.app.model.Speaker; import com.nilhcem.droidconde.ui.core.picasso.CircleTransformation; import com.squareup.picasso.Picasso; import butterknife.BindView; import butterknife.ButterKnife; package com.nilhcem.droidconde.ui.sessions.details; public class SessionDetailsSpeaker extends FrameLayout { @BindView(R.id.session_details_speaker_photo) ImageView photo; @BindView(R.id.session_details_speaker_name) TextView name; @BindView(R.id.session_details_speaker_title) TextView title; public SessionDetailsSpeaker(Context context, Speaker speaker, Picasso picasso) { super(context); int[] attrs = new int[]{android.R.attr.selectableItemBackground}; TypedArray ta = context.obtainStyledAttributes(attrs); setForeground(ta.getDrawable(0)); ta.recycle(); LayoutInflater.from(context).inflate(R.layout.session_details_speaker, this); ButterKnife.bind(this, this); bind(speaker, picasso); } private void bind(Speaker speaker, Picasso picasso) { String photoUrl = speaker.getPhoto(); if (!TextUtils.isEmpty(photoUrl)) {
picasso.load(photoUrl).transform(new CircleTransformation()).into(photo);
Nilhcem/droidconde-2016
app/src/main/java/com/nilhcem/droidconde/ui/speakers/list/SpeakersListMvp.java
// Path: app/src/main/java/com/nilhcem/droidconde/data/app/model/Speaker.java // @Value // public class Speaker implements Parcelable { // // public static final Parcelable.Creator<Speaker> CREATOR = new Parcelable.Creator<Speaker>() { // public Speaker createFromParcel(Parcel source) { // return new Speaker(source); // } // // public Speaker[] newArray(int size) { // return new Speaker[size]; // } // }; // // int id; // String name; // String title; // String bio; // String website; // String twitter; // String github; // String photo; // // public Speaker(int id, String name, String title, String bio, String website, String twitter, String github, String photo) { // this.id = id; // this.name = name; // this.title = title; // this.bio = bio; // this.website = website; // this.twitter = twitter; // this.github = github; // this.photo = photo; // } // // protected Speaker(Parcel in) { // id = in.readInt(); // name = in.readString(); // title = in.readString(); // bio = in.readString(); // website = in.readString(); // twitter = in.readString(); // github = in.readString(); // photo = in.readString(); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(id); // dest.writeString(name); // dest.writeString(title); // dest.writeString(bio); // dest.writeString(website); // dest.writeString(twitter); // dest.writeString(github); // dest.writeString(photo); // } // }
import com.nilhcem.droidconde.data.app.model.Speaker; import java.util.List;
package com.nilhcem.droidconde.ui.speakers.list; public interface SpeakersListMvp { interface View {
// Path: app/src/main/java/com/nilhcem/droidconde/data/app/model/Speaker.java // @Value // public class Speaker implements Parcelable { // // public static final Parcelable.Creator<Speaker> CREATOR = new Parcelable.Creator<Speaker>() { // public Speaker createFromParcel(Parcel source) { // return new Speaker(source); // } // // public Speaker[] newArray(int size) { // return new Speaker[size]; // } // }; // // int id; // String name; // String title; // String bio; // String website; // String twitter; // String github; // String photo; // // public Speaker(int id, String name, String title, String bio, String website, String twitter, String github, String photo) { // this.id = id; // this.name = name; // this.title = title; // this.bio = bio; // this.website = website; // this.twitter = twitter; // this.github = github; // this.photo = photo; // } // // protected Speaker(Parcel in) { // id = in.readInt(); // name = in.readString(); // title = in.readString(); // bio = in.readString(); // website = in.readString(); // twitter = in.readString(); // github = in.readString(); // photo = in.readString(); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(id); // dest.writeString(name); // dest.writeString(title); // dest.writeString(bio); // dest.writeString(website); // dest.writeString(twitter); // dest.writeString(github); // dest.writeString(photo); // } // } // Path: app/src/main/java/com/nilhcem/droidconde/ui/speakers/list/SpeakersListMvp.java import com.nilhcem.droidconde.data.app.model.Speaker; import java.util.List; package com.nilhcem.droidconde.ui.speakers.list; public interface SpeakersListMvp { interface View {
void displaySpeakers(List<Speaker> speakers);
Nilhcem/droidconde-2016
app/src/main/java/com/nilhcem/droidconde/ui/schedule/day/ScheduleDayMvp.java
// Path: app/src/main/java/com/nilhcem/droidconde/data/app/model/ScheduleSlot.java // @Value // public class ScheduleSlot implements Parcelable { // // public static final Parcelable.Creator<ScheduleSlot> CREATOR = new Parcelable.Creator<ScheduleSlot>() { // public ScheduleSlot createFromParcel(Parcel source) { // return new ScheduleSlot(source); // } // // public ScheduleSlot[] newArray(int size) { // return new ScheduleSlot[size]; // } // }; // // LocalDateTime time; // List<Session> sessions; // // public ScheduleSlot(LocalDateTime time, List<Session> sessions) { // this.time = time; // this.sessions = sessions; // } // // protected ScheduleSlot(Parcel in) { // time = (LocalDateTime) in.readSerializable(); // sessions = in.createTypedArrayList(Session.CREATOR); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeSerializable(time); // dest.writeTypedList(sessions); // } // }
import com.nilhcem.droidconde.data.app.model.ScheduleSlot; import java.util.List;
package com.nilhcem.droidconde.ui.schedule.day; public interface ScheduleDayMvp { interface View {
// Path: app/src/main/java/com/nilhcem/droidconde/data/app/model/ScheduleSlot.java // @Value // public class ScheduleSlot implements Parcelable { // // public static final Parcelable.Creator<ScheduleSlot> CREATOR = new Parcelable.Creator<ScheduleSlot>() { // public ScheduleSlot createFromParcel(Parcel source) { // return new ScheduleSlot(source); // } // // public ScheduleSlot[] newArray(int size) { // return new ScheduleSlot[size]; // } // }; // // LocalDateTime time; // List<Session> sessions; // // public ScheduleSlot(LocalDateTime time, List<Session> sessions) { // this.time = time; // this.sessions = sessions; // } // // protected ScheduleSlot(Parcel in) { // time = (LocalDateTime) in.readSerializable(); // sessions = in.createTypedArrayList(Session.CREATOR); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeSerializable(time); // dest.writeTypedList(sessions); // } // } // Path: app/src/main/java/com/nilhcem/droidconde/ui/schedule/day/ScheduleDayMvp.java import com.nilhcem.droidconde.data.app.model.ScheduleSlot; import java.util.List; package com.nilhcem.droidconde.ui.schedule.day; public interface ScheduleDayMvp { interface View {
void initSlotsList(List<ScheduleSlot> slots);
Nilhcem/droidconde-2016
app/src/main/java/com/nilhcem/droidconde/data/database/model/Session.java
// Path: app/src/main/java/com/nilhcem/droidconde/utils/Database.java // public class Database { // // private Database() { // throw new UnsupportedOperationException(); // } // // public static String getString(Cursor cursor, String columnName) { // return cursor.getString(cursor.getColumnIndexOrThrow(columnName)); // } // // public static int getInt(Cursor cursor, String columnName) { // return cursor.getInt(cursor.getColumnIndexOrThrow(columnName)); // } // }
import android.content.ContentValues; import android.database.Cursor; import com.nilhcem.droidconde.utils.Database; import rx.functions.Func1;
package com.nilhcem.droidconde.data.database.model; public class Session { public static final String TABLE = "sessions"; public static final String ID = "_id"; public static final String START_AT = "start_at"; public static final String DURATION = "duration"; public static final String ROOM_ID = "room_id"; public static final String SPEAKERS_IDS = "speakers_ids"; public static final String TITLE = "title"; public static final String DESCRIPTION = "description"; public final int id; public final String startAt; public final int duration; public final int roomId; public final String speakersIds; public final String title; public final String description; public static final Func1<Cursor, Session> MAPPER = cursor -> {
// Path: app/src/main/java/com/nilhcem/droidconde/utils/Database.java // public class Database { // // private Database() { // throw new UnsupportedOperationException(); // } // // public static String getString(Cursor cursor, String columnName) { // return cursor.getString(cursor.getColumnIndexOrThrow(columnName)); // } // // public static int getInt(Cursor cursor, String columnName) { // return cursor.getInt(cursor.getColumnIndexOrThrow(columnName)); // } // } // Path: app/src/main/java/com/nilhcem/droidconde/data/database/model/Session.java import android.content.ContentValues; import android.database.Cursor; import com.nilhcem.droidconde.utils.Database; import rx.functions.Func1; package com.nilhcem.droidconde.data.database.model; public class Session { public static final String TABLE = "sessions"; public static final String ID = "_id"; public static final String START_AT = "start_at"; public static final String DURATION = "duration"; public static final String ROOM_ID = "room_id"; public static final String SPEAKERS_IDS = "speakers_ids"; public static final String TITLE = "title"; public static final String DESCRIPTION = "description"; public final int id; public final String startAt; public final int duration; public final int roomId; public final String speakersIds; public final String title; public final String description; public static final Func1<Cursor, Session> MAPPER = cursor -> {
int id = Database.getInt(cursor, ID);
Nilhcem/droidconde-2016
app/src/test/java/com/nilhcem/droidconde/data/app/AppMapperTest.java
// Path: app/src/main/java/com/nilhcem/droidconde/data/app/model/Schedule.java // public class Schedule extends ArrayList<ScheduleDay> implements Parcelable { // // public static final Parcelable.Creator<Schedule> CREATOR = new Parcelable.Creator<Schedule>() { // public Schedule createFromParcel(Parcel source) { // return new Schedule(source); // } // // public Schedule[] newArray(int size) { // return new Schedule[size]; // } // }; // // public Schedule() { // } // // protected Schedule(Parcel in) { // addAll(in.createTypedArrayList(ScheduleDay.CREATOR)); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeTypedList(this); // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/data/app/model/Session.java // @Value // public class Session implements Parcelable { // // public static final Parcelable.Creator<Session> CREATOR = new Parcelable.Creator<Session>() { // public Session createFromParcel(Parcel source) { // return new Session(source); // } // // public Session[] newArray(int size) { // return new Session[size]; // } // }; // // int id; // String room; // List<Speaker> speakers; // String title; // String description; // LocalDateTime fromTime; // LocalDateTime toTime; // // public Session(int id, String room, List<Speaker> speakers, String title, String description, LocalDateTime fromTime, LocalDateTime toTime) { // this.id = id; // this.room = room; // this.speakers = speakers; // this.title = title; // this.description = description; // this.fromTime = fromTime; // this.toTime = toTime; // } // // protected Session(Parcel in) { // id = in.readInt(); // room = in.readString(); // speakers = in.createTypedArrayList(Speaker.CREATOR); // title = in.readString(); // description = in.readString(); // fromTime = (LocalDateTime) in.readSerializable(); // toTime = (LocalDateTime) in.readSerializable(); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(id); // dest.writeString(room); // dest.writeTypedList(speakers); // dest.writeString(title); // dest.writeString(description); // dest.writeSerializable(fromTime); // dest.writeSerializable(toTime); // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/data/app/model/Speaker.java // @Value // public class Speaker implements Parcelable { // // public static final Parcelable.Creator<Speaker> CREATOR = new Parcelable.Creator<Speaker>() { // public Speaker createFromParcel(Parcel source) { // return new Speaker(source); // } // // public Speaker[] newArray(int size) { // return new Speaker[size]; // } // }; // // int id; // String name; // String title; // String bio; // String website; // String twitter; // String github; // String photo; // // public Speaker(int id, String name, String title, String bio, String website, String twitter, String github, String photo) { // this.id = id; // this.name = name; // this.title = title; // this.bio = bio; // this.website = website; // this.twitter = twitter; // this.github = github; // this.photo = photo; // } // // protected Speaker(Parcel in) { // id = in.readInt(); // name = in.readString(); // title = in.readString(); // bio = in.readString(); // website = in.readString(); // twitter = in.readString(); // github = in.readString(); // photo = in.readString(); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(id); // dest.writeString(name); // dest.writeString(title); // dest.writeString(bio); // dest.writeString(website); // dest.writeString(twitter); // dest.writeString(github); // dest.writeString(photo); // } // }
import android.os.Build; import com.nilhcem.droidconde.BuildConfig; import com.nilhcem.droidconde.data.app.model.Schedule; import com.nilhcem.droidconde.data.app.model.Session; import com.nilhcem.droidconde.data.app.model.Speaker; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricGradleTestRunner; import org.robolectric.annotation.Config; import org.threeten.bp.LocalDateTime; import java.util.Arrays; import java.util.List; import java.util.Map; import static com.google.common.truth.Truth.assertThat; import static java.util.Collections.singletonList;
package com.nilhcem.droidconde.data.app; @RunWith(RobolectricGradleTestRunner.class) @Config(constants = BuildConfig.class, sdk = Build.VERSION_CODES.LOLLIPOP) public class AppMapperTest { private final AppMapper appMapper = new AppMapper();
// Path: app/src/main/java/com/nilhcem/droidconde/data/app/model/Schedule.java // public class Schedule extends ArrayList<ScheduleDay> implements Parcelable { // // public static final Parcelable.Creator<Schedule> CREATOR = new Parcelable.Creator<Schedule>() { // public Schedule createFromParcel(Parcel source) { // return new Schedule(source); // } // // public Schedule[] newArray(int size) { // return new Schedule[size]; // } // }; // // public Schedule() { // } // // protected Schedule(Parcel in) { // addAll(in.createTypedArrayList(ScheduleDay.CREATOR)); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeTypedList(this); // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/data/app/model/Session.java // @Value // public class Session implements Parcelable { // // public static final Parcelable.Creator<Session> CREATOR = new Parcelable.Creator<Session>() { // public Session createFromParcel(Parcel source) { // return new Session(source); // } // // public Session[] newArray(int size) { // return new Session[size]; // } // }; // // int id; // String room; // List<Speaker> speakers; // String title; // String description; // LocalDateTime fromTime; // LocalDateTime toTime; // // public Session(int id, String room, List<Speaker> speakers, String title, String description, LocalDateTime fromTime, LocalDateTime toTime) { // this.id = id; // this.room = room; // this.speakers = speakers; // this.title = title; // this.description = description; // this.fromTime = fromTime; // this.toTime = toTime; // } // // protected Session(Parcel in) { // id = in.readInt(); // room = in.readString(); // speakers = in.createTypedArrayList(Speaker.CREATOR); // title = in.readString(); // description = in.readString(); // fromTime = (LocalDateTime) in.readSerializable(); // toTime = (LocalDateTime) in.readSerializable(); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(id); // dest.writeString(room); // dest.writeTypedList(speakers); // dest.writeString(title); // dest.writeString(description); // dest.writeSerializable(fromTime); // dest.writeSerializable(toTime); // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/data/app/model/Speaker.java // @Value // public class Speaker implements Parcelable { // // public static final Parcelable.Creator<Speaker> CREATOR = new Parcelable.Creator<Speaker>() { // public Speaker createFromParcel(Parcel source) { // return new Speaker(source); // } // // public Speaker[] newArray(int size) { // return new Speaker[size]; // } // }; // // int id; // String name; // String title; // String bio; // String website; // String twitter; // String github; // String photo; // // public Speaker(int id, String name, String title, String bio, String website, String twitter, String github, String photo) { // this.id = id; // this.name = name; // this.title = title; // this.bio = bio; // this.website = website; // this.twitter = twitter; // this.github = github; // this.photo = photo; // } // // protected Speaker(Parcel in) { // id = in.readInt(); // name = in.readString(); // title = in.readString(); // bio = in.readString(); // website = in.readString(); // twitter = in.readString(); // github = in.readString(); // photo = in.readString(); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(id); // dest.writeString(name); // dest.writeString(title); // dest.writeString(bio); // dest.writeString(website); // dest.writeString(twitter); // dest.writeString(github); // dest.writeString(photo); // } // } // Path: app/src/test/java/com/nilhcem/droidconde/data/app/AppMapperTest.java import android.os.Build; import com.nilhcem.droidconde.BuildConfig; import com.nilhcem.droidconde.data.app.model.Schedule; import com.nilhcem.droidconde.data.app.model.Session; import com.nilhcem.droidconde.data.app.model.Speaker; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricGradleTestRunner; import org.robolectric.annotation.Config; import org.threeten.bp.LocalDateTime; import java.util.Arrays; import java.util.List; import java.util.Map; import static com.google.common.truth.Truth.assertThat; import static java.util.Collections.singletonList; package com.nilhcem.droidconde.data.app; @RunWith(RobolectricGradleTestRunner.class) @Config(constants = BuildConfig.class, sdk = Build.VERSION_CODES.LOLLIPOP) public class AppMapperTest { private final AppMapper appMapper = new AppMapper();
private final Speaker speaker1 = new Speaker(10, "Gautier", null, null, null, null, null, null);
Nilhcem/droidconde-2016
app/src/main/java/com/nilhcem/droidconde/receiver/BootReceiver.java
// Path: app/src/main/java/com/nilhcem/droidconde/DroidconApp.java // @DebugLog // public class DroidconApp extends Application { // // private AppComponent component; // // public static DroidconApp get(Context context) { // return (DroidconApp) context.getApplicationContext(); // } // // @Override // public void onCreate() { // super.onCreate(); // AndroidThreeTen.init(this); // initGraph(); // initLogger(); // } // // public AppComponent component() { // return component; // } // // private void initGraph() { // component = AppComponent.Initializer.init(this); // } // // private void initLogger() { // Timber.plant(new Timber.DebugTree()); // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/receiver/reminder/SessionsReminder.java // @Singleton // public class SessionsReminder { // // private final Context context; // private final SessionsDao sessionsDao; // private final SharedPreferences preferences; // private final AlarmManager alarmManager; // // @Inject // public SessionsReminder(Application app, SessionsDao sessionsDao, SharedPreferences preferences) { // this.context = app; // this.sessionsDao = sessionsDao; // this.preferences = preferences; // alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); // } // // public boolean isEnabled() { // return preferences.getBoolean(context.getString(R.string.settings_notify_key), false); // } // // public void enableSessionReminder() { // performOnSelectedSessions(this::addSessionReminder); // } // // public void disableSessionReminder() { // performOnSelectedSessions(this::removeSessionReminder); // } // // public void addSessionReminder(@NonNull Session session) { // if (!isEnabled()) { // Timber.d("SessionsReminder is not enable, skip adding session"); // return; // } // // PendingIntent intent = createSessionReminderIntent(session); // LocalDateTime now = LocalDateTime.now(); // LocalDateTime sessionStartTime = session.getFromTime().minusMinutes(3); // if (!sessionStartTime.isAfter(now)) { // Timber.w("Do not set reminder for passed session"); // return; // } // Timber.d("Setting reminder on %s", sessionStartTime); // App.setExactAlarm(alarmManager, sessionStartTime.atZone(ZoneOffset.systemDefault()).toInstant().toEpochMilli(), intent); // } // // public void removeSessionReminder(@NonNull Session session) { // Timber.d("Cancelling reminder on %s", session.getFromTime().minusMinutes(3)); // createSessionReminderIntent(session).cancel(); // } // // private PendingIntent createSessionReminderIntent(@NonNull Session session) { // Intent intent = new ReminderReceiverIntentBuilder(session).build(context); // return PendingIntent.getBroadcast(context, session.getId(), intent, PendingIntent.FLAG_UPDATE_CURRENT); // } // // private void performOnSelectedSessions(Action1<? super Session> onNext) { // sessionsDao.getSelectedSessions() // .flatMap(Observable::from) // .subscribeOn(Schedulers.io()) // .observeOn(Schedulers.computation()) // .subscribe(onNext, throwable -> Timber.e(throwable, "Error getting sessions")); // } // }
import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import com.nilhcem.droidconde.DroidconApp; import com.nilhcem.droidconde.receiver.reminder.SessionsReminder; import javax.inject.Inject; import hugo.weaving.DebugLog;
package com.nilhcem.droidconde.receiver; @DebugLog public class BootReceiver extends BroadcastReceiver {
// Path: app/src/main/java/com/nilhcem/droidconde/DroidconApp.java // @DebugLog // public class DroidconApp extends Application { // // private AppComponent component; // // public static DroidconApp get(Context context) { // return (DroidconApp) context.getApplicationContext(); // } // // @Override // public void onCreate() { // super.onCreate(); // AndroidThreeTen.init(this); // initGraph(); // initLogger(); // } // // public AppComponent component() { // return component; // } // // private void initGraph() { // component = AppComponent.Initializer.init(this); // } // // private void initLogger() { // Timber.plant(new Timber.DebugTree()); // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/receiver/reminder/SessionsReminder.java // @Singleton // public class SessionsReminder { // // private final Context context; // private final SessionsDao sessionsDao; // private final SharedPreferences preferences; // private final AlarmManager alarmManager; // // @Inject // public SessionsReminder(Application app, SessionsDao sessionsDao, SharedPreferences preferences) { // this.context = app; // this.sessionsDao = sessionsDao; // this.preferences = preferences; // alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); // } // // public boolean isEnabled() { // return preferences.getBoolean(context.getString(R.string.settings_notify_key), false); // } // // public void enableSessionReminder() { // performOnSelectedSessions(this::addSessionReminder); // } // // public void disableSessionReminder() { // performOnSelectedSessions(this::removeSessionReminder); // } // // public void addSessionReminder(@NonNull Session session) { // if (!isEnabled()) { // Timber.d("SessionsReminder is not enable, skip adding session"); // return; // } // // PendingIntent intent = createSessionReminderIntent(session); // LocalDateTime now = LocalDateTime.now(); // LocalDateTime sessionStartTime = session.getFromTime().minusMinutes(3); // if (!sessionStartTime.isAfter(now)) { // Timber.w("Do not set reminder for passed session"); // return; // } // Timber.d("Setting reminder on %s", sessionStartTime); // App.setExactAlarm(alarmManager, sessionStartTime.atZone(ZoneOffset.systemDefault()).toInstant().toEpochMilli(), intent); // } // // public void removeSessionReminder(@NonNull Session session) { // Timber.d("Cancelling reminder on %s", session.getFromTime().minusMinutes(3)); // createSessionReminderIntent(session).cancel(); // } // // private PendingIntent createSessionReminderIntent(@NonNull Session session) { // Intent intent = new ReminderReceiverIntentBuilder(session).build(context); // return PendingIntent.getBroadcast(context, session.getId(), intent, PendingIntent.FLAG_UPDATE_CURRENT); // } // // private void performOnSelectedSessions(Action1<? super Session> onNext) { // sessionsDao.getSelectedSessions() // .flatMap(Observable::from) // .subscribeOn(Schedulers.io()) // .observeOn(Schedulers.computation()) // .subscribe(onNext, throwable -> Timber.e(throwable, "Error getting sessions")); // } // } // Path: app/src/main/java/com/nilhcem/droidconde/receiver/BootReceiver.java import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import com.nilhcem.droidconde.DroidconApp; import com.nilhcem.droidconde.receiver.reminder.SessionsReminder; import javax.inject.Inject; import hugo.weaving.DebugLog; package com.nilhcem.droidconde.receiver; @DebugLog public class BootReceiver extends BroadcastReceiver {
@Inject SessionsReminder sessionsReminder;
Nilhcem/droidconde-2016
app/src/main/java/com/nilhcem/droidconde/receiver/BootReceiver.java
// Path: app/src/main/java/com/nilhcem/droidconde/DroidconApp.java // @DebugLog // public class DroidconApp extends Application { // // private AppComponent component; // // public static DroidconApp get(Context context) { // return (DroidconApp) context.getApplicationContext(); // } // // @Override // public void onCreate() { // super.onCreate(); // AndroidThreeTen.init(this); // initGraph(); // initLogger(); // } // // public AppComponent component() { // return component; // } // // private void initGraph() { // component = AppComponent.Initializer.init(this); // } // // private void initLogger() { // Timber.plant(new Timber.DebugTree()); // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/receiver/reminder/SessionsReminder.java // @Singleton // public class SessionsReminder { // // private final Context context; // private final SessionsDao sessionsDao; // private final SharedPreferences preferences; // private final AlarmManager alarmManager; // // @Inject // public SessionsReminder(Application app, SessionsDao sessionsDao, SharedPreferences preferences) { // this.context = app; // this.sessionsDao = sessionsDao; // this.preferences = preferences; // alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); // } // // public boolean isEnabled() { // return preferences.getBoolean(context.getString(R.string.settings_notify_key), false); // } // // public void enableSessionReminder() { // performOnSelectedSessions(this::addSessionReminder); // } // // public void disableSessionReminder() { // performOnSelectedSessions(this::removeSessionReminder); // } // // public void addSessionReminder(@NonNull Session session) { // if (!isEnabled()) { // Timber.d("SessionsReminder is not enable, skip adding session"); // return; // } // // PendingIntent intent = createSessionReminderIntent(session); // LocalDateTime now = LocalDateTime.now(); // LocalDateTime sessionStartTime = session.getFromTime().minusMinutes(3); // if (!sessionStartTime.isAfter(now)) { // Timber.w("Do not set reminder for passed session"); // return; // } // Timber.d("Setting reminder on %s", sessionStartTime); // App.setExactAlarm(alarmManager, sessionStartTime.atZone(ZoneOffset.systemDefault()).toInstant().toEpochMilli(), intent); // } // // public void removeSessionReminder(@NonNull Session session) { // Timber.d("Cancelling reminder on %s", session.getFromTime().minusMinutes(3)); // createSessionReminderIntent(session).cancel(); // } // // private PendingIntent createSessionReminderIntent(@NonNull Session session) { // Intent intent = new ReminderReceiverIntentBuilder(session).build(context); // return PendingIntent.getBroadcast(context, session.getId(), intent, PendingIntent.FLAG_UPDATE_CURRENT); // } // // private void performOnSelectedSessions(Action1<? super Session> onNext) { // sessionsDao.getSelectedSessions() // .flatMap(Observable::from) // .subscribeOn(Schedulers.io()) // .observeOn(Schedulers.computation()) // .subscribe(onNext, throwable -> Timber.e(throwable, "Error getting sessions")); // } // }
import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import com.nilhcem.droidconde.DroidconApp; import com.nilhcem.droidconde.receiver.reminder.SessionsReminder; import javax.inject.Inject; import hugo.weaving.DebugLog;
package com.nilhcem.droidconde.receiver; @DebugLog public class BootReceiver extends BroadcastReceiver { @Inject SessionsReminder sessionsReminder; public BootReceiver() { } public static void enable(Context context) { setActivationState(context, PackageManager.COMPONENT_ENABLED_STATE_ENABLED); } public static void disable(Context context) { setActivationState(context, PackageManager.COMPONENT_ENABLED_STATE_DISABLED); } private static void setActivationState(Context context, int state) { ComponentName componentName = new ComponentName(context, BootReceiver.class); PackageManager pm = context.getPackageManager(); pm.setComponentEnabledSetting(componentName, state, PackageManager.DONT_KILL_APP); } @Override public void onReceive(Context context, Intent intent) {
// Path: app/src/main/java/com/nilhcem/droidconde/DroidconApp.java // @DebugLog // public class DroidconApp extends Application { // // private AppComponent component; // // public static DroidconApp get(Context context) { // return (DroidconApp) context.getApplicationContext(); // } // // @Override // public void onCreate() { // super.onCreate(); // AndroidThreeTen.init(this); // initGraph(); // initLogger(); // } // // public AppComponent component() { // return component; // } // // private void initGraph() { // component = AppComponent.Initializer.init(this); // } // // private void initLogger() { // Timber.plant(new Timber.DebugTree()); // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/receiver/reminder/SessionsReminder.java // @Singleton // public class SessionsReminder { // // private final Context context; // private final SessionsDao sessionsDao; // private final SharedPreferences preferences; // private final AlarmManager alarmManager; // // @Inject // public SessionsReminder(Application app, SessionsDao sessionsDao, SharedPreferences preferences) { // this.context = app; // this.sessionsDao = sessionsDao; // this.preferences = preferences; // alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); // } // // public boolean isEnabled() { // return preferences.getBoolean(context.getString(R.string.settings_notify_key), false); // } // // public void enableSessionReminder() { // performOnSelectedSessions(this::addSessionReminder); // } // // public void disableSessionReminder() { // performOnSelectedSessions(this::removeSessionReminder); // } // // public void addSessionReminder(@NonNull Session session) { // if (!isEnabled()) { // Timber.d("SessionsReminder is not enable, skip adding session"); // return; // } // // PendingIntent intent = createSessionReminderIntent(session); // LocalDateTime now = LocalDateTime.now(); // LocalDateTime sessionStartTime = session.getFromTime().minusMinutes(3); // if (!sessionStartTime.isAfter(now)) { // Timber.w("Do not set reminder for passed session"); // return; // } // Timber.d("Setting reminder on %s", sessionStartTime); // App.setExactAlarm(alarmManager, sessionStartTime.atZone(ZoneOffset.systemDefault()).toInstant().toEpochMilli(), intent); // } // // public void removeSessionReminder(@NonNull Session session) { // Timber.d("Cancelling reminder on %s", session.getFromTime().minusMinutes(3)); // createSessionReminderIntent(session).cancel(); // } // // private PendingIntent createSessionReminderIntent(@NonNull Session session) { // Intent intent = new ReminderReceiverIntentBuilder(session).build(context); // return PendingIntent.getBroadcast(context, session.getId(), intent, PendingIntent.FLAG_UPDATE_CURRENT); // } // // private void performOnSelectedSessions(Action1<? super Session> onNext) { // sessionsDao.getSelectedSessions() // .flatMap(Observable::from) // .subscribeOn(Schedulers.io()) // .observeOn(Schedulers.computation()) // .subscribe(onNext, throwable -> Timber.e(throwable, "Error getting sessions")); // } // } // Path: app/src/main/java/com/nilhcem/droidconde/receiver/BootReceiver.java import android.content.BroadcastReceiver; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import com.nilhcem.droidconde.DroidconApp; import com.nilhcem.droidconde.receiver.reminder.SessionsReminder; import javax.inject.Inject; import hugo.weaving.DebugLog; package com.nilhcem.droidconde.receiver; @DebugLog public class BootReceiver extends BroadcastReceiver { @Inject SessionsReminder sessionsReminder; public BootReceiver() { } public static void enable(Context context) { setActivationState(context, PackageManager.COMPONENT_ENABLED_STATE_ENABLED); } public static void disable(Context context) { setActivationState(context, PackageManager.COMPONENT_ENABLED_STATE_DISABLED); } private static void setActivationState(Context context, int state) { ComponentName componentName = new ComponentName(context, BootReceiver.class); PackageManager pm = context.getPackageManager(); pm.setComponentEnabledSetting(componentName, state, PackageManager.DONT_KILL_APP); } @Override public void onReceive(Context context, Intent intent) {
DroidconApp.get(context).component().inject(this);
Nilhcem/droidconde-2016
app/src/main/java/com/nilhcem/droidconde/ui/sessions/list/SessionsListPresenter.java
// Path: app/src/main/java/com/nilhcem/droidconde/data/app/model/ScheduleSlot.java // @Value // public class ScheduleSlot implements Parcelable { // // public static final Parcelable.Creator<ScheduleSlot> CREATOR = new Parcelable.Creator<ScheduleSlot>() { // public ScheduleSlot createFromParcel(Parcel source) { // return new ScheduleSlot(source); // } // // public ScheduleSlot[] newArray(int size) { // return new ScheduleSlot[size]; // } // }; // // LocalDateTime time; // List<Session> sessions; // // public ScheduleSlot(LocalDateTime time, List<Session> sessions) { // this.time = time; // this.sessions = sessions; // } // // protected ScheduleSlot(Parcel in) { // time = (LocalDateTime) in.readSerializable(); // sessions = in.createTypedArrayList(Session.CREATOR); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeSerializable(time); // dest.writeTypedList(sessions); // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/data/app/model/Session.java // @Value // public class Session implements Parcelable { // // public static final Parcelable.Creator<Session> CREATOR = new Parcelable.Creator<Session>() { // public Session createFromParcel(Parcel source) { // return new Session(source); // } // // public Session[] newArray(int size) { // return new Session[size]; // } // }; // // int id; // String room; // List<Speaker> speakers; // String title; // String description; // LocalDateTime fromTime; // LocalDateTime toTime; // // public Session(int id, String room, List<Speaker> speakers, String title, String description, LocalDateTime fromTime, LocalDateTime toTime) { // this.id = id; // this.room = room; // this.speakers = speakers; // this.title = title; // this.description = description; // this.fromTime = fromTime; // this.toTime = toTime; // } // // protected Session(Parcel in) { // id = in.readInt(); // room = in.readString(); // speakers = in.createTypedArrayList(Speaker.CREATOR); // title = in.readString(); // description = in.readString(); // fromTime = (LocalDateTime) in.readSerializable(); // toTime = (LocalDateTime) in.readSerializable(); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(id); // dest.writeString(room); // dest.writeTypedList(speakers); // dest.writeString(title); // dest.writeString(description); // dest.writeSerializable(fromTime); // dest.writeSerializable(toTime); // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/ui/BaseActivityPresenter.java // public abstract class BaseActivityPresenter<V> extends BasePresenter<V> { // // public BaseActivityPresenter(V view) { // super(view); // } // // public void onPostCreate(Bundle savedInstanceState) { // // Nothing to do by default // } // // public void onResume() { // // Nothing to do by default // } // // @CallSuper // public void onSaveInstanceState(Bundle outState) { // Icepick.saveInstanceState(this, outState); // } // // @CallSuper // public void onRestoreInstanceState(Bundle savedInstanceState) { // Icepick.restoreInstanceState(this, savedInstanceState); // } // // public void onNavigationItemSelected(@IdRes int itemId) { // // Nothing to do by default // } // // public boolean onBackPressed() { // return false; // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/utils/Strings.java // public class Strings { // // private Strings() { // throw new UnsupportedOperationException(); // } // // public static String capitalizeFirstLetter(@NonNull String src) { // return src.substring(0, 1).toUpperCase(Locale.getDefault()) + src.substring(1); // } // }
import android.content.Context; import android.os.Bundle; import com.nilhcem.droidconde.R; import com.nilhcem.droidconde.data.app.model.ScheduleSlot; import com.nilhcem.droidconde.data.app.model.Session; import com.nilhcem.droidconde.ui.BaseActivityPresenter; import com.nilhcem.droidconde.utils.Strings; import org.threeten.bp.LocalDateTime; import org.threeten.bp.format.DateTimeFormatter; import org.threeten.bp.format.FormatStyle; import java.util.List; import java.util.Locale;
package com.nilhcem.droidconde.ui.sessions.list; public class SessionsListPresenter extends BaseActivityPresenter<SessionsListMvp.View> { private final List<Session> sessions;
// Path: app/src/main/java/com/nilhcem/droidconde/data/app/model/ScheduleSlot.java // @Value // public class ScheduleSlot implements Parcelable { // // public static final Parcelable.Creator<ScheduleSlot> CREATOR = new Parcelable.Creator<ScheduleSlot>() { // public ScheduleSlot createFromParcel(Parcel source) { // return new ScheduleSlot(source); // } // // public ScheduleSlot[] newArray(int size) { // return new ScheduleSlot[size]; // } // }; // // LocalDateTime time; // List<Session> sessions; // // public ScheduleSlot(LocalDateTime time, List<Session> sessions) { // this.time = time; // this.sessions = sessions; // } // // protected ScheduleSlot(Parcel in) { // time = (LocalDateTime) in.readSerializable(); // sessions = in.createTypedArrayList(Session.CREATOR); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeSerializable(time); // dest.writeTypedList(sessions); // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/data/app/model/Session.java // @Value // public class Session implements Parcelable { // // public static final Parcelable.Creator<Session> CREATOR = new Parcelable.Creator<Session>() { // public Session createFromParcel(Parcel source) { // return new Session(source); // } // // public Session[] newArray(int size) { // return new Session[size]; // } // }; // // int id; // String room; // List<Speaker> speakers; // String title; // String description; // LocalDateTime fromTime; // LocalDateTime toTime; // // public Session(int id, String room, List<Speaker> speakers, String title, String description, LocalDateTime fromTime, LocalDateTime toTime) { // this.id = id; // this.room = room; // this.speakers = speakers; // this.title = title; // this.description = description; // this.fromTime = fromTime; // this.toTime = toTime; // } // // protected Session(Parcel in) { // id = in.readInt(); // room = in.readString(); // speakers = in.createTypedArrayList(Speaker.CREATOR); // title = in.readString(); // description = in.readString(); // fromTime = (LocalDateTime) in.readSerializable(); // toTime = (LocalDateTime) in.readSerializable(); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(id); // dest.writeString(room); // dest.writeTypedList(speakers); // dest.writeString(title); // dest.writeString(description); // dest.writeSerializable(fromTime); // dest.writeSerializable(toTime); // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/ui/BaseActivityPresenter.java // public abstract class BaseActivityPresenter<V> extends BasePresenter<V> { // // public BaseActivityPresenter(V view) { // super(view); // } // // public void onPostCreate(Bundle savedInstanceState) { // // Nothing to do by default // } // // public void onResume() { // // Nothing to do by default // } // // @CallSuper // public void onSaveInstanceState(Bundle outState) { // Icepick.saveInstanceState(this, outState); // } // // @CallSuper // public void onRestoreInstanceState(Bundle savedInstanceState) { // Icepick.restoreInstanceState(this, savedInstanceState); // } // // public void onNavigationItemSelected(@IdRes int itemId) { // // Nothing to do by default // } // // public boolean onBackPressed() { // return false; // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/utils/Strings.java // public class Strings { // // private Strings() { // throw new UnsupportedOperationException(); // } // // public static String capitalizeFirstLetter(@NonNull String src) { // return src.substring(0, 1).toUpperCase(Locale.getDefault()) + src.substring(1); // } // } // Path: app/src/main/java/com/nilhcem/droidconde/ui/sessions/list/SessionsListPresenter.java import android.content.Context; import android.os.Bundle; import com.nilhcem.droidconde.R; import com.nilhcem.droidconde.data.app.model.ScheduleSlot; import com.nilhcem.droidconde.data.app.model.Session; import com.nilhcem.droidconde.ui.BaseActivityPresenter; import com.nilhcem.droidconde.utils.Strings; import org.threeten.bp.LocalDateTime; import org.threeten.bp.format.DateTimeFormatter; import org.threeten.bp.format.FormatStyle; import java.util.List; import java.util.Locale; package com.nilhcem.droidconde.ui.sessions.list; public class SessionsListPresenter extends BaseActivityPresenter<SessionsListMvp.View> { private final List<Session> sessions;
public SessionsListPresenter(Context context, SessionsListMvp.View view, ScheduleSlot slot) {
Nilhcem/droidconde-2016
app/src/main/java/com/nilhcem/droidconde/ui/sessions/list/SessionsListPresenter.java
// Path: app/src/main/java/com/nilhcem/droidconde/data/app/model/ScheduleSlot.java // @Value // public class ScheduleSlot implements Parcelable { // // public static final Parcelable.Creator<ScheduleSlot> CREATOR = new Parcelable.Creator<ScheduleSlot>() { // public ScheduleSlot createFromParcel(Parcel source) { // return new ScheduleSlot(source); // } // // public ScheduleSlot[] newArray(int size) { // return new ScheduleSlot[size]; // } // }; // // LocalDateTime time; // List<Session> sessions; // // public ScheduleSlot(LocalDateTime time, List<Session> sessions) { // this.time = time; // this.sessions = sessions; // } // // protected ScheduleSlot(Parcel in) { // time = (LocalDateTime) in.readSerializable(); // sessions = in.createTypedArrayList(Session.CREATOR); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeSerializable(time); // dest.writeTypedList(sessions); // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/data/app/model/Session.java // @Value // public class Session implements Parcelable { // // public static final Parcelable.Creator<Session> CREATOR = new Parcelable.Creator<Session>() { // public Session createFromParcel(Parcel source) { // return new Session(source); // } // // public Session[] newArray(int size) { // return new Session[size]; // } // }; // // int id; // String room; // List<Speaker> speakers; // String title; // String description; // LocalDateTime fromTime; // LocalDateTime toTime; // // public Session(int id, String room, List<Speaker> speakers, String title, String description, LocalDateTime fromTime, LocalDateTime toTime) { // this.id = id; // this.room = room; // this.speakers = speakers; // this.title = title; // this.description = description; // this.fromTime = fromTime; // this.toTime = toTime; // } // // protected Session(Parcel in) { // id = in.readInt(); // room = in.readString(); // speakers = in.createTypedArrayList(Speaker.CREATOR); // title = in.readString(); // description = in.readString(); // fromTime = (LocalDateTime) in.readSerializable(); // toTime = (LocalDateTime) in.readSerializable(); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(id); // dest.writeString(room); // dest.writeTypedList(speakers); // dest.writeString(title); // dest.writeString(description); // dest.writeSerializable(fromTime); // dest.writeSerializable(toTime); // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/ui/BaseActivityPresenter.java // public abstract class BaseActivityPresenter<V> extends BasePresenter<V> { // // public BaseActivityPresenter(V view) { // super(view); // } // // public void onPostCreate(Bundle savedInstanceState) { // // Nothing to do by default // } // // public void onResume() { // // Nothing to do by default // } // // @CallSuper // public void onSaveInstanceState(Bundle outState) { // Icepick.saveInstanceState(this, outState); // } // // @CallSuper // public void onRestoreInstanceState(Bundle savedInstanceState) { // Icepick.restoreInstanceState(this, savedInstanceState); // } // // public void onNavigationItemSelected(@IdRes int itemId) { // // Nothing to do by default // } // // public boolean onBackPressed() { // return false; // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/utils/Strings.java // public class Strings { // // private Strings() { // throw new UnsupportedOperationException(); // } // // public static String capitalizeFirstLetter(@NonNull String src) { // return src.substring(0, 1).toUpperCase(Locale.getDefault()) + src.substring(1); // } // }
import android.content.Context; import android.os.Bundle; import com.nilhcem.droidconde.R; import com.nilhcem.droidconde.data.app.model.ScheduleSlot; import com.nilhcem.droidconde.data.app.model.Session; import com.nilhcem.droidconde.ui.BaseActivityPresenter; import com.nilhcem.droidconde.utils.Strings; import org.threeten.bp.LocalDateTime; import org.threeten.bp.format.DateTimeFormatter; import org.threeten.bp.format.FormatStyle; import java.util.List; import java.util.Locale;
package com.nilhcem.droidconde.ui.sessions.list; public class SessionsListPresenter extends BaseActivityPresenter<SessionsListMvp.View> { private final List<Session> sessions; public SessionsListPresenter(Context context, SessionsListMvp.View view, ScheduleSlot slot) { super(view); this.view.initToobar(formatDateTime(context, slot.getTime())); sessions = slot.getSessions(); } @Override public void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); this.view.initSessionsList(sessions); } private String formatDateTime(Context context, LocalDateTime dateTime) { String dayPattern = context.getString(R.string.schedule_pager_day_pattern); DateTimeFormatter dayFormatter = DateTimeFormatter.ofPattern(dayPattern, Locale.getDefault()); DateTimeFormatter timeFormatter = DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT); String formatted = context.getString(R.string.schedule_browse_sessions_title_pattern, dateTime.format(dayFormatter), dateTime.format(timeFormatter));
// Path: app/src/main/java/com/nilhcem/droidconde/data/app/model/ScheduleSlot.java // @Value // public class ScheduleSlot implements Parcelable { // // public static final Parcelable.Creator<ScheduleSlot> CREATOR = new Parcelable.Creator<ScheduleSlot>() { // public ScheduleSlot createFromParcel(Parcel source) { // return new ScheduleSlot(source); // } // // public ScheduleSlot[] newArray(int size) { // return new ScheduleSlot[size]; // } // }; // // LocalDateTime time; // List<Session> sessions; // // public ScheduleSlot(LocalDateTime time, List<Session> sessions) { // this.time = time; // this.sessions = sessions; // } // // protected ScheduleSlot(Parcel in) { // time = (LocalDateTime) in.readSerializable(); // sessions = in.createTypedArrayList(Session.CREATOR); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeSerializable(time); // dest.writeTypedList(sessions); // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/data/app/model/Session.java // @Value // public class Session implements Parcelable { // // public static final Parcelable.Creator<Session> CREATOR = new Parcelable.Creator<Session>() { // public Session createFromParcel(Parcel source) { // return new Session(source); // } // // public Session[] newArray(int size) { // return new Session[size]; // } // }; // // int id; // String room; // List<Speaker> speakers; // String title; // String description; // LocalDateTime fromTime; // LocalDateTime toTime; // // public Session(int id, String room, List<Speaker> speakers, String title, String description, LocalDateTime fromTime, LocalDateTime toTime) { // this.id = id; // this.room = room; // this.speakers = speakers; // this.title = title; // this.description = description; // this.fromTime = fromTime; // this.toTime = toTime; // } // // protected Session(Parcel in) { // id = in.readInt(); // room = in.readString(); // speakers = in.createTypedArrayList(Speaker.CREATOR); // title = in.readString(); // description = in.readString(); // fromTime = (LocalDateTime) in.readSerializable(); // toTime = (LocalDateTime) in.readSerializable(); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(id); // dest.writeString(room); // dest.writeTypedList(speakers); // dest.writeString(title); // dest.writeString(description); // dest.writeSerializable(fromTime); // dest.writeSerializable(toTime); // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/ui/BaseActivityPresenter.java // public abstract class BaseActivityPresenter<V> extends BasePresenter<V> { // // public BaseActivityPresenter(V view) { // super(view); // } // // public void onPostCreate(Bundle savedInstanceState) { // // Nothing to do by default // } // // public void onResume() { // // Nothing to do by default // } // // @CallSuper // public void onSaveInstanceState(Bundle outState) { // Icepick.saveInstanceState(this, outState); // } // // @CallSuper // public void onRestoreInstanceState(Bundle savedInstanceState) { // Icepick.restoreInstanceState(this, savedInstanceState); // } // // public void onNavigationItemSelected(@IdRes int itemId) { // // Nothing to do by default // } // // public boolean onBackPressed() { // return false; // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/utils/Strings.java // public class Strings { // // private Strings() { // throw new UnsupportedOperationException(); // } // // public static String capitalizeFirstLetter(@NonNull String src) { // return src.substring(0, 1).toUpperCase(Locale.getDefault()) + src.substring(1); // } // } // Path: app/src/main/java/com/nilhcem/droidconde/ui/sessions/list/SessionsListPresenter.java import android.content.Context; import android.os.Bundle; import com.nilhcem.droidconde.R; import com.nilhcem.droidconde.data.app.model.ScheduleSlot; import com.nilhcem.droidconde.data.app.model.Session; import com.nilhcem.droidconde.ui.BaseActivityPresenter; import com.nilhcem.droidconde.utils.Strings; import org.threeten.bp.LocalDateTime; import org.threeten.bp.format.DateTimeFormatter; import org.threeten.bp.format.FormatStyle; import java.util.List; import java.util.Locale; package com.nilhcem.droidconde.ui.sessions.list; public class SessionsListPresenter extends BaseActivityPresenter<SessionsListMvp.View> { private final List<Session> sessions; public SessionsListPresenter(Context context, SessionsListMvp.View view, ScheduleSlot slot) { super(view); this.view.initToobar(formatDateTime(context, slot.getTime())); sessions = slot.getSessions(); } @Override public void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); this.view.initSessionsList(sessions); } private String formatDateTime(Context context, LocalDateTime dateTime) { String dayPattern = context.getString(R.string.schedule_pager_day_pattern); DateTimeFormatter dayFormatter = DateTimeFormatter.ofPattern(dayPattern, Locale.getDefault()); DateTimeFormatter timeFormatter = DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT); String formatted = context.getString(R.string.schedule_browse_sessions_title_pattern, dateTime.format(dayFormatter), dateTime.format(timeFormatter));
return Strings.capitalizeFirstLetter(formatted);
Nilhcem/droidconde-2016
app/src/main/java/com/nilhcem/droidconde/utils/App.java
// Path: app/src/main/java/com/nilhcem/droidconde/data/app/model/Session.java // @Value // public class Session implements Parcelable { // // public static final Parcelable.Creator<Session> CREATOR = new Parcelable.Creator<Session>() { // public Session createFromParcel(Parcel source) { // return new Session(source); // } // // public Session[] newArray(int size) { // return new Session[size]; // } // }; // // int id; // String room; // List<Speaker> speakers; // String title; // String description; // LocalDateTime fromTime; // LocalDateTime toTime; // // public Session(int id, String room, List<Speaker> speakers, String title, String description, LocalDateTime fromTime, LocalDateTime toTime) { // this.id = id; // this.room = room; // this.speakers = speakers; // this.title = title; // this.description = description; // this.fromTime = fromTime; // this.toTime = toTime; // } // // protected Session(Parcel in) { // id = in.readInt(); // room = in.readString(); // speakers = in.createTypedArrayList(Speaker.CREATOR); // title = in.readString(); // description = in.readString(); // fromTime = (LocalDateTime) in.readSerializable(); // toTime = (LocalDateTime) in.readSerializable(); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(id); // dest.writeString(room); // dest.writeTypedList(speakers); // dest.writeString(title); // dest.writeString(description); // dest.writeSerializable(fromTime); // dest.writeSerializable(toTime); // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/data/app/model/Speaker.java // @Value // public class Speaker implements Parcelable { // // public static final Parcelable.Creator<Speaker> CREATOR = new Parcelable.Creator<Speaker>() { // public Speaker createFromParcel(Parcel source) { // return new Speaker(source); // } // // public Speaker[] newArray(int size) { // return new Speaker[size]; // } // }; // // int id; // String name; // String title; // String bio; // String website; // String twitter; // String github; // String photo; // // public Speaker(int id, String name, String title, String bio, String website, String twitter, String github, String photo) { // this.id = id; // this.name = name; // this.title = title; // this.bio = bio; // this.website = website; // this.twitter = twitter; // this.github = github; // this.photo = photo; // } // // protected Speaker(Parcel in) { // id = in.readInt(); // name = in.readString(); // title = in.readString(); // bio = in.readString(); // website = in.readString(); // twitter = in.readString(); // github = in.readString(); // photo = in.readString(); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(id); // dest.writeString(name); // dest.writeString(title); // dest.writeString(bio); // dest.writeString(website); // dest.writeString(twitter); // dest.writeString(github); // dest.writeString(photo); // } // }
import android.app.AlarmManager; import android.app.PendingIntent; import android.os.Build; import android.support.annotation.Nullable; import com.nilhcem.droidconde.BuildConfig; import com.nilhcem.droidconde.data.app.model.Session; import com.nilhcem.droidconde.data.app.model.Speaker; import java.util.List; import java.util.Locale;
package com.nilhcem.droidconde.utils; public final class App { private App() { throw new UnsupportedOperationException(); } public static boolean isCompatible(int apiLevel) { return android.os.Build.VERSION.SDK_INT >= apiLevel; } public static String getVersion() { String version = String.format(Locale.US, "%s (#%d)", BuildConfig.VERSION_NAME, BuildConfig.VERSION_CODE); if (BuildConfig.INTERNAL_BUILD) { version = String.format(Locale.US, "%s — commit %s", version, BuildConfig.GIT_SHA); } return version; } public static void setExactAlarm(AlarmManager alarmManager, long triggerAtMillis, PendingIntent operation) { if (isCompatible(Build.VERSION_CODES.KITKAT)) { alarmManager.setExact(AlarmManager.RTC_WAKEUP, triggerAtMillis, operation); } else { alarmManager.set(AlarmManager.RTC_WAKEUP, triggerAtMillis, operation); } } @Nullable
// Path: app/src/main/java/com/nilhcem/droidconde/data/app/model/Session.java // @Value // public class Session implements Parcelable { // // public static final Parcelable.Creator<Session> CREATOR = new Parcelable.Creator<Session>() { // public Session createFromParcel(Parcel source) { // return new Session(source); // } // // public Session[] newArray(int size) { // return new Session[size]; // } // }; // // int id; // String room; // List<Speaker> speakers; // String title; // String description; // LocalDateTime fromTime; // LocalDateTime toTime; // // public Session(int id, String room, List<Speaker> speakers, String title, String description, LocalDateTime fromTime, LocalDateTime toTime) { // this.id = id; // this.room = room; // this.speakers = speakers; // this.title = title; // this.description = description; // this.fromTime = fromTime; // this.toTime = toTime; // } // // protected Session(Parcel in) { // id = in.readInt(); // room = in.readString(); // speakers = in.createTypedArrayList(Speaker.CREATOR); // title = in.readString(); // description = in.readString(); // fromTime = (LocalDateTime) in.readSerializable(); // toTime = (LocalDateTime) in.readSerializable(); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(id); // dest.writeString(room); // dest.writeTypedList(speakers); // dest.writeString(title); // dest.writeString(description); // dest.writeSerializable(fromTime); // dest.writeSerializable(toTime); // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/data/app/model/Speaker.java // @Value // public class Speaker implements Parcelable { // // public static final Parcelable.Creator<Speaker> CREATOR = new Parcelable.Creator<Speaker>() { // public Speaker createFromParcel(Parcel source) { // return new Speaker(source); // } // // public Speaker[] newArray(int size) { // return new Speaker[size]; // } // }; // // int id; // String name; // String title; // String bio; // String website; // String twitter; // String github; // String photo; // // public Speaker(int id, String name, String title, String bio, String website, String twitter, String github, String photo) { // this.id = id; // this.name = name; // this.title = title; // this.bio = bio; // this.website = website; // this.twitter = twitter; // this.github = github; // this.photo = photo; // } // // protected Speaker(Parcel in) { // id = in.readInt(); // name = in.readString(); // title = in.readString(); // bio = in.readString(); // website = in.readString(); // twitter = in.readString(); // github = in.readString(); // photo = in.readString(); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(id); // dest.writeString(name); // dest.writeString(title); // dest.writeString(bio); // dest.writeString(website); // dest.writeString(twitter); // dest.writeString(github); // dest.writeString(photo); // } // } // Path: app/src/main/java/com/nilhcem/droidconde/utils/App.java import android.app.AlarmManager; import android.app.PendingIntent; import android.os.Build; import android.support.annotation.Nullable; import com.nilhcem.droidconde.BuildConfig; import com.nilhcem.droidconde.data.app.model.Session; import com.nilhcem.droidconde.data.app.model.Speaker; import java.util.List; import java.util.Locale; package com.nilhcem.droidconde.utils; public final class App { private App() { throw new UnsupportedOperationException(); } public static boolean isCompatible(int apiLevel) { return android.os.Build.VERSION.SDK_INT >= apiLevel; } public static String getVersion() { String version = String.format(Locale.US, "%s (#%d)", BuildConfig.VERSION_NAME, BuildConfig.VERSION_CODE); if (BuildConfig.INTERNAL_BUILD) { version = String.format(Locale.US, "%s — commit %s", version, BuildConfig.GIT_SHA); } return version; } public static void setExactAlarm(AlarmManager alarmManager, long triggerAtMillis, PendingIntent operation) { if (isCompatible(Build.VERSION_CODES.KITKAT)) { alarmManager.setExact(AlarmManager.RTC_WAKEUP, triggerAtMillis, operation); } else { alarmManager.set(AlarmManager.RTC_WAKEUP, triggerAtMillis, operation); } } @Nullable
public static String getPhotoUrl(@Nullable Session session) {
Nilhcem/droidconde-2016
app/src/main/java/com/nilhcem/droidconde/utils/App.java
// Path: app/src/main/java/com/nilhcem/droidconde/data/app/model/Session.java // @Value // public class Session implements Parcelable { // // public static final Parcelable.Creator<Session> CREATOR = new Parcelable.Creator<Session>() { // public Session createFromParcel(Parcel source) { // return new Session(source); // } // // public Session[] newArray(int size) { // return new Session[size]; // } // }; // // int id; // String room; // List<Speaker> speakers; // String title; // String description; // LocalDateTime fromTime; // LocalDateTime toTime; // // public Session(int id, String room, List<Speaker> speakers, String title, String description, LocalDateTime fromTime, LocalDateTime toTime) { // this.id = id; // this.room = room; // this.speakers = speakers; // this.title = title; // this.description = description; // this.fromTime = fromTime; // this.toTime = toTime; // } // // protected Session(Parcel in) { // id = in.readInt(); // room = in.readString(); // speakers = in.createTypedArrayList(Speaker.CREATOR); // title = in.readString(); // description = in.readString(); // fromTime = (LocalDateTime) in.readSerializable(); // toTime = (LocalDateTime) in.readSerializable(); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(id); // dest.writeString(room); // dest.writeTypedList(speakers); // dest.writeString(title); // dest.writeString(description); // dest.writeSerializable(fromTime); // dest.writeSerializable(toTime); // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/data/app/model/Speaker.java // @Value // public class Speaker implements Parcelable { // // public static final Parcelable.Creator<Speaker> CREATOR = new Parcelable.Creator<Speaker>() { // public Speaker createFromParcel(Parcel source) { // return new Speaker(source); // } // // public Speaker[] newArray(int size) { // return new Speaker[size]; // } // }; // // int id; // String name; // String title; // String bio; // String website; // String twitter; // String github; // String photo; // // public Speaker(int id, String name, String title, String bio, String website, String twitter, String github, String photo) { // this.id = id; // this.name = name; // this.title = title; // this.bio = bio; // this.website = website; // this.twitter = twitter; // this.github = github; // this.photo = photo; // } // // protected Speaker(Parcel in) { // id = in.readInt(); // name = in.readString(); // title = in.readString(); // bio = in.readString(); // website = in.readString(); // twitter = in.readString(); // github = in.readString(); // photo = in.readString(); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(id); // dest.writeString(name); // dest.writeString(title); // dest.writeString(bio); // dest.writeString(website); // dest.writeString(twitter); // dest.writeString(github); // dest.writeString(photo); // } // }
import android.app.AlarmManager; import android.app.PendingIntent; import android.os.Build; import android.support.annotation.Nullable; import com.nilhcem.droidconde.BuildConfig; import com.nilhcem.droidconde.data.app.model.Session; import com.nilhcem.droidconde.data.app.model.Speaker; import java.util.List; import java.util.Locale;
package com.nilhcem.droidconde.utils; public final class App { private App() { throw new UnsupportedOperationException(); } public static boolean isCompatible(int apiLevel) { return android.os.Build.VERSION.SDK_INT >= apiLevel; } public static String getVersion() { String version = String.format(Locale.US, "%s (#%d)", BuildConfig.VERSION_NAME, BuildConfig.VERSION_CODE); if (BuildConfig.INTERNAL_BUILD) { version = String.format(Locale.US, "%s — commit %s", version, BuildConfig.GIT_SHA); } return version; } public static void setExactAlarm(AlarmManager alarmManager, long triggerAtMillis, PendingIntent operation) { if (isCompatible(Build.VERSION_CODES.KITKAT)) { alarmManager.setExact(AlarmManager.RTC_WAKEUP, triggerAtMillis, operation); } else { alarmManager.set(AlarmManager.RTC_WAKEUP, triggerAtMillis, operation); } } @Nullable public static String getPhotoUrl(@Nullable Session session) { String photoUrl = null; if (session != null) {
// Path: app/src/main/java/com/nilhcem/droidconde/data/app/model/Session.java // @Value // public class Session implements Parcelable { // // public static final Parcelable.Creator<Session> CREATOR = new Parcelable.Creator<Session>() { // public Session createFromParcel(Parcel source) { // return new Session(source); // } // // public Session[] newArray(int size) { // return new Session[size]; // } // }; // // int id; // String room; // List<Speaker> speakers; // String title; // String description; // LocalDateTime fromTime; // LocalDateTime toTime; // // public Session(int id, String room, List<Speaker> speakers, String title, String description, LocalDateTime fromTime, LocalDateTime toTime) { // this.id = id; // this.room = room; // this.speakers = speakers; // this.title = title; // this.description = description; // this.fromTime = fromTime; // this.toTime = toTime; // } // // protected Session(Parcel in) { // id = in.readInt(); // room = in.readString(); // speakers = in.createTypedArrayList(Speaker.CREATOR); // title = in.readString(); // description = in.readString(); // fromTime = (LocalDateTime) in.readSerializable(); // toTime = (LocalDateTime) in.readSerializable(); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(id); // dest.writeString(room); // dest.writeTypedList(speakers); // dest.writeString(title); // dest.writeString(description); // dest.writeSerializable(fromTime); // dest.writeSerializable(toTime); // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/data/app/model/Speaker.java // @Value // public class Speaker implements Parcelable { // // public static final Parcelable.Creator<Speaker> CREATOR = new Parcelable.Creator<Speaker>() { // public Speaker createFromParcel(Parcel source) { // return new Speaker(source); // } // // public Speaker[] newArray(int size) { // return new Speaker[size]; // } // }; // // int id; // String name; // String title; // String bio; // String website; // String twitter; // String github; // String photo; // // public Speaker(int id, String name, String title, String bio, String website, String twitter, String github, String photo) { // this.id = id; // this.name = name; // this.title = title; // this.bio = bio; // this.website = website; // this.twitter = twitter; // this.github = github; // this.photo = photo; // } // // protected Speaker(Parcel in) { // id = in.readInt(); // name = in.readString(); // title = in.readString(); // bio = in.readString(); // website = in.readString(); // twitter = in.readString(); // github = in.readString(); // photo = in.readString(); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(id); // dest.writeString(name); // dest.writeString(title); // dest.writeString(bio); // dest.writeString(website); // dest.writeString(twitter); // dest.writeString(github); // dest.writeString(photo); // } // } // Path: app/src/main/java/com/nilhcem/droidconde/utils/App.java import android.app.AlarmManager; import android.app.PendingIntent; import android.os.Build; import android.support.annotation.Nullable; import com.nilhcem.droidconde.BuildConfig; import com.nilhcem.droidconde.data.app.model.Session; import com.nilhcem.droidconde.data.app.model.Speaker; import java.util.List; import java.util.Locale; package com.nilhcem.droidconde.utils; public final class App { private App() { throw new UnsupportedOperationException(); } public static boolean isCompatible(int apiLevel) { return android.os.Build.VERSION.SDK_INT >= apiLevel; } public static String getVersion() { String version = String.format(Locale.US, "%s (#%d)", BuildConfig.VERSION_NAME, BuildConfig.VERSION_CODE); if (BuildConfig.INTERNAL_BUILD) { version = String.format(Locale.US, "%s — commit %s", version, BuildConfig.GIT_SHA); } return version; } public static void setExactAlarm(AlarmManager alarmManager, long triggerAtMillis, PendingIntent operation) { if (isCompatible(Build.VERSION_CODES.KITKAT)) { alarmManager.setExact(AlarmManager.RTC_WAKEUP, triggerAtMillis, operation); } else { alarmManager.set(AlarmManager.RTC_WAKEUP, triggerAtMillis, operation); } } @Nullable public static String getPhotoUrl(@Nullable Session session) { String photoUrl = null; if (session != null) {
List<Speaker> speakers = session.getSpeakers();
Nilhcem/droidconde-2016
app/src/main/java/com/nilhcem/droidconde/ui/schedule/pager/SchedulePagerMvp.java
// Path: app/src/main/java/com/nilhcem/droidconde/data/app/model/Schedule.java // public class Schedule extends ArrayList<ScheduleDay> implements Parcelable { // // public static final Parcelable.Creator<Schedule> CREATOR = new Parcelable.Creator<Schedule>() { // public Schedule createFromParcel(Parcel source) { // return new Schedule(source); // } // // public Schedule[] newArray(int size) { // return new Schedule[size]; // } // }; // // public Schedule() { // } // // protected Schedule(Parcel in) { // addAll(in.createTypedArrayList(ScheduleDay.CREATOR)); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeTypedList(this); // } // }
import com.nilhcem.droidconde.data.app.model.Schedule;
package com.nilhcem.droidconde.ui.schedule.pager; public interface SchedulePagerMvp { interface View {
// Path: app/src/main/java/com/nilhcem/droidconde/data/app/model/Schedule.java // public class Schedule extends ArrayList<ScheduleDay> implements Parcelable { // // public static final Parcelable.Creator<Schedule> CREATOR = new Parcelable.Creator<Schedule>() { // public Schedule createFromParcel(Parcel source) { // return new Schedule(source); // } // // public Schedule[] newArray(int size) { // return new Schedule[size]; // } // }; // // public Schedule() { // } // // protected Schedule(Parcel in) { // addAll(in.createTypedArrayList(ScheduleDay.CREATOR)); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeTypedList(this); // } // } // Path: app/src/main/java/com/nilhcem/droidconde/ui/schedule/pager/SchedulePagerMvp.java import com.nilhcem.droidconde.data.app.model.Schedule; package com.nilhcem.droidconde.ui.schedule.pager; public interface SchedulePagerMvp { interface View {
void displaySchedule(Schedule schedule);
Nilhcem/droidconde-2016
app/src/internal/java/com/nilhcem/droidconde/debug/stetho/StethoInitializer.java
// Path: app/src/internal/java/com/nilhcem/droidconde/debug/lifecycle/ActivityProvider.java // @Singleton // public class ActivityProvider implements Application.ActivityLifecycleCallbacks { // // private Activity currentActivity; // // @Inject // public ActivityProvider() { // } // // public void init(Application app) { // app.registerActivityLifecycleCallbacks(this); // } // // public Activity getCurrentActivity() { // return currentActivity; // } // // @Override // public void onActivityCreated(Activity activity, Bundle savedInstanceState) { // } // // @Override // public void onActivityStarted(Activity activity) { // } // // @Override // public void onActivityResumed(Activity activity) { // this.currentActivity = activity; // } // // @Override // public void onActivityPaused(Activity activity) { // currentActivity = null; // } // // @Override // public void onActivityStopped(Activity activity) { // } // // @Override // public void onActivitySaveInstanceState(Activity activity, Bundle outState) { // } // // @Override // public void onActivityDestroyed(Activity activity) { // } // }
import android.app.Application; import android.content.Context; import com.facebook.stetho.DumperPluginsProvider; import com.facebook.stetho.InspectorModulesProvider; import com.facebook.stetho.Stetho; import com.facebook.stetho.dumpapp.DumperPlugin; import com.facebook.stetho.rhino.JsRuntimeReplFactoryBuilder; import com.facebook.stetho.timber.StethoTree; import com.nilhcem.droidconde.debug.lifecycle.ActivityProvider; import org.mozilla.javascript.BaseFunction; import org.mozilla.javascript.Scriptable; import java.util.ArrayList; import java.util.List; import javax.inject.Inject; import timber.log.Timber;
package com.nilhcem.droidconde.debug.stetho; public class StethoInitializer implements DumperPluginsProvider { private final Context context; private final AppDumperPlugin appDumper;
// Path: app/src/internal/java/com/nilhcem/droidconde/debug/lifecycle/ActivityProvider.java // @Singleton // public class ActivityProvider implements Application.ActivityLifecycleCallbacks { // // private Activity currentActivity; // // @Inject // public ActivityProvider() { // } // // public void init(Application app) { // app.registerActivityLifecycleCallbacks(this); // } // // public Activity getCurrentActivity() { // return currentActivity; // } // // @Override // public void onActivityCreated(Activity activity, Bundle savedInstanceState) { // } // // @Override // public void onActivityStarted(Activity activity) { // } // // @Override // public void onActivityResumed(Activity activity) { // this.currentActivity = activity; // } // // @Override // public void onActivityPaused(Activity activity) { // currentActivity = null; // } // // @Override // public void onActivityStopped(Activity activity) { // } // // @Override // public void onActivitySaveInstanceState(Activity activity, Bundle outState) { // } // // @Override // public void onActivityDestroyed(Activity activity) { // } // } // Path: app/src/internal/java/com/nilhcem/droidconde/debug/stetho/StethoInitializer.java import android.app.Application; import android.content.Context; import com.facebook.stetho.DumperPluginsProvider; import com.facebook.stetho.InspectorModulesProvider; import com.facebook.stetho.Stetho; import com.facebook.stetho.dumpapp.DumperPlugin; import com.facebook.stetho.rhino.JsRuntimeReplFactoryBuilder; import com.facebook.stetho.timber.StethoTree; import com.nilhcem.droidconde.debug.lifecycle.ActivityProvider; import org.mozilla.javascript.BaseFunction; import org.mozilla.javascript.Scriptable; import java.util.ArrayList; import java.util.List; import javax.inject.Inject; import timber.log.Timber; package com.nilhcem.droidconde.debug.stetho; public class StethoInitializer implements DumperPluginsProvider { private final Context context; private final AppDumperPlugin appDumper;
private final ActivityProvider activityProvider;
Nilhcem/droidconde-2016
app/src/main/java/com/nilhcem/droidconde/DroidconApp.java
// Path: app/src/internal/java/com/nilhcem/droidconde/core/dagger/AppComponent.java // @Singleton // @Component(modules = {AppModule.class, ApiModule.class, DataModule.class, DatabaseModule.class}) // public interface AppComponent extends InternalAppGraph { // // /** // * An initializer that creates the internal graph from an application. // */ // final class Initializer { // // private Initializer() { // throw new UnsupportedOperationException(); // } // // public static AppComponent init(DroidconApp app) { // return DaggerAppComponent.builder() // .appModule(new AppModule(app)) // .apiModule(new ApiModule()) // .dataModule(new DataModule()) // .databaseModule(new DatabaseModule()) // .build(); // } // } // }
import android.app.Application; import android.content.Context; import com.jakewharton.threetenabp.AndroidThreeTen; import com.nilhcem.droidconde.core.dagger.AppComponent; import hugo.weaving.DebugLog; import timber.log.Timber;
package com.nilhcem.droidconde; @DebugLog public class DroidconApp extends Application {
// Path: app/src/internal/java/com/nilhcem/droidconde/core/dagger/AppComponent.java // @Singleton // @Component(modules = {AppModule.class, ApiModule.class, DataModule.class, DatabaseModule.class}) // public interface AppComponent extends InternalAppGraph { // // /** // * An initializer that creates the internal graph from an application. // */ // final class Initializer { // // private Initializer() { // throw new UnsupportedOperationException(); // } // // public static AppComponent init(DroidconApp app) { // return DaggerAppComponent.builder() // .appModule(new AppModule(app)) // .apiModule(new ApiModule()) // .dataModule(new DataModule()) // .databaseModule(new DatabaseModule()) // .build(); // } // } // } // Path: app/src/main/java/com/nilhcem/droidconde/DroidconApp.java import android.app.Application; import android.content.Context; import com.jakewharton.threetenabp.AndroidThreeTen; import com.nilhcem.droidconde.core.dagger.AppComponent; import hugo.weaving.DebugLog; import timber.log.Timber; package com.nilhcem.droidconde; @DebugLog public class DroidconApp extends Application {
private AppComponent component;
Nilhcem/droidconde-2016
app/src/main/java/com/nilhcem/droidconde/ui/sessions/list/SessionsListMvp.java
// Path: app/src/main/java/com/nilhcem/droidconde/data/app/model/Session.java // @Value // public class Session implements Parcelable { // // public static final Parcelable.Creator<Session> CREATOR = new Parcelable.Creator<Session>() { // public Session createFromParcel(Parcel source) { // return new Session(source); // } // // public Session[] newArray(int size) { // return new Session[size]; // } // }; // // int id; // String room; // List<Speaker> speakers; // String title; // String description; // LocalDateTime fromTime; // LocalDateTime toTime; // // public Session(int id, String room, List<Speaker> speakers, String title, String description, LocalDateTime fromTime, LocalDateTime toTime) { // this.id = id; // this.room = room; // this.speakers = speakers; // this.title = title; // this.description = description; // this.fromTime = fromTime; // this.toTime = toTime; // } // // protected Session(Parcel in) { // id = in.readInt(); // room = in.readString(); // speakers = in.createTypedArrayList(Speaker.CREATOR); // title = in.readString(); // description = in.readString(); // fromTime = (LocalDateTime) in.readSerializable(); // toTime = (LocalDateTime) in.readSerializable(); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(id); // dest.writeString(room); // dest.writeTypedList(speakers); // dest.writeString(title); // dest.writeString(description); // dest.writeSerializable(fromTime); // dest.writeSerializable(toTime); // } // }
import com.nilhcem.droidconde.data.app.model.Session; import java.util.List;
package com.nilhcem.droidconde.ui.sessions.list; public interface SessionsListMvp { interface View { void initToobar(String title);
// Path: app/src/main/java/com/nilhcem/droidconde/data/app/model/Session.java // @Value // public class Session implements Parcelable { // // public static final Parcelable.Creator<Session> CREATOR = new Parcelable.Creator<Session>() { // public Session createFromParcel(Parcel source) { // return new Session(source); // } // // public Session[] newArray(int size) { // return new Session[size]; // } // }; // // int id; // String room; // List<Speaker> speakers; // String title; // String description; // LocalDateTime fromTime; // LocalDateTime toTime; // // public Session(int id, String room, List<Speaker> speakers, String title, String description, LocalDateTime fromTime, LocalDateTime toTime) { // this.id = id; // this.room = room; // this.speakers = speakers; // this.title = title; // this.description = description; // this.fromTime = fromTime; // this.toTime = toTime; // } // // protected Session(Parcel in) { // id = in.readInt(); // room = in.readString(); // speakers = in.createTypedArrayList(Speaker.CREATOR); // title = in.readString(); // description = in.readString(); // fromTime = (LocalDateTime) in.readSerializable(); // toTime = (LocalDateTime) in.readSerializable(); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(id); // dest.writeString(room); // dest.writeTypedList(speakers); // dest.writeString(title); // dest.writeString(description); // dest.writeSerializable(fromTime); // dest.writeSerializable(toTime); // } // } // Path: app/src/main/java/com/nilhcem/droidconde/ui/sessions/list/SessionsListMvp.java import com.nilhcem.droidconde.data.app.model.Session; import java.util.List; package com.nilhcem.droidconde.ui.sessions.list; public interface SessionsListMvp { interface View { void initToobar(String title);
void initSessionsList(List<Session> sessions);
Nilhcem/droidconde-2016
app/src/main/java/com/nilhcem/droidconde/ui/sessions/list/SessionsListAdapter.java
// Path: app/src/main/java/com/nilhcem/droidconde/data/app/SelectedSessionsMemory.java // @Singleton // public class SelectedSessionsMemory { // // private final Map<LocalDateTime, Integer> selectedSessions = new ConcurrentHashMap<>(); // // @Inject // public SelectedSessionsMemory() { // } // // public boolean isSelected(Session session) { // Integer sessionId = selectedSessions.get(session.getFromTime()); // return sessionId != null && session.getId() == sessionId; // } // // public void setSelectedSessions(Map<LocalDateTime, Integer> selectedSessions) { // this.selectedSessions.clear(); // this.selectedSessions.putAll(selectedSessions); // } // // public Integer get(LocalDateTime slotTime) { // return selectedSessions.get(slotTime); // } // // public void toggleSessionState(com.nilhcem.droidconde.data.app.model.Session session, boolean insert) { // selectedSessions.remove(session.getFromTime()); // if (insert) { // selectedSessions.put(session.getFromTime(), session.getId()); // } // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/data/app/model/Session.java // @Value // public class Session implements Parcelable { // // public static final Parcelable.Creator<Session> CREATOR = new Parcelable.Creator<Session>() { // public Session createFromParcel(Parcel source) { // return new Session(source); // } // // public Session[] newArray(int size) { // return new Session[size]; // } // }; // // int id; // String room; // List<Speaker> speakers; // String title; // String description; // LocalDateTime fromTime; // LocalDateTime toTime; // // public Session(int id, String room, List<Speaker> speakers, String title, String description, LocalDateTime fromTime, LocalDateTime toTime) { // this.id = id; // this.room = room; // this.speakers = speakers; // this.title = title; // this.description = description; // this.fromTime = fromTime; // this.toTime = toTime; // } // // protected Session(Parcel in) { // id = in.readInt(); // room = in.readString(); // speakers = in.createTypedArrayList(Speaker.CREATOR); // title = in.readString(); // description = in.readString(); // fromTime = (LocalDateTime) in.readSerializable(); // toTime = (LocalDateTime) in.readSerializable(); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(id); // dest.writeString(room); // dest.writeTypedList(speakers); // dest.writeString(title); // dest.writeString(description); // dest.writeSerializable(fromTime); // dest.writeSerializable(toTime); // } // }
import android.support.v7.widget.RecyclerView; import android.view.ViewGroup; import com.nilhcem.droidconde.data.app.SelectedSessionsMemory; import com.nilhcem.droidconde.data.app.model.Session; import com.squareup.picasso.Picasso; import java.util.List;
package com.nilhcem.droidconde.ui.sessions.list; public class SessionsListAdapter extends RecyclerView.Adapter<SessionsListEntry> { private final List<Session> sessions; private final Picasso picasso;
// Path: app/src/main/java/com/nilhcem/droidconde/data/app/SelectedSessionsMemory.java // @Singleton // public class SelectedSessionsMemory { // // private final Map<LocalDateTime, Integer> selectedSessions = new ConcurrentHashMap<>(); // // @Inject // public SelectedSessionsMemory() { // } // // public boolean isSelected(Session session) { // Integer sessionId = selectedSessions.get(session.getFromTime()); // return sessionId != null && session.getId() == sessionId; // } // // public void setSelectedSessions(Map<LocalDateTime, Integer> selectedSessions) { // this.selectedSessions.clear(); // this.selectedSessions.putAll(selectedSessions); // } // // public Integer get(LocalDateTime slotTime) { // return selectedSessions.get(slotTime); // } // // public void toggleSessionState(com.nilhcem.droidconde.data.app.model.Session session, boolean insert) { // selectedSessions.remove(session.getFromTime()); // if (insert) { // selectedSessions.put(session.getFromTime(), session.getId()); // } // } // } // // Path: app/src/main/java/com/nilhcem/droidconde/data/app/model/Session.java // @Value // public class Session implements Parcelable { // // public static final Parcelable.Creator<Session> CREATOR = new Parcelable.Creator<Session>() { // public Session createFromParcel(Parcel source) { // return new Session(source); // } // // public Session[] newArray(int size) { // return new Session[size]; // } // }; // // int id; // String room; // List<Speaker> speakers; // String title; // String description; // LocalDateTime fromTime; // LocalDateTime toTime; // // public Session(int id, String room, List<Speaker> speakers, String title, String description, LocalDateTime fromTime, LocalDateTime toTime) { // this.id = id; // this.room = room; // this.speakers = speakers; // this.title = title; // this.description = description; // this.fromTime = fromTime; // this.toTime = toTime; // } // // protected Session(Parcel in) { // id = in.readInt(); // room = in.readString(); // speakers = in.createTypedArrayList(Speaker.CREATOR); // title = in.readString(); // description = in.readString(); // fromTime = (LocalDateTime) in.readSerializable(); // toTime = (LocalDateTime) in.readSerializable(); // } // // @Override // public int describeContents() { // return 0; // } // // @Override // public void writeToParcel(Parcel dest, int flags) { // dest.writeInt(id); // dest.writeString(room); // dest.writeTypedList(speakers); // dest.writeString(title); // dest.writeString(description); // dest.writeSerializable(fromTime); // dest.writeSerializable(toTime); // } // } // Path: app/src/main/java/com/nilhcem/droidconde/ui/sessions/list/SessionsListAdapter.java import android.support.v7.widget.RecyclerView; import android.view.ViewGroup; import com.nilhcem.droidconde.data.app.SelectedSessionsMemory; import com.nilhcem.droidconde.data.app.model.Session; import com.squareup.picasso.Picasso; import java.util.List; package com.nilhcem.droidconde.ui.sessions.list; public class SessionsListAdapter extends RecyclerView.Adapter<SessionsListEntry> { private final List<Session> sessions; private final Picasso picasso;
private final SelectedSessionsMemory selectedSessionsMemory;
cloudera/cm_ext
cm-schema/src/test/java/com/cloudera/csd/validation/monitoring/constraints/DenominatorValidatorTest.java
// Path: cm-schema/src/main/java/com/cloudera/csd/validation/monitoring/MonitoringValidationContext.java // public class MonitoringValidationContext { // // public final ServiceMonitoringDefinitionsDescriptor serviceDescriptor; // public final ImmutableMap<String, MetricDescriptor> metricsDefined; // public final ImmutableMap<String, MetricEntityTypeDescriptor> entitiesDefined; // public final ImmutableMap<String, RoleMonitoringDefinitionsDescriptor> rolesDefined; // public final ImmutableMap<String, MetricEntityAttributeDescriptor> attributesDefined; // // public MonitoringValidationContext( // ServiceMonitoringDefinitionsDescriptor serviceDescriptor) { // Preconditions.checkNotNull(serviceDescriptor); // this.serviceDescriptor = serviceDescriptor; // ImmutableMap.Builder<String, RoleMonitoringDefinitionsDescriptor> // rolesDefinedBuilder = ImmutableMap.builder(); // // We can't use an ImmutableMap.Builder since it will not allow multiple // // entries with the same key. Instead we build a local hash map and make // // it immutable below. // Map<String, MetricDescriptor> metricsDefinedBuilder = Maps.newHashMap(); // metricsDefinedBuilder.putAll( // extractMetrics(serviceDescriptor.getMetricDefinitions())); // if (null != serviceDescriptor.getRoles()) { // for (RoleMonitoringDefinitionsDescriptor role : // serviceDescriptor.getRoles()) { // rolesDefinedBuilder.put( // MonitoringConventions.getRoleMetricEntityTypeName( // serviceDescriptor.getName(), // role.getName()), // role); // metricsDefinedBuilder.putAll( // extractMetrics(role.getMetricDefinitions())); // } // } // if (null != serviceDescriptor.getMetricEntityTypeDefinitions()) { // for (MetricEntityTypeDescriptor entity : // serviceDescriptor.getMetricEntityTypeDefinitions()) { // metricsDefinedBuilder.putAll( // extractMetrics(entity.getMetricDefinitions())); // } // } // ImmutableMap.Builder<String, MetricEntityTypeDescriptor> // entitiesDefinedBuilder = ImmutableMap.builder(); // if (null != serviceDescriptor.getMetricEntityTypeDefinitions()) { // for (MetricEntityTypeDescriptor entity : // serviceDescriptor.getMetricEntityTypeDefinitions()) { // entitiesDefinedBuilder.put(entity.getName(), entity); // } // } // ImmutableMap.Builder<String, MetricEntityAttributeDescriptor> // attributesDefinedBuilder = ImmutableMap.builder(); // if (null != serviceDescriptor.getMetricEntityAttributeDefinitions()) { // for (MetricEntityAttributeDescriptor attribute : // serviceDescriptor.getMetricEntityAttributeDefinitions()) { // attributesDefinedBuilder.put(attribute.getName(), attribute); // } // } // metricsDefined = ImmutableMap.copyOf(metricsDefinedBuilder); // rolesDefined = rolesDefinedBuilder.build(); // entitiesDefined = entitiesDefinedBuilder.build(); // attributesDefined = attributesDefinedBuilder.build(); // } // // private Map<String, MetricDescriptor> extractMetrics( // @Nullable List<MetricDescriptor> metrics) { // if (null == metrics) { // return ImmutableMap.of(); // } // Map<String, MetricDescriptor> ret = Maps.newHashMap(); // for (MetricDescriptor metric : metrics) { // ret.put(metric.getName(), metric); // } // return ret; // } // }
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import com.cloudera.csd.validation.monitoring.MonitoringValidationContext; import org.junit.Before; import org.junit.Test;
// Licensed to Cloudera, Inc. under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. Cloudera, Inc. licenses this file // to you 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.cloudera.csd.validation.monitoring.constraints; public class DenominatorValidatorTest extends AbstractMonitoringValidatorBaseTest { private DenominatorValidator validator;
// Path: cm-schema/src/main/java/com/cloudera/csd/validation/monitoring/MonitoringValidationContext.java // public class MonitoringValidationContext { // // public final ServiceMonitoringDefinitionsDescriptor serviceDescriptor; // public final ImmutableMap<String, MetricDescriptor> metricsDefined; // public final ImmutableMap<String, MetricEntityTypeDescriptor> entitiesDefined; // public final ImmutableMap<String, RoleMonitoringDefinitionsDescriptor> rolesDefined; // public final ImmutableMap<String, MetricEntityAttributeDescriptor> attributesDefined; // // public MonitoringValidationContext( // ServiceMonitoringDefinitionsDescriptor serviceDescriptor) { // Preconditions.checkNotNull(serviceDescriptor); // this.serviceDescriptor = serviceDescriptor; // ImmutableMap.Builder<String, RoleMonitoringDefinitionsDescriptor> // rolesDefinedBuilder = ImmutableMap.builder(); // // We can't use an ImmutableMap.Builder since it will not allow multiple // // entries with the same key. Instead we build a local hash map and make // // it immutable below. // Map<String, MetricDescriptor> metricsDefinedBuilder = Maps.newHashMap(); // metricsDefinedBuilder.putAll( // extractMetrics(serviceDescriptor.getMetricDefinitions())); // if (null != serviceDescriptor.getRoles()) { // for (RoleMonitoringDefinitionsDescriptor role : // serviceDescriptor.getRoles()) { // rolesDefinedBuilder.put( // MonitoringConventions.getRoleMetricEntityTypeName( // serviceDescriptor.getName(), // role.getName()), // role); // metricsDefinedBuilder.putAll( // extractMetrics(role.getMetricDefinitions())); // } // } // if (null != serviceDescriptor.getMetricEntityTypeDefinitions()) { // for (MetricEntityTypeDescriptor entity : // serviceDescriptor.getMetricEntityTypeDefinitions()) { // metricsDefinedBuilder.putAll( // extractMetrics(entity.getMetricDefinitions())); // } // } // ImmutableMap.Builder<String, MetricEntityTypeDescriptor> // entitiesDefinedBuilder = ImmutableMap.builder(); // if (null != serviceDescriptor.getMetricEntityTypeDefinitions()) { // for (MetricEntityTypeDescriptor entity : // serviceDescriptor.getMetricEntityTypeDefinitions()) { // entitiesDefinedBuilder.put(entity.getName(), entity); // } // } // ImmutableMap.Builder<String, MetricEntityAttributeDescriptor> // attributesDefinedBuilder = ImmutableMap.builder(); // if (null != serviceDescriptor.getMetricEntityAttributeDefinitions()) { // for (MetricEntityAttributeDescriptor attribute : // serviceDescriptor.getMetricEntityAttributeDefinitions()) { // attributesDefinedBuilder.put(attribute.getName(), attribute); // } // } // metricsDefined = ImmutableMap.copyOf(metricsDefinedBuilder); // rolesDefined = rolesDefinedBuilder.build(); // entitiesDefined = entitiesDefinedBuilder.build(); // attributesDefined = attributesDefinedBuilder.build(); // } // // private Map<String, MetricDescriptor> extractMetrics( // @Nullable List<MetricDescriptor> metrics) { // if (null == metrics) { // return ImmutableMap.of(); // } // Map<String, MetricDescriptor> ret = Maps.newHashMap(); // for (MetricDescriptor metric : metrics) { // ret.put(metric.getName(), metric); // } // return ret; // } // } // Path: cm-schema/src/test/java/com/cloudera/csd/validation/monitoring/constraints/DenominatorValidatorTest.java import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import com.cloudera.csd.validation.monitoring.MonitoringValidationContext; import org.junit.Before; import org.junit.Test; // Licensed to Cloudera, Inc. under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. Cloudera, Inc. licenses this file // to you 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.cloudera.csd.validation.monitoring.constraints; public class DenominatorValidatorTest extends AbstractMonitoringValidatorBaseTest { private DenominatorValidator validator;
private MonitoringValidationContext context;
cloudera/cm_ext
cm-schema/src/test/java/com/cloudera/csd/validation/components/ServiceMonitoringDefinitionsDescriptorValidatorImplTest.java
// Path: cm-schema/src/test/java/com/cloudera/csd/validation/SdlTestUtils.java // public class SdlTestUtils { // // public static final JsonSdlObjectMapper OBJECT_MAPPER; // public static final JsonSdlParser SDL_PARSER; // public static final JsonMdlParser MDL_PARSER; // public static final ServiceDescriptor FULL_DESCRIPTOR; // public static final DescriptorValidator<ServiceDescriptor> // FAKE_SDL_VALIDATOR; // public static final DescriptorValidator<ServiceMonitoringDefinitionsDescriptor> // FAKE_MDL_VALIDATOR; // // private static final String RESOURCE_PATH = "/com/cloudera/csd/"; // public static final String SDL_VALIDATOR_RESOURCE_PATH = RESOURCE_PATH + "validator/"; // public static final String SDL_REFERENCE_VALIDATOR_RESOURCE_PATH = SDL_VALIDATOR_RESOURCE_PATH + "references/"; // public static final String SDL_PARSER_RESOURCE_PATH = RESOURCE_PATH + "parser/"; // // // Initialize our variables // static { // OBJECT_MAPPER = new JsonSdlObjectMapper(); // SDL_PARSER = new JsonSdlParser(OBJECT_MAPPER); // MDL_PARSER = new JsonMdlParser(OBJECT_MAPPER); // FULL_DESCRIPTOR = getParserSdl("service_full.sdl"); // FAKE_SDL_VALIDATOR = getAlwaysPassingSdlValidator(); // FAKE_MDL_VALIDATOR = getAlwaysPassingMdlValidator(); // } // // public static ServiceDescriptor parseSDL(String path) { // try { // InputStream stream = SdlTestUtils.class.getResourceAsStream(path); // return SDL_PARSER.parse(IOUtils.toByteArray(stream)); // } catch (IOException io) { // throw new RuntimeException(io); // } // } // // public static ServiceMonitoringDefinitionsDescriptor parseMDL(String path) { // try { // InputStream stream = SdlTestUtils.class.getResourceAsStream(path); // return MDL_PARSER.parse(IOUtils.toByteArray(stream)); // } catch (IOException io) { // throw new RuntimeException(io); // } // } // // public static ServiceDescriptor getParserSdl(String filename) { // return parseSDL(SDL_PARSER_RESOURCE_PATH + filename); // } // // public static ServiceDescriptor getValidatorSdl(String filename) { // return parseSDL(SDL_VALIDATOR_RESOURCE_PATH + filename); // } // // public static ServiceMonitoringDefinitionsDescriptor getValidatorMdl( // String filename) { // return parseMDL(SDL_VALIDATOR_RESOURCE_PATH + filename); // } // // public static ServiceDescriptor getReferenceValidatorSdl(String filename) { // return parseSDL(SDL_REFERENCE_VALIDATOR_RESOURCE_PATH + filename); // } // // public static DescriptorValidator<ServiceDescriptor> // getAlwaysPassingSdlValidator() { // return new DescriptorValidator<ServiceDescriptor>() { // public Set<String> validate(ServiceDescriptor serviceDescriptor) { // return Sets.newHashSet(); // } // }; // } // // public static DescriptorValidator<ServiceMonitoringDefinitionsDescriptor> // getAlwaysPassingMdlValidator() { // return new DescriptorValidator<ServiceMonitoringDefinitionsDescriptor>() { // public Set<String> validate( // ServiceMonitoringDefinitionsDescriptor serviceDescriptor) { // return Sets.newHashSet(); // } // }; // } // // public static Map<String, RoleDescriptor> makeRoleMap(Collection<RoleDescriptor> roles) { // ImmutableMap.Builder<String, RoleDescriptor> builder = ImmutableMap.builder(); // for (RoleDescriptor r : roles) { // builder.put(r.getName(), r); // } // return builder.build(); // } // }
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import com.cloudera.csd.descriptors.ServiceMonitoringDefinitionsDescriptor; import com.cloudera.csd.validation.SdlTestUtils; import java.util.Set; import javax.validation.ConstraintViolation; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration;
// Licensed to Cloudera, Inc. under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. Cloudera, Inc. licenses this file // to you 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.cloudera.csd.validation.components; @ContextConfiguration({"classpath:spring-config.xml"}) @RunWith(SpringJUnit4ClassRunner.class) public class ServiceMonitoringDefinitionsDescriptorValidatorImplTest { @Autowired private ServiceMonitoringDefinitionsDescriptorValidatorImpl validator; @Test public void testGoodServiceMonitoringDefinitionsDescriptor() throws Exception { assertEquals(0,
// Path: cm-schema/src/test/java/com/cloudera/csd/validation/SdlTestUtils.java // public class SdlTestUtils { // // public static final JsonSdlObjectMapper OBJECT_MAPPER; // public static final JsonSdlParser SDL_PARSER; // public static final JsonMdlParser MDL_PARSER; // public static final ServiceDescriptor FULL_DESCRIPTOR; // public static final DescriptorValidator<ServiceDescriptor> // FAKE_SDL_VALIDATOR; // public static final DescriptorValidator<ServiceMonitoringDefinitionsDescriptor> // FAKE_MDL_VALIDATOR; // // private static final String RESOURCE_PATH = "/com/cloudera/csd/"; // public static final String SDL_VALIDATOR_RESOURCE_PATH = RESOURCE_PATH + "validator/"; // public static final String SDL_REFERENCE_VALIDATOR_RESOURCE_PATH = SDL_VALIDATOR_RESOURCE_PATH + "references/"; // public static final String SDL_PARSER_RESOURCE_PATH = RESOURCE_PATH + "parser/"; // // // Initialize our variables // static { // OBJECT_MAPPER = new JsonSdlObjectMapper(); // SDL_PARSER = new JsonSdlParser(OBJECT_MAPPER); // MDL_PARSER = new JsonMdlParser(OBJECT_MAPPER); // FULL_DESCRIPTOR = getParserSdl("service_full.sdl"); // FAKE_SDL_VALIDATOR = getAlwaysPassingSdlValidator(); // FAKE_MDL_VALIDATOR = getAlwaysPassingMdlValidator(); // } // // public static ServiceDescriptor parseSDL(String path) { // try { // InputStream stream = SdlTestUtils.class.getResourceAsStream(path); // return SDL_PARSER.parse(IOUtils.toByteArray(stream)); // } catch (IOException io) { // throw new RuntimeException(io); // } // } // // public static ServiceMonitoringDefinitionsDescriptor parseMDL(String path) { // try { // InputStream stream = SdlTestUtils.class.getResourceAsStream(path); // return MDL_PARSER.parse(IOUtils.toByteArray(stream)); // } catch (IOException io) { // throw new RuntimeException(io); // } // } // // public static ServiceDescriptor getParserSdl(String filename) { // return parseSDL(SDL_PARSER_RESOURCE_PATH + filename); // } // // public static ServiceDescriptor getValidatorSdl(String filename) { // return parseSDL(SDL_VALIDATOR_RESOURCE_PATH + filename); // } // // public static ServiceMonitoringDefinitionsDescriptor getValidatorMdl( // String filename) { // return parseMDL(SDL_VALIDATOR_RESOURCE_PATH + filename); // } // // public static ServiceDescriptor getReferenceValidatorSdl(String filename) { // return parseSDL(SDL_REFERENCE_VALIDATOR_RESOURCE_PATH + filename); // } // // public static DescriptorValidator<ServiceDescriptor> // getAlwaysPassingSdlValidator() { // return new DescriptorValidator<ServiceDescriptor>() { // public Set<String> validate(ServiceDescriptor serviceDescriptor) { // return Sets.newHashSet(); // } // }; // } // // public static DescriptorValidator<ServiceMonitoringDefinitionsDescriptor> // getAlwaysPassingMdlValidator() { // return new DescriptorValidator<ServiceMonitoringDefinitionsDescriptor>() { // public Set<String> validate( // ServiceMonitoringDefinitionsDescriptor serviceDescriptor) { // return Sets.newHashSet(); // } // }; // } // // public static Map<String, RoleDescriptor> makeRoleMap(Collection<RoleDescriptor> roles) { // ImmutableMap.Builder<String, RoleDescriptor> builder = ImmutableMap.builder(); // for (RoleDescriptor r : roles) { // builder.put(r.getName(), r); // } // return builder.build(); // } // } // Path: cm-schema/src/test/java/com/cloudera/csd/validation/components/ServiceMonitoringDefinitionsDescriptorValidatorImplTest.java import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import com.cloudera.csd.descriptors.ServiceMonitoringDefinitionsDescriptor; import com.cloudera.csd.validation.SdlTestUtils; import java.util.Set; import javax.validation.ConstraintViolation; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; // Licensed to Cloudera, Inc. under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. Cloudera, Inc. licenses this file // to you 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.cloudera.csd.validation.components; @ContextConfiguration({"classpath:spring-config.xml"}) @RunWith(SpringJUnit4ClassRunner.class) public class ServiceMonitoringDefinitionsDescriptorValidatorImplTest { @Autowired private ServiceMonitoringDefinitionsDescriptorValidatorImpl validator; @Test public void testGoodServiceMonitoringDefinitionsDescriptor() throws Exception { assertEquals(0,
validator.validate(SdlTestUtils.getValidatorMdl(
cloudera/cm_ext
cm-schema/src/test/java/com/cloudera/csd/validation/monitoring/constraints/MetricNamePrefixedWithServiceNameValidatorTest.java
// Path: cm-schema/src/main/java/com/cloudera/csd/validation/monitoring/MonitoringValidationContext.java // public class MonitoringValidationContext { // // public final ServiceMonitoringDefinitionsDescriptor serviceDescriptor; // public final ImmutableMap<String, MetricDescriptor> metricsDefined; // public final ImmutableMap<String, MetricEntityTypeDescriptor> entitiesDefined; // public final ImmutableMap<String, RoleMonitoringDefinitionsDescriptor> rolesDefined; // public final ImmutableMap<String, MetricEntityAttributeDescriptor> attributesDefined; // // public MonitoringValidationContext( // ServiceMonitoringDefinitionsDescriptor serviceDescriptor) { // Preconditions.checkNotNull(serviceDescriptor); // this.serviceDescriptor = serviceDescriptor; // ImmutableMap.Builder<String, RoleMonitoringDefinitionsDescriptor> // rolesDefinedBuilder = ImmutableMap.builder(); // // We can't use an ImmutableMap.Builder since it will not allow multiple // // entries with the same key. Instead we build a local hash map and make // // it immutable below. // Map<String, MetricDescriptor> metricsDefinedBuilder = Maps.newHashMap(); // metricsDefinedBuilder.putAll( // extractMetrics(serviceDescriptor.getMetricDefinitions())); // if (null != serviceDescriptor.getRoles()) { // for (RoleMonitoringDefinitionsDescriptor role : // serviceDescriptor.getRoles()) { // rolesDefinedBuilder.put( // MonitoringConventions.getRoleMetricEntityTypeName( // serviceDescriptor.getName(), // role.getName()), // role); // metricsDefinedBuilder.putAll( // extractMetrics(role.getMetricDefinitions())); // } // } // if (null != serviceDescriptor.getMetricEntityTypeDefinitions()) { // for (MetricEntityTypeDescriptor entity : // serviceDescriptor.getMetricEntityTypeDefinitions()) { // metricsDefinedBuilder.putAll( // extractMetrics(entity.getMetricDefinitions())); // } // } // ImmutableMap.Builder<String, MetricEntityTypeDescriptor> // entitiesDefinedBuilder = ImmutableMap.builder(); // if (null != serviceDescriptor.getMetricEntityTypeDefinitions()) { // for (MetricEntityTypeDescriptor entity : // serviceDescriptor.getMetricEntityTypeDefinitions()) { // entitiesDefinedBuilder.put(entity.getName(), entity); // } // } // ImmutableMap.Builder<String, MetricEntityAttributeDescriptor> // attributesDefinedBuilder = ImmutableMap.builder(); // if (null != serviceDescriptor.getMetricEntityAttributeDefinitions()) { // for (MetricEntityAttributeDescriptor attribute : // serviceDescriptor.getMetricEntityAttributeDefinitions()) { // attributesDefinedBuilder.put(attribute.getName(), attribute); // } // } // metricsDefined = ImmutableMap.copyOf(metricsDefinedBuilder); // rolesDefined = rolesDefinedBuilder.build(); // entitiesDefined = entitiesDefinedBuilder.build(); // attributesDefined = attributesDefinedBuilder.build(); // } // // private Map<String, MetricDescriptor> extractMetrics( // @Nullable List<MetricDescriptor> metrics) { // if (null == metrics) { // return ImmutableMap.of(); // } // Map<String, MetricDescriptor> ret = Maps.newHashMap(); // for (MetricDescriptor metric : metrics) { // ret.put(metric.getName(), metric); // } // return ret; // } // }
import com.cloudera.csd.validation.monitoring.MonitoringValidationContext; import com.google.common.collect.Iterables; import java.util.List; import javax.validation.ConstraintViolation; import org.junit.Assert; import org.junit.Before; import org.junit.Test;
// Licensed to Cloudera, Inc. under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. Cloudera, Inc. licenses this file // to you 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.cloudera.csd.validation.monitoring.constraints; public class MetricNamePrefixedWithServiceNameValidatorTest extends AbstractMonitoringValidatorBaseTest { private MetricNamePrefixedWithServiceNameValidator validator;
// Path: cm-schema/src/main/java/com/cloudera/csd/validation/monitoring/MonitoringValidationContext.java // public class MonitoringValidationContext { // // public final ServiceMonitoringDefinitionsDescriptor serviceDescriptor; // public final ImmutableMap<String, MetricDescriptor> metricsDefined; // public final ImmutableMap<String, MetricEntityTypeDescriptor> entitiesDefined; // public final ImmutableMap<String, RoleMonitoringDefinitionsDescriptor> rolesDefined; // public final ImmutableMap<String, MetricEntityAttributeDescriptor> attributesDefined; // // public MonitoringValidationContext( // ServiceMonitoringDefinitionsDescriptor serviceDescriptor) { // Preconditions.checkNotNull(serviceDescriptor); // this.serviceDescriptor = serviceDescriptor; // ImmutableMap.Builder<String, RoleMonitoringDefinitionsDescriptor> // rolesDefinedBuilder = ImmutableMap.builder(); // // We can't use an ImmutableMap.Builder since it will not allow multiple // // entries with the same key. Instead we build a local hash map and make // // it immutable below. // Map<String, MetricDescriptor> metricsDefinedBuilder = Maps.newHashMap(); // metricsDefinedBuilder.putAll( // extractMetrics(serviceDescriptor.getMetricDefinitions())); // if (null != serviceDescriptor.getRoles()) { // for (RoleMonitoringDefinitionsDescriptor role : // serviceDescriptor.getRoles()) { // rolesDefinedBuilder.put( // MonitoringConventions.getRoleMetricEntityTypeName( // serviceDescriptor.getName(), // role.getName()), // role); // metricsDefinedBuilder.putAll( // extractMetrics(role.getMetricDefinitions())); // } // } // if (null != serviceDescriptor.getMetricEntityTypeDefinitions()) { // for (MetricEntityTypeDescriptor entity : // serviceDescriptor.getMetricEntityTypeDefinitions()) { // metricsDefinedBuilder.putAll( // extractMetrics(entity.getMetricDefinitions())); // } // } // ImmutableMap.Builder<String, MetricEntityTypeDescriptor> // entitiesDefinedBuilder = ImmutableMap.builder(); // if (null != serviceDescriptor.getMetricEntityTypeDefinitions()) { // for (MetricEntityTypeDescriptor entity : // serviceDescriptor.getMetricEntityTypeDefinitions()) { // entitiesDefinedBuilder.put(entity.getName(), entity); // } // } // ImmutableMap.Builder<String, MetricEntityAttributeDescriptor> // attributesDefinedBuilder = ImmutableMap.builder(); // if (null != serviceDescriptor.getMetricEntityAttributeDefinitions()) { // for (MetricEntityAttributeDescriptor attribute : // serviceDescriptor.getMetricEntityAttributeDefinitions()) { // attributesDefinedBuilder.put(attribute.getName(), attribute); // } // } // metricsDefined = ImmutableMap.copyOf(metricsDefinedBuilder); // rolesDefined = rolesDefinedBuilder.build(); // entitiesDefined = entitiesDefinedBuilder.build(); // attributesDefined = attributesDefinedBuilder.build(); // } // // private Map<String, MetricDescriptor> extractMetrics( // @Nullable List<MetricDescriptor> metrics) { // if (null == metrics) { // return ImmutableMap.of(); // } // Map<String, MetricDescriptor> ret = Maps.newHashMap(); // for (MetricDescriptor metric : metrics) { // ret.put(metric.getName(), metric); // } // return ret; // } // } // Path: cm-schema/src/test/java/com/cloudera/csd/validation/monitoring/constraints/MetricNamePrefixedWithServiceNameValidatorTest.java import com.cloudera.csd.validation.monitoring.MonitoringValidationContext; import com.google.common.collect.Iterables; import java.util.List; import javax.validation.ConstraintViolation; import org.junit.Assert; import org.junit.Before; import org.junit.Test; // Licensed to Cloudera, Inc. under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. Cloudera, Inc. licenses this file // to you 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.cloudera.csd.validation.monitoring.constraints; public class MetricNamePrefixedWithServiceNameValidatorTest extends AbstractMonitoringValidatorBaseTest { private MetricNamePrefixedWithServiceNameValidator validator;
private MonitoringValidationContext context;
cloudera/cm_ext
cm-schema/src/test/java/com/cloudera/parcel/components/JsonManifestParserTest.java
// Path: cm-schema/src/main/java/com/cloudera/parcel/descriptors/ParcelInfoDescriptor.java // public interface ParcelInfoDescriptor { // // @NotBlank // String getParcelName(); // // @NotBlank // String getHash(); // // @UniqueField("name") // @Valid // @NotNull // List<ComponentDescriptor> getComponents(); // // Instant getReleased(); // // String getDepends(); // // String getReplaces(); // // String getConflicts(); // // String getReleaseNotes(); // // ServicesRestartDescriptor getServicesRestartInfo(); // } // // Path: cm-schema/src/main/java/com/cloudera/parcel/descriptors/VersionServicesRestartDescriptor.java // public interface VersionServicesRestartDescriptor { // // enum Scope { // SERVICE_ONLY, // DEPENDENTS_ONLY, // SERVICE_AND_DEPENDENTS // } // // /** // * Contains a map of service type to {@link Scope} // * @return a map of service type to {@link Scope} // */ // @NotNull // Map<String, Scope> getServiceInfo(); // // /** // * Parent parcel version of this version descriptor. // * // * Can be null, in which case this is determined to be the oldest version // * supported from which the restart information will be used for selective restarts. // * // * @return parent version, if specified. // */ // String getParentVersion(); // // /** // * Child parcel version of this version descriptor. // * // * Can be null, in which case this is determined to be the newest version // * supported from which the restart information will be used for selective restarts. // * // * @return child version, if specified. // */ // String getChildVersion(); // } // // Path: cm-schema/src/main/java/com/cloudera/parcel/descriptors/VersionServicesRestartDescriptor.java // enum Scope { // SERVICE_ONLY, // DEPENDENTS_ONLY, // SERVICE_AND_DEPENDENTS // }
import static org.junit.Assert.*; import com.cloudera.parcel.descriptors.ManifestDescriptor; import com.cloudera.parcel.descriptors.ParcelInfoDescriptor; import com.cloudera.parcel.descriptors.VersionServicesRestartDescriptor; import com.cloudera.parcel.descriptors.VersionServicesRestartDescriptor.Scope; import com.cloudera.parcel.validation.ParcelTestUtils; import java.io.IOException; import java.util.List; import java.util.Map; import org.joda.time.Instant; import org.junit.Test;
// Licensed to Cloudera, Inc. under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. Cloudera, Inc. licenses this file // to you 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.cloudera.parcel.components; public class JsonManifestParserTest { private JsonManifestParser parser = new JsonManifestParser(); @Test public void testParseGoodFile() throws IOException { ManifestDescriptor descriptor = parser.parse(ParcelTestUtils.getParcelJson("good_manifest.json")); assertEquals(new Instant(1392073012), descriptor.getLastUpdated());
// Path: cm-schema/src/main/java/com/cloudera/parcel/descriptors/ParcelInfoDescriptor.java // public interface ParcelInfoDescriptor { // // @NotBlank // String getParcelName(); // // @NotBlank // String getHash(); // // @UniqueField("name") // @Valid // @NotNull // List<ComponentDescriptor> getComponents(); // // Instant getReleased(); // // String getDepends(); // // String getReplaces(); // // String getConflicts(); // // String getReleaseNotes(); // // ServicesRestartDescriptor getServicesRestartInfo(); // } // // Path: cm-schema/src/main/java/com/cloudera/parcel/descriptors/VersionServicesRestartDescriptor.java // public interface VersionServicesRestartDescriptor { // // enum Scope { // SERVICE_ONLY, // DEPENDENTS_ONLY, // SERVICE_AND_DEPENDENTS // } // // /** // * Contains a map of service type to {@link Scope} // * @return a map of service type to {@link Scope} // */ // @NotNull // Map<String, Scope> getServiceInfo(); // // /** // * Parent parcel version of this version descriptor. // * // * Can be null, in which case this is determined to be the oldest version // * supported from which the restart information will be used for selective restarts. // * // * @return parent version, if specified. // */ // String getParentVersion(); // // /** // * Child parcel version of this version descriptor. // * // * Can be null, in which case this is determined to be the newest version // * supported from which the restart information will be used for selective restarts. // * // * @return child version, if specified. // */ // String getChildVersion(); // } // // Path: cm-schema/src/main/java/com/cloudera/parcel/descriptors/VersionServicesRestartDescriptor.java // enum Scope { // SERVICE_ONLY, // DEPENDENTS_ONLY, // SERVICE_AND_DEPENDENTS // } // Path: cm-schema/src/test/java/com/cloudera/parcel/components/JsonManifestParserTest.java import static org.junit.Assert.*; import com.cloudera.parcel.descriptors.ManifestDescriptor; import com.cloudera.parcel.descriptors.ParcelInfoDescriptor; import com.cloudera.parcel.descriptors.VersionServicesRestartDescriptor; import com.cloudera.parcel.descriptors.VersionServicesRestartDescriptor.Scope; import com.cloudera.parcel.validation.ParcelTestUtils; import java.io.IOException; import java.util.List; import java.util.Map; import org.joda.time.Instant; import org.junit.Test; // Licensed to Cloudera, Inc. under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. Cloudera, Inc. licenses this file // to you 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.cloudera.parcel.components; public class JsonManifestParserTest { private JsonManifestParser parser = new JsonManifestParser(); @Test public void testParseGoodFile() throws IOException { ManifestDescriptor descriptor = parser.parse(ParcelTestUtils.getParcelJson("good_manifest.json")); assertEquals(new Instant(1392073012), descriptor.getLastUpdated());
List<ParcelInfoDescriptor> parcels = descriptor.getParcels();
cloudera/cm_ext
cm-schema/src/test/java/com/cloudera/parcel/components/JsonManifestParserTest.java
// Path: cm-schema/src/main/java/com/cloudera/parcel/descriptors/ParcelInfoDescriptor.java // public interface ParcelInfoDescriptor { // // @NotBlank // String getParcelName(); // // @NotBlank // String getHash(); // // @UniqueField("name") // @Valid // @NotNull // List<ComponentDescriptor> getComponents(); // // Instant getReleased(); // // String getDepends(); // // String getReplaces(); // // String getConflicts(); // // String getReleaseNotes(); // // ServicesRestartDescriptor getServicesRestartInfo(); // } // // Path: cm-schema/src/main/java/com/cloudera/parcel/descriptors/VersionServicesRestartDescriptor.java // public interface VersionServicesRestartDescriptor { // // enum Scope { // SERVICE_ONLY, // DEPENDENTS_ONLY, // SERVICE_AND_DEPENDENTS // } // // /** // * Contains a map of service type to {@link Scope} // * @return a map of service type to {@link Scope} // */ // @NotNull // Map<String, Scope> getServiceInfo(); // // /** // * Parent parcel version of this version descriptor. // * // * Can be null, in which case this is determined to be the oldest version // * supported from which the restart information will be used for selective restarts. // * // * @return parent version, if specified. // */ // String getParentVersion(); // // /** // * Child parcel version of this version descriptor. // * // * Can be null, in which case this is determined to be the newest version // * supported from which the restart information will be used for selective restarts. // * // * @return child version, if specified. // */ // String getChildVersion(); // } // // Path: cm-schema/src/main/java/com/cloudera/parcel/descriptors/VersionServicesRestartDescriptor.java // enum Scope { // SERVICE_ONLY, // DEPENDENTS_ONLY, // SERVICE_AND_DEPENDENTS // }
import static org.junit.Assert.*; import com.cloudera.parcel.descriptors.ManifestDescriptor; import com.cloudera.parcel.descriptors.ParcelInfoDescriptor; import com.cloudera.parcel.descriptors.VersionServicesRestartDescriptor; import com.cloudera.parcel.descriptors.VersionServicesRestartDescriptor.Scope; import com.cloudera.parcel.validation.ParcelTestUtils; import java.io.IOException; import java.util.List; import java.util.Map; import org.joda.time.Instant; import org.junit.Test;
// Licensed to Cloudera, Inc. under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. Cloudera, Inc. licenses this file // to you 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.cloudera.parcel.components; public class JsonManifestParserTest { private JsonManifestParser parser = new JsonManifestParser(); @Test public void testParseGoodFile() throws IOException { ManifestDescriptor descriptor = parser.parse(ParcelTestUtils.getParcelJson("good_manifest.json")); assertEquals(new Instant(1392073012), descriptor.getLastUpdated()); List<ParcelInfoDescriptor> parcels = descriptor.getParcels(); assertEquals(3, parcels.size()); ParcelInfoDescriptor parcelInfo = parcels.get(0); assertEquals("CDH-5.0.0-0.cdh5b2.p0.282-wheezy.parcel", parcelInfo.getParcelName()); assertEquals("ec6e65de6e192949fd095b391b9e3b8b2d13e780", parcelInfo.getHash()); assertEquals("IMPALA, SOLR, SPARK", parcelInfo.getReplaces()); assertEquals(27, parcelInfo.getComponents().size()); parcelInfo = parcels.get(1); assertEquals("CDH-5.0.0-0.cdh5b2.p0.30-el6.parcel", parcelInfo.getParcelName()); assertEquals("d4d5d146e00c2d3ff19e95476f3485be64fd0f71", parcelInfo.getHash()); assertEquals("IMPALA, SOLR, SPARK", parcelInfo.getReplaces()); assertEquals(27, parcelInfo.getComponents().size()); parcelInfo = parcels.get(2); assertEquals("CDH-5.5.0-0.cdh5b2.p0.1-el6.parcel", parcelInfo.getParcelName()); assertEquals("f4asdas146e00c2d3ff19e95476f3485be64fd0f", parcelInfo.getHash()); assertEquals("IMPALA, SOLR, SPARK", parcelInfo.getReplaces()); assertEquals(27, parcelInfo.getComponents().size()); assertNotNull(parcelInfo.getServicesRestartInfo()); assertNotNull(parcelInfo.getServicesRestartInfo().getVersionInfo());
// Path: cm-schema/src/main/java/com/cloudera/parcel/descriptors/ParcelInfoDescriptor.java // public interface ParcelInfoDescriptor { // // @NotBlank // String getParcelName(); // // @NotBlank // String getHash(); // // @UniqueField("name") // @Valid // @NotNull // List<ComponentDescriptor> getComponents(); // // Instant getReleased(); // // String getDepends(); // // String getReplaces(); // // String getConflicts(); // // String getReleaseNotes(); // // ServicesRestartDescriptor getServicesRestartInfo(); // } // // Path: cm-schema/src/main/java/com/cloudera/parcel/descriptors/VersionServicesRestartDescriptor.java // public interface VersionServicesRestartDescriptor { // // enum Scope { // SERVICE_ONLY, // DEPENDENTS_ONLY, // SERVICE_AND_DEPENDENTS // } // // /** // * Contains a map of service type to {@link Scope} // * @return a map of service type to {@link Scope} // */ // @NotNull // Map<String, Scope> getServiceInfo(); // // /** // * Parent parcel version of this version descriptor. // * // * Can be null, in which case this is determined to be the oldest version // * supported from which the restart information will be used for selective restarts. // * // * @return parent version, if specified. // */ // String getParentVersion(); // // /** // * Child parcel version of this version descriptor. // * // * Can be null, in which case this is determined to be the newest version // * supported from which the restart information will be used for selective restarts. // * // * @return child version, if specified. // */ // String getChildVersion(); // } // // Path: cm-schema/src/main/java/com/cloudera/parcel/descriptors/VersionServicesRestartDescriptor.java // enum Scope { // SERVICE_ONLY, // DEPENDENTS_ONLY, // SERVICE_AND_DEPENDENTS // } // Path: cm-schema/src/test/java/com/cloudera/parcel/components/JsonManifestParserTest.java import static org.junit.Assert.*; import com.cloudera.parcel.descriptors.ManifestDescriptor; import com.cloudera.parcel.descriptors.ParcelInfoDescriptor; import com.cloudera.parcel.descriptors.VersionServicesRestartDescriptor; import com.cloudera.parcel.descriptors.VersionServicesRestartDescriptor.Scope; import com.cloudera.parcel.validation.ParcelTestUtils; import java.io.IOException; import java.util.List; import java.util.Map; import org.joda.time.Instant; import org.junit.Test; // Licensed to Cloudera, Inc. under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. Cloudera, Inc. licenses this file // to you 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.cloudera.parcel.components; public class JsonManifestParserTest { private JsonManifestParser parser = new JsonManifestParser(); @Test public void testParseGoodFile() throws IOException { ManifestDescriptor descriptor = parser.parse(ParcelTestUtils.getParcelJson("good_manifest.json")); assertEquals(new Instant(1392073012), descriptor.getLastUpdated()); List<ParcelInfoDescriptor> parcels = descriptor.getParcels(); assertEquals(3, parcels.size()); ParcelInfoDescriptor parcelInfo = parcels.get(0); assertEquals("CDH-5.0.0-0.cdh5b2.p0.282-wheezy.parcel", parcelInfo.getParcelName()); assertEquals("ec6e65de6e192949fd095b391b9e3b8b2d13e780", parcelInfo.getHash()); assertEquals("IMPALA, SOLR, SPARK", parcelInfo.getReplaces()); assertEquals(27, parcelInfo.getComponents().size()); parcelInfo = parcels.get(1); assertEquals("CDH-5.0.0-0.cdh5b2.p0.30-el6.parcel", parcelInfo.getParcelName()); assertEquals("d4d5d146e00c2d3ff19e95476f3485be64fd0f71", parcelInfo.getHash()); assertEquals("IMPALA, SOLR, SPARK", parcelInfo.getReplaces()); assertEquals(27, parcelInfo.getComponents().size()); parcelInfo = parcels.get(2); assertEquals("CDH-5.5.0-0.cdh5b2.p0.1-el6.parcel", parcelInfo.getParcelName()); assertEquals("f4asdas146e00c2d3ff19e95476f3485be64fd0f", parcelInfo.getHash()); assertEquals("IMPALA, SOLR, SPARK", parcelInfo.getReplaces()); assertEquals(27, parcelInfo.getComponents().size()); assertNotNull(parcelInfo.getServicesRestartInfo()); assertNotNull(parcelInfo.getServicesRestartInfo().getVersionInfo());
Map<String, VersionServicesRestartDescriptor> versionServicesRestartDescriptorMap =
cloudera/cm_ext
cm-schema/src/test/java/com/cloudera/parcel/components/JsonManifestParserTest.java
// Path: cm-schema/src/main/java/com/cloudera/parcel/descriptors/ParcelInfoDescriptor.java // public interface ParcelInfoDescriptor { // // @NotBlank // String getParcelName(); // // @NotBlank // String getHash(); // // @UniqueField("name") // @Valid // @NotNull // List<ComponentDescriptor> getComponents(); // // Instant getReleased(); // // String getDepends(); // // String getReplaces(); // // String getConflicts(); // // String getReleaseNotes(); // // ServicesRestartDescriptor getServicesRestartInfo(); // } // // Path: cm-schema/src/main/java/com/cloudera/parcel/descriptors/VersionServicesRestartDescriptor.java // public interface VersionServicesRestartDescriptor { // // enum Scope { // SERVICE_ONLY, // DEPENDENTS_ONLY, // SERVICE_AND_DEPENDENTS // } // // /** // * Contains a map of service type to {@link Scope} // * @return a map of service type to {@link Scope} // */ // @NotNull // Map<String, Scope> getServiceInfo(); // // /** // * Parent parcel version of this version descriptor. // * // * Can be null, in which case this is determined to be the oldest version // * supported from which the restart information will be used for selective restarts. // * // * @return parent version, if specified. // */ // String getParentVersion(); // // /** // * Child parcel version of this version descriptor. // * // * Can be null, in which case this is determined to be the newest version // * supported from which the restart information will be used for selective restarts. // * // * @return child version, if specified. // */ // String getChildVersion(); // } // // Path: cm-schema/src/main/java/com/cloudera/parcel/descriptors/VersionServicesRestartDescriptor.java // enum Scope { // SERVICE_ONLY, // DEPENDENTS_ONLY, // SERVICE_AND_DEPENDENTS // }
import static org.junit.Assert.*; import com.cloudera.parcel.descriptors.ManifestDescriptor; import com.cloudera.parcel.descriptors.ParcelInfoDescriptor; import com.cloudera.parcel.descriptors.VersionServicesRestartDescriptor; import com.cloudera.parcel.descriptors.VersionServicesRestartDescriptor.Scope; import com.cloudera.parcel.validation.ParcelTestUtils; import java.io.IOException; import java.util.List; import java.util.Map; import org.joda.time.Instant; import org.junit.Test;
assertEquals("IMPALA, SOLR, SPARK", parcelInfo.getReplaces()); assertEquals(27, parcelInfo.getComponents().size()); parcelInfo = parcels.get(2); assertEquals("CDH-5.5.0-0.cdh5b2.p0.1-el6.parcel", parcelInfo.getParcelName()); assertEquals("f4asdas146e00c2d3ff19e95476f3485be64fd0f", parcelInfo.getHash()); assertEquals("IMPALA, SOLR, SPARK", parcelInfo.getReplaces()); assertEquals(27, parcelInfo.getComponents().size()); assertNotNull(parcelInfo.getServicesRestartInfo()); assertNotNull(parcelInfo.getServicesRestartInfo().getVersionInfo()); Map<String, VersionServicesRestartDescriptor> versionServicesRestartDescriptorMap = parcelInfo.getServicesRestartInfo().getVersionInfo(); assertEquals(3, versionServicesRestartDescriptorMap.size()); assertTrue(versionServicesRestartDescriptorMap.containsKey("5.5.0-0.cdh5b2.p0.1")); assertTrue(versionServicesRestartDescriptorMap.containsKey("5.5.0-0.cdh5b2")); assertTrue(versionServicesRestartDescriptorMap.containsKey("5.5.0-0.cdh5b")); VersionServicesRestartDescriptor p01 = versionServicesRestartDescriptorMap.get("5.5.0-0.cdh5b2.p0.1"); VersionServicesRestartDescriptor p00 = versionServicesRestartDescriptorMap.get("5.5.0-0.cdh5b2"); VersionServicesRestartDescriptor base = versionServicesRestartDescriptorMap.get("5.5.0-0.cdh5b"); assertNull(p01.getChildVersion()); assertEquals("5.5.0-0.cdh5b2", p01.getParentVersion()); assertTrue(p01.getServiceInfo().containsKey("IMPALA"));
// Path: cm-schema/src/main/java/com/cloudera/parcel/descriptors/ParcelInfoDescriptor.java // public interface ParcelInfoDescriptor { // // @NotBlank // String getParcelName(); // // @NotBlank // String getHash(); // // @UniqueField("name") // @Valid // @NotNull // List<ComponentDescriptor> getComponents(); // // Instant getReleased(); // // String getDepends(); // // String getReplaces(); // // String getConflicts(); // // String getReleaseNotes(); // // ServicesRestartDescriptor getServicesRestartInfo(); // } // // Path: cm-schema/src/main/java/com/cloudera/parcel/descriptors/VersionServicesRestartDescriptor.java // public interface VersionServicesRestartDescriptor { // // enum Scope { // SERVICE_ONLY, // DEPENDENTS_ONLY, // SERVICE_AND_DEPENDENTS // } // // /** // * Contains a map of service type to {@link Scope} // * @return a map of service type to {@link Scope} // */ // @NotNull // Map<String, Scope> getServiceInfo(); // // /** // * Parent parcel version of this version descriptor. // * // * Can be null, in which case this is determined to be the oldest version // * supported from which the restart information will be used for selective restarts. // * // * @return parent version, if specified. // */ // String getParentVersion(); // // /** // * Child parcel version of this version descriptor. // * // * Can be null, in which case this is determined to be the newest version // * supported from which the restart information will be used for selective restarts. // * // * @return child version, if specified. // */ // String getChildVersion(); // } // // Path: cm-schema/src/main/java/com/cloudera/parcel/descriptors/VersionServicesRestartDescriptor.java // enum Scope { // SERVICE_ONLY, // DEPENDENTS_ONLY, // SERVICE_AND_DEPENDENTS // } // Path: cm-schema/src/test/java/com/cloudera/parcel/components/JsonManifestParserTest.java import static org.junit.Assert.*; import com.cloudera.parcel.descriptors.ManifestDescriptor; import com.cloudera.parcel.descriptors.ParcelInfoDescriptor; import com.cloudera.parcel.descriptors.VersionServicesRestartDescriptor; import com.cloudera.parcel.descriptors.VersionServicesRestartDescriptor.Scope; import com.cloudera.parcel.validation.ParcelTestUtils; import java.io.IOException; import java.util.List; import java.util.Map; import org.joda.time.Instant; import org.junit.Test; assertEquals("IMPALA, SOLR, SPARK", parcelInfo.getReplaces()); assertEquals(27, parcelInfo.getComponents().size()); parcelInfo = parcels.get(2); assertEquals("CDH-5.5.0-0.cdh5b2.p0.1-el6.parcel", parcelInfo.getParcelName()); assertEquals("f4asdas146e00c2d3ff19e95476f3485be64fd0f", parcelInfo.getHash()); assertEquals("IMPALA, SOLR, SPARK", parcelInfo.getReplaces()); assertEquals(27, parcelInfo.getComponents().size()); assertNotNull(parcelInfo.getServicesRestartInfo()); assertNotNull(parcelInfo.getServicesRestartInfo().getVersionInfo()); Map<String, VersionServicesRestartDescriptor> versionServicesRestartDescriptorMap = parcelInfo.getServicesRestartInfo().getVersionInfo(); assertEquals(3, versionServicesRestartDescriptorMap.size()); assertTrue(versionServicesRestartDescriptorMap.containsKey("5.5.0-0.cdh5b2.p0.1")); assertTrue(versionServicesRestartDescriptorMap.containsKey("5.5.0-0.cdh5b2")); assertTrue(versionServicesRestartDescriptorMap.containsKey("5.5.0-0.cdh5b")); VersionServicesRestartDescriptor p01 = versionServicesRestartDescriptorMap.get("5.5.0-0.cdh5b2.p0.1"); VersionServicesRestartDescriptor p00 = versionServicesRestartDescriptorMap.get("5.5.0-0.cdh5b2"); VersionServicesRestartDescriptor base = versionServicesRestartDescriptorMap.get("5.5.0-0.cdh5b"); assertNull(p01.getChildVersion()); assertEquals("5.5.0-0.cdh5b2", p01.getParentVersion()); assertTrue(p01.getServiceInfo().containsKey("IMPALA"));
assertTrue(p01.getServiceInfo().containsValue(Scope.DEPENDENTS_ONLY));
cloudera/cm_ext
cm-schema/src/test/java/com/cloudera/csd/tools/codahale/CodahaleMetricDefinitionFixtureTest.java
// Path: cm-schema/src/main/java/com/cloudera/csd/tools/codahale/CodahaleMetricTypes.java // public enum CodahaleMetricType { // GAUGE, // COUNTER, // HISTOGRAM, // TIMER, // METER // }
import com.cloudera.csd.tools.JsonUtil; import com.cloudera.csd.tools.JsonUtil.JsonRuntimeException; import com.cloudera.csd.tools.codahale.CodahaleMetricTypes.CodahaleMetricType; import java.io.InputStream; import org.apache.commons.io.IOUtils; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.fail;
public void testEmptyFixture() { InputStream in = null; try { in = this.getClass().getResourceAsStream( "/com/cloudera/csd/tools/codahale/empty_but_valid.json"); CodahaleMetricDefinitionFixture fixture = JsonUtil.valueFromStream( CodahaleMetricDefinitionFixture.class, in); assertNotNull(fixture.getServiceName()); } finally { IOUtils.closeQuietly(in); } } @Test public void testValidFixture() { InputStream in = null; try { in = this.getClass().getResourceAsStream( "/com/cloudera/csd/tools/codahale/valid.json"); CodahaleMetricDefinitionFixture fixture = JsonUtil.valueFromStream( CodahaleMetricDefinitionFixture.class, in); assertEquals("test_service", fixture.getServiceName()); assertEquals(1, fixture.getServiceMetrics().size()); assertEquals(2, fixture.getRolesMetrics().size()); assertEquals(2, fixture.getRolesMetrics().get("test_role1_metrics").size()); CodahaleMetric metric = fixture.getRolesMetrics().get("test_role1_metrics").get(1);
// Path: cm-schema/src/main/java/com/cloudera/csd/tools/codahale/CodahaleMetricTypes.java // public enum CodahaleMetricType { // GAUGE, // COUNTER, // HISTOGRAM, // TIMER, // METER // } // Path: cm-schema/src/test/java/com/cloudera/csd/tools/codahale/CodahaleMetricDefinitionFixtureTest.java import com.cloudera.csd.tools.JsonUtil; import com.cloudera.csd.tools.JsonUtil.JsonRuntimeException; import com.cloudera.csd.tools.codahale.CodahaleMetricTypes.CodahaleMetricType; import java.io.InputStream; import org.apache.commons.io.IOUtils; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.fail; public void testEmptyFixture() { InputStream in = null; try { in = this.getClass().getResourceAsStream( "/com/cloudera/csd/tools/codahale/empty_but_valid.json"); CodahaleMetricDefinitionFixture fixture = JsonUtil.valueFromStream( CodahaleMetricDefinitionFixture.class, in); assertNotNull(fixture.getServiceName()); } finally { IOUtils.closeQuietly(in); } } @Test public void testValidFixture() { InputStream in = null; try { in = this.getClass().getResourceAsStream( "/com/cloudera/csd/tools/codahale/valid.json"); CodahaleMetricDefinitionFixture fixture = JsonUtil.valueFromStream( CodahaleMetricDefinitionFixture.class, in); assertEquals("test_service", fixture.getServiceName()); assertEquals(1, fixture.getServiceMetrics().size()); assertEquals(2, fixture.getRolesMetrics().size()); assertEquals(2, fixture.getRolesMetrics().get("test_role1_metrics").size()); CodahaleMetric metric = fixture.getRolesMetrics().get("test_role1_metrics").get(1);
validateMetric(metric, "test_role1_metric2", CodahaleMetricType.GAUGE);
cloudera/cm_ext
cm-schema/src/test/java/com/cloudera/parcel/components/JsonParcelParserTest.java
// Path: cm-schema/src/main/java/com/cloudera/parcel/descriptors/ParcelDescriptor.java // public interface ParcelDescriptor { // // @NotNull // @Range(min = 1, max = 1) // Integer getSchema_version(); // // @NotBlank // @Pattern(regexp="^((?!-).)*$", message="{custom.validation.constraints.ParcelName.message}") // String getName(); // // @NotBlank // String getVersion(); // // Map<String, String> getExtraVersionInfo(); // // @NotNull // Boolean getSetActiveSymlink(); // // String getDepends(); // // String getReplaces(); // // String getConflicts(); // // Set<String> getProvides(); // // @Valid // @NotNull // ScriptsDescriptor getScripts(); // // @UniqueField("name") // @Valid // @NotNull // Set<PackageDescriptor> getPackages(); // // @UniqueField("name") // @Valid // @NotNull // Set<ComponentDescriptor> getComponents(); // // @Valid // @NotNull // Map<String, UserDescriptor> getUsers(); // // @NotNull // Set<String> getGroups(); // // ServicesRestartDescriptor getServicesRestartInfo(); // } // // Path: cm-schema/src/main/java/com/cloudera/parcel/descriptors/VersionServicesRestartDescriptor.java // public interface VersionServicesRestartDescriptor { // // enum Scope { // SERVICE_ONLY, // DEPENDENTS_ONLY, // SERVICE_AND_DEPENDENTS // } // // /** // * Contains a map of service type to {@link Scope} // * @return a map of service type to {@link Scope} // */ // @NotNull // Map<String, Scope> getServiceInfo(); // // /** // * Parent parcel version of this version descriptor. // * // * Can be null, in which case this is determined to be the oldest version // * supported from which the restart information will be used for selective restarts. // * // * @return parent version, if specified. // */ // String getParentVersion(); // // /** // * Child parcel version of this version descriptor. // * // * Can be null, in which case this is determined to be the newest version // * supported from which the restart information will be used for selective restarts. // * // * @return child version, if specified. // */ // String getChildVersion(); // } // // Path: cm-schema/src/main/java/com/cloudera/parcel/descriptors/VersionServicesRestartDescriptor.java // enum Scope { // SERVICE_ONLY, // DEPENDENTS_ONLY, // SERVICE_AND_DEPENDENTS // }
import java.util.Set; import org.junit.Test; import static org.junit.Assert.*; import com.cloudera.parcel.descriptors.ComponentDescriptor; import com.cloudera.parcel.descriptors.PackageDescriptor; import com.cloudera.parcel.descriptors.ParcelDescriptor; import com.cloudera.parcel.descriptors.UserDescriptor; import com.cloudera.parcel.descriptors.VersionServicesRestartDescriptor; import com.cloudera.parcel.descriptors.VersionServicesRestartDescriptor.Scope; import com.cloudera.parcel.validation.ParcelTestUtils; import com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; import java.io.IOException; import java.util.Map;
// Licensed to Cloudera, Inc. under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. Cloudera, Inc. licenses this file // to you 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.cloudera.parcel.components; public class JsonParcelParserTest { private JsonParcelParser parser = new JsonParcelParser(); @Test public void testParseGoodFile() throws IOException {
// Path: cm-schema/src/main/java/com/cloudera/parcel/descriptors/ParcelDescriptor.java // public interface ParcelDescriptor { // // @NotNull // @Range(min = 1, max = 1) // Integer getSchema_version(); // // @NotBlank // @Pattern(regexp="^((?!-).)*$", message="{custom.validation.constraints.ParcelName.message}") // String getName(); // // @NotBlank // String getVersion(); // // Map<String, String> getExtraVersionInfo(); // // @NotNull // Boolean getSetActiveSymlink(); // // String getDepends(); // // String getReplaces(); // // String getConflicts(); // // Set<String> getProvides(); // // @Valid // @NotNull // ScriptsDescriptor getScripts(); // // @UniqueField("name") // @Valid // @NotNull // Set<PackageDescriptor> getPackages(); // // @UniqueField("name") // @Valid // @NotNull // Set<ComponentDescriptor> getComponents(); // // @Valid // @NotNull // Map<String, UserDescriptor> getUsers(); // // @NotNull // Set<String> getGroups(); // // ServicesRestartDescriptor getServicesRestartInfo(); // } // // Path: cm-schema/src/main/java/com/cloudera/parcel/descriptors/VersionServicesRestartDescriptor.java // public interface VersionServicesRestartDescriptor { // // enum Scope { // SERVICE_ONLY, // DEPENDENTS_ONLY, // SERVICE_AND_DEPENDENTS // } // // /** // * Contains a map of service type to {@link Scope} // * @return a map of service type to {@link Scope} // */ // @NotNull // Map<String, Scope> getServiceInfo(); // // /** // * Parent parcel version of this version descriptor. // * // * Can be null, in which case this is determined to be the oldest version // * supported from which the restart information will be used for selective restarts. // * // * @return parent version, if specified. // */ // String getParentVersion(); // // /** // * Child parcel version of this version descriptor. // * // * Can be null, in which case this is determined to be the newest version // * supported from which the restart information will be used for selective restarts. // * // * @return child version, if specified. // */ // String getChildVersion(); // } // // Path: cm-schema/src/main/java/com/cloudera/parcel/descriptors/VersionServicesRestartDescriptor.java // enum Scope { // SERVICE_ONLY, // DEPENDENTS_ONLY, // SERVICE_AND_DEPENDENTS // } // Path: cm-schema/src/test/java/com/cloudera/parcel/components/JsonParcelParserTest.java import java.util.Set; import org.junit.Test; import static org.junit.Assert.*; import com.cloudera.parcel.descriptors.ComponentDescriptor; import com.cloudera.parcel.descriptors.PackageDescriptor; import com.cloudera.parcel.descriptors.ParcelDescriptor; import com.cloudera.parcel.descriptors.UserDescriptor; import com.cloudera.parcel.descriptors.VersionServicesRestartDescriptor; import com.cloudera.parcel.descriptors.VersionServicesRestartDescriptor.Scope; import com.cloudera.parcel.validation.ParcelTestUtils; import com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; import java.io.IOException; import java.util.Map; // Licensed to Cloudera, Inc. under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. Cloudera, Inc. licenses this file // to you 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.cloudera.parcel.components; public class JsonParcelParserTest { private JsonParcelParser parser = new JsonParcelParser(); @Test public void testParseGoodFile() throws IOException {
ParcelDescriptor parcel = parser.parse(ParcelTestUtils.getParcelJson("good_parcel.json"));
cloudera/cm_ext
cm-schema/src/test/java/com/cloudera/parcel/components/JsonParcelParserTest.java
// Path: cm-schema/src/main/java/com/cloudera/parcel/descriptors/ParcelDescriptor.java // public interface ParcelDescriptor { // // @NotNull // @Range(min = 1, max = 1) // Integer getSchema_version(); // // @NotBlank // @Pattern(regexp="^((?!-).)*$", message="{custom.validation.constraints.ParcelName.message}") // String getName(); // // @NotBlank // String getVersion(); // // Map<String, String> getExtraVersionInfo(); // // @NotNull // Boolean getSetActiveSymlink(); // // String getDepends(); // // String getReplaces(); // // String getConflicts(); // // Set<String> getProvides(); // // @Valid // @NotNull // ScriptsDescriptor getScripts(); // // @UniqueField("name") // @Valid // @NotNull // Set<PackageDescriptor> getPackages(); // // @UniqueField("name") // @Valid // @NotNull // Set<ComponentDescriptor> getComponents(); // // @Valid // @NotNull // Map<String, UserDescriptor> getUsers(); // // @NotNull // Set<String> getGroups(); // // ServicesRestartDescriptor getServicesRestartInfo(); // } // // Path: cm-schema/src/main/java/com/cloudera/parcel/descriptors/VersionServicesRestartDescriptor.java // public interface VersionServicesRestartDescriptor { // // enum Scope { // SERVICE_ONLY, // DEPENDENTS_ONLY, // SERVICE_AND_DEPENDENTS // } // // /** // * Contains a map of service type to {@link Scope} // * @return a map of service type to {@link Scope} // */ // @NotNull // Map<String, Scope> getServiceInfo(); // // /** // * Parent parcel version of this version descriptor. // * // * Can be null, in which case this is determined to be the oldest version // * supported from which the restart information will be used for selective restarts. // * // * @return parent version, if specified. // */ // String getParentVersion(); // // /** // * Child parcel version of this version descriptor. // * // * Can be null, in which case this is determined to be the newest version // * supported from which the restart information will be used for selective restarts. // * // * @return child version, if specified. // */ // String getChildVersion(); // } // // Path: cm-schema/src/main/java/com/cloudera/parcel/descriptors/VersionServicesRestartDescriptor.java // enum Scope { // SERVICE_ONLY, // DEPENDENTS_ONLY, // SERVICE_AND_DEPENDENTS // }
import java.util.Set; import org.junit.Test; import static org.junit.Assert.*; import com.cloudera.parcel.descriptors.ComponentDescriptor; import com.cloudera.parcel.descriptors.PackageDescriptor; import com.cloudera.parcel.descriptors.ParcelDescriptor; import com.cloudera.parcel.descriptors.UserDescriptor; import com.cloudera.parcel.descriptors.VersionServicesRestartDescriptor; import com.cloudera.parcel.descriptors.VersionServicesRestartDescriptor.Scope; import com.cloudera.parcel.validation.ParcelTestUtils; import com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; import java.io.IOException; import java.util.Map;
assertEquals(2, components.size()); names = Sets.newHashSet(); for (ComponentDescriptor cmp : components) { assertEquals("2.2.0-cdh5.0.0-SNAPSHOT", cmp.getVersion()); assertEquals("2.2.0+cdh5.0.0+609", cmp.getPkg_version()); names.add(cmp.getName()); } assertEquals(ImmutableSet.of("hadoop", "hadoop-hdfs"), names); Map<String, UserDescriptor> users = parcel.getUsers(); assertEquals(2, users.size()); UserDescriptor hdfs = users.get("hdfs"); assertNotNull(hdfs); assertEquals("Hadoop HDFS", hdfs.getLongname()); assertEquals("/var/lib/hadoop-hdfs", hdfs.getHome()); assertEquals("/bin/bash", hdfs.getShell()); assertEquals(ImmutableSet.of("hadoop"), hdfs.getExtra_groups()); UserDescriptor impala = users.get("impala"); assertEquals("Impala", impala.getLongname()); assertEquals("/var/run/impala", impala.getHome()); assertEquals("/bin/bash", impala.getShell()); assertEquals(ImmutableSet.of("hive", "hdfs"), impala.getExtra_groups()); assertEquals(ImmutableSet.of("hadoop"), parcel.getGroups()); assertNotNull(parcel.getServicesRestartInfo()); assertNotNull(parcel.getServicesRestartInfo().getVersionInfo());
// Path: cm-schema/src/main/java/com/cloudera/parcel/descriptors/ParcelDescriptor.java // public interface ParcelDescriptor { // // @NotNull // @Range(min = 1, max = 1) // Integer getSchema_version(); // // @NotBlank // @Pattern(regexp="^((?!-).)*$", message="{custom.validation.constraints.ParcelName.message}") // String getName(); // // @NotBlank // String getVersion(); // // Map<String, String> getExtraVersionInfo(); // // @NotNull // Boolean getSetActiveSymlink(); // // String getDepends(); // // String getReplaces(); // // String getConflicts(); // // Set<String> getProvides(); // // @Valid // @NotNull // ScriptsDescriptor getScripts(); // // @UniqueField("name") // @Valid // @NotNull // Set<PackageDescriptor> getPackages(); // // @UniqueField("name") // @Valid // @NotNull // Set<ComponentDescriptor> getComponents(); // // @Valid // @NotNull // Map<String, UserDescriptor> getUsers(); // // @NotNull // Set<String> getGroups(); // // ServicesRestartDescriptor getServicesRestartInfo(); // } // // Path: cm-schema/src/main/java/com/cloudera/parcel/descriptors/VersionServicesRestartDescriptor.java // public interface VersionServicesRestartDescriptor { // // enum Scope { // SERVICE_ONLY, // DEPENDENTS_ONLY, // SERVICE_AND_DEPENDENTS // } // // /** // * Contains a map of service type to {@link Scope} // * @return a map of service type to {@link Scope} // */ // @NotNull // Map<String, Scope> getServiceInfo(); // // /** // * Parent parcel version of this version descriptor. // * // * Can be null, in which case this is determined to be the oldest version // * supported from which the restart information will be used for selective restarts. // * // * @return parent version, if specified. // */ // String getParentVersion(); // // /** // * Child parcel version of this version descriptor. // * // * Can be null, in which case this is determined to be the newest version // * supported from which the restart information will be used for selective restarts. // * // * @return child version, if specified. // */ // String getChildVersion(); // } // // Path: cm-schema/src/main/java/com/cloudera/parcel/descriptors/VersionServicesRestartDescriptor.java // enum Scope { // SERVICE_ONLY, // DEPENDENTS_ONLY, // SERVICE_AND_DEPENDENTS // } // Path: cm-schema/src/test/java/com/cloudera/parcel/components/JsonParcelParserTest.java import java.util.Set; import org.junit.Test; import static org.junit.Assert.*; import com.cloudera.parcel.descriptors.ComponentDescriptor; import com.cloudera.parcel.descriptors.PackageDescriptor; import com.cloudera.parcel.descriptors.ParcelDescriptor; import com.cloudera.parcel.descriptors.UserDescriptor; import com.cloudera.parcel.descriptors.VersionServicesRestartDescriptor; import com.cloudera.parcel.descriptors.VersionServicesRestartDescriptor.Scope; import com.cloudera.parcel.validation.ParcelTestUtils; import com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; import java.io.IOException; import java.util.Map; assertEquals(2, components.size()); names = Sets.newHashSet(); for (ComponentDescriptor cmp : components) { assertEquals("2.2.0-cdh5.0.0-SNAPSHOT", cmp.getVersion()); assertEquals("2.2.0+cdh5.0.0+609", cmp.getPkg_version()); names.add(cmp.getName()); } assertEquals(ImmutableSet.of("hadoop", "hadoop-hdfs"), names); Map<String, UserDescriptor> users = parcel.getUsers(); assertEquals(2, users.size()); UserDescriptor hdfs = users.get("hdfs"); assertNotNull(hdfs); assertEquals("Hadoop HDFS", hdfs.getLongname()); assertEquals("/var/lib/hadoop-hdfs", hdfs.getHome()); assertEquals("/bin/bash", hdfs.getShell()); assertEquals(ImmutableSet.of("hadoop"), hdfs.getExtra_groups()); UserDescriptor impala = users.get("impala"); assertEquals("Impala", impala.getLongname()); assertEquals("/var/run/impala", impala.getHome()); assertEquals("/bin/bash", impala.getShell()); assertEquals(ImmutableSet.of("hive", "hdfs"), impala.getExtra_groups()); assertEquals(ImmutableSet.of("hadoop"), parcel.getGroups()); assertNotNull(parcel.getServicesRestartInfo()); assertNotNull(parcel.getServicesRestartInfo().getVersionInfo());
Map<String, VersionServicesRestartDescriptor> versionServicesRestartDescriptorMap =
cloudera/cm_ext
cm-schema/src/test/java/com/cloudera/parcel/components/JsonParcelParserTest.java
// Path: cm-schema/src/main/java/com/cloudera/parcel/descriptors/ParcelDescriptor.java // public interface ParcelDescriptor { // // @NotNull // @Range(min = 1, max = 1) // Integer getSchema_version(); // // @NotBlank // @Pattern(regexp="^((?!-).)*$", message="{custom.validation.constraints.ParcelName.message}") // String getName(); // // @NotBlank // String getVersion(); // // Map<String, String> getExtraVersionInfo(); // // @NotNull // Boolean getSetActiveSymlink(); // // String getDepends(); // // String getReplaces(); // // String getConflicts(); // // Set<String> getProvides(); // // @Valid // @NotNull // ScriptsDescriptor getScripts(); // // @UniqueField("name") // @Valid // @NotNull // Set<PackageDescriptor> getPackages(); // // @UniqueField("name") // @Valid // @NotNull // Set<ComponentDescriptor> getComponents(); // // @Valid // @NotNull // Map<String, UserDescriptor> getUsers(); // // @NotNull // Set<String> getGroups(); // // ServicesRestartDescriptor getServicesRestartInfo(); // } // // Path: cm-schema/src/main/java/com/cloudera/parcel/descriptors/VersionServicesRestartDescriptor.java // public interface VersionServicesRestartDescriptor { // // enum Scope { // SERVICE_ONLY, // DEPENDENTS_ONLY, // SERVICE_AND_DEPENDENTS // } // // /** // * Contains a map of service type to {@link Scope} // * @return a map of service type to {@link Scope} // */ // @NotNull // Map<String, Scope> getServiceInfo(); // // /** // * Parent parcel version of this version descriptor. // * // * Can be null, in which case this is determined to be the oldest version // * supported from which the restart information will be used for selective restarts. // * // * @return parent version, if specified. // */ // String getParentVersion(); // // /** // * Child parcel version of this version descriptor. // * // * Can be null, in which case this is determined to be the newest version // * supported from which the restart information will be used for selective restarts. // * // * @return child version, if specified. // */ // String getChildVersion(); // } // // Path: cm-schema/src/main/java/com/cloudera/parcel/descriptors/VersionServicesRestartDescriptor.java // enum Scope { // SERVICE_ONLY, // DEPENDENTS_ONLY, // SERVICE_AND_DEPENDENTS // }
import java.util.Set; import org.junit.Test; import static org.junit.Assert.*; import com.cloudera.parcel.descriptors.ComponentDescriptor; import com.cloudera.parcel.descriptors.PackageDescriptor; import com.cloudera.parcel.descriptors.ParcelDescriptor; import com.cloudera.parcel.descriptors.UserDescriptor; import com.cloudera.parcel.descriptors.VersionServicesRestartDescriptor; import com.cloudera.parcel.descriptors.VersionServicesRestartDescriptor.Scope; import com.cloudera.parcel.validation.ParcelTestUtils; import com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; import java.io.IOException; import java.util.Map;
Map<String, UserDescriptor> users = parcel.getUsers(); assertEquals(2, users.size()); UserDescriptor hdfs = users.get("hdfs"); assertNotNull(hdfs); assertEquals("Hadoop HDFS", hdfs.getLongname()); assertEquals("/var/lib/hadoop-hdfs", hdfs.getHome()); assertEquals("/bin/bash", hdfs.getShell()); assertEquals(ImmutableSet.of("hadoop"), hdfs.getExtra_groups()); UserDescriptor impala = users.get("impala"); assertEquals("Impala", impala.getLongname()); assertEquals("/var/run/impala", impala.getHome()); assertEquals("/bin/bash", impala.getShell()); assertEquals(ImmutableSet.of("hive", "hdfs"), impala.getExtra_groups()); assertEquals(ImmutableSet.of("hadoop"), parcel.getGroups()); assertNotNull(parcel.getServicesRestartInfo()); assertNotNull(parcel.getServicesRestartInfo().getVersionInfo()); Map<String, VersionServicesRestartDescriptor> versionServicesRestartDescriptorMap = parcel.getServicesRestartInfo().getVersionInfo(); assertEquals(3, versionServicesRestartDescriptorMap.size()); assertTrue(versionServicesRestartDescriptorMap.containsKey("5.0.0-0.cdh5b2.p0.282")); assertTrue(versionServicesRestartDescriptorMap.containsKey("5.0.0-0.cdh5b2.p0.281")); assertTrue(versionServicesRestartDescriptorMap.containsKey("5.0.0-0.cdh5b2.p0.280")); assertTrue(versionServicesRestartDescriptorMap.get("5.0.0-0.cdh5b2.p0.282").getParentVersion().equals("5.0.0-0.cdh5b2.p0.281")); assertTrue(versionServicesRestartDescriptorMap.get("5.0.0-0.cdh5b2.p0.282").getServiceInfo().containsKey("IMPALA"));
// Path: cm-schema/src/main/java/com/cloudera/parcel/descriptors/ParcelDescriptor.java // public interface ParcelDescriptor { // // @NotNull // @Range(min = 1, max = 1) // Integer getSchema_version(); // // @NotBlank // @Pattern(regexp="^((?!-).)*$", message="{custom.validation.constraints.ParcelName.message}") // String getName(); // // @NotBlank // String getVersion(); // // Map<String, String> getExtraVersionInfo(); // // @NotNull // Boolean getSetActiveSymlink(); // // String getDepends(); // // String getReplaces(); // // String getConflicts(); // // Set<String> getProvides(); // // @Valid // @NotNull // ScriptsDescriptor getScripts(); // // @UniqueField("name") // @Valid // @NotNull // Set<PackageDescriptor> getPackages(); // // @UniqueField("name") // @Valid // @NotNull // Set<ComponentDescriptor> getComponents(); // // @Valid // @NotNull // Map<String, UserDescriptor> getUsers(); // // @NotNull // Set<String> getGroups(); // // ServicesRestartDescriptor getServicesRestartInfo(); // } // // Path: cm-schema/src/main/java/com/cloudera/parcel/descriptors/VersionServicesRestartDescriptor.java // public interface VersionServicesRestartDescriptor { // // enum Scope { // SERVICE_ONLY, // DEPENDENTS_ONLY, // SERVICE_AND_DEPENDENTS // } // // /** // * Contains a map of service type to {@link Scope} // * @return a map of service type to {@link Scope} // */ // @NotNull // Map<String, Scope> getServiceInfo(); // // /** // * Parent parcel version of this version descriptor. // * // * Can be null, in which case this is determined to be the oldest version // * supported from which the restart information will be used for selective restarts. // * // * @return parent version, if specified. // */ // String getParentVersion(); // // /** // * Child parcel version of this version descriptor. // * // * Can be null, in which case this is determined to be the newest version // * supported from which the restart information will be used for selective restarts. // * // * @return child version, if specified. // */ // String getChildVersion(); // } // // Path: cm-schema/src/main/java/com/cloudera/parcel/descriptors/VersionServicesRestartDescriptor.java // enum Scope { // SERVICE_ONLY, // DEPENDENTS_ONLY, // SERVICE_AND_DEPENDENTS // } // Path: cm-schema/src/test/java/com/cloudera/parcel/components/JsonParcelParserTest.java import java.util.Set; import org.junit.Test; import static org.junit.Assert.*; import com.cloudera.parcel.descriptors.ComponentDescriptor; import com.cloudera.parcel.descriptors.PackageDescriptor; import com.cloudera.parcel.descriptors.ParcelDescriptor; import com.cloudera.parcel.descriptors.UserDescriptor; import com.cloudera.parcel.descriptors.VersionServicesRestartDescriptor; import com.cloudera.parcel.descriptors.VersionServicesRestartDescriptor.Scope; import com.cloudera.parcel.validation.ParcelTestUtils; import com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; import java.io.IOException; import java.util.Map; Map<String, UserDescriptor> users = parcel.getUsers(); assertEquals(2, users.size()); UserDescriptor hdfs = users.get("hdfs"); assertNotNull(hdfs); assertEquals("Hadoop HDFS", hdfs.getLongname()); assertEquals("/var/lib/hadoop-hdfs", hdfs.getHome()); assertEquals("/bin/bash", hdfs.getShell()); assertEquals(ImmutableSet.of("hadoop"), hdfs.getExtra_groups()); UserDescriptor impala = users.get("impala"); assertEquals("Impala", impala.getLongname()); assertEquals("/var/run/impala", impala.getHome()); assertEquals("/bin/bash", impala.getShell()); assertEquals(ImmutableSet.of("hive", "hdfs"), impala.getExtra_groups()); assertEquals(ImmutableSet.of("hadoop"), parcel.getGroups()); assertNotNull(parcel.getServicesRestartInfo()); assertNotNull(parcel.getServicesRestartInfo().getVersionInfo()); Map<String, VersionServicesRestartDescriptor> versionServicesRestartDescriptorMap = parcel.getServicesRestartInfo().getVersionInfo(); assertEquals(3, versionServicesRestartDescriptorMap.size()); assertTrue(versionServicesRestartDescriptorMap.containsKey("5.0.0-0.cdh5b2.p0.282")); assertTrue(versionServicesRestartDescriptorMap.containsKey("5.0.0-0.cdh5b2.p0.281")); assertTrue(versionServicesRestartDescriptorMap.containsKey("5.0.0-0.cdh5b2.p0.280")); assertTrue(versionServicesRestartDescriptorMap.get("5.0.0-0.cdh5b2.p0.282").getParentVersion().equals("5.0.0-0.cdh5b2.p0.281")); assertTrue(versionServicesRestartDescriptorMap.get("5.0.0-0.cdh5b2.p0.282").getServiceInfo().containsKey("IMPALA"));
assertTrue(versionServicesRestartDescriptorMap.get("5.0.0-0.cdh5b2.p0.282").getServiceInfo().containsValue(Scope.DEPENDENTS_ONLY));
cloudera/cm_ext
cm-schema/src/main/java/com/cloudera/csd/tools/impala/ImpalaMetric.java
// Path: cm-schema/src/main/java/com/cloudera/csd/tools/AbstractMetricDefinition.java // @JsonIgnoreProperties(ignoreUnknown = true) // public abstract class AbstractMetricDefinition { // // public static class Builder<S extends AbstractMetricDefinition.Builder<?>> { // protected String name; // protected String label; // protected String description; // protected String numerator; // protected String denominator; // protected String context; // // @SuppressWarnings("unchecked") // public S setName(String name) { // Preconditions.checkNotNull(name); // this.name = name; // return (S) this; // } // // @SuppressWarnings("unchecked") // public S setLabel(String label) { // Preconditions.checkNotNull(label); // this.label = label; // return (S) this; // } // // @SuppressWarnings("unchecked") // public S setDescription(String description) { // Preconditions.checkNotNull(description); // this.description = description; // return (S) this; // } // // @SuppressWarnings("unchecked") // public S setNumerator(String numerator) { // Preconditions.checkNotNull(numerator); // this.numerator = numerator; // return (S) this; // } // // @SuppressWarnings("unchecked") // public S setDenominator(String denominator) { // this.denominator = denominator; // return (S) this; // } // // @SuppressWarnings("unchecked") // public S setContext(String context) { // this.context = context; // return (S) this; // } // } // // // The name of the metric. // @JsonIgnore // protected String name; // // // The display name of the metric. // @JsonIgnore // protected String label; // // // The description for the metric. // @JsonIgnore // protected String description; // // // A string used for the numerator display name. For example, "bytes", // // "calls", "partitions". // @JsonIgnore // protected String numeratorUnit; // // // The string used for the denominator display name. For example, "seconds", // // "minutes", "yards". // @JsonIgnore // protected String denominatorUnit; // // // The context for the metric. The full context for each Cloudera Manager // // metric is constructed in the CodahaleMetricAdapter. // @JsonIgnore // protected String context; // // @JsonCreator // protected AbstractMetricDefinition() { // } // // protected AbstractMetricDefinition(String name, // String label, // String description, // String numerator, // String denominator, // String context) { // Preconditions.checkNotNull(name); // Preconditions.checkNotNull(label); // Preconditions.checkNotNull(description); // Preconditions.checkNotNull(numerator); // this.name = name; // this.label = label; // this.description = description; // this.numeratorUnit = numerator; // this.denominatorUnit = denominator; // this.context = context; // } // // @JsonProperty // public String getName() { // return name; // } // // @JsonProperty // public void setName(String name) { // this.name = name; // } // // @JsonProperty // public String getLabel() { // return label; // } // // @JsonProperty // public void setLabel(String label) { // this.label = label; // } // // @JsonProperty // public String getDescription() { // return description; // } // // @JsonProperty // public void setDescription(String description) { // this.description = description; // } // // @JsonProperty // public String getNumeratorUnit() { // return numeratorUnit; // } // // @JsonProperty // public void setNumeratorUnit(String numeratorUnit) { // this.numeratorUnit = numeratorUnit; // } // // @JsonProperty // public String getDenominatorUnit() { // return denominatorUnit; // } // // @JsonProperty // public void setDenominatorUnit(String denominatorUnit) { // this.denominatorUnit = denominatorUnit; // } // // @JsonProperty // public String getContext() { // return context; // } // // @JsonProperty // public void setContext(String context) { // this.context = context; // } // } // // Path: cm-schema/src/main/java/com/cloudera/csd/tools/impala/ImpalaMetricTypes.java // public static enum ImpalaMetricType { // GAUGE, // COUNTER, // STATISTICAL // }
import com.cloudera.csd.tools.AbstractMetricDefinition; import com.cloudera.csd.tools.impala.ImpalaMetricTypes.ImpalaMetricType; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.base.Preconditions; import javax.annotation.Nullable;
// Licensed to Cloudera, Inc. under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. Cloudera, Inc. licenses this file // to you 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.cloudera.csd.tools.impala; /** * A helper class defining the metadata for a single Impala metric. */ @JsonIgnoreProperties(ignoreUnknown = true) public class ImpalaMetric extends AbstractMetricDefinition { public static class Builder extends AbstractMetricDefinition.Builder<ImpalaMetric.Builder> {
// Path: cm-schema/src/main/java/com/cloudera/csd/tools/AbstractMetricDefinition.java // @JsonIgnoreProperties(ignoreUnknown = true) // public abstract class AbstractMetricDefinition { // // public static class Builder<S extends AbstractMetricDefinition.Builder<?>> { // protected String name; // protected String label; // protected String description; // protected String numerator; // protected String denominator; // protected String context; // // @SuppressWarnings("unchecked") // public S setName(String name) { // Preconditions.checkNotNull(name); // this.name = name; // return (S) this; // } // // @SuppressWarnings("unchecked") // public S setLabel(String label) { // Preconditions.checkNotNull(label); // this.label = label; // return (S) this; // } // // @SuppressWarnings("unchecked") // public S setDescription(String description) { // Preconditions.checkNotNull(description); // this.description = description; // return (S) this; // } // // @SuppressWarnings("unchecked") // public S setNumerator(String numerator) { // Preconditions.checkNotNull(numerator); // this.numerator = numerator; // return (S) this; // } // // @SuppressWarnings("unchecked") // public S setDenominator(String denominator) { // this.denominator = denominator; // return (S) this; // } // // @SuppressWarnings("unchecked") // public S setContext(String context) { // this.context = context; // return (S) this; // } // } // // // The name of the metric. // @JsonIgnore // protected String name; // // // The display name of the metric. // @JsonIgnore // protected String label; // // // The description for the metric. // @JsonIgnore // protected String description; // // // A string used for the numerator display name. For example, "bytes", // // "calls", "partitions". // @JsonIgnore // protected String numeratorUnit; // // // The string used for the denominator display name. For example, "seconds", // // "minutes", "yards". // @JsonIgnore // protected String denominatorUnit; // // // The context for the metric. The full context for each Cloudera Manager // // metric is constructed in the CodahaleMetricAdapter. // @JsonIgnore // protected String context; // // @JsonCreator // protected AbstractMetricDefinition() { // } // // protected AbstractMetricDefinition(String name, // String label, // String description, // String numerator, // String denominator, // String context) { // Preconditions.checkNotNull(name); // Preconditions.checkNotNull(label); // Preconditions.checkNotNull(description); // Preconditions.checkNotNull(numerator); // this.name = name; // this.label = label; // this.description = description; // this.numeratorUnit = numerator; // this.denominatorUnit = denominator; // this.context = context; // } // // @JsonProperty // public String getName() { // return name; // } // // @JsonProperty // public void setName(String name) { // this.name = name; // } // // @JsonProperty // public String getLabel() { // return label; // } // // @JsonProperty // public void setLabel(String label) { // this.label = label; // } // // @JsonProperty // public String getDescription() { // return description; // } // // @JsonProperty // public void setDescription(String description) { // this.description = description; // } // // @JsonProperty // public String getNumeratorUnit() { // return numeratorUnit; // } // // @JsonProperty // public void setNumeratorUnit(String numeratorUnit) { // this.numeratorUnit = numeratorUnit; // } // // @JsonProperty // public String getDenominatorUnit() { // return denominatorUnit; // } // // @JsonProperty // public void setDenominatorUnit(String denominatorUnit) { // this.denominatorUnit = denominatorUnit; // } // // @JsonProperty // public String getContext() { // return context; // } // // @JsonProperty // public void setContext(String context) { // this.context = context; // } // } // // Path: cm-schema/src/main/java/com/cloudera/csd/tools/impala/ImpalaMetricTypes.java // public static enum ImpalaMetricType { // GAUGE, // COUNTER, // STATISTICAL // } // Path: cm-schema/src/main/java/com/cloudera/csd/tools/impala/ImpalaMetric.java import com.cloudera.csd.tools.AbstractMetricDefinition; import com.cloudera.csd.tools.impala.ImpalaMetricTypes.ImpalaMetricType; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.base.Preconditions; import javax.annotation.Nullable; // Licensed to Cloudera, Inc. under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. Cloudera, Inc. licenses this file // to you 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.cloudera.csd.tools.impala; /** * A helper class defining the metadata for a single Impala metric. */ @JsonIgnoreProperties(ignoreUnknown = true) public class ImpalaMetric extends AbstractMetricDefinition { public static class Builder extends AbstractMetricDefinition.Builder<ImpalaMetric.Builder> {
private ImpalaMetricType impalaMetricType;
cloudera/cm_ext
cm-schema/src/test/java/com/cloudera/csd/validation/monitoring/constraints/NameForCrossEntityAggregatesIsUniqueValidatorTest.java
// Path: cm-schema/src/main/java/com/cloudera/csd/validation/monitoring/MonitoringValidationContext.java // public class MonitoringValidationContext { // // public final ServiceMonitoringDefinitionsDescriptor serviceDescriptor; // public final ImmutableMap<String, MetricDescriptor> metricsDefined; // public final ImmutableMap<String, MetricEntityTypeDescriptor> entitiesDefined; // public final ImmutableMap<String, RoleMonitoringDefinitionsDescriptor> rolesDefined; // public final ImmutableMap<String, MetricEntityAttributeDescriptor> attributesDefined; // // public MonitoringValidationContext( // ServiceMonitoringDefinitionsDescriptor serviceDescriptor) { // Preconditions.checkNotNull(serviceDescriptor); // this.serviceDescriptor = serviceDescriptor; // ImmutableMap.Builder<String, RoleMonitoringDefinitionsDescriptor> // rolesDefinedBuilder = ImmutableMap.builder(); // // We can't use an ImmutableMap.Builder since it will not allow multiple // // entries with the same key. Instead we build a local hash map and make // // it immutable below. // Map<String, MetricDescriptor> metricsDefinedBuilder = Maps.newHashMap(); // metricsDefinedBuilder.putAll( // extractMetrics(serviceDescriptor.getMetricDefinitions())); // if (null != serviceDescriptor.getRoles()) { // for (RoleMonitoringDefinitionsDescriptor role : // serviceDescriptor.getRoles()) { // rolesDefinedBuilder.put( // MonitoringConventions.getRoleMetricEntityTypeName( // serviceDescriptor.getName(), // role.getName()), // role); // metricsDefinedBuilder.putAll( // extractMetrics(role.getMetricDefinitions())); // } // } // if (null != serviceDescriptor.getMetricEntityTypeDefinitions()) { // for (MetricEntityTypeDescriptor entity : // serviceDescriptor.getMetricEntityTypeDefinitions()) { // metricsDefinedBuilder.putAll( // extractMetrics(entity.getMetricDefinitions())); // } // } // ImmutableMap.Builder<String, MetricEntityTypeDescriptor> // entitiesDefinedBuilder = ImmutableMap.builder(); // if (null != serviceDescriptor.getMetricEntityTypeDefinitions()) { // for (MetricEntityTypeDescriptor entity : // serviceDescriptor.getMetricEntityTypeDefinitions()) { // entitiesDefinedBuilder.put(entity.getName(), entity); // } // } // ImmutableMap.Builder<String, MetricEntityAttributeDescriptor> // attributesDefinedBuilder = ImmutableMap.builder(); // if (null != serviceDescriptor.getMetricEntityAttributeDefinitions()) { // for (MetricEntityAttributeDescriptor attribute : // serviceDescriptor.getMetricEntityAttributeDefinitions()) { // attributesDefinedBuilder.put(attribute.getName(), attribute); // } // } // metricsDefined = ImmutableMap.copyOf(metricsDefinedBuilder); // rolesDefined = rolesDefinedBuilder.build(); // entitiesDefined = entitiesDefinedBuilder.build(); // attributesDefined = attributesDefinedBuilder.build(); // } // // private Map<String, MetricDescriptor> extractMetrics( // @Nullable List<MetricDescriptor> metrics) { // if (null == metrics) { // return ImmutableMap.of(); // } // Map<String, MetricDescriptor> ret = Maps.newHashMap(); // for (MetricDescriptor metric : metrics) { // ret.put(metric.getName(), metric); // } // return ret; // } // }
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import com.cloudera.csd.validation.monitoring.MonitoringValidationContext; import com.google.common.collect.Iterables; import java.util.List; import javax.validation.ConstraintViolation; import org.junit.Before; import org.junit.Test;
// Licensed to Cloudera, Inc. under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. Cloudera, Inc. licenses this file // to you 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.cloudera.csd.validation.monitoring.constraints; public class NameForCrossEntityAggregatesIsUniqueValidatorTest extends AbstractMonitoringValidatorBaseTest { private NameForCrossEntityAggregatesIsUniqueValidator validator;
// Path: cm-schema/src/main/java/com/cloudera/csd/validation/monitoring/MonitoringValidationContext.java // public class MonitoringValidationContext { // // public final ServiceMonitoringDefinitionsDescriptor serviceDescriptor; // public final ImmutableMap<String, MetricDescriptor> metricsDefined; // public final ImmutableMap<String, MetricEntityTypeDescriptor> entitiesDefined; // public final ImmutableMap<String, RoleMonitoringDefinitionsDescriptor> rolesDefined; // public final ImmutableMap<String, MetricEntityAttributeDescriptor> attributesDefined; // // public MonitoringValidationContext( // ServiceMonitoringDefinitionsDescriptor serviceDescriptor) { // Preconditions.checkNotNull(serviceDescriptor); // this.serviceDescriptor = serviceDescriptor; // ImmutableMap.Builder<String, RoleMonitoringDefinitionsDescriptor> // rolesDefinedBuilder = ImmutableMap.builder(); // // We can't use an ImmutableMap.Builder since it will not allow multiple // // entries with the same key. Instead we build a local hash map and make // // it immutable below. // Map<String, MetricDescriptor> metricsDefinedBuilder = Maps.newHashMap(); // metricsDefinedBuilder.putAll( // extractMetrics(serviceDescriptor.getMetricDefinitions())); // if (null != serviceDescriptor.getRoles()) { // for (RoleMonitoringDefinitionsDescriptor role : // serviceDescriptor.getRoles()) { // rolesDefinedBuilder.put( // MonitoringConventions.getRoleMetricEntityTypeName( // serviceDescriptor.getName(), // role.getName()), // role); // metricsDefinedBuilder.putAll( // extractMetrics(role.getMetricDefinitions())); // } // } // if (null != serviceDescriptor.getMetricEntityTypeDefinitions()) { // for (MetricEntityTypeDescriptor entity : // serviceDescriptor.getMetricEntityTypeDefinitions()) { // metricsDefinedBuilder.putAll( // extractMetrics(entity.getMetricDefinitions())); // } // } // ImmutableMap.Builder<String, MetricEntityTypeDescriptor> // entitiesDefinedBuilder = ImmutableMap.builder(); // if (null != serviceDescriptor.getMetricEntityTypeDefinitions()) { // for (MetricEntityTypeDescriptor entity : // serviceDescriptor.getMetricEntityTypeDefinitions()) { // entitiesDefinedBuilder.put(entity.getName(), entity); // } // } // ImmutableMap.Builder<String, MetricEntityAttributeDescriptor> // attributesDefinedBuilder = ImmutableMap.builder(); // if (null != serviceDescriptor.getMetricEntityAttributeDefinitions()) { // for (MetricEntityAttributeDescriptor attribute : // serviceDescriptor.getMetricEntityAttributeDefinitions()) { // attributesDefinedBuilder.put(attribute.getName(), attribute); // } // } // metricsDefined = ImmutableMap.copyOf(metricsDefinedBuilder); // rolesDefined = rolesDefinedBuilder.build(); // entitiesDefined = entitiesDefinedBuilder.build(); // attributesDefined = attributesDefinedBuilder.build(); // } // // private Map<String, MetricDescriptor> extractMetrics( // @Nullable List<MetricDescriptor> metrics) { // if (null == metrics) { // return ImmutableMap.of(); // } // Map<String, MetricDescriptor> ret = Maps.newHashMap(); // for (MetricDescriptor metric : metrics) { // ret.put(metric.getName(), metric); // } // return ret; // } // } // Path: cm-schema/src/test/java/com/cloudera/csd/validation/monitoring/constraints/NameForCrossEntityAggregatesIsUniqueValidatorTest.java import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import com.cloudera.csd.validation.monitoring.MonitoringValidationContext; import com.google.common.collect.Iterables; import java.util.List; import javax.validation.ConstraintViolation; import org.junit.Before; import org.junit.Test; // Licensed to Cloudera, Inc. under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. Cloudera, Inc. licenses this file // to you 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.cloudera.csd.validation.monitoring.constraints; public class NameForCrossEntityAggregatesIsUniqueValidatorTest extends AbstractMonitoringValidatorBaseTest { private NameForCrossEntityAggregatesIsUniqueValidator validator;
private MonitoringValidationContext context;
cloudera/cm_ext
cm-schema/src/test/java/com/cloudera/csd/tools/impala/ImpalaMetricDefinitionFixtureTest.java
// Path: cm-schema/src/main/java/com/cloudera/csd/tools/impala/ImpalaMetricTypes.java // public static enum ImpalaMetricType { // GAUGE, // COUNTER, // STATISTICAL // }
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.fail; import com.cloudera.csd.tools.JsonUtil; import com.cloudera.csd.tools.JsonUtil.JsonRuntimeException; import com.cloudera.csd.tools.impala.ImpalaMetricTypes.ImpalaMetricType; import java.io.InputStream; import org.apache.commons.io.IOUtils; import org.junit.Test;
public void testEmptyFixture() { InputStream in = null; try { in = this.getClass().getResourceAsStream( "/com/cloudera/csd/tools/impala/empty_but_valid.json"); ImpalaMetricDefinitionFixture fixture = JsonUtil.valueFromStream( ImpalaMetricDefinitionFixture.class, in); assertNotNull(fixture.getServiceName()); } finally { IOUtils.closeQuietly(in); } } @Test public void testValidFixture() { InputStream in = null; try { in = this.getClass().getResourceAsStream( "/com/cloudera/csd/tools/impala/valid.json"); ImpalaMetricDefinitionFixture fixture = JsonUtil.valueFromStream( ImpalaMetricDefinitionFixture.class, in); assertEquals("test_service", fixture.getServiceName()); assertEquals(1, fixture.getServiceMetrics().size()); assertEquals(2, fixture.getRolesMetrics().size()); assertEquals(2, fixture.getRolesMetrics().get("test_role1_metrics").size()); ImpalaMetric metric = fixture.getRolesMetrics().get("test_role1_metrics").get(1);
// Path: cm-schema/src/main/java/com/cloudera/csd/tools/impala/ImpalaMetricTypes.java // public static enum ImpalaMetricType { // GAUGE, // COUNTER, // STATISTICAL // } // Path: cm-schema/src/test/java/com/cloudera/csd/tools/impala/ImpalaMetricDefinitionFixtureTest.java import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.fail; import com.cloudera.csd.tools.JsonUtil; import com.cloudera.csd.tools.JsonUtil.JsonRuntimeException; import com.cloudera.csd.tools.impala.ImpalaMetricTypes.ImpalaMetricType; import java.io.InputStream; import org.apache.commons.io.IOUtils; import org.junit.Test; public void testEmptyFixture() { InputStream in = null; try { in = this.getClass().getResourceAsStream( "/com/cloudera/csd/tools/impala/empty_but_valid.json"); ImpalaMetricDefinitionFixture fixture = JsonUtil.valueFromStream( ImpalaMetricDefinitionFixture.class, in); assertNotNull(fixture.getServiceName()); } finally { IOUtils.closeQuietly(in); } } @Test public void testValidFixture() { InputStream in = null; try { in = this.getClass().getResourceAsStream( "/com/cloudera/csd/tools/impala/valid.json"); ImpalaMetricDefinitionFixture fixture = JsonUtil.valueFromStream( ImpalaMetricDefinitionFixture.class, in); assertEquals("test_service", fixture.getServiceName()); assertEquals(1, fixture.getServiceMetrics().size()); assertEquals(2, fixture.getRolesMetrics().size()); assertEquals(2, fixture.getRolesMetrics().get("test_role1_metrics").size()); ImpalaMetric metric = fixture.getRolesMetrics().get("test_role1_metrics").get(1);
validateMetric(metric, "test_role1_metric2", ImpalaMetricType.GAUGE);
cloudera/cm_ext
cm-schema/src/test/java/com/cloudera/csd/tools/impala/ImpalaMetricAdapterTest.java
// Path: cm-schema/src/main/java/com/cloudera/csd/tools/impala/ImpalaMetricTypes.java // public enum StatisticalMetricType implements ComplexImpalaMetric { // COUNT("_count", ImpalaMetricClass.COUNTER, ": Samples"), // LAST("_last", ImpalaMetricClass.GAUGE, ": Last"), // MIN("_min", ImpalaMetricClass.GAUGE, ": Min"), // MAX("_max", ImpalaMetricClass.GAUGE, ": Max"), // MEAN("_mean", ImpalaMetricClass.GAUGE, ": Mean"), // STDDEV("_stddev", ImpalaMetricClass.GAUGE, ": Standard Deviation"); // // private final String metricNameSuffix; // private final ImpalaMetricClass metricClass; // private final String descriptionSuffix; // // private StatisticalMetricType(String val, // ImpalaMetricClass metricClass, // String descriptionSuffix) { // Preconditions.checkNotNull(val); // Preconditions.checkNotNull(metricClass); // Preconditions.checkNotNull(descriptionSuffix); // this.metricNameSuffix = val; // this.metricClass = metricClass; // this.descriptionSuffix = descriptionSuffix; // } // // public String suffix() { // return metricNameSuffix; // } // // @Override // public boolean isCounter() { // return metricClass.equals(ImpalaMetricClass.COUNTER); // } // // @Override // public boolean isRate() { // return false; // } // // public String descriptionSuffix() { // return descriptionSuffix; // } // // @Override // public String makeMetricName(String metricName) { // Preconditions.checkNotNull(metricName); // return String.format("%s%s", metricName, suffix()); // } // // public String makeMetricLabel(String baseLabel) { // return makeMetricDescription(baseLabel); // } // // public String makeMetricDescription(String baseDescription) { // Preconditions.checkNotNull(baseDescription); // return String.format("%s%s", baseDescription, descriptionSuffix()); // } // }
import com.cloudera.csd.descriptors.MetricDescriptor; import com.cloudera.csd.tools.impala.ImpalaMetricTypes.StatisticalMetricType; import java.util.List; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue;
getMetricsForRole(adapter, "test_role1_metrics"); assertEquals(2, metrics.size()); validateSimpleMetric(metrics.get(1), adapter.getServiceName(), "test_role1_metric2", !COUNTER); } @Test public void testCounterMetrics() throws Exception { String source = this.getClass().getResource( "/com/cloudera/csd/tools/impala/valid.json").getPath(); adapter.init(source, null); assertEquals(2, adapter.getRoleNames().size()); List<MetricDescriptor> metrics = getMetricsForRole(adapter, "test_role1_metrics"); assertEquals(2, metrics.size()); validateSimpleMetric(metrics.get(0), adapter.getServiceName(), "test_role1_metric1", COUNTER); } @Test public void testStatisticalMetrics() throws Exception { String source = this.getClass().getResource( "/com/cloudera/csd/tools/impala/valid.json").getPath(); adapter.init(source, null); List<MetricDescriptor> metrics = getMetricsForEntity(adapter, "test_entity1_metrics");
// Path: cm-schema/src/main/java/com/cloudera/csd/tools/impala/ImpalaMetricTypes.java // public enum StatisticalMetricType implements ComplexImpalaMetric { // COUNT("_count", ImpalaMetricClass.COUNTER, ": Samples"), // LAST("_last", ImpalaMetricClass.GAUGE, ": Last"), // MIN("_min", ImpalaMetricClass.GAUGE, ": Min"), // MAX("_max", ImpalaMetricClass.GAUGE, ": Max"), // MEAN("_mean", ImpalaMetricClass.GAUGE, ": Mean"), // STDDEV("_stddev", ImpalaMetricClass.GAUGE, ": Standard Deviation"); // // private final String metricNameSuffix; // private final ImpalaMetricClass metricClass; // private final String descriptionSuffix; // // private StatisticalMetricType(String val, // ImpalaMetricClass metricClass, // String descriptionSuffix) { // Preconditions.checkNotNull(val); // Preconditions.checkNotNull(metricClass); // Preconditions.checkNotNull(descriptionSuffix); // this.metricNameSuffix = val; // this.metricClass = metricClass; // this.descriptionSuffix = descriptionSuffix; // } // // public String suffix() { // return metricNameSuffix; // } // // @Override // public boolean isCounter() { // return metricClass.equals(ImpalaMetricClass.COUNTER); // } // // @Override // public boolean isRate() { // return false; // } // // public String descriptionSuffix() { // return descriptionSuffix; // } // // @Override // public String makeMetricName(String metricName) { // Preconditions.checkNotNull(metricName); // return String.format("%s%s", metricName, suffix()); // } // // public String makeMetricLabel(String baseLabel) { // return makeMetricDescription(baseLabel); // } // // public String makeMetricDescription(String baseDescription) { // Preconditions.checkNotNull(baseDescription); // return String.format("%s%s", baseDescription, descriptionSuffix()); // } // } // Path: cm-schema/src/test/java/com/cloudera/csd/tools/impala/ImpalaMetricAdapterTest.java import com.cloudera.csd.descriptors.MetricDescriptor; import com.cloudera.csd.tools.impala.ImpalaMetricTypes.StatisticalMetricType; import java.util.List; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; getMetricsForRole(adapter, "test_role1_metrics"); assertEquals(2, metrics.size()); validateSimpleMetric(metrics.get(1), adapter.getServiceName(), "test_role1_metric2", !COUNTER); } @Test public void testCounterMetrics() throws Exception { String source = this.getClass().getResource( "/com/cloudera/csd/tools/impala/valid.json").getPath(); adapter.init(source, null); assertEquals(2, adapter.getRoleNames().size()); List<MetricDescriptor> metrics = getMetricsForRole(adapter, "test_role1_metrics"); assertEquals(2, metrics.size()); validateSimpleMetric(metrics.get(0), adapter.getServiceName(), "test_role1_metric1", COUNTER); } @Test public void testStatisticalMetrics() throws Exception { String source = this.getClass().getResource( "/com/cloudera/csd/tools/impala/valid.json").getPath(); adapter.init(source, null); List<MetricDescriptor> metrics = getMetricsForEntity(adapter, "test_entity1_metrics");
assertEquals(StatisticalMetricType.values().length,
cloudera/cm_ext
validator/src/main/java/com/cloudera/cli/validator/components/ParcelFileRunner.java
// Path: cm-schema/src/main/java/com/cloudera/parcel/descriptors/ParcelDescriptor.java // public interface ParcelDescriptor { // // @NotNull // @Range(min = 1, max = 1) // Integer getSchema_version(); // // @NotBlank // @Pattern(regexp="^((?!-).)*$", message="{custom.validation.constraints.ParcelName.message}") // String getName(); // // @NotBlank // String getVersion(); // // Map<String, String> getExtraVersionInfo(); // // @NotNull // Boolean getSetActiveSymlink(); // // String getDepends(); // // String getReplaces(); // // String getConflicts(); // // Set<String> getProvides(); // // @Valid // @NotNull // ScriptsDescriptor getScripts(); // // @UniqueField("name") // @Valid // @NotNull // Set<PackageDescriptor> getPackages(); // // @UniqueField("name") // @Valid // @NotNull // Set<ComponentDescriptor> getComponents(); // // @Valid // @NotNull // Map<String, UserDescriptor> getUsers(); // // @NotNull // Set<String> getGroups(); // // ServicesRestartDescriptor getServicesRestartInfo(); // }
import com.cloudera.common.Parser; import com.cloudera.parcel.descriptors.AlternativeDescriptor; import com.cloudera.parcel.descriptors.AlternativesDescriptor; import com.cloudera.parcel.descriptors.ParcelDescriptor; import com.cloudera.parcel.descriptors.PermissionDescriptor; import com.cloudera.parcel.descriptors.PermissionsDescriptor; import com.cloudera.validation.DescriptorRunner; import com.cloudera.validation.ValidationRunner; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.Writer; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.compress.archivers.tar.TarArchiveEntry; import org.apache.commons.compress.archivers.tar.TarArchiveInputStream; import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Component;
// Licensed to Cloudera, Inc. under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. Cloudera, Inc. licenses this file // to you 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.cloudera.cli.validator.components; /** * This {@link ValidationRunner} validates a complete parcel file. * * It validates the parcel's filename as well as the contents of the parcel, * ensuring consistency between the filename, directory and contained metadata. */ @Component public class ParcelFileRunner implements ValidationRunner { /** * This pattern defines the expected form for a regular parcel package. * [product]-[version]-[distro].parcel * The group for [version] is greedy so that it captures embedded '-'s. * The [product] and [distro] are not allowed to have embedded '-'s. */ private static final Pattern PARCEL_PATTERN = Pattern.compile("^(.*?)-(.*)-(.*?)\\.parcel$"); // This is the set of distros that CM is currently aware of. Future versions // of CM may understand more, and this list should be updated accordingly. private static final Set<String> KNOWN_DISTROS = ImmutableSet.of( "el5", "el6", "el7", "sles11", "sles12", "lucid", "precise", "trusty", "squeeze", "wheezy", "jessie"); private static final String PARCEL_JSON_PATH = "/meta/parcel.json"; private static final String ALTERNATIVES_JSON_PATH = "/meta/alternatives.json"; private static final String PERMISSIONS_JSON_PATH = "/meta/permissions.json"; @Autowired @Qualifier("parcelParser")
// Path: cm-schema/src/main/java/com/cloudera/parcel/descriptors/ParcelDescriptor.java // public interface ParcelDescriptor { // // @NotNull // @Range(min = 1, max = 1) // Integer getSchema_version(); // // @NotBlank // @Pattern(regexp="^((?!-).)*$", message="{custom.validation.constraints.ParcelName.message}") // String getName(); // // @NotBlank // String getVersion(); // // Map<String, String> getExtraVersionInfo(); // // @NotNull // Boolean getSetActiveSymlink(); // // String getDepends(); // // String getReplaces(); // // String getConflicts(); // // Set<String> getProvides(); // // @Valid // @NotNull // ScriptsDescriptor getScripts(); // // @UniqueField("name") // @Valid // @NotNull // Set<PackageDescriptor> getPackages(); // // @UniqueField("name") // @Valid // @NotNull // Set<ComponentDescriptor> getComponents(); // // @Valid // @NotNull // Map<String, UserDescriptor> getUsers(); // // @NotNull // Set<String> getGroups(); // // ServicesRestartDescriptor getServicesRestartInfo(); // } // Path: validator/src/main/java/com/cloudera/cli/validator/components/ParcelFileRunner.java import com.cloudera.common.Parser; import com.cloudera.parcel.descriptors.AlternativeDescriptor; import com.cloudera.parcel.descriptors.AlternativesDescriptor; import com.cloudera.parcel.descriptors.ParcelDescriptor; import com.cloudera.parcel.descriptors.PermissionDescriptor; import com.cloudera.parcel.descriptors.PermissionsDescriptor; import com.cloudera.validation.DescriptorRunner; import com.cloudera.validation.ValidationRunner; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.Writer; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.compress.archivers.tar.TarArchiveEntry; import org.apache.commons.compress.archivers.tar.TarArchiveInputStream; import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Component; // Licensed to Cloudera, Inc. under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. Cloudera, Inc. licenses this file // to you 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.cloudera.cli.validator.components; /** * This {@link ValidationRunner} validates a complete parcel file. * * It validates the parcel's filename as well as the contents of the parcel, * ensuring consistency between the filename, directory and contained metadata. */ @Component public class ParcelFileRunner implements ValidationRunner { /** * This pattern defines the expected form for a regular parcel package. * [product]-[version]-[distro].parcel * The group for [version] is greedy so that it captures embedded '-'s. * The [product] and [distro] are not allowed to have embedded '-'s. */ private static final Pattern PARCEL_PATTERN = Pattern.compile("^(.*?)-(.*)-(.*?)\\.parcel$"); // This is the set of distros that CM is currently aware of. Future versions // of CM may understand more, and this list should be updated accordingly. private static final Set<String> KNOWN_DISTROS = ImmutableSet.of( "el5", "el6", "el7", "sles11", "sles12", "lucid", "precise", "trusty", "squeeze", "wheezy", "jessie"); private static final String PARCEL_JSON_PATH = "/meta/parcel.json"; private static final String ALTERNATIVES_JSON_PATH = "/meta/alternatives.json"; private static final String PERMISSIONS_JSON_PATH = "/meta/permissions.json"; @Autowired @Qualifier("parcelParser")
private Parser<ParcelDescriptor> parcelParser;
cloudera/cm_ext
cm-schema/src/test/java/com/cloudera/csd/validation/monitoring/constraints/AttributeNamePrefixedWithServiceNameValidatorTest.java
// Path: cm-schema/src/main/java/com/cloudera/csd/descriptors/MetricEntityAttributeDescriptor.java // @Unstable // @Named // public interface MetricEntityAttributeDescriptor { // // /** // * Returns the name of the attribute. This name uniquely identifies this // * attribute and is used to reference the metric in the Cloudera Manager // * API and charting features. // * @return // */ // @MetricEntityAttributeNameFormat // String getName(); // // /** // * Returns the display name of the attribute. // * @return // */ // @NotEmpty // String getLabel(); // // /** // * Returns the description of the attribute. // * @return // */ // @NotEmpty // String getDescription(); // // /** // * Returns whether to treat attribute values as case-sensitive. // * @return // */ // boolean isValueCaseSensitive(); // } // // Path: cm-schema/src/main/java/com/cloudera/csd/validation/monitoring/MonitoringValidationContext.java // public class MonitoringValidationContext { // // public final ServiceMonitoringDefinitionsDescriptor serviceDescriptor; // public final ImmutableMap<String, MetricDescriptor> metricsDefined; // public final ImmutableMap<String, MetricEntityTypeDescriptor> entitiesDefined; // public final ImmutableMap<String, RoleMonitoringDefinitionsDescriptor> rolesDefined; // public final ImmutableMap<String, MetricEntityAttributeDescriptor> attributesDefined; // // public MonitoringValidationContext( // ServiceMonitoringDefinitionsDescriptor serviceDescriptor) { // Preconditions.checkNotNull(serviceDescriptor); // this.serviceDescriptor = serviceDescriptor; // ImmutableMap.Builder<String, RoleMonitoringDefinitionsDescriptor> // rolesDefinedBuilder = ImmutableMap.builder(); // // We can't use an ImmutableMap.Builder since it will not allow multiple // // entries with the same key. Instead we build a local hash map and make // // it immutable below. // Map<String, MetricDescriptor> metricsDefinedBuilder = Maps.newHashMap(); // metricsDefinedBuilder.putAll( // extractMetrics(serviceDescriptor.getMetricDefinitions())); // if (null != serviceDescriptor.getRoles()) { // for (RoleMonitoringDefinitionsDescriptor role : // serviceDescriptor.getRoles()) { // rolesDefinedBuilder.put( // MonitoringConventions.getRoleMetricEntityTypeName( // serviceDescriptor.getName(), // role.getName()), // role); // metricsDefinedBuilder.putAll( // extractMetrics(role.getMetricDefinitions())); // } // } // if (null != serviceDescriptor.getMetricEntityTypeDefinitions()) { // for (MetricEntityTypeDescriptor entity : // serviceDescriptor.getMetricEntityTypeDefinitions()) { // metricsDefinedBuilder.putAll( // extractMetrics(entity.getMetricDefinitions())); // } // } // ImmutableMap.Builder<String, MetricEntityTypeDescriptor> // entitiesDefinedBuilder = ImmutableMap.builder(); // if (null != serviceDescriptor.getMetricEntityTypeDefinitions()) { // for (MetricEntityTypeDescriptor entity : // serviceDescriptor.getMetricEntityTypeDefinitions()) { // entitiesDefinedBuilder.put(entity.getName(), entity); // } // } // ImmutableMap.Builder<String, MetricEntityAttributeDescriptor> // attributesDefinedBuilder = ImmutableMap.builder(); // if (null != serviceDescriptor.getMetricEntityAttributeDefinitions()) { // for (MetricEntityAttributeDescriptor attribute : // serviceDescriptor.getMetricEntityAttributeDefinitions()) { // attributesDefinedBuilder.put(attribute.getName(), attribute); // } // } // metricsDefined = ImmutableMap.copyOf(metricsDefinedBuilder); // rolesDefined = rolesDefinedBuilder.build(); // entitiesDefined = entitiesDefinedBuilder.build(); // attributesDefined = attributesDefinedBuilder.build(); // } // // private Map<String, MetricDescriptor> extractMetrics( // @Nullable List<MetricDescriptor> metrics) { // if (null == metrics) { // return ImmutableMap.of(); // } // Map<String, MetricDescriptor> ret = Maps.newHashMap(); // for (MetricDescriptor metric : metrics) { // ret.put(metric.getName(), metric); // } // return ret; // } // }
import static org.junit.Assert.assertTrue; import com.cloudera.csd.descriptors.MetricEntityAttributeDescriptor; import com.cloudera.csd.validation.monitoring.MonitoringValidationContext; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import java.util.List; import javax.validation.ConstraintViolation; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse;
// Licensed to Cloudera, Inc. under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. Cloudera, Inc. licenses this file // to you 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.cloudera.csd.validation.monitoring.constraints; public class AttributeNamePrefixedWithServiceNameValidatorTest extends AbstractMonitoringValidatorBaseTest { private AttributeNamePrefixedWithServiceNameValidator validator;
// Path: cm-schema/src/main/java/com/cloudera/csd/descriptors/MetricEntityAttributeDescriptor.java // @Unstable // @Named // public interface MetricEntityAttributeDescriptor { // // /** // * Returns the name of the attribute. This name uniquely identifies this // * attribute and is used to reference the metric in the Cloudera Manager // * API and charting features. // * @return // */ // @MetricEntityAttributeNameFormat // String getName(); // // /** // * Returns the display name of the attribute. // * @return // */ // @NotEmpty // String getLabel(); // // /** // * Returns the description of the attribute. // * @return // */ // @NotEmpty // String getDescription(); // // /** // * Returns whether to treat attribute values as case-sensitive. // * @return // */ // boolean isValueCaseSensitive(); // } // // Path: cm-schema/src/main/java/com/cloudera/csd/validation/monitoring/MonitoringValidationContext.java // public class MonitoringValidationContext { // // public final ServiceMonitoringDefinitionsDescriptor serviceDescriptor; // public final ImmutableMap<String, MetricDescriptor> metricsDefined; // public final ImmutableMap<String, MetricEntityTypeDescriptor> entitiesDefined; // public final ImmutableMap<String, RoleMonitoringDefinitionsDescriptor> rolesDefined; // public final ImmutableMap<String, MetricEntityAttributeDescriptor> attributesDefined; // // public MonitoringValidationContext( // ServiceMonitoringDefinitionsDescriptor serviceDescriptor) { // Preconditions.checkNotNull(serviceDescriptor); // this.serviceDescriptor = serviceDescriptor; // ImmutableMap.Builder<String, RoleMonitoringDefinitionsDescriptor> // rolesDefinedBuilder = ImmutableMap.builder(); // // We can't use an ImmutableMap.Builder since it will not allow multiple // // entries with the same key. Instead we build a local hash map and make // // it immutable below. // Map<String, MetricDescriptor> metricsDefinedBuilder = Maps.newHashMap(); // metricsDefinedBuilder.putAll( // extractMetrics(serviceDescriptor.getMetricDefinitions())); // if (null != serviceDescriptor.getRoles()) { // for (RoleMonitoringDefinitionsDescriptor role : // serviceDescriptor.getRoles()) { // rolesDefinedBuilder.put( // MonitoringConventions.getRoleMetricEntityTypeName( // serviceDescriptor.getName(), // role.getName()), // role); // metricsDefinedBuilder.putAll( // extractMetrics(role.getMetricDefinitions())); // } // } // if (null != serviceDescriptor.getMetricEntityTypeDefinitions()) { // for (MetricEntityTypeDescriptor entity : // serviceDescriptor.getMetricEntityTypeDefinitions()) { // metricsDefinedBuilder.putAll( // extractMetrics(entity.getMetricDefinitions())); // } // } // ImmutableMap.Builder<String, MetricEntityTypeDescriptor> // entitiesDefinedBuilder = ImmutableMap.builder(); // if (null != serviceDescriptor.getMetricEntityTypeDefinitions()) { // for (MetricEntityTypeDescriptor entity : // serviceDescriptor.getMetricEntityTypeDefinitions()) { // entitiesDefinedBuilder.put(entity.getName(), entity); // } // } // ImmutableMap.Builder<String, MetricEntityAttributeDescriptor> // attributesDefinedBuilder = ImmutableMap.builder(); // if (null != serviceDescriptor.getMetricEntityAttributeDefinitions()) { // for (MetricEntityAttributeDescriptor attribute : // serviceDescriptor.getMetricEntityAttributeDefinitions()) { // attributesDefinedBuilder.put(attribute.getName(), attribute); // } // } // metricsDefined = ImmutableMap.copyOf(metricsDefinedBuilder); // rolesDefined = rolesDefinedBuilder.build(); // entitiesDefined = entitiesDefinedBuilder.build(); // attributesDefined = attributesDefinedBuilder.build(); // } // // private Map<String, MetricDescriptor> extractMetrics( // @Nullable List<MetricDescriptor> metrics) { // if (null == metrics) { // return ImmutableMap.of(); // } // Map<String, MetricDescriptor> ret = Maps.newHashMap(); // for (MetricDescriptor metric : metrics) { // ret.put(metric.getName(), metric); // } // return ret; // } // } // Path: cm-schema/src/test/java/com/cloudera/csd/validation/monitoring/constraints/AttributeNamePrefixedWithServiceNameValidatorTest.java import static org.junit.Assert.assertTrue; import com.cloudera.csd.descriptors.MetricEntityAttributeDescriptor; import com.cloudera.csd.validation.monitoring.MonitoringValidationContext; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import java.util.List; import javax.validation.ConstraintViolation; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; // Licensed to Cloudera, Inc. under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. Cloudera, Inc. licenses this file // to you 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.cloudera.csd.validation.monitoring.constraints; public class AttributeNamePrefixedWithServiceNameValidatorTest extends AbstractMonitoringValidatorBaseTest { private AttributeNamePrefixedWithServiceNameValidator validator;
private MonitoringValidationContext context;
cloudera/cm_ext
cm-schema/src/test/java/com/cloudera/csd/validation/monitoring/constraints/AttributeNamePrefixedWithServiceNameValidatorTest.java
// Path: cm-schema/src/main/java/com/cloudera/csd/descriptors/MetricEntityAttributeDescriptor.java // @Unstable // @Named // public interface MetricEntityAttributeDescriptor { // // /** // * Returns the name of the attribute. This name uniquely identifies this // * attribute and is used to reference the metric in the Cloudera Manager // * API and charting features. // * @return // */ // @MetricEntityAttributeNameFormat // String getName(); // // /** // * Returns the display name of the attribute. // * @return // */ // @NotEmpty // String getLabel(); // // /** // * Returns the description of the attribute. // * @return // */ // @NotEmpty // String getDescription(); // // /** // * Returns whether to treat attribute values as case-sensitive. // * @return // */ // boolean isValueCaseSensitive(); // } // // Path: cm-schema/src/main/java/com/cloudera/csd/validation/monitoring/MonitoringValidationContext.java // public class MonitoringValidationContext { // // public final ServiceMonitoringDefinitionsDescriptor serviceDescriptor; // public final ImmutableMap<String, MetricDescriptor> metricsDefined; // public final ImmutableMap<String, MetricEntityTypeDescriptor> entitiesDefined; // public final ImmutableMap<String, RoleMonitoringDefinitionsDescriptor> rolesDefined; // public final ImmutableMap<String, MetricEntityAttributeDescriptor> attributesDefined; // // public MonitoringValidationContext( // ServiceMonitoringDefinitionsDescriptor serviceDescriptor) { // Preconditions.checkNotNull(serviceDescriptor); // this.serviceDescriptor = serviceDescriptor; // ImmutableMap.Builder<String, RoleMonitoringDefinitionsDescriptor> // rolesDefinedBuilder = ImmutableMap.builder(); // // We can't use an ImmutableMap.Builder since it will not allow multiple // // entries with the same key. Instead we build a local hash map and make // // it immutable below. // Map<String, MetricDescriptor> metricsDefinedBuilder = Maps.newHashMap(); // metricsDefinedBuilder.putAll( // extractMetrics(serviceDescriptor.getMetricDefinitions())); // if (null != serviceDescriptor.getRoles()) { // for (RoleMonitoringDefinitionsDescriptor role : // serviceDescriptor.getRoles()) { // rolesDefinedBuilder.put( // MonitoringConventions.getRoleMetricEntityTypeName( // serviceDescriptor.getName(), // role.getName()), // role); // metricsDefinedBuilder.putAll( // extractMetrics(role.getMetricDefinitions())); // } // } // if (null != serviceDescriptor.getMetricEntityTypeDefinitions()) { // for (MetricEntityTypeDescriptor entity : // serviceDescriptor.getMetricEntityTypeDefinitions()) { // metricsDefinedBuilder.putAll( // extractMetrics(entity.getMetricDefinitions())); // } // } // ImmutableMap.Builder<String, MetricEntityTypeDescriptor> // entitiesDefinedBuilder = ImmutableMap.builder(); // if (null != serviceDescriptor.getMetricEntityTypeDefinitions()) { // for (MetricEntityTypeDescriptor entity : // serviceDescriptor.getMetricEntityTypeDefinitions()) { // entitiesDefinedBuilder.put(entity.getName(), entity); // } // } // ImmutableMap.Builder<String, MetricEntityAttributeDescriptor> // attributesDefinedBuilder = ImmutableMap.builder(); // if (null != serviceDescriptor.getMetricEntityAttributeDefinitions()) { // for (MetricEntityAttributeDescriptor attribute : // serviceDescriptor.getMetricEntityAttributeDefinitions()) { // attributesDefinedBuilder.put(attribute.getName(), attribute); // } // } // metricsDefined = ImmutableMap.copyOf(metricsDefinedBuilder); // rolesDefined = rolesDefinedBuilder.build(); // entitiesDefined = entitiesDefinedBuilder.build(); // attributesDefined = attributesDefinedBuilder.build(); // } // // private Map<String, MetricDescriptor> extractMetrics( // @Nullable List<MetricDescriptor> metrics) { // if (null == metrics) { // return ImmutableMap.of(); // } // Map<String, MetricDescriptor> ret = Maps.newHashMap(); // for (MetricDescriptor metric : metrics) { // ret.put(metric.getName(), metric); // } // return ret; // } // }
import static org.junit.Assert.assertTrue; import com.cloudera.csd.descriptors.MetricEntityAttributeDescriptor; import com.cloudera.csd.validation.monitoring.MonitoringValidationContext; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import java.util.List; import javax.validation.ConstraintViolation; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse;
// Licensed to Cloudera, Inc. under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. Cloudera, Inc. licenses this file // to you 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.cloudera.csd.validation.monitoring.constraints; public class AttributeNamePrefixedWithServiceNameValidatorTest extends AbstractMonitoringValidatorBaseTest { private AttributeNamePrefixedWithServiceNameValidator validator; private MonitoringValidationContext context; @Before public void setupEntityNamePrefixedWithServiceNameValidator() { validator = new AttributeNamePrefixedWithServiceNameValidator( ImmutableSet.of("builtInAttribute")); context = new MonitoringValidationContext(serviceDescriptor); } @Test public void testValidEntity() {
// Path: cm-schema/src/main/java/com/cloudera/csd/descriptors/MetricEntityAttributeDescriptor.java // @Unstable // @Named // public interface MetricEntityAttributeDescriptor { // // /** // * Returns the name of the attribute. This name uniquely identifies this // * attribute and is used to reference the metric in the Cloudera Manager // * API and charting features. // * @return // */ // @MetricEntityAttributeNameFormat // String getName(); // // /** // * Returns the display name of the attribute. // * @return // */ // @NotEmpty // String getLabel(); // // /** // * Returns the description of the attribute. // * @return // */ // @NotEmpty // String getDescription(); // // /** // * Returns whether to treat attribute values as case-sensitive. // * @return // */ // boolean isValueCaseSensitive(); // } // // Path: cm-schema/src/main/java/com/cloudera/csd/validation/monitoring/MonitoringValidationContext.java // public class MonitoringValidationContext { // // public final ServiceMonitoringDefinitionsDescriptor serviceDescriptor; // public final ImmutableMap<String, MetricDescriptor> metricsDefined; // public final ImmutableMap<String, MetricEntityTypeDescriptor> entitiesDefined; // public final ImmutableMap<String, RoleMonitoringDefinitionsDescriptor> rolesDefined; // public final ImmutableMap<String, MetricEntityAttributeDescriptor> attributesDefined; // // public MonitoringValidationContext( // ServiceMonitoringDefinitionsDescriptor serviceDescriptor) { // Preconditions.checkNotNull(serviceDescriptor); // this.serviceDescriptor = serviceDescriptor; // ImmutableMap.Builder<String, RoleMonitoringDefinitionsDescriptor> // rolesDefinedBuilder = ImmutableMap.builder(); // // We can't use an ImmutableMap.Builder since it will not allow multiple // // entries with the same key. Instead we build a local hash map and make // // it immutable below. // Map<String, MetricDescriptor> metricsDefinedBuilder = Maps.newHashMap(); // metricsDefinedBuilder.putAll( // extractMetrics(serviceDescriptor.getMetricDefinitions())); // if (null != serviceDescriptor.getRoles()) { // for (RoleMonitoringDefinitionsDescriptor role : // serviceDescriptor.getRoles()) { // rolesDefinedBuilder.put( // MonitoringConventions.getRoleMetricEntityTypeName( // serviceDescriptor.getName(), // role.getName()), // role); // metricsDefinedBuilder.putAll( // extractMetrics(role.getMetricDefinitions())); // } // } // if (null != serviceDescriptor.getMetricEntityTypeDefinitions()) { // for (MetricEntityTypeDescriptor entity : // serviceDescriptor.getMetricEntityTypeDefinitions()) { // metricsDefinedBuilder.putAll( // extractMetrics(entity.getMetricDefinitions())); // } // } // ImmutableMap.Builder<String, MetricEntityTypeDescriptor> // entitiesDefinedBuilder = ImmutableMap.builder(); // if (null != serviceDescriptor.getMetricEntityTypeDefinitions()) { // for (MetricEntityTypeDescriptor entity : // serviceDescriptor.getMetricEntityTypeDefinitions()) { // entitiesDefinedBuilder.put(entity.getName(), entity); // } // } // ImmutableMap.Builder<String, MetricEntityAttributeDescriptor> // attributesDefinedBuilder = ImmutableMap.builder(); // if (null != serviceDescriptor.getMetricEntityAttributeDefinitions()) { // for (MetricEntityAttributeDescriptor attribute : // serviceDescriptor.getMetricEntityAttributeDefinitions()) { // attributesDefinedBuilder.put(attribute.getName(), attribute); // } // } // metricsDefined = ImmutableMap.copyOf(metricsDefinedBuilder); // rolesDefined = rolesDefinedBuilder.build(); // entitiesDefined = entitiesDefinedBuilder.build(); // attributesDefined = attributesDefinedBuilder.build(); // } // // private Map<String, MetricDescriptor> extractMetrics( // @Nullable List<MetricDescriptor> metrics) { // if (null == metrics) { // return ImmutableMap.of(); // } // Map<String, MetricDescriptor> ret = Maps.newHashMap(); // for (MetricDescriptor metric : metrics) { // ret.put(metric.getName(), metric); // } // return ret; // } // } // Path: cm-schema/src/test/java/com/cloudera/csd/validation/monitoring/constraints/AttributeNamePrefixedWithServiceNameValidatorTest.java import static org.junit.Assert.assertTrue; import com.cloudera.csd.descriptors.MetricEntityAttributeDescriptor; import com.cloudera.csd.validation.monitoring.MonitoringValidationContext; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import java.util.List; import javax.validation.ConstraintViolation; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; // Licensed to Cloudera, Inc. under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. Cloudera, Inc. licenses this file // to you 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.cloudera.csd.validation.monitoring.constraints; public class AttributeNamePrefixedWithServiceNameValidatorTest extends AbstractMonitoringValidatorBaseTest { private AttributeNamePrefixedWithServiceNameValidator validator; private MonitoringValidationContext context; @Before public void setupEntityNamePrefixedWithServiceNameValidator() { validator = new AttributeNamePrefixedWithServiceNameValidator( ImmutableSet.of("builtInAttribute")); context = new MonitoringValidationContext(serviceDescriptor); } @Test public void testValidEntity() {
MetricEntityAttributeDescriptor attribute = mockAttribute("foobarAttribute");
cloudera/cm_ext
cm-schema/src/main/java/com/cloudera/csd/validation/monitoring/MonitoringConventions.java
// Path: cm-schema/src/main/java/com/cloudera/csd/descriptors/MetricEntityTypeDescriptor.java // @Named // @Unstable // public interface MetricEntityTypeDescriptor { // // /** // * Returns the name of the entity type. This name uniquely identifies this // * entity type and is used to reference the type in the Cloudera Manager // * API and charting features. // * @return // */ // @MetricEntityTypeFormat // String getName(); // // /** // * Returns the string to use to pluralize the name of the entity for cross // * entity aggregate metrics. For example, for an entity named "ECHO_ENTITY" // * this should be "echo_entities". Cross entity aggregate metric names will be // * composed using this to generate metrics named like // * 'fd_open_across_echo_entities'. // * // * The string must be prefixed with the service name and be unique within this // * descriptor. // * // * If this is not specified the name will be constructed from the service // * name, the entity name, and an "s". // * @return // */ // @NameForCrossEntityAggregatesFormat // String getNameForCrossEntityAggregateMetrics(); // // /** // * Returns the display name of the entity type. // * @return // */ // @NotEmpty // String getLabel(); // // /** // * Returns the display name of the entity type in plural form. // * @return // */ // @NotEmpty // String getLabelPlural(); // // /** // * Returns the description of the entity type. // * @return // */ // @NotEmpty // String getDescription(); // // /** // * Returns the list immutable attributes for this entity type. Immutable // * attributes values for an entity may not change over its lifetime. // * @return // */ // @NotEmpty // List<String> getImmutableAttributeNames(); // // /** // * Returns the list mutable attributes for this entity type. Mutable // * attributes for an entity may change over its lifetime. // * @return // */ // List<String> getMutableAttributeNames(); // // /** // * Returns a list of attribute names that will be used to construct entity // * names for entities of this type. The attributes named here must be immutable // * attributes of this type or a parent type. // * @return // */ // @NotEmpty // List<String> getEntityNameFormat(); // // /** // * Returns a format string that will be used to construct the display name of // * entities of this type. If this returns null the entity name would be used // * as the display name. // * // * The entity attribute values are used to replace $attribute name portions of // * this format string. For example, an entity with roleType "DATANODE" and // * hostname "foo.com" will have a display name "DATANODE (foo.com)" if the // * format is "$roleType ($hostname)". // * @return // */ // String getEntityLabelFormat(); // // /** // * Returns a list of metric entity type names which are parents of this // * metric entity type. A metric entity type inherits the attributes of // * its ancestors. For example a role metric entity type has its service as a // * parent. A service metric entity type has a cluster as a parent. The role // * type inherits its cluster name attribute through its service parent. Only // * parent ancestors should be returned here. In the example given, only the // * service metric entity type should be specified in the parent list. // */ // List<String> getParentMetricEntityTypeNames(); // // /** // * Specifies metrics that will be registered for this metric entity type. // * @return // */ // @UniqueField("name") // List<MetricDescriptor> getMetricDefinitions(); // }
import com.cloudera.csd.descriptors.MetricEntityTypeDescriptor; import com.google.common.base.Preconditions; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.annotation.Nullable;
* name that will be used for role cross entity aggregate metrics instead. * @param serviceType * @param roleType * @return */ public static String getNameForRoleCrossEntityAggregateMetrics( String serviceType, String roleType) { Preconditions.checkNotNull(serviceType); Preconditions.checkNotNull(roleType); String normalizedRoleType = roleType.toLowerCase(); String normalizedServiceType = serviceType.toLowerCase() + "_"; if (normalizedRoleType.startsWith(normalizedServiceType)) { return normalizedRoleType + "s"; } return String.format("%s%ss", normalizedServiceType, normalizedRoleType); } /** * Returns the name for cross entity aggregate metrics for an entity. For * example for the metric fd_open, echo service and echo_entity_one the cross * entity aggregate will be fd_open_across_echo_entity_ones. For the * metric fd_open echo service, and foobar the cross entity aggregate * will be fd_open_across_echo_foobars. Note that a CSD can provide a * name that will be used for entity cross entity aggregate metrics instead. * @param entityDescriptor * @param serviceType * @return */ public static String getNameForEntityTypeCrossEntityAggregateMetrics(
// Path: cm-schema/src/main/java/com/cloudera/csd/descriptors/MetricEntityTypeDescriptor.java // @Named // @Unstable // public interface MetricEntityTypeDescriptor { // // /** // * Returns the name of the entity type. This name uniquely identifies this // * entity type and is used to reference the type in the Cloudera Manager // * API and charting features. // * @return // */ // @MetricEntityTypeFormat // String getName(); // // /** // * Returns the string to use to pluralize the name of the entity for cross // * entity aggregate metrics. For example, for an entity named "ECHO_ENTITY" // * this should be "echo_entities". Cross entity aggregate metric names will be // * composed using this to generate metrics named like // * 'fd_open_across_echo_entities'. // * // * The string must be prefixed with the service name and be unique within this // * descriptor. // * // * If this is not specified the name will be constructed from the service // * name, the entity name, and an "s". // * @return // */ // @NameForCrossEntityAggregatesFormat // String getNameForCrossEntityAggregateMetrics(); // // /** // * Returns the display name of the entity type. // * @return // */ // @NotEmpty // String getLabel(); // // /** // * Returns the display name of the entity type in plural form. // * @return // */ // @NotEmpty // String getLabelPlural(); // // /** // * Returns the description of the entity type. // * @return // */ // @NotEmpty // String getDescription(); // // /** // * Returns the list immutable attributes for this entity type. Immutable // * attributes values for an entity may not change over its lifetime. // * @return // */ // @NotEmpty // List<String> getImmutableAttributeNames(); // // /** // * Returns the list mutable attributes for this entity type. Mutable // * attributes for an entity may change over its lifetime. // * @return // */ // List<String> getMutableAttributeNames(); // // /** // * Returns a list of attribute names that will be used to construct entity // * names for entities of this type. The attributes named here must be immutable // * attributes of this type or a parent type. // * @return // */ // @NotEmpty // List<String> getEntityNameFormat(); // // /** // * Returns a format string that will be used to construct the display name of // * entities of this type. If this returns null the entity name would be used // * as the display name. // * // * The entity attribute values are used to replace $attribute name portions of // * this format string. For example, an entity with roleType "DATANODE" and // * hostname "foo.com" will have a display name "DATANODE (foo.com)" if the // * format is "$roleType ($hostname)". // * @return // */ // String getEntityLabelFormat(); // // /** // * Returns a list of metric entity type names which are parents of this // * metric entity type. A metric entity type inherits the attributes of // * its ancestors. For example a role metric entity type has its service as a // * parent. A service metric entity type has a cluster as a parent. The role // * type inherits its cluster name attribute through its service parent. Only // * parent ancestors should be returned here. In the example given, only the // * service metric entity type should be specified in the parent list. // */ // List<String> getParentMetricEntityTypeNames(); // // /** // * Specifies metrics that will be registered for this metric entity type. // * @return // */ // @UniqueField("name") // List<MetricDescriptor> getMetricDefinitions(); // } // Path: cm-schema/src/main/java/com/cloudera/csd/validation/monitoring/MonitoringConventions.java import com.cloudera.csd.descriptors.MetricEntityTypeDescriptor; import com.google.common.base.Preconditions; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.annotation.Nullable; * name that will be used for role cross entity aggregate metrics instead. * @param serviceType * @param roleType * @return */ public static String getNameForRoleCrossEntityAggregateMetrics( String serviceType, String roleType) { Preconditions.checkNotNull(serviceType); Preconditions.checkNotNull(roleType); String normalizedRoleType = roleType.toLowerCase(); String normalizedServiceType = serviceType.toLowerCase() + "_"; if (normalizedRoleType.startsWith(normalizedServiceType)) { return normalizedRoleType + "s"; } return String.format("%s%ss", normalizedServiceType, normalizedRoleType); } /** * Returns the name for cross entity aggregate metrics for an entity. For * example for the metric fd_open, echo service and echo_entity_one the cross * entity aggregate will be fd_open_across_echo_entity_ones. For the * metric fd_open echo service, and foobar the cross entity aggregate * will be fd_open_across_echo_foobars. Note that a CSD can provide a * name that will be used for entity cross entity aggregate metrics instead. * @param entityDescriptor * @param serviceType * @return */ public static String getNameForEntityTypeCrossEntityAggregateMetrics(
MetricEntityTypeDescriptor entityDescriptor,
cloudera/cm_ext
cm-schema/src/main/java/com/cloudera/csd/tools/impala/ImpalaMetricDefinitionFixture.java
// Path: cm-schema/src/main/java/com/cloudera/csd/tools/MetricDefinitionFixture.java // @JsonIgnoreProperties(ignoreUnknown = true) // public class MetricDefinitionFixture // <T extends AbstractMetricDefinition> { // // @JsonIgnore // private String serviceName; // @JsonIgnore // private List<T> serviceMetrics; // @JsonIgnore // private Map<String, List<T>> rolesMetrics; // @JsonIgnore // private Map<String, List<T>> additionalServiceEntityTypesMetrics; // @JsonIgnore // private final Set<String> serviceMetricNames; // @JsonIgnore // private final Map<String, Set<String>> rolesMetricsNames; // @JsonIgnore // private final Map<String, Set<String>> entitiesMetricsNames; // // public MetricDefinitionFixture() { // serviceMetricNames = Sets.newHashSet(); // serviceMetrics = Lists.newArrayList(); // rolesMetricsNames = Maps.newHashMap(); // rolesMetrics = Maps.newHashMap(); // entitiesMetricsNames = Maps.newHashMap(); // additionalServiceEntityTypesMetrics = Maps.newHashMap(); // } // // @JsonProperty // public String getServiceName() { // return serviceName; // } // // @JsonProperty // public void setServiceName(String serviceName) { // if (null == serviceName || serviceName.isEmpty()) { // throw new IllegalArgumentException("Invalid empty or null service name"); // } // this.serviceName = serviceName; // } // // @JsonProperty // public List<T> getServiceMetrics() { // return serviceMetrics; // } // // @JsonProperty // public void setServiceMetrics(List<T> serviceMetrics) { // this.serviceMetrics = serviceMetrics; // } // // @JsonProperty // public Map<String, List<T>> getRolesMetrics() { // return rolesMetrics; // } // // @JsonProperty // public void setRolesMetrics(Map<String, List<T>> rolesMetrics) { // this.rolesMetrics = rolesMetrics; // } // // @JsonProperty // public Map<String, List<T>> getAdditionalServiceEntityTypesMetrics() { // return additionalServiceEntityTypesMetrics; // } // // @JsonProperty // public void setAdditionalServiceEntityTypesMetrics( // Map<String, List<T>> additionalServiceEntityTypesMetrics) { // this.additionalServiceEntityTypesMetrics = // additionalServiceEntityTypesMetrics; // } // // @JsonIgnore // public void addServiceMetric(T metric) { // if (serviceMetricNames.contains(metric.getName())) { // throw new IllegalArgumentException("Metric " + metric.getName() + // "already added"); // } // serviceMetrics.add(metric); // serviceMetricNames.add(metric.getName()); // } // // @JsonIgnore // public void addRoleMetric(String roleName, T metric) { // addIfNew(roleName, // metric, // rolesMetricsNames, // rolesMetrics); // } // // @JsonIgnore // public void addEntityMetric(String entityName, T metric) { // addIfNew(entityName, // metric, // entitiesMetricsNames, // additionalServiceEntityTypesMetrics); // } // // private void addIfNew(String entity, // T metric, // Map<String, Set<String>> existing, // Map<String, List<T>> metrics) { // Preconditions.checkNotNull(entity); // Preconditions.checkNotNull(metric); // Preconditions.checkNotNull(existing); // Preconditions.checkNotNull(metrics); // // if (existing.containsKey(entity) && // existing.get(entity).contains(metric.getName())) { // return; // } // List<T> entityMetrics = metrics.get(entity); // Set<String> entityMetricsNames = existing.get(entity); // if (null == entityMetrics) { // entityMetrics = Lists.newArrayList(); // entityMetricsNames = Sets.newHashSet(); // metrics.put(entity, entityMetrics); // existing.put(entity, entityMetricsNames); // } // entityMetrics.add(metric); // entityMetricsNames.add(metric.getName()); // } // }
import com.cloudera.csd.tools.MetricDefinitionFixture; import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
// Licensed to Cloudera, Inc. under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. Cloudera, Inc. licenses this file // to you 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.cloudera.csd.tools.impala; /** * A helper class for generating ServiceMonitoringDefinitions for Impala. */ @JsonIgnoreProperties(ignoreUnknown = true) public class ImpalaMetricDefinitionFixture
// Path: cm-schema/src/main/java/com/cloudera/csd/tools/MetricDefinitionFixture.java // @JsonIgnoreProperties(ignoreUnknown = true) // public class MetricDefinitionFixture // <T extends AbstractMetricDefinition> { // // @JsonIgnore // private String serviceName; // @JsonIgnore // private List<T> serviceMetrics; // @JsonIgnore // private Map<String, List<T>> rolesMetrics; // @JsonIgnore // private Map<String, List<T>> additionalServiceEntityTypesMetrics; // @JsonIgnore // private final Set<String> serviceMetricNames; // @JsonIgnore // private final Map<String, Set<String>> rolesMetricsNames; // @JsonIgnore // private final Map<String, Set<String>> entitiesMetricsNames; // // public MetricDefinitionFixture() { // serviceMetricNames = Sets.newHashSet(); // serviceMetrics = Lists.newArrayList(); // rolesMetricsNames = Maps.newHashMap(); // rolesMetrics = Maps.newHashMap(); // entitiesMetricsNames = Maps.newHashMap(); // additionalServiceEntityTypesMetrics = Maps.newHashMap(); // } // // @JsonProperty // public String getServiceName() { // return serviceName; // } // // @JsonProperty // public void setServiceName(String serviceName) { // if (null == serviceName || serviceName.isEmpty()) { // throw new IllegalArgumentException("Invalid empty or null service name"); // } // this.serviceName = serviceName; // } // // @JsonProperty // public List<T> getServiceMetrics() { // return serviceMetrics; // } // // @JsonProperty // public void setServiceMetrics(List<T> serviceMetrics) { // this.serviceMetrics = serviceMetrics; // } // // @JsonProperty // public Map<String, List<T>> getRolesMetrics() { // return rolesMetrics; // } // // @JsonProperty // public void setRolesMetrics(Map<String, List<T>> rolesMetrics) { // this.rolesMetrics = rolesMetrics; // } // // @JsonProperty // public Map<String, List<T>> getAdditionalServiceEntityTypesMetrics() { // return additionalServiceEntityTypesMetrics; // } // // @JsonProperty // public void setAdditionalServiceEntityTypesMetrics( // Map<String, List<T>> additionalServiceEntityTypesMetrics) { // this.additionalServiceEntityTypesMetrics = // additionalServiceEntityTypesMetrics; // } // // @JsonIgnore // public void addServiceMetric(T metric) { // if (serviceMetricNames.contains(metric.getName())) { // throw new IllegalArgumentException("Metric " + metric.getName() + // "already added"); // } // serviceMetrics.add(metric); // serviceMetricNames.add(metric.getName()); // } // // @JsonIgnore // public void addRoleMetric(String roleName, T metric) { // addIfNew(roleName, // metric, // rolesMetricsNames, // rolesMetrics); // } // // @JsonIgnore // public void addEntityMetric(String entityName, T metric) { // addIfNew(entityName, // metric, // entitiesMetricsNames, // additionalServiceEntityTypesMetrics); // } // // private void addIfNew(String entity, // T metric, // Map<String, Set<String>> existing, // Map<String, List<T>> metrics) { // Preconditions.checkNotNull(entity); // Preconditions.checkNotNull(metric); // Preconditions.checkNotNull(existing); // Preconditions.checkNotNull(metrics); // // if (existing.containsKey(entity) && // existing.get(entity).contains(metric.getName())) { // return; // } // List<T> entityMetrics = metrics.get(entity); // Set<String> entityMetricsNames = existing.get(entity); // if (null == entityMetrics) { // entityMetrics = Lists.newArrayList(); // entityMetricsNames = Sets.newHashSet(); // metrics.put(entity, entityMetrics); // existing.put(entity, entityMetricsNames); // } // entityMetrics.add(metric); // entityMetricsNames.add(metric.getName()); // } // } // Path: cm-schema/src/main/java/com/cloudera/csd/tools/impala/ImpalaMetricDefinitionFixture.java import com.cloudera.csd.tools.MetricDefinitionFixture; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; // Licensed to Cloudera, Inc. under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. Cloudera, Inc. licenses this file // to you 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.cloudera.csd.tools.impala; /** * A helper class for generating ServiceMonitoringDefinitions for Impala. */ @JsonIgnoreProperties(ignoreUnknown = true) public class ImpalaMetricDefinitionFixture
extends MetricDefinitionFixture<ImpalaMetric> {
cloudera/cm_ext
cm-schema/src/test/java/com/cloudera/csd/validation/monitoring/constraints/WeightingMetricValidatorTest.java
// Path: cm-schema/src/main/java/com/cloudera/csd/validation/monitoring/MonitoringValidationContext.java // public class MonitoringValidationContext { // // public final ServiceMonitoringDefinitionsDescriptor serviceDescriptor; // public final ImmutableMap<String, MetricDescriptor> metricsDefined; // public final ImmutableMap<String, MetricEntityTypeDescriptor> entitiesDefined; // public final ImmutableMap<String, RoleMonitoringDefinitionsDescriptor> rolesDefined; // public final ImmutableMap<String, MetricEntityAttributeDescriptor> attributesDefined; // // public MonitoringValidationContext( // ServiceMonitoringDefinitionsDescriptor serviceDescriptor) { // Preconditions.checkNotNull(serviceDescriptor); // this.serviceDescriptor = serviceDescriptor; // ImmutableMap.Builder<String, RoleMonitoringDefinitionsDescriptor> // rolesDefinedBuilder = ImmutableMap.builder(); // // We can't use an ImmutableMap.Builder since it will not allow multiple // // entries with the same key. Instead we build a local hash map and make // // it immutable below. // Map<String, MetricDescriptor> metricsDefinedBuilder = Maps.newHashMap(); // metricsDefinedBuilder.putAll( // extractMetrics(serviceDescriptor.getMetricDefinitions())); // if (null != serviceDescriptor.getRoles()) { // for (RoleMonitoringDefinitionsDescriptor role : // serviceDescriptor.getRoles()) { // rolesDefinedBuilder.put( // MonitoringConventions.getRoleMetricEntityTypeName( // serviceDescriptor.getName(), // role.getName()), // role); // metricsDefinedBuilder.putAll( // extractMetrics(role.getMetricDefinitions())); // } // } // if (null != serviceDescriptor.getMetricEntityTypeDefinitions()) { // for (MetricEntityTypeDescriptor entity : // serviceDescriptor.getMetricEntityTypeDefinitions()) { // metricsDefinedBuilder.putAll( // extractMetrics(entity.getMetricDefinitions())); // } // } // ImmutableMap.Builder<String, MetricEntityTypeDescriptor> // entitiesDefinedBuilder = ImmutableMap.builder(); // if (null != serviceDescriptor.getMetricEntityTypeDefinitions()) { // for (MetricEntityTypeDescriptor entity : // serviceDescriptor.getMetricEntityTypeDefinitions()) { // entitiesDefinedBuilder.put(entity.getName(), entity); // } // } // ImmutableMap.Builder<String, MetricEntityAttributeDescriptor> // attributesDefinedBuilder = ImmutableMap.builder(); // if (null != serviceDescriptor.getMetricEntityAttributeDefinitions()) { // for (MetricEntityAttributeDescriptor attribute : // serviceDescriptor.getMetricEntityAttributeDefinitions()) { // attributesDefinedBuilder.put(attribute.getName(), attribute); // } // } // metricsDefined = ImmutableMap.copyOf(metricsDefinedBuilder); // rolesDefined = rolesDefinedBuilder.build(); // entitiesDefined = entitiesDefinedBuilder.build(); // attributesDefined = attributesDefinedBuilder.build(); // } // // private Map<String, MetricDescriptor> extractMetrics( // @Nullable List<MetricDescriptor> metrics) { // if (null == metrics) { // return ImmutableMap.of(); // } // Map<String, MetricDescriptor> ret = Maps.newHashMap(); // for (MetricDescriptor metric : metrics) { // ret.put(metric.getName(), metric); // } // return ret; // } // }
import com.cloudera.csd.descriptors.MetricDescriptor; import com.cloudera.csd.validation.monitoring.MonitoringValidationContext; import com.google.common.collect.ImmutableList; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue;
// Licensed to Cloudera, Inc. under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. Cloudera, Inc. licenses this file // to you 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.cloudera.csd.validation.monitoring.constraints; public class WeightingMetricValidatorTest extends AbstractMonitoringValidatorBaseTest { private WeightingMetricValidator validator;
// Path: cm-schema/src/main/java/com/cloudera/csd/validation/monitoring/MonitoringValidationContext.java // public class MonitoringValidationContext { // // public final ServiceMonitoringDefinitionsDescriptor serviceDescriptor; // public final ImmutableMap<String, MetricDescriptor> metricsDefined; // public final ImmutableMap<String, MetricEntityTypeDescriptor> entitiesDefined; // public final ImmutableMap<String, RoleMonitoringDefinitionsDescriptor> rolesDefined; // public final ImmutableMap<String, MetricEntityAttributeDescriptor> attributesDefined; // // public MonitoringValidationContext( // ServiceMonitoringDefinitionsDescriptor serviceDescriptor) { // Preconditions.checkNotNull(serviceDescriptor); // this.serviceDescriptor = serviceDescriptor; // ImmutableMap.Builder<String, RoleMonitoringDefinitionsDescriptor> // rolesDefinedBuilder = ImmutableMap.builder(); // // We can't use an ImmutableMap.Builder since it will not allow multiple // // entries with the same key. Instead we build a local hash map and make // // it immutable below. // Map<String, MetricDescriptor> metricsDefinedBuilder = Maps.newHashMap(); // metricsDefinedBuilder.putAll( // extractMetrics(serviceDescriptor.getMetricDefinitions())); // if (null != serviceDescriptor.getRoles()) { // for (RoleMonitoringDefinitionsDescriptor role : // serviceDescriptor.getRoles()) { // rolesDefinedBuilder.put( // MonitoringConventions.getRoleMetricEntityTypeName( // serviceDescriptor.getName(), // role.getName()), // role); // metricsDefinedBuilder.putAll( // extractMetrics(role.getMetricDefinitions())); // } // } // if (null != serviceDescriptor.getMetricEntityTypeDefinitions()) { // for (MetricEntityTypeDescriptor entity : // serviceDescriptor.getMetricEntityTypeDefinitions()) { // metricsDefinedBuilder.putAll( // extractMetrics(entity.getMetricDefinitions())); // } // } // ImmutableMap.Builder<String, MetricEntityTypeDescriptor> // entitiesDefinedBuilder = ImmutableMap.builder(); // if (null != serviceDescriptor.getMetricEntityTypeDefinitions()) { // for (MetricEntityTypeDescriptor entity : // serviceDescriptor.getMetricEntityTypeDefinitions()) { // entitiesDefinedBuilder.put(entity.getName(), entity); // } // } // ImmutableMap.Builder<String, MetricEntityAttributeDescriptor> // attributesDefinedBuilder = ImmutableMap.builder(); // if (null != serviceDescriptor.getMetricEntityAttributeDefinitions()) { // for (MetricEntityAttributeDescriptor attribute : // serviceDescriptor.getMetricEntityAttributeDefinitions()) { // attributesDefinedBuilder.put(attribute.getName(), attribute); // } // } // metricsDefined = ImmutableMap.copyOf(metricsDefinedBuilder); // rolesDefined = rolesDefinedBuilder.build(); // entitiesDefined = entitiesDefinedBuilder.build(); // attributesDefined = attributesDefinedBuilder.build(); // } // // private Map<String, MetricDescriptor> extractMetrics( // @Nullable List<MetricDescriptor> metrics) { // if (null == metrics) { // return ImmutableMap.of(); // } // Map<String, MetricDescriptor> ret = Maps.newHashMap(); // for (MetricDescriptor metric : metrics) { // ret.put(metric.getName(), metric); // } // return ret; // } // } // Path: cm-schema/src/test/java/com/cloudera/csd/validation/monitoring/constraints/WeightingMetricValidatorTest.java import com.cloudera.csd.descriptors.MetricDescriptor; import com.cloudera.csd.validation.monitoring.MonitoringValidationContext; import com.google.common.collect.ImmutableList; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; // Licensed to Cloudera, Inc. under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. Cloudera, Inc. licenses this file // to you 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.cloudera.csd.validation.monitoring.constraints; public class WeightingMetricValidatorTest extends AbstractMonitoringValidatorBaseTest { private WeightingMetricValidator validator;
private MonitoringValidationContext context;
stridercheng/chatui
app/src/main/java/com/rance/chatui/util/GlobalOnItemClickManagerUtils.java
// Path: app/src/main/java/com/rance/chatui/adapter/EmotionGridViewAdapter.java // public class EmotionGridViewAdapter extends BaseAdapter { // // private Context context; // private List<String> emotionNames; // private int itemWidth; // // public EmotionGridViewAdapter(Context context, List<String> emotionNames, int itemWidth) { // this.context = context; // this.emotionNames = emotionNames; // this.itemWidth = itemWidth; // } // // @Override // public int getCount() { // // +1 最后一个为删除按钮 // return emotionNames.size() + 1; // } // // @Override // public String getItem(int position) { // return emotionNames.get(position); // } // // @Override // public long getItemId(int position) { // return position; // } // // @Override // public View getView(int position, View convertView, ViewGroup parent) { // ImageView iv_emotion = new ImageView(context); // // 设置内边距 // iv_emotion.setPadding(itemWidth / 8, itemWidth / 8, itemWidth / 8, itemWidth / 8); // LayoutParams params = new LayoutParams(itemWidth, itemWidth); // iv_emotion.setLayoutParams(params); // // //判断是否为最后一个item // if (position == getCount() - 1) { // iv_emotion.setImageResource(R.drawable.compose_emotion_delete); // } else { // String emotionName = emotionNames.get(position); // iv_emotion.setImageResource(EmotionUtils.EMOTION_STATIC_MAP.get(emotionName)); // } // // return iv_emotion; // } // // }
import android.content.Context; import android.view.KeyEvent; import android.view.View; import android.widget.AdapterView; import android.widget.EditText; import com.rance.chatui.adapter.EmotionGridViewAdapter;
package com.rance.chatui.util; /** * 作者:Rance on 2016/11/29 10:47 * 邮箱:[email protected] * 点击表情的全局监听管理类 */ public class GlobalOnItemClickManagerUtils { private static GlobalOnItemClickManagerUtils instance; private EditText mEditText;//输入框 private static Context mContext; public static GlobalOnItemClickManagerUtils getInstance(Context context) { mContext = context; if (instance == null) { synchronized (GlobalOnItemClickManagerUtils.class) { if (instance == null) { instance = new GlobalOnItemClickManagerUtils(); } } } return instance; } public void attachToEditText(EditText editText) { mEditText = editText; } public AdapterView.OnItemClickListener getOnItemClickListener() { return new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Object itemAdapter = parent.getAdapter();
// Path: app/src/main/java/com/rance/chatui/adapter/EmotionGridViewAdapter.java // public class EmotionGridViewAdapter extends BaseAdapter { // // private Context context; // private List<String> emotionNames; // private int itemWidth; // // public EmotionGridViewAdapter(Context context, List<String> emotionNames, int itemWidth) { // this.context = context; // this.emotionNames = emotionNames; // this.itemWidth = itemWidth; // } // // @Override // public int getCount() { // // +1 最后一个为删除按钮 // return emotionNames.size() + 1; // } // // @Override // public String getItem(int position) { // return emotionNames.get(position); // } // // @Override // public long getItemId(int position) { // return position; // } // // @Override // public View getView(int position, View convertView, ViewGroup parent) { // ImageView iv_emotion = new ImageView(context); // // 设置内边距 // iv_emotion.setPadding(itemWidth / 8, itemWidth / 8, itemWidth / 8, itemWidth / 8); // LayoutParams params = new LayoutParams(itemWidth, itemWidth); // iv_emotion.setLayoutParams(params); // // //判断是否为最后一个item // if (position == getCount() - 1) { // iv_emotion.setImageResource(R.drawable.compose_emotion_delete); // } else { // String emotionName = emotionNames.get(position); // iv_emotion.setImageResource(EmotionUtils.EMOTION_STATIC_MAP.get(emotionName)); // } // // return iv_emotion; // } // // } // Path: app/src/main/java/com/rance/chatui/util/GlobalOnItemClickManagerUtils.java import android.content.Context; import android.view.KeyEvent; import android.view.View; import android.widget.AdapterView; import android.widget.EditText; import com.rance.chatui.adapter.EmotionGridViewAdapter; package com.rance.chatui.util; /** * 作者:Rance on 2016/11/29 10:47 * 邮箱:[email protected] * 点击表情的全局监听管理类 */ public class GlobalOnItemClickManagerUtils { private static GlobalOnItemClickManagerUtils instance; private EditText mEditText;//输入框 private static Context mContext; public static GlobalOnItemClickManagerUtils getInstance(Context context) { mContext = context; if (instance == null) { synchronized (GlobalOnItemClickManagerUtils.class) { if (instance == null) { instance = new GlobalOnItemClickManagerUtils(); } } } return instance; } public void attachToEditText(EditText editText) { mEditText = editText; } public AdapterView.OnItemClickListener getOnItemClickListener() { return new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Object itemAdapter = parent.getAdapter();
if (itemAdapter instanceof EmotionGridViewAdapter) {
stridercheng/chatui
app/src/main/java/com/rance/chatui/util/MessageCenter.java
// Path: app/src/main/java/com/rance/chatui/enity/Link.java // public class Link { // String subject, text, stream, url; // // public String getSubject() { // return subject; // } // // public void setSubject(String subject) { // this.subject = subject; // } // // public String getText() { // return text; // } // // public void setText(String text) { // this.text = text; // } // // public String getStream() { // return stream; // } // // public void setStream(String stream) { // this.stream = stream; // } // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // this.url = url; // } // } // // Path: app/src/main/java/com/rance/chatui/enity/MessageInfo.java // public class MessageInfo { // private int type; // private String content; // private String filepath; // private int sendState; // private String time; // private String header; // private long voiceTime; // private String msgId; // private String fileType; // private Object object; // private String mimeType; // // public Object getObject() { // return object; // } // // public void setObject(Object object) { // this.object = object; // } // // public String getFileType() { // return fileType; // } // // public void setFileType(String fileType) { // this.fileType = fileType; // } // // public int getType() { // return type; // } // // public void setType(int type) { // this.type = type; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // public String getFilepath() { // return filepath; // } // // public void setFilepath(String filepath) { // this.filepath = filepath; // } // // public int getSendState() { // return sendState; // } // // public void setSendState(int sendState) { // this.sendState = sendState; // } // // public String getTime() { // return time; // } // // public void setTime(String time) { // this.time = time; // } // // public String getHeader() { // return header; // } // // public void setHeader(String header) { // this.header = header; // } // // public long getVoiceTime() { // return voiceTime; // } // // public void setVoiceTime(long voiceTime) { // this.voiceTime = voiceTime; // } // // public String getMsgId() { // return msgId; // } // // public void setMsgId(String msgId) { // this.msgId = msgId; // } // // public String getMimeType() { // return mimeType; // } // // public void setMimeType(String mimeType) { // this.mimeType = mimeType; // } // // @Override // public String toString() { // return "MessageInfo{" + // "type=" + type + // ", content='" + content + '\'' + // ", filepath='" + filepath + '\'' + // ", sendState=" + sendState + // ", time='" + time + '\'' + // ", header='" + header + '\'' + // ", mimeType='" + mimeType + '\'' + // ", voiceTime=" + voiceTime + // ", msgId='" + msgId + '\'' + // ", fileType='" + fileType + '\'' + // ", object=" + object + // '}'; // } // }
import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.util.Log; import com.rance.chatui.enity.Link; import com.rance.chatui.enity.MessageInfo; import org.greenrobot.eventbus.EventBus;
public final static String MIME_TYPE_DOCX = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"; public final static String MIME_TYPE_PPT = "application/vnd.ms-powerpoint"; public final static String MIME_TYPE_PPTX = "application/vnd.openxmlformats-officedocument.presentationml.presentation"; public final static String MIME_TYPE_TEXT = "text/plain"; /** * process received messages * @param bundle * @param mimeType */ public static void handleIncoming(Bundle bundle, String mimeType, Activity activity) { for (String key : bundle.keySet()) { Log.e(TAG, "handleIncomeAction: " + key + " => " + bundle.get(key) + ";"); } // // Log.e(TAG, "handleIncomeAction: ->" + mimeType); Log.e(TAG, "handleIncoming: mimeType->" + mimeType); if (mimeType == null) { return; } switch (mimeType) { case MIME_TYPE_IMAGE: case MIME_TYPE_IMAGE_JPG: case MIME_TYPE_IMAGE_JPEG: case MIME_TYPE_IMAGE_PNG: case MIME_TYPE_IMAGE_BMP: case MIME_TYPE_IMAGE_OTHER: if (bundle.containsKey("url") && bundle.getString("url") != null && !"" .equals(bundle.getString("url"))) { Log.e(TAG, "handleIncoming: url->" + bundle.getString("url") ); // link
// Path: app/src/main/java/com/rance/chatui/enity/Link.java // public class Link { // String subject, text, stream, url; // // public String getSubject() { // return subject; // } // // public void setSubject(String subject) { // this.subject = subject; // } // // public String getText() { // return text; // } // // public void setText(String text) { // this.text = text; // } // // public String getStream() { // return stream; // } // // public void setStream(String stream) { // this.stream = stream; // } // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // this.url = url; // } // } // // Path: app/src/main/java/com/rance/chatui/enity/MessageInfo.java // public class MessageInfo { // private int type; // private String content; // private String filepath; // private int sendState; // private String time; // private String header; // private long voiceTime; // private String msgId; // private String fileType; // private Object object; // private String mimeType; // // public Object getObject() { // return object; // } // // public void setObject(Object object) { // this.object = object; // } // // public String getFileType() { // return fileType; // } // // public void setFileType(String fileType) { // this.fileType = fileType; // } // // public int getType() { // return type; // } // // public void setType(int type) { // this.type = type; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // public String getFilepath() { // return filepath; // } // // public void setFilepath(String filepath) { // this.filepath = filepath; // } // // public int getSendState() { // return sendState; // } // // public void setSendState(int sendState) { // this.sendState = sendState; // } // // public String getTime() { // return time; // } // // public void setTime(String time) { // this.time = time; // } // // public String getHeader() { // return header; // } // // public void setHeader(String header) { // this.header = header; // } // // public long getVoiceTime() { // return voiceTime; // } // // public void setVoiceTime(long voiceTime) { // this.voiceTime = voiceTime; // } // // public String getMsgId() { // return msgId; // } // // public void setMsgId(String msgId) { // this.msgId = msgId; // } // // public String getMimeType() { // return mimeType; // } // // public void setMimeType(String mimeType) { // this.mimeType = mimeType; // } // // @Override // public String toString() { // return "MessageInfo{" + // "type=" + type + // ", content='" + content + '\'' + // ", filepath='" + filepath + '\'' + // ", sendState=" + sendState + // ", time='" + time + '\'' + // ", header='" + header + '\'' + // ", mimeType='" + mimeType + '\'' + // ", voiceTime=" + voiceTime + // ", msgId='" + msgId + '\'' + // ", fileType='" + fileType + '\'' + // ", object=" + object + // '}'; // } // } // Path: app/src/main/java/com/rance/chatui/util/MessageCenter.java import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.util.Log; import com.rance.chatui.enity.Link; import com.rance.chatui.enity.MessageInfo; import org.greenrobot.eventbus.EventBus; public final static String MIME_TYPE_DOCX = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"; public final static String MIME_TYPE_PPT = "application/vnd.ms-powerpoint"; public final static String MIME_TYPE_PPTX = "application/vnd.openxmlformats-officedocument.presentationml.presentation"; public final static String MIME_TYPE_TEXT = "text/plain"; /** * process received messages * @param bundle * @param mimeType */ public static void handleIncoming(Bundle bundle, String mimeType, Activity activity) { for (String key : bundle.keySet()) { Log.e(TAG, "handleIncomeAction: " + key + " => " + bundle.get(key) + ";"); } // // Log.e(TAG, "handleIncomeAction: ->" + mimeType); Log.e(TAG, "handleIncoming: mimeType->" + mimeType); if (mimeType == null) { return; } switch (mimeType) { case MIME_TYPE_IMAGE: case MIME_TYPE_IMAGE_JPG: case MIME_TYPE_IMAGE_JPEG: case MIME_TYPE_IMAGE_PNG: case MIME_TYPE_IMAGE_BMP: case MIME_TYPE_IMAGE_OTHER: if (bundle.containsKey("url") && bundle.getString("url") != null && !"" .equals(bundle.getString("url"))) { Log.e(TAG, "handleIncoming: url->" + bundle.getString("url") ); // link
MessageInfo messageInfo = new MessageInfo();
stridercheng/chatui
app/src/main/java/com/rance/chatui/util/MessageCenter.java
// Path: app/src/main/java/com/rance/chatui/enity/Link.java // public class Link { // String subject, text, stream, url; // // public String getSubject() { // return subject; // } // // public void setSubject(String subject) { // this.subject = subject; // } // // public String getText() { // return text; // } // // public void setText(String text) { // this.text = text; // } // // public String getStream() { // return stream; // } // // public void setStream(String stream) { // this.stream = stream; // } // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // this.url = url; // } // } // // Path: app/src/main/java/com/rance/chatui/enity/MessageInfo.java // public class MessageInfo { // private int type; // private String content; // private String filepath; // private int sendState; // private String time; // private String header; // private long voiceTime; // private String msgId; // private String fileType; // private Object object; // private String mimeType; // // public Object getObject() { // return object; // } // // public void setObject(Object object) { // this.object = object; // } // // public String getFileType() { // return fileType; // } // // public void setFileType(String fileType) { // this.fileType = fileType; // } // // public int getType() { // return type; // } // // public void setType(int type) { // this.type = type; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // public String getFilepath() { // return filepath; // } // // public void setFilepath(String filepath) { // this.filepath = filepath; // } // // public int getSendState() { // return sendState; // } // // public void setSendState(int sendState) { // this.sendState = sendState; // } // // public String getTime() { // return time; // } // // public void setTime(String time) { // this.time = time; // } // // public String getHeader() { // return header; // } // // public void setHeader(String header) { // this.header = header; // } // // public long getVoiceTime() { // return voiceTime; // } // // public void setVoiceTime(long voiceTime) { // this.voiceTime = voiceTime; // } // // public String getMsgId() { // return msgId; // } // // public void setMsgId(String msgId) { // this.msgId = msgId; // } // // public String getMimeType() { // return mimeType; // } // // public void setMimeType(String mimeType) { // this.mimeType = mimeType; // } // // @Override // public String toString() { // return "MessageInfo{" + // "type=" + type + // ", content='" + content + '\'' + // ", filepath='" + filepath + '\'' + // ", sendState=" + sendState + // ", time='" + time + '\'' + // ", header='" + header + '\'' + // ", mimeType='" + mimeType + '\'' + // ", voiceTime=" + voiceTime + // ", msgId='" + msgId + '\'' + // ", fileType='" + fileType + '\'' + // ", object=" + object + // '}'; // } // }
import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.util.Log; import com.rance.chatui.enity.Link; import com.rance.chatui.enity.MessageInfo; import org.greenrobot.eventbus.EventBus;
public final static String MIME_TYPE_TEXT = "text/plain"; /** * process received messages * @param bundle * @param mimeType */ public static void handleIncoming(Bundle bundle, String mimeType, Activity activity) { for (String key : bundle.keySet()) { Log.e(TAG, "handleIncomeAction: " + key + " => " + bundle.get(key) + ";"); } // // Log.e(TAG, "handleIncomeAction: ->" + mimeType); Log.e(TAG, "handleIncoming: mimeType->" + mimeType); if (mimeType == null) { return; } switch (mimeType) { case MIME_TYPE_IMAGE: case MIME_TYPE_IMAGE_JPG: case MIME_TYPE_IMAGE_JPEG: case MIME_TYPE_IMAGE_PNG: case MIME_TYPE_IMAGE_BMP: case MIME_TYPE_IMAGE_OTHER: if (bundle.containsKey("url") && bundle.getString("url") != null && !"" .equals(bundle.getString("url"))) { Log.e(TAG, "handleIncoming: url->" + bundle.getString("url") ); // link MessageInfo messageInfo = new MessageInfo(); messageInfo.setMimeType(mimeType); messageInfo.setFileType(Constants.CHAT_FILE_TYPE_LINK);
// Path: app/src/main/java/com/rance/chatui/enity/Link.java // public class Link { // String subject, text, stream, url; // // public String getSubject() { // return subject; // } // // public void setSubject(String subject) { // this.subject = subject; // } // // public String getText() { // return text; // } // // public void setText(String text) { // this.text = text; // } // // public String getStream() { // return stream; // } // // public void setStream(String stream) { // this.stream = stream; // } // // public String getUrl() { // return url; // } // // public void setUrl(String url) { // this.url = url; // } // } // // Path: app/src/main/java/com/rance/chatui/enity/MessageInfo.java // public class MessageInfo { // private int type; // private String content; // private String filepath; // private int sendState; // private String time; // private String header; // private long voiceTime; // private String msgId; // private String fileType; // private Object object; // private String mimeType; // // public Object getObject() { // return object; // } // // public void setObject(Object object) { // this.object = object; // } // // public String getFileType() { // return fileType; // } // // public void setFileType(String fileType) { // this.fileType = fileType; // } // // public int getType() { // return type; // } // // public void setType(int type) { // this.type = type; // } // // public String getContent() { // return content; // } // // public void setContent(String content) { // this.content = content; // } // // public String getFilepath() { // return filepath; // } // // public void setFilepath(String filepath) { // this.filepath = filepath; // } // // public int getSendState() { // return sendState; // } // // public void setSendState(int sendState) { // this.sendState = sendState; // } // // public String getTime() { // return time; // } // // public void setTime(String time) { // this.time = time; // } // // public String getHeader() { // return header; // } // // public void setHeader(String header) { // this.header = header; // } // // public long getVoiceTime() { // return voiceTime; // } // // public void setVoiceTime(long voiceTime) { // this.voiceTime = voiceTime; // } // // public String getMsgId() { // return msgId; // } // // public void setMsgId(String msgId) { // this.msgId = msgId; // } // // public String getMimeType() { // return mimeType; // } // // public void setMimeType(String mimeType) { // this.mimeType = mimeType; // } // // @Override // public String toString() { // return "MessageInfo{" + // "type=" + type + // ", content='" + content + '\'' + // ", filepath='" + filepath + '\'' + // ", sendState=" + sendState + // ", time='" + time + '\'' + // ", header='" + header + '\'' + // ", mimeType='" + mimeType + '\'' + // ", voiceTime=" + voiceTime + // ", msgId='" + msgId + '\'' + // ", fileType='" + fileType + '\'' + // ", object=" + object + // '}'; // } // } // Path: app/src/main/java/com/rance/chatui/util/MessageCenter.java import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.util.Log; import com.rance.chatui.enity.Link; import com.rance.chatui.enity.MessageInfo; import org.greenrobot.eventbus.EventBus; public final static String MIME_TYPE_TEXT = "text/plain"; /** * process received messages * @param bundle * @param mimeType */ public static void handleIncoming(Bundle bundle, String mimeType, Activity activity) { for (String key : bundle.keySet()) { Log.e(TAG, "handleIncomeAction: " + key + " => " + bundle.get(key) + ";"); } // // Log.e(TAG, "handleIncomeAction: ->" + mimeType); Log.e(TAG, "handleIncoming: mimeType->" + mimeType); if (mimeType == null) { return; } switch (mimeType) { case MIME_TYPE_IMAGE: case MIME_TYPE_IMAGE_JPG: case MIME_TYPE_IMAGE_JPEG: case MIME_TYPE_IMAGE_PNG: case MIME_TYPE_IMAGE_BMP: case MIME_TYPE_IMAGE_OTHER: if (bundle.containsKey("url") && bundle.getString("url") != null && !"" .equals(bundle.getString("url"))) { Log.e(TAG, "handleIncoming: url->" + bundle.getString("url") ); // link MessageInfo messageInfo = new MessageInfo(); messageInfo.setMimeType(mimeType); messageInfo.setFileType(Constants.CHAT_FILE_TYPE_LINK);
Link link = new Link();
stridercheng/chatui
app/src/main/java/com/rance/chatui/widget/IndicatorView.java
// Path: app/src/main/java/com/rance/chatui/util/Utils.java // public class Utils { // /** // * dp转dip // * // * @param context // * @param dp // * @return // */ // public static int dp2px(Context context, float dp) { // float density = context.getResources().getDisplayMetrics().density; // return (int) (dp * density + 0.5F); // } // // /** // * 文本中的emojb字符处理为表情图片 // * // * @param context // * @param tv // * @param source // * @return // */ // public static SpannableString getEmotionContent(final Context context, final TextView tv, String source) { // SpannableString spannableString = new SpannableString(source); // Resources res = context.getResources(); // // String regexEmotion = "\\[([\u4e00-\u9fa5\\w])+\\]"; // Pattern patternEmotion = Pattern.compile(regexEmotion); // Matcher matcherEmotion = patternEmotion.matcher(spannableString); // // while (matcherEmotion.find()) { // // 获取匹配到的具体字符 // String key = matcherEmotion.group(); // // 匹配字符串的开始位置 // int start = matcherEmotion.start(); // // 利用表情名字获取到对应的图片 // Integer imgRes = EmotionUtils.EMOTION_STATIC_MAP.get(key); // if (imgRes != null) { // // 压缩表情图片 // int size = (int) tv.getTextSize() * 13 / 8; // Bitmap bitmap = BitmapFactory.decodeResource(res, imgRes); // Bitmap scaleBitmap = Bitmap.createScaledBitmap(bitmap, size, size, true); // // ImageSpan span = new ImageSpan(context, scaleBitmap); // spannableString.setSpan(span, start, start + key.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); // } // } // return spannableString; // } // // /** // * 返回当前时间的格式为 yyyyMMddHHmmss // * // * @return // */ // public static String getCurrentTime() { // SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss"); // return sdf.format(System.currentTimeMillis()); // } // // //毫秒转秒 // public static String long2String(long time) { // //毫秒转秒 // int sec = (int) time / 1000; // int min = sec / 60; //分钟 // sec = sec % 60; //秒 // if (min < 10) { //分钟补0 // if (sec < 10) { //秒补0 // return "0" + min + ":0" + sec; // } else { // return "0" + min + ":" + sec; // } // } else { // if (sec < 10) { //秒补0 // return min + ":0" + sec; // } else { // return min + ":" + sec; // } // } // } // // /** // * 毫秒转化时分秒毫秒 // * // * @param ms // * @return // */ // public static String formatTime(Long ms) { // Integer ss = 1000; // Integer mi = ss * 60; // Integer hh = mi * 60; // Integer dd = hh * 24; // // Long day = ms / dd; // Long hour = (ms - day * dd) / hh; // Long minute = (ms - day * dd - hour * hh) / mi; // Long second = (ms - day * dd - hour * hh - minute * mi) / ss; // // StringBuffer sb = new StringBuffer(); // if (day > 0) { // sb.append(day + "d"); // } // if (hour > 0) { // sb.append(hour + "h"); // } // if (minute > 0) { // sb.append(minute + "′"); // } // if (second > 0) { // sb.append(second + "″"); // } // return sb.toString(); // } // }
import android.content.Context; import android.util.AttributeSet; import android.view.View; import android.widget.LinearLayout; import com.rance.chatui.R; import com.rance.chatui.util.Utils; import java.util.ArrayList;
package com.rance.chatui.widget; /** * 作者:Rance on 2016/11/29 10:47 * 邮箱:[email protected] * 自定义表情底部指示器 */ public class IndicatorView extends LinearLayout { private Context mContext; private ArrayList<View> mImageViews;//所有指示器集合 private int size = 6; private int marginSize = 15; private int pointSize;//指示器的大小 private int marginLeft;//间距 public IndicatorView(Context context) { this(context, null); } public IndicatorView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public IndicatorView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); mContext = context;
// Path: app/src/main/java/com/rance/chatui/util/Utils.java // public class Utils { // /** // * dp转dip // * // * @param context // * @param dp // * @return // */ // public static int dp2px(Context context, float dp) { // float density = context.getResources().getDisplayMetrics().density; // return (int) (dp * density + 0.5F); // } // // /** // * 文本中的emojb字符处理为表情图片 // * // * @param context // * @param tv // * @param source // * @return // */ // public static SpannableString getEmotionContent(final Context context, final TextView tv, String source) { // SpannableString spannableString = new SpannableString(source); // Resources res = context.getResources(); // // String regexEmotion = "\\[([\u4e00-\u9fa5\\w])+\\]"; // Pattern patternEmotion = Pattern.compile(regexEmotion); // Matcher matcherEmotion = patternEmotion.matcher(spannableString); // // while (matcherEmotion.find()) { // // 获取匹配到的具体字符 // String key = matcherEmotion.group(); // // 匹配字符串的开始位置 // int start = matcherEmotion.start(); // // 利用表情名字获取到对应的图片 // Integer imgRes = EmotionUtils.EMOTION_STATIC_MAP.get(key); // if (imgRes != null) { // // 压缩表情图片 // int size = (int) tv.getTextSize() * 13 / 8; // Bitmap bitmap = BitmapFactory.decodeResource(res, imgRes); // Bitmap scaleBitmap = Bitmap.createScaledBitmap(bitmap, size, size, true); // // ImageSpan span = new ImageSpan(context, scaleBitmap); // spannableString.setSpan(span, start, start + key.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); // } // } // return spannableString; // } // // /** // * 返回当前时间的格式为 yyyyMMddHHmmss // * // * @return // */ // public static String getCurrentTime() { // SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss"); // return sdf.format(System.currentTimeMillis()); // } // // //毫秒转秒 // public static String long2String(long time) { // //毫秒转秒 // int sec = (int) time / 1000; // int min = sec / 60; //分钟 // sec = sec % 60; //秒 // if (min < 10) { //分钟补0 // if (sec < 10) { //秒补0 // return "0" + min + ":0" + sec; // } else { // return "0" + min + ":" + sec; // } // } else { // if (sec < 10) { //秒补0 // return min + ":0" + sec; // } else { // return min + ":" + sec; // } // } // } // // /** // * 毫秒转化时分秒毫秒 // * // * @param ms // * @return // */ // public static String formatTime(Long ms) { // Integer ss = 1000; // Integer mi = ss * 60; // Integer hh = mi * 60; // Integer dd = hh * 24; // // Long day = ms / dd; // Long hour = (ms - day * dd) / hh; // Long minute = (ms - day * dd - hour * hh) / mi; // Long second = (ms - day * dd - hour * hh - minute * mi) / ss; // // StringBuffer sb = new StringBuffer(); // if (day > 0) { // sb.append(day + "d"); // } // if (hour > 0) { // sb.append(hour + "h"); // } // if (minute > 0) { // sb.append(minute + "′"); // } // if (second > 0) { // sb.append(second + "″"); // } // return sb.toString(); // } // } // Path: app/src/main/java/com/rance/chatui/widget/IndicatorView.java import android.content.Context; import android.util.AttributeSet; import android.view.View; import android.widget.LinearLayout; import com.rance.chatui.R; import com.rance.chatui.util.Utils; import java.util.ArrayList; package com.rance.chatui.widget; /** * 作者:Rance on 2016/11/29 10:47 * 邮箱:[email protected] * 自定义表情底部指示器 */ public class IndicatorView extends LinearLayout { private Context mContext; private ArrayList<View> mImageViews;//所有指示器集合 private int size = 6; private int marginSize = 15; private int pointSize;//指示器的大小 private int marginLeft;//间距 public IndicatorView(Context context) { this(context, null); } public IndicatorView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public IndicatorView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); mContext = context;
pointSize = Utils.dp2px(context, size);
stridercheng/chatui
app/src/main/java/com/rance/chatui/adapter/ContactAdapter.java
// Path: app/src/main/java/com/rance/chatui/enity/IMContact.java // public class IMContact { // String name, phonenumber, surname; // // public IMContact(String name, String phonenumber) { // this.name = name; // this.phonenumber = phonenumber; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getPhonenumber() { // return phonenumber; // } // // public void setPhonenumber(String phonenumber) { // this.phonenumber = phonenumber; // } // // public String getSurname() { // return surname; // } // // public void setSurname(String surname) { // this.surname = surname; // } // }
import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.rance.chatui.R; import com.rance.chatui.enity.IMContact; import java.util.List;
package com.rance.chatui.adapter; /** * Created by chengz * * @date 2017/8/3. */ public class ContactAdapter extends RecyclerView.Adapter<ContactAdapter.ViewHolder> implements View.OnClickListener {
// Path: app/src/main/java/com/rance/chatui/enity/IMContact.java // public class IMContact { // String name, phonenumber, surname; // // public IMContact(String name, String phonenumber) { // this.name = name; // this.phonenumber = phonenumber; // } // // public String getName() { // return name; // } // // public void setName(String name) { // this.name = name; // } // // public String getPhonenumber() { // return phonenumber; // } // // public void setPhonenumber(String phonenumber) { // this.phonenumber = phonenumber; // } // // public String getSurname() { // return surname; // } // // public void setSurname(String surname) { // this.surname = surname; // } // } // Path: app/src/main/java/com/rance/chatui/adapter/ContactAdapter.java import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.rance.chatui.R; import com.rance.chatui.enity.IMContact; import java.util.List; package com.rance.chatui.adapter; /** * Created by chengz * * @date 2017/8/3. */ public class ContactAdapter extends RecyclerView.Adapter<ContactAdapter.ViewHolder> implements View.OnClickListener {
private List<IMContact> imContactList;
stridercheng/chatui
app/src/main/java/com/rance/chatui/ui/activity/FullImageActivity.java
// Path: app/src/main/java/com/rance/chatui/enity/FullImageInfo.java // public class FullImageInfo { // private int locationX; // private int locationY; // private int width; // private int height; // private String imageUrl; // // public int getLocationX() { // return locationX; // } // // public void setLocationX(int locationX) { // this.locationX = locationX; // } // // public int getLocationY() { // return locationY; // } // // public void setLocationY(int locationY) { // this.locationY = locationY; // } // // public int getWidth() { // return width; // } // // public void setWidth(int width) { // this.width = width; // } // // public int getHeight() { // return height; // } // // public void setHeight(int height) { // this.height = height; // } // // public String getImageUrl() { // return imageUrl; // } // // public void setImageUrl(String imageUrl) { // this.imageUrl = imageUrl; // } // }
import android.animation.ObjectAnimator; import android.annotation.TargetApi; import android.app.Activity; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.os.Build; import android.os.Bundle; import android.view.View; import android.view.ViewTreeObserver; import android.view.Window; import android.view.WindowManager; import android.view.animation.DecelerateInterpolator; import android.widget.ImageView; import android.widget.LinearLayout; import com.bumptech.glide.Glide; import com.rance.chatui.R; import com.rance.chatui.enity.FullImageInfo; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import org.greenrobot.eventbus.ThreadMode;
package com.rance.chatui.ui.activity; /** * 作者:Rance on 2016/12/15 15:56 * 邮箱:[email protected] */ public class FullImageActivity extends Activity { ImageView fullImage; LinearLayout fullLay; private int mLeft; private int mTop; private float mScaleX; private float mScaleY; private Drawable mBackground; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.activity_full_image); fullImage = (ImageView) findViewById(R.id.full_image); fullLay = (LinearLayout) findViewById(R.id.full_lay); fullImage.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onImageClick(); } }); EventBus.getDefault().register(this); } @TargetApi(Build.VERSION_CODES.JELLY_BEAN) @Subscribe(threadMode = ThreadMode.MAIN, sticky = true) //在ui线程执行
// Path: app/src/main/java/com/rance/chatui/enity/FullImageInfo.java // public class FullImageInfo { // private int locationX; // private int locationY; // private int width; // private int height; // private String imageUrl; // // public int getLocationX() { // return locationX; // } // // public void setLocationX(int locationX) { // this.locationX = locationX; // } // // public int getLocationY() { // return locationY; // } // // public void setLocationY(int locationY) { // this.locationY = locationY; // } // // public int getWidth() { // return width; // } // // public void setWidth(int width) { // this.width = width; // } // // public int getHeight() { // return height; // } // // public void setHeight(int height) { // this.height = height; // } // // public String getImageUrl() { // return imageUrl; // } // // public void setImageUrl(String imageUrl) { // this.imageUrl = imageUrl; // } // } // Path: app/src/main/java/com/rance/chatui/ui/activity/FullImageActivity.java import android.animation.ObjectAnimator; import android.annotation.TargetApi; import android.app.Activity; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.os.Build; import android.os.Bundle; import android.view.View; import android.view.ViewTreeObserver; import android.view.Window; import android.view.WindowManager; import android.view.animation.DecelerateInterpolator; import android.widget.ImageView; import android.widget.LinearLayout; import com.bumptech.glide.Glide; import com.rance.chatui.R; import com.rance.chatui.enity.FullImageInfo; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import org.greenrobot.eventbus.ThreadMode; package com.rance.chatui.ui.activity; /** * 作者:Rance on 2016/12/15 15:56 * 邮箱:[email protected] */ public class FullImageActivity extends Activity { ImageView fullImage; LinearLayout fullLay; private int mLeft; private int mTop; private float mScaleX; private float mScaleY; private Drawable mBackground; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.activity_full_image); fullImage = (ImageView) findViewById(R.id.full_image); fullLay = (LinearLayout) findViewById(R.id.full_lay); fullImage.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onImageClick(); } }); EventBus.getDefault().register(this); } @TargetApi(Build.VERSION_CODES.JELLY_BEAN) @Subscribe(threadMode = ThreadMode.MAIN, sticky = true) //在ui线程执行
public void onDataSynEvent(final FullImageInfo fullImageInfo) {
stridercheng/chatui
app/src/main/java/com/rance/chatui/util/PhotoUtils.java
// Path: app/src/main/java/com/rance/chatui/base/BaseFragment.java // public class BaseFragment extends Fragment { // public Activity mActivity; // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { // mActivity = getActivity(); // return super.onCreateView(inflater, container, savedInstanceState); // } // // @Override // public void onViewCreated(View view, Bundle savedInstanceState) { // super.onViewCreated(view, savedInstanceState); // mActivity = getActivity(); // } // // public void toastShow(int resId) { // Toast.makeText(mActivity, resId, Toast.LENGTH_SHORT).show(); // } // // public void toastShow(String resId) { // Toast.makeText(mActivity, resId, Toast.LENGTH_SHORT).show(); // } // // public ProgressDialog progressDialog; // // public ProgressDialog showProgressDialog() { // progressDialog = new ProgressDialog(mActivity); // progressDialog.setMessage("加载中"); // progressDialog.show(); // return progressDialog; // } // // public ProgressDialog showProgressDialog(CharSequence message) { // progressDialog = new ProgressDialog(mActivity); // progressDialog.setMessage(message); // progressDialog.show(); // return progressDialog; // } // // public void dismissProgressDialog() { // if (progressDialog != null && progressDialog.isShowing()) { // // progressDialog.hide();会导致android.view.WindowLeaked // progressDialog.dismiss(); // } // } // }
import android.app.Activity; import android.content.Intent; import android.graphics.Bitmap; import android.net.Uri; import android.os.Build; import android.provider.MediaStore; import android.support.v4.app.Fragment; import android.util.Log; import com.rance.chatui.base.BaseFragment;
package com.rance.chatui.util; /** * Created by chengz * * @date 2017/8/1. */ public class PhotoUtils { private static final String TAG = "PhotoUtils"; /** * 拍照方法 * @param baseFragment * @param imageUri * @param requestCodeCamera */
// Path: app/src/main/java/com/rance/chatui/base/BaseFragment.java // public class BaseFragment extends Fragment { // public Activity mActivity; // // @Nullable // @Override // public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { // mActivity = getActivity(); // return super.onCreateView(inflater, container, savedInstanceState); // } // // @Override // public void onViewCreated(View view, Bundle savedInstanceState) { // super.onViewCreated(view, savedInstanceState); // mActivity = getActivity(); // } // // public void toastShow(int resId) { // Toast.makeText(mActivity, resId, Toast.LENGTH_SHORT).show(); // } // // public void toastShow(String resId) { // Toast.makeText(mActivity, resId, Toast.LENGTH_SHORT).show(); // } // // public ProgressDialog progressDialog; // // public ProgressDialog showProgressDialog() { // progressDialog = new ProgressDialog(mActivity); // progressDialog.setMessage("加载中"); // progressDialog.show(); // return progressDialog; // } // // public ProgressDialog showProgressDialog(CharSequence message) { // progressDialog = new ProgressDialog(mActivity); // progressDialog.setMessage(message); // progressDialog.show(); // return progressDialog; // } // // public void dismissProgressDialog() { // if (progressDialog != null && progressDialog.isShowing()) { // // progressDialog.hide();会导致android.view.WindowLeaked // progressDialog.dismiss(); // } // } // } // Path: app/src/main/java/com/rance/chatui/util/PhotoUtils.java import android.app.Activity; import android.content.Intent; import android.graphics.Bitmap; import android.net.Uri; import android.os.Build; import android.provider.MediaStore; import android.support.v4.app.Fragment; import android.util.Log; import com.rance.chatui.base.BaseFragment; package com.rance.chatui.util; /** * Created by chengz * * @date 2017/8/1. */ public class PhotoUtils { private static final String TAG = "PhotoUtils"; /** * 拍照方法 * @param baseFragment * @param imageUri * @param requestCodeCamera */
public static void takePicture(BaseFragment baseFragment, Uri imageUri, int requestCodeCamera) {
chclaus/spring-boot-examples
spring-boot-mapped-supertype/src/test/java/de/chclaus/example/MappedSupertypeTest.java
// Path: spring-boot-mapped-supertype/src/main/java/de/chclaus/example/domain/User.java // @Entity // @Table(name = "t_user") // @Where(clause = "deleted='false'") // @SQLDelete(sql = "UPDATE t_user SET deleted = true WHERE id = ? and version = ?") // public class User extends BaseEntity { // // @Column(length = 100) // private String username; // // @Column(length = 100) // private String password; // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // } // // Path: spring-boot-mapped-supertype/src/main/java/de/chclaus/example/domain/UserRepository.java // public interface UserRepository extends JpaRepository<User, Integer> { // // @Query(value = "SELECT count(u.id) FROM t_user u WHERE u.deleted='true'", nativeQuery = true) // long countDeletedEntries(); // }
import de.chclaus.example.domain.User; import de.chclaus.example.domain.UserRepository; 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.test.context.junit4.SpringJUnit4ClassRunner; import java.sql.Timestamp; import java.util.Date; import java.util.List; import static org.junit.Assert.*;
package de.chclaus.example; /** * Tests for the mapped supertype demo. * * @author chclaus ([email protected]) */ @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = MappedSupertypeApplication.class) public class MappedSupertypeTest { @Autowired
// Path: spring-boot-mapped-supertype/src/main/java/de/chclaus/example/domain/User.java // @Entity // @Table(name = "t_user") // @Where(clause = "deleted='false'") // @SQLDelete(sql = "UPDATE t_user SET deleted = true WHERE id = ? and version = ?") // public class User extends BaseEntity { // // @Column(length = 100) // private String username; // // @Column(length = 100) // private String password; // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // } // // Path: spring-boot-mapped-supertype/src/main/java/de/chclaus/example/domain/UserRepository.java // public interface UserRepository extends JpaRepository<User, Integer> { // // @Query(value = "SELECT count(u.id) FROM t_user u WHERE u.deleted='true'", nativeQuery = true) // long countDeletedEntries(); // } // Path: spring-boot-mapped-supertype/src/test/java/de/chclaus/example/MappedSupertypeTest.java import de.chclaus.example.domain.User; import de.chclaus.example.domain.UserRepository; 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.test.context.junit4.SpringJUnit4ClassRunner; import java.sql.Timestamp; import java.util.Date; import java.util.List; import static org.junit.Assert.*; package de.chclaus.example; /** * Tests for the mapped supertype demo. * * @author chclaus ([email protected]) */ @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = MappedSupertypeApplication.class) public class MappedSupertypeTest { @Autowired
private UserRepository userRepository;
chclaus/spring-boot-examples
spring-boot-mapped-supertype/src/test/java/de/chclaus/example/MappedSupertypeTest.java
// Path: spring-boot-mapped-supertype/src/main/java/de/chclaus/example/domain/User.java // @Entity // @Table(name = "t_user") // @Where(clause = "deleted='false'") // @SQLDelete(sql = "UPDATE t_user SET deleted = true WHERE id = ? and version = ?") // public class User extends BaseEntity { // // @Column(length = 100) // private String username; // // @Column(length = 100) // private String password; // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // } // // Path: spring-boot-mapped-supertype/src/main/java/de/chclaus/example/domain/UserRepository.java // public interface UserRepository extends JpaRepository<User, Integer> { // // @Query(value = "SELECT count(u.id) FROM t_user u WHERE u.deleted='true'", nativeQuery = true) // long countDeletedEntries(); // }
import de.chclaus.example.domain.User; import de.chclaus.example.domain.UserRepository; 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.test.context.junit4.SpringJUnit4ClassRunner; import java.sql.Timestamp; import java.util.Date; import java.util.List; import static org.junit.Assert.*;
package de.chclaus.example; /** * Tests for the mapped supertype demo. * * @author chclaus ([email protected]) */ @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = MappedSupertypeApplication.class) public class MappedSupertypeTest { @Autowired private UserRepository userRepository; /** * Tests if last modified date and creation date will be injected automatically * to the entity */ @Test public void testMappedSupertypeWithAuditing() {
// Path: spring-boot-mapped-supertype/src/main/java/de/chclaus/example/domain/User.java // @Entity // @Table(name = "t_user") // @Where(clause = "deleted='false'") // @SQLDelete(sql = "UPDATE t_user SET deleted = true WHERE id = ? and version = ?") // public class User extends BaseEntity { // // @Column(length = 100) // private String username; // // @Column(length = 100) // private String password; // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // } // // Path: spring-boot-mapped-supertype/src/main/java/de/chclaus/example/domain/UserRepository.java // public interface UserRepository extends JpaRepository<User, Integer> { // // @Query(value = "SELECT count(u.id) FROM t_user u WHERE u.deleted='true'", nativeQuery = true) // long countDeletedEntries(); // } // Path: spring-boot-mapped-supertype/src/test/java/de/chclaus/example/MappedSupertypeTest.java import de.chclaus.example.domain.User; import de.chclaus.example.domain.UserRepository; 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.test.context.junit4.SpringJUnit4ClassRunner; import java.sql.Timestamp; import java.util.Date; import java.util.List; import static org.junit.Assert.*; package de.chclaus.example; /** * Tests for the mapped supertype demo. * * @author chclaus ([email protected]) */ @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = MappedSupertypeApplication.class) public class MappedSupertypeTest { @Autowired private UserRepository userRepository; /** * Tests if last modified date and creation date will be injected automatically * to the entity */ @Test public void testMappedSupertypeWithAuditing() {
User user = new User();
chclaus/spring-boot-examples
spring-boot-jpa-optimistic-locking/src/test/java/de/chclaus/example/OptimisticLockingApplicationTests.java
// Path: spring-boot-jpa-optimistic-locking/src/main/java/de/chclaus/example/domain/Movie.java // @Entity // @Table(name = "t_movie") // public class Movie implements Serializable { // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // private Integer id; // // @Version // private Integer version; // // private String title; // // private Integer rating; // // // public Movie() { // // empty constructor for (de)serialization // } // // public Movie(String title, Integer rating) { // this.title = title; // this.rating = rating; // } // // public Integer getId() { // return id; // } // // public Movie setId(Integer id) { // this.id = id; // return this; // } // // public Integer getVersion() { // return version; // } // // public Movie setVersion(Integer version) { // this.version = version; // return this; // } // // public String getTitle() { // return title; // } // // public Movie setTitle(String title) { // this.title = title; // return this; // } // // public Integer getRating() { // return rating; // } // // public Movie setRating(Integer rating) { // this.rating = rating; // return this; // } // } // // Path: spring-boot-jpa-optimistic-locking/src/main/java/de/chclaus/example/domain/MovieRepository.java // public interface MovieRepository extends CrudRepository<Movie, Integer> { // // Movie findByTitle(String title); // }
import de.chclaus.example.domain.Movie; import de.chclaus.example.domain.MovieRepository; import org.junit.Before; 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.orm.ObjectOptimisticLockingFailureException; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import static org.junit.Assert.assertEquals;
package de.chclaus.example; /** * @author Christian Claus ([email protected]) */ @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = OptimisticLockingApplication.class) public class OptimisticLockingApplicationTests { @Autowired
// Path: spring-boot-jpa-optimistic-locking/src/main/java/de/chclaus/example/domain/Movie.java // @Entity // @Table(name = "t_movie") // public class Movie implements Serializable { // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // private Integer id; // // @Version // private Integer version; // // private String title; // // private Integer rating; // // // public Movie() { // // empty constructor for (de)serialization // } // // public Movie(String title, Integer rating) { // this.title = title; // this.rating = rating; // } // // public Integer getId() { // return id; // } // // public Movie setId(Integer id) { // this.id = id; // return this; // } // // public Integer getVersion() { // return version; // } // // public Movie setVersion(Integer version) { // this.version = version; // return this; // } // // public String getTitle() { // return title; // } // // public Movie setTitle(String title) { // this.title = title; // return this; // } // // public Integer getRating() { // return rating; // } // // public Movie setRating(Integer rating) { // this.rating = rating; // return this; // } // } // // Path: spring-boot-jpa-optimistic-locking/src/main/java/de/chclaus/example/domain/MovieRepository.java // public interface MovieRepository extends CrudRepository<Movie, Integer> { // // Movie findByTitle(String title); // } // Path: spring-boot-jpa-optimistic-locking/src/test/java/de/chclaus/example/OptimisticLockingApplicationTests.java import de.chclaus.example.domain.Movie; import de.chclaus.example.domain.MovieRepository; import org.junit.Before; 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.orm.ObjectOptimisticLockingFailureException; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import static org.junit.Assert.assertEquals; package de.chclaus.example; /** * @author Christian Claus ([email protected]) */ @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = OptimisticLockingApplication.class) public class OptimisticLockingApplicationTests { @Autowired
private MovieRepository movieRepository;
chclaus/spring-boot-examples
spring-boot-jpa-optimistic-locking/src/test/java/de/chclaus/example/OptimisticLockingApplicationTests.java
// Path: spring-boot-jpa-optimistic-locking/src/main/java/de/chclaus/example/domain/Movie.java // @Entity // @Table(name = "t_movie") // public class Movie implements Serializable { // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // private Integer id; // // @Version // private Integer version; // // private String title; // // private Integer rating; // // // public Movie() { // // empty constructor for (de)serialization // } // // public Movie(String title, Integer rating) { // this.title = title; // this.rating = rating; // } // // public Integer getId() { // return id; // } // // public Movie setId(Integer id) { // this.id = id; // return this; // } // // public Integer getVersion() { // return version; // } // // public Movie setVersion(Integer version) { // this.version = version; // return this; // } // // public String getTitle() { // return title; // } // // public Movie setTitle(String title) { // this.title = title; // return this; // } // // public Integer getRating() { // return rating; // } // // public Movie setRating(Integer rating) { // this.rating = rating; // return this; // } // } // // Path: spring-boot-jpa-optimistic-locking/src/main/java/de/chclaus/example/domain/MovieRepository.java // public interface MovieRepository extends CrudRepository<Movie, Integer> { // // Movie findByTitle(String title); // }
import de.chclaus.example.domain.Movie; import de.chclaus.example.domain.MovieRepository; import org.junit.Before; 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.orm.ObjectOptimisticLockingFailureException; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import static org.junit.Assert.assertEquals;
package de.chclaus.example; /** * @author Christian Claus ([email protected]) */ @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = OptimisticLockingApplication.class) public class OptimisticLockingApplicationTests { @Autowired private MovieRepository movieRepository; @Before public void setUp() throws Exception {
// Path: spring-boot-jpa-optimistic-locking/src/main/java/de/chclaus/example/domain/Movie.java // @Entity // @Table(name = "t_movie") // public class Movie implements Serializable { // // @Id // @GeneratedValue(strategy = GenerationType.AUTO) // private Integer id; // // @Version // private Integer version; // // private String title; // // private Integer rating; // // // public Movie() { // // empty constructor for (de)serialization // } // // public Movie(String title, Integer rating) { // this.title = title; // this.rating = rating; // } // // public Integer getId() { // return id; // } // // public Movie setId(Integer id) { // this.id = id; // return this; // } // // public Integer getVersion() { // return version; // } // // public Movie setVersion(Integer version) { // this.version = version; // return this; // } // // public String getTitle() { // return title; // } // // public Movie setTitle(String title) { // this.title = title; // return this; // } // // public Integer getRating() { // return rating; // } // // public Movie setRating(Integer rating) { // this.rating = rating; // return this; // } // } // // Path: spring-boot-jpa-optimistic-locking/src/main/java/de/chclaus/example/domain/MovieRepository.java // public interface MovieRepository extends CrudRepository<Movie, Integer> { // // Movie findByTitle(String title); // } // Path: spring-boot-jpa-optimistic-locking/src/test/java/de/chclaus/example/OptimisticLockingApplicationTests.java import de.chclaus.example.domain.Movie; import de.chclaus.example.domain.MovieRepository; import org.junit.Before; 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.orm.ObjectOptimisticLockingFailureException; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import static org.junit.Assert.assertEquals; package de.chclaus.example; /** * @author Christian Claus ([email protected]) */ @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = OptimisticLockingApplication.class) public class OptimisticLockingApplicationTests { @Autowired private MovieRepository movieRepository; @Before public void setUp() throws Exception {
movieRepository.save(new Movie("The great movie", 5));
chclaus/spring-boot-examples
spring-boot-mapped-supertype/src/test/java/de/chclaus/example/DeleteRepositoryTest.java
// Path: spring-boot-mapped-supertype/src/main/java/de/chclaus/example/domain/User.java // @Entity // @Table(name = "t_user") // @Where(clause = "deleted='false'") // @SQLDelete(sql = "UPDATE t_user SET deleted = true WHERE id = ? and version = ?") // public class User extends BaseEntity { // // @Column(length = 100) // private String username; // // @Column(length = 100) // private String password; // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // } // // Path: spring-boot-mapped-supertype/src/main/java/de/chclaus/example/domain/UserRepository.java // public interface UserRepository extends JpaRepository<User, Integer> { // // @Query(value = "SELECT count(u.id) FROM t_user u WHERE u.deleted='true'", nativeQuery = true) // long countDeletedEntries(); // }
import de.chclaus.example.domain.User; import de.chclaus.example.domain.UserRepository; import org.junit.Assert; 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.test.context.junit4.SpringJUnit4ClassRunner; import static org.junit.Assert.*;
package de.chclaus.example; /** * Test to validate the correctness of the soft-delete implementation. * * @author Christian Claus ([email protected]) */ @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = MappedSupertypeApplication.class) public class DeleteRepositoryTest { @Autowired
// Path: spring-boot-mapped-supertype/src/main/java/de/chclaus/example/domain/User.java // @Entity // @Table(name = "t_user") // @Where(clause = "deleted='false'") // @SQLDelete(sql = "UPDATE t_user SET deleted = true WHERE id = ? and version = ?") // public class User extends BaseEntity { // // @Column(length = 100) // private String username; // // @Column(length = 100) // private String password; // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // } // // Path: spring-boot-mapped-supertype/src/main/java/de/chclaus/example/domain/UserRepository.java // public interface UserRepository extends JpaRepository<User, Integer> { // // @Query(value = "SELECT count(u.id) FROM t_user u WHERE u.deleted='true'", nativeQuery = true) // long countDeletedEntries(); // } // Path: spring-boot-mapped-supertype/src/test/java/de/chclaus/example/DeleteRepositoryTest.java import de.chclaus.example.domain.User; import de.chclaus.example.domain.UserRepository; import org.junit.Assert; 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.test.context.junit4.SpringJUnit4ClassRunner; import static org.junit.Assert.*; package de.chclaus.example; /** * Test to validate the correctness of the soft-delete implementation. * * @author Christian Claus ([email protected]) */ @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = MappedSupertypeApplication.class) public class DeleteRepositoryTest { @Autowired
private UserRepository userRepository;
chclaus/spring-boot-examples
spring-boot-mapped-supertype/src/test/java/de/chclaus/example/DeleteRepositoryTest.java
// Path: spring-boot-mapped-supertype/src/main/java/de/chclaus/example/domain/User.java // @Entity // @Table(name = "t_user") // @Where(clause = "deleted='false'") // @SQLDelete(sql = "UPDATE t_user SET deleted = true WHERE id = ? and version = ?") // public class User extends BaseEntity { // // @Column(length = 100) // private String username; // // @Column(length = 100) // private String password; // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // } // // Path: spring-boot-mapped-supertype/src/main/java/de/chclaus/example/domain/UserRepository.java // public interface UserRepository extends JpaRepository<User, Integer> { // // @Query(value = "SELECT count(u.id) FROM t_user u WHERE u.deleted='true'", nativeQuery = true) // long countDeletedEntries(); // }
import de.chclaus.example.domain.User; import de.chclaus.example.domain.UserRepository; import org.junit.Assert; 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.test.context.junit4.SpringJUnit4ClassRunner; import static org.junit.Assert.*;
package de.chclaus.example; /** * Test to validate the correctness of the soft-delete implementation. * * @author Christian Claus ([email protected]) */ @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = MappedSupertypeApplication.class) public class DeleteRepositoryTest { @Autowired private UserRepository userRepository; @Test public void testDeletion() throws Exception { // Validates if there are no users in the repository. assertEquals(0, userRepository.count()); assertEquals(0, userRepository.countDeletedEntries()); // Creates a new user and saves it.
// Path: spring-boot-mapped-supertype/src/main/java/de/chclaus/example/domain/User.java // @Entity // @Table(name = "t_user") // @Where(clause = "deleted='false'") // @SQLDelete(sql = "UPDATE t_user SET deleted = true WHERE id = ? and version = ?") // public class User extends BaseEntity { // // @Column(length = 100) // private String username; // // @Column(length = 100) // private String password; // // public String getUsername() { // return username; // } // // public void setUsername(String username) { // this.username = username; // } // // public String getPassword() { // return password; // } // // public void setPassword(String password) { // this.password = password; // } // } // // Path: spring-boot-mapped-supertype/src/main/java/de/chclaus/example/domain/UserRepository.java // public interface UserRepository extends JpaRepository<User, Integer> { // // @Query(value = "SELECT count(u.id) FROM t_user u WHERE u.deleted='true'", nativeQuery = true) // long countDeletedEntries(); // } // Path: spring-boot-mapped-supertype/src/test/java/de/chclaus/example/DeleteRepositoryTest.java import de.chclaus.example.domain.User; import de.chclaus.example.domain.UserRepository; import org.junit.Assert; 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.test.context.junit4.SpringJUnit4ClassRunner; import static org.junit.Assert.*; package de.chclaus.example; /** * Test to validate the correctness of the soft-delete implementation. * * @author Christian Claus ([email protected]) */ @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = MappedSupertypeApplication.class) public class DeleteRepositoryTest { @Autowired private UserRepository userRepository; @Test public void testDeletion() throws Exception { // Validates if there are no users in the repository. assertEquals(0, userRepository.count()); assertEquals(0, userRepository.countDeletedEntries()); // Creates a new user and saves it.
User user = new User();
chclaus/spring-boot-examples
spring-boot-error-handling/src/main/java/de/chclaus/examples/controller/user/UserController.java
// Path: spring-boot-error-handling/src/main/java/de/chclaus/examples/service/user/UserService.java // @Service // public class UserService { // // /** // * Method to demonstrate a fake user lookup. // * @param username The username... There is just an admin account. // * @return a DTO representation of an user. // */ // public UserDTO findUserByName(String username) { // // // We just have an administrator account. Nothing else. ;) // if ("admin".equals(username)) { // return new UserDTO(username); // } // // throw new UsernameNotFoundException(String.format("Username not found. username=%s", username)); // } // }
import de.chclaus.examples.service.user.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController;
package de.chclaus.examples.controller.user; /** * An example controller to demonstrate exception (error) handling. * * @author Christian Claus ([email protected]) */ @RestController public class UserController { @Autowired
// Path: spring-boot-error-handling/src/main/java/de/chclaus/examples/service/user/UserService.java // @Service // public class UserService { // // /** // * Method to demonstrate a fake user lookup. // * @param username The username... There is just an admin account. // * @return a DTO representation of an user. // */ // public UserDTO findUserByName(String username) { // // // We just have an administrator account. Nothing else. ;) // if ("admin".equals(username)) { // return new UserDTO(username); // } // // throw new UsernameNotFoundException(String.format("Username not found. username=%s", username)); // } // } // Path: spring-boot-error-handling/src/main/java/de/chclaus/examples/controller/user/UserController.java import de.chclaus.examples.service.user.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; package de.chclaus.examples.controller.user; /** * An example controller to demonstrate exception (error) handling. * * @author Christian Claus ([email protected]) */ @RestController public class UserController { @Autowired
private UserService userService;
chclaus/spring-boot-examples
spring-boot-error-handling/src/main/java/de/chclaus/examples/service/user/UserService.java
// Path: spring-boot-error-handling/src/main/java/de/chclaus/examples/controller/user/UserDTO.java // public class UserDTO implements Serializable { // // private String username; // // public UserDTO() { // // Empty for deserialization // } // // public UserDTO(String username) { // this.username = username; // } // // public String getUsername() { // return username; // } // // public UserDTO setUsername(String username) { // this.username = username; // return this; // } // }
import de.chclaus.examples.controller.user.UserDTO; import org.springframework.stereotype.Service;
package de.chclaus.examples.service.user; /** * Simple service to demonstrate exception handling. * * @author Christian Claus ([email protected]) */ @Service public class UserService { /** * Method to demonstrate a fake user lookup. * @param username The username... There is just an admin account. * @return a DTO representation of an user. */
// Path: spring-boot-error-handling/src/main/java/de/chclaus/examples/controller/user/UserDTO.java // public class UserDTO implements Serializable { // // private String username; // // public UserDTO() { // // Empty for deserialization // } // // public UserDTO(String username) { // this.username = username; // } // // public String getUsername() { // return username; // } // // public UserDTO setUsername(String username) { // this.username = username; // return this; // } // } // Path: spring-boot-error-handling/src/main/java/de/chclaus/examples/service/user/UserService.java import de.chclaus.examples.controller.user.UserDTO; import org.springframework.stereotype.Service; package de.chclaus.examples.service.user; /** * Simple service to demonstrate exception handling. * * @author Christian Claus ([email protected]) */ @Service public class UserService { /** * Method to demonstrate a fake user lookup. * @param username The username... There is just an admin account. * @return a DTO representation of an user. */
public UserDTO findUserByName(String username) {
cuplv/droidel
stubs/src/android/view/View.java
// Path: stubs/src/android/app/ActivityThread.java // public static DroidelStubs droidelStubs;
import static android.app.ActivityThread.droidelStubs; import android.content.ClipData; import android.content.Context; import android.content.res.Configuration; import android.content.res.Resources; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.Camera; import android.graphics.Canvas; import android.graphics.Insets; import android.graphics.Interpolator; import android.graphics.LinearGradient; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.PixelFormat; import android.graphics.Point; import android.graphics.PorterDuff; import android.graphics.PorterDuffXfermode; import android.graphics.Rect; import android.graphics.RectF; import android.graphics.Region; import android.graphics.Shader; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.hardware.display.DisplayManagerGlobal; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.os.Parcel; import android.os.Parcelable; import android.os.RemoteException; import android.os.SystemClock; import android.os.SystemProperties; import android.text.TextUtils; import android.util.AttributeSet; import android.util.FloatProperty; import android.util.LayoutDirection; import android.util.Log; import android.util.LongSparseLongArray; import android.util.Pools.SynchronizedPool; import android.util.Property; import android.util.SparseArray; import android.util.SuperNotCalledException; import android.util.TypedValue; import android.view.ContextMenu.ContextMenuInfo; import android.view.AccessibilityIterators.TextSegmentIterator; import android.view.AccessibilityIterators.CharacterTextSegmentIterator; import android.view.AccessibilityIterators.WordTextSegmentIterator; import android.view.AccessibilityIterators.ParagraphTextSegmentIterator; import android.view.accessibility.AccessibilityEvent; import android.view.accessibility.AccessibilityEventSource; import android.view.accessibility.AccessibilityManager; import android.view.accessibility.AccessibilityNodeInfo; import android.view.accessibility.AccessibilityNodeProvider; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.view.animation.Transformation; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputConnection; import android.view.inputmethod.InputMethodManager; import android.widget.ScrollBarDrawable; import static android.os.Build.VERSION_CODES.*; import static java.lang.Math.max; import com.android.internal.R; import com.android.internal.util.Predicate; import com.android.internal.view.menu.MenuBuilder; import java.lang.ref.WeakReference; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Locale; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.atomic.AtomicInteger;
mMinHeight = a.getDimensionPixelSize(attr, 0); break; case R.styleable.View_onClick: if (context.isRestricted()) { throw new IllegalStateException("The android:onClick attribute cannot " + "be used within a restricted context"); } final String handlerName = a.getString(attr); if (handlerName != null) { setOnClickListener(new OnClickListener() { private Method mHandler; public void onClick(View v) { if (mHandler == null) { try { mHandler = getContext().getClass().getMethod(handlerName, View.class); } catch (NoSuchMethodException e) { int id = getId(); String idText = id == NO_ID ? "" : " with id '" + getContext().getResources().getResourceEntryName( id) + "'"; throw new IllegalStateException("Could not find a method " + handlerName + "(View) in the activity " + getContext().getClass() + " for onClick handler" + " on view " + View.this.getClass() + idText, e); } }
// Path: stubs/src/android/app/ActivityThread.java // public static DroidelStubs droidelStubs; // Path: stubs/src/android/view/View.java import static android.app.ActivityThread.droidelStubs; import android.content.ClipData; import android.content.Context; import android.content.res.Configuration; import android.content.res.Resources; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.Camera; import android.graphics.Canvas; import android.graphics.Insets; import android.graphics.Interpolator; import android.graphics.LinearGradient; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.PixelFormat; import android.graphics.Point; import android.graphics.PorterDuff; import android.graphics.PorterDuffXfermode; import android.graphics.Rect; import android.graphics.RectF; import android.graphics.Region; import android.graphics.Shader; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.hardware.display.DisplayManagerGlobal; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.os.Parcel; import android.os.Parcelable; import android.os.RemoteException; import android.os.SystemClock; import android.os.SystemProperties; import android.text.TextUtils; import android.util.AttributeSet; import android.util.FloatProperty; import android.util.LayoutDirection; import android.util.Log; import android.util.LongSparseLongArray; import android.util.Pools.SynchronizedPool; import android.util.Property; import android.util.SparseArray; import android.util.SuperNotCalledException; import android.util.TypedValue; import android.view.ContextMenu.ContextMenuInfo; import android.view.AccessibilityIterators.TextSegmentIterator; import android.view.AccessibilityIterators.CharacterTextSegmentIterator; import android.view.AccessibilityIterators.WordTextSegmentIterator; import android.view.AccessibilityIterators.ParagraphTextSegmentIterator; import android.view.accessibility.AccessibilityEvent; import android.view.accessibility.AccessibilityEventSource; import android.view.accessibility.AccessibilityManager; import android.view.accessibility.AccessibilityNodeInfo; import android.view.accessibility.AccessibilityNodeProvider; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.view.animation.Transformation; import android.view.inputmethod.EditorInfo; import android.view.inputmethod.InputConnection; import android.view.inputmethod.InputMethodManager; import android.widget.ScrollBarDrawable; import static android.os.Build.VERSION_CODES.*; import static java.lang.Math.max; import com.android.internal.R; import com.android.internal.util.Predicate; import com.android.internal.view.menu.MenuBuilder; import java.lang.ref.WeakReference; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Locale; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.atomic.AtomicInteger; mMinHeight = a.getDimensionPixelSize(attr, 0); break; case R.styleable.View_onClick: if (context.isRestricted()) { throw new IllegalStateException("The android:onClick attribute cannot " + "be used within a restricted context"); } final String handlerName = a.getString(attr); if (handlerName != null) { setOnClickListener(new OnClickListener() { private Method mHandler; public void onClick(View v) { if (mHandler == null) { try { mHandler = getContext().getClass().getMethod(handlerName, View.class); } catch (NoSuchMethodException e) { int id = getId(); String idText = id == NO_ID ? "" : " with id '" + getContext().getResources().getResourceEntryName( id) + "'"; throw new IllegalStateException("Could not find a method " + handlerName + "(View) in the activity " + getContext().getClass() + " for onClick handler" + " on view " + View.this.getClass() + idText, e); } }
droidelStubs.callXMLRegisteredCallback(getContext(), View.this);
cuplv/droidel
stubs/src/android/app/Instrumentation.java
// Path: stubs/src/android/app/ActivityThread.java // public static DroidelStubs droidelStubs;
import static android.app.ActivityThread.droidelStubs; import android.content.ActivityNotFoundException; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.ActivityInfo; import android.content.res.Configuration; import android.hardware.input.InputManager; import android.os.Bundle; import android.os.Debug; import android.os.IBinder; import android.os.Looper; import android.os.MessageQueue; import android.os.PerformanceCollector; import android.os.Process; import android.os.RemoteException; import android.os.ServiceManager; import android.os.SystemClock; import android.os.UserHandle; import android.util.AndroidRuntimeException; import android.util.Log; import android.view.IWindowManager; import android.view.InputDevice; import android.view.KeyCharacterMap; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.ViewConfiguration; import android.view.Window; import java.io.File; import java.util.ArrayList; import java.util.List;
* to update its display as a result, it may still be in the process of * doing that. * * @param event A motion event describing the trackball action. (As noted in * {@link MotionEvent#obtain(long, long, int, float, float, int)}, be sure to use * {@link SystemClock#uptimeMillis()} as the timebase. */ public void sendTrackballEventSync(MotionEvent event) { validateNotAppThread(); if ((event.getSource() & InputDevice.SOURCE_CLASS_TRACKBALL) == 0) { event.setSource(InputDevice.SOURCE_TRACKBALL); } InputManager.getInstance().injectInputEvent(event, InputManager.INJECT_INPUT_EVENT_MODE_WAIT_FOR_FINISH); } /** * Perform instantiation of the process's {@link Application} object. The * default implementation provides the normal system behavior. * * @param cl The ClassLoader with which to instantiate the object. * @param className The name of the class implementing the Application * object. * @param context The context to initialize the application with * * @return The newly instantiated Application object. */ public Application newApplication(ClassLoader cl, String className, Context context) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
// Path: stubs/src/android/app/ActivityThread.java // public static DroidelStubs droidelStubs; // Path: stubs/src/android/app/Instrumentation.java import static android.app.ActivityThread.droidelStubs; import android.content.ActivityNotFoundException; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.ActivityInfo; import android.content.res.Configuration; import android.hardware.input.InputManager; import android.os.Bundle; import android.os.Debug; import android.os.IBinder; import android.os.Looper; import android.os.MessageQueue; import android.os.PerformanceCollector; import android.os.Process; import android.os.RemoteException; import android.os.ServiceManager; import android.os.SystemClock; import android.os.UserHandle; import android.util.AndroidRuntimeException; import android.util.Log; import android.view.IWindowManager; import android.view.InputDevice; import android.view.KeyCharacterMap; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.ViewConfiguration; import android.view.Window; import java.io.File; import java.util.ArrayList; import java.util.List; * to update its display as a result, it may still be in the process of * doing that. * * @param event A motion event describing the trackball action. (As noted in * {@link MotionEvent#obtain(long, long, int, float, float, int)}, be sure to use * {@link SystemClock#uptimeMillis()} as the timebase. */ public void sendTrackballEventSync(MotionEvent event) { validateNotAppThread(); if ((event.getSource() & InputDevice.SOURCE_CLASS_TRACKBALL) == 0) { event.setSource(InputDevice.SOURCE_TRACKBALL); } InputManager.getInstance().injectInputEvent(event, InputManager.INJECT_INPUT_EVENT_MODE_WAIT_FOR_FINISH); } /** * Perform instantiation of the process's {@link Application} object. The * default implementation provides the normal system behavior. * * @param cl The ClassLoader with which to instantiate the object. * @param className The name of the class implementing the Application * object. * @param context The context to initialize the application with * * @return The newly instantiated Application object. */ public Application newApplication(ClassLoader cl, String className, Context context) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
return droidelStubs.getApplication(className);
dkharrat/NexusData
nexusdata/src/main/java/com/github/dkharrat/nexusdata/predicate/parser/NameParselet.java
// Path: nexusdata/src/main/java/com/github/dkharrat/nexusdata/predicate/Expression.java // public interface Expression<T> { // // public <V> V accept(ExpressionVisitor<V> visitor); // public T evaluate(Object object); // } // // Path: nexusdata/src/main/java/com/github/dkharrat/nexusdata/predicate/FieldPathExpression.java // public class FieldPathExpression implements Expression<Object> { // // private final String fieldPath; // // public FieldPathExpression(String fieldPath) { // this.fieldPath = fieldPath; // } // // public String getFieldPath() { // return fieldPath; // } // // @Override // public <T> T accept(ExpressionVisitor<T> visitor) { // return visitor.visit(this); // } // // @Override // public Object evaluate(Object object) { // try { // if (object instanceof ManagedObject) { // return ((ManagedObject)object).getValue(fieldPath); // } else { // Field field = object.getClass().getDeclaredField(fieldPath); // field.setAccessible(true); // return field.get(object); // } // } catch (Exception e) { // throw new RuntimeException(e); // } // } // // @Override // public String toString() { // return fieldPath; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // FieldPathExpression that = (FieldPathExpression) o; // // if (!fieldPath.equals(that.fieldPath)) return false; // // return true; // } // // @Override // public int hashCode() { // return fieldPath.hashCode(); // } // } // // Path: nexusdata/src/main/java/com/github/dkharrat/nexusdata/predicate/parser/PredicateParser.java // public static enum TokenType { // AND, // OR, // OPEN_PAREN, // CLOSE_PAREN, // EQUAL, // GREATER_THAN_OR_EQUAL, // LESS_THAN_OR_EQUAL, // NOT_EQUAL, // GREATER_THAN, // LESS_THAN, // FIELD_NAME, // CONSTANT, // EOF // }
import com.github.dkharrat.nexusdata.predicate.Expression; import com.github.dkharrat.nexusdata.predicate.FieldPathExpression; import static com.github.dkharrat.nexusdata.predicate.parser.PredicateParser.TokenType;
package com.github.dkharrat.nexusdata.predicate.parser; class NameParselet implements PrefixParselet<TokenType,Expression<?>> { public Expression<?> parse(Parser<TokenType,Expression<?>> parser, Token<TokenType> token) {
// Path: nexusdata/src/main/java/com/github/dkharrat/nexusdata/predicate/Expression.java // public interface Expression<T> { // // public <V> V accept(ExpressionVisitor<V> visitor); // public T evaluate(Object object); // } // // Path: nexusdata/src/main/java/com/github/dkharrat/nexusdata/predicate/FieldPathExpression.java // public class FieldPathExpression implements Expression<Object> { // // private final String fieldPath; // // public FieldPathExpression(String fieldPath) { // this.fieldPath = fieldPath; // } // // public String getFieldPath() { // return fieldPath; // } // // @Override // public <T> T accept(ExpressionVisitor<T> visitor) { // return visitor.visit(this); // } // // @Override // public Object evaluate(Object object) { // try { // if (object instanceof ManagedObject) { // return ((ManagedObject)object).getValue(fieldPath); // } else { // Field field = object.getClass().getDeclaredField(fieldPath); // field.setAccessible(true); // return field.get(object); // } // } catch (Exception e) { // throw new RuntimeException(e); // } // } // // @Override // public String toString() { // return fieldPath; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // FieldPathExpression that = (FieldPathExpression) o; // // if (!fieldPath.equals(that.fieldPath)) return false; // // return true; // } // // @Override // public int hashCode() { // return fieldPath.hashCode(); // } // } // // Path: nexusdata/src/main/java/com/github/dkharrat/nexusdata/predicate/parser/PredicateParser.java // public static enum TokenType { // AND, // OR, // OPEN_PAREN, // CLOSE_PAREN, // EQUAL, // GREATER_THAN_OR_EQUAL, // LESS_THAN_OR_EQUAL, // NOT_EQUAL, // GREATER_THAN, // LESS_THAN, // FIELD_NAME, // CONSTANT, // EOF // } // Path: nexusdata/src/main/java/com/github/dkharrat/nexusdata/predicate/parser/NameParselet.java import com.github.dkharrat.nexusdata.predicate.Expression; import com.github.dkharrat.nexusdata.predicate.FieldPathExpression; import static com.github.dkharrat.nexusdata.predicate.parser.PredicateParser.TokenType; package com.github.dkharrat.nexusdata.predicate.parser; class NameParselet implements PrefixParselet<TokenType,Expression<?>> { public Expression<?> parse(Parser<TokenType,Expression<?>> parser, Token<TokenType> token) {
return new FieldPathExpression(token.getText());
dkharrat/NexusData
nexusdata/src/main/java/com/github/dkharrat/nexusdata/predicate/parser/PredicateParser.java
// Path: nexusdata/src/main/java/com/github/dkharrat/nexusdata/predicate/CompoundPredicate.java // public class CompoundPredicate implements Predicate { // public static enum Operator { // AND, // OR, // } // // private final Predicate lhs, rhs; // private final Operator op; // // public CompoundPredicate(Predicate lhs, Operator op, Predicate rhs) { // this.lhs = lhs; // this.op = op; // this.rhs = rhs; // } // // public Predicate getLhs() { // return lhs; // } // // public Operator getOperator() { // return op; // } // // public Predicate getRhs() { // return rhs; // } // // @Override // public <T> T accept(ExpressionVisitor<T> visitor) { // return visitor.visit(this); // } // // @Override // public Boolean evaluate(Object object) { // boolean lhsValue = lhs.evaluate(object); // boolean rhsValue = rhs.evaluate(object); // // switch (op) { // case AND: // return lhsValue && rhsValue; // case OR: // return lhsValue || rhsValue; // default: // throw new UnsupportedOperationException("Unsupported compound operator: " + op); // } // } // // @Override // public String toString() { // return "(" + lhs + " " + op + " " + rhs + ")"; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // CompoundPredicate that = (CompoundPredicate) o; // // if (!lhs.equals(that.lhs)) return false; // if (op != that.op) return false; // if (!rhs.equals(that.rhs)) return false; // // return true; // } // // @Override // public int hashCode() { // int result = lhs.hashCode(); // result = 31 * result + rhs.hashCode(); // result = 31 * result + op.hashCode(); // return result; // } // } // // Path: nexusdata/src/main/java/com/github/dkharrat/nexusdata/predicate/Expression.java // public interface Expression<T> { // // public <V> V accept(ExpressionVisitor<V> visitor); // public T evaluate(Object object); // }
import com.github.dkharrat.nexusdata.predicate.ComparisonPredicate; import com.github.dkharrat.nexusdata.predicate.CompoundPredicate; import com.github.dkharrat.nexusdata.predicate.Expression; import com.github.dkharrat.nexusdata.predicate.Predicate;
package com.github.dkharrat.nexusdata.predicate.parser; public class PredicateParser { public static enum TokenType { AND, OR, OPEN_PAREN, CLOSE_PAREN, EQUAL, GREATER_THAN_OR_EQUAL, LESS_THAN_OR_EQUAL, NOT_EQUAL, GREATER_THAN, LESS_THAN, FIELD_NAME, CONSTANT, EOF } public static interface Precedence { public static final int OR = 1; public static final int AND = 2; public static final int EQUALITY = 3; public static final int INEQUALITY = 4; public static final int NOT = 5; public static final int PREFIX = 6; public static final int POSTFIX = 7; }
// Path: nexusdata/src/main/java/com/github/dkharrat/nexusdata/predicate/CompoundPredicate.java // public class CompoundPredicate implements Predicate { // public static enum Operator { // AND, // OR, // } // // private final Predicate lhs, rhs; // private final Operator op; // // public CompoundPredicate(Predicate lhs, Operator op, Predicate rhs) { // this.lhs = lhs; // this.op = op; // this.rhs = rhs; // } // // public Predicate getLhs() { // return lhs; // } // // public Operator getOperator() { // return op; // } // // public Predicate getRhs() { // return rhs; // } // // @Override // public <T> T accept(ExpressionVisitor<T> visitor) { // return visitor.visit(this); // } // // @Override // public Boolean evaluate(Object object) { // boolean lhsValue = lhs.evaluate(object); // boolean rhsValue = rhs.evaluate(object); // // switch (op) { // case AND: // return lhsValue && rhsValue; // case OR: // return lhsValue || rhsValue; // default: // throw new UnsupportedOperationException("Unsupported compound operator: " + op); // } // } // // @Override // public String toString() { // return "(" + lhs + " " + op + " " + rhs + ")"; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // CompoundPredicate that = (CompoundPredicate) o; // // if (!lhs.equals(that.lhs)) return false; // if (op != that.op) return false; // if (!rhs.equals(that.rhs)) return false; // // return true; // } // // @Override // public int hashCode() { // int result = lhs.hashCode(); // result = 31 * result + rhs.hashCode(); // result = 31 * result + op.hashCode(); // return result; // } // } // // Path: nexusdata/src/main/java/com/github/dkharrat/nexusdata/predicate/Expression.java // public interface Expression<T> { // // public <V> V accept(ExpressionVisitor<V> visitor); // public T evaluate(Object object); // } // Path: nexusdata/src/main/java/com/github/dkharrat/nexusdata/predicate/parser/PredicateParser.java import com.github.dkharrat.nexusdata.predicate.ComparisonPredicate; import com.github.dkharrat.nexusdata.predicate.CompoundPredicate; import com.github.dkharrat.nexusdata.predicate.Expression; import com.github.dkharrat.nexusdata.predicate.Predicate; package com.github.dkharrat.nexusdata.predicate.parser; public class PredicateParser { public static enum TokenType { AND, OR, OPEN_PAREN, CLOSE_PAREN, EQUAL, GREATER_THAN_OR_EQUAL, LESS_THAN_OR_EQUAL, NOT_EQUAL, GREATER_THAN, LESS_THAN, FIELD_NAME, CONSTANT, EOF } public static interface Precedence { public static final int OR = 1; public static final int AND = 2; public static final int EQUALITY = 3; public static final int INEQUALITY = 4; public static final int NOT = 5; public static final int PREFIX = 6; public static final int POSTFIX = 7; }
private final Parser<TokenType,Expression<?>> parser;
dkharrat/NexusData
nexusdata/src/main/java/com/github/dkharrat/nexusdata/predicate/parser/PredicateParser.java
// Path: nexusdata/src/main/java/com/github/dkharrat/nexusdata/predicate/CompoundPredicate.java // public class CompoundPredicate implements Predicate { // public static enum Operator { // AND, // OR, // } // // private final Predicate lhs, rhs; // private final Operator op; // // public CompoundPredicate(Predicate lhs, Operator op, Predicate rhs) { // this.lhs = lhs; // this.op = op; // this.rhs = rhs; // } // // public Predicate getLhs() { // return lhs; // } // // public Operator getOperator() { // return op; // } // // public Predicate getRhs() { // return rhs; // } // // @Override // public <T> T accept(ExpressionVisitor<T> visitor) { // return visitor.visit(this); // } // // @Override // public Boolean evaluate(Object object) { // boolean lhsValue = lhs.evaluate(object); // boolean rhsValue = rhs.evaluate(object); // // switch (op) { // case AND: // return lhsValue && rhsValue; // case OR: // return lhsValue || rhsValue; // default: // throw new UnsupportedOperationException("Unsupported compound operator: " + op); // } // } // // @Override // public String toString() { // return "(" + lhs + " " + op + " " + rhs + ")"; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // CompoundPredicate that = (CompoundPredicate) o; // // if (!lhs.equals(that.lhs)) return false; // if (op != that.op) return false; // if (!rhs.equals(that.rhs)) return false; // // return true; // } // // @Override // public int hashCode() { // int result = lhs.hashCode(); // result = 31 * result + rhs.hashCode(); // result = 31 * result + op.hashCode(); // return result; // } // } // // Path: nexusdata/src/main/java/com/github/dkharrat/nexusdata/predicate/Expression.java // public interface Expression<T> { // // public <V> V accept(ExpressionVisitor<V> visitor); // public T evaluate(Object object); // }
import com.github.dkharrat.nexusdata.predicate.ComparisonPredicate; import com.github.dkharrat.nexusdata.predicate.CompoundPredicate; import com.github.dkharrat.nexusdata.predicate.Expression; import com.github.dkharrat.nexusdata.predicate.Predicate;
public static final int POSTFIX = 7; } private final Parser<TokenType,Expression<?>> parser; private final static LexerGrammar<TokenType> lexerGrammar = new LexerGrammar<TokenType>(TokenType.EOF); static { lexerGrammar.add("\\(", TokenType.OPEN_PAREN); lexerGrammar.add("\\)", TokenType.CLOSE_PAREN); lexerGrammar.add("&&", TokenType.AND); lexerGrammar.add("\\|\\|", TokenType.OR); lexerGrammar.add("==", TokenType.EQUAL); lexerGrammar.add("!=", TokenType.NOT_EQUAL); lexerGrammar.add(">=", TokenType.GREATER_THAN_OR_EQUAL); lexerGrammar.add("<=", TokenType.LESS_THAN_OR_EQUAL); lexerGrammar.add(">", TokenType.GREATER_THAN); lexerGrammar.add("<", TokenType.LESS_THAN); lexerGrammar.add("(\"[^\"\\\\\\r\\n]*(?:\\\\.[^\"\\\\\\r\\n]*)*\")|\\d+|true|false|null", TokenType.CONSTANT); lexerGrammar.add("[a-zA-Z][a-zA-Z0-9_]*", TokenType.FIELD_NAME); } public PredicateParser(String text) { Lexer<TokenType> tokenizer = new Lexer<TokenType>(lexerGrammar, text); parser = new Parser<TokenType,Expression<?>>(tokenizer); parser.registerParslets(TokenType.OPEN_PAREN, new GroupParselet()); parser.registerParslets(TokenType.EQUAL, new ComparisonParselet(ComparisonPredicate.Operator.EQUAL, Precedence.EQUALITY)); parser.registerParslets(TokenType.NOT_EQUAL, new ComparisonParselet(ComparisonPredicate.Operator.NOT_EQUAL, Precedence.EQUALITY)); parser.registerParslets(TokenType.GREATER_THAN, new ComparisonParselet(ComparisonPredicate.Operator.GREATER_THAN, Precedence.INEQUALITY)); parser.registerParslets(TokenType.GREATER_THAN_OR_EQUAL, new ComparisonParselet(ComparisonPredicate.Operator.GREATER_THAN_OR_EQUAL, Precedence.INEQUALITY)); parser.registerParslets(TokenType.LESS_THAN, new ComparisonParselet(ComparisonPredicate.Operator.LESS_THAN, Precedence.INEQUALITY)); parser.registerParslets(TokenType.LESS_THAN_OR_EQUAL, new ComparisonParselet(ComparisonPredicate.Operator.LESS_THAN_OR_EQUAL, Precedence.INEQUALITY));
// Path: nexusdata/src/main/java/com/github/dkharrat/nexusdata/predicate/CompoundPredicate.java // public class CompoundPredicate implements Predicate { // public static enum Operator { // AND, // OR, // } // // private final Predicate lhs, rhs; // private final Operator op; // // public CompoundPredicate(Predicate lhs, Operator op, Predicate rhs) { // this.lhs = lhs; // this.op = op; // this.rhs = rhs; // } // // public Predicate getLhs() { // return lhs; // } // // public Operator getOperator() { // return op; // } // // public Predicate getRhs() { // return rhs; // } // // @Override // public <T> T accept(ExpressionVisitor<T> visitor) { // return visitor.visit(this); // } // // @Override // public Boolean evaluate(Object object) { // boolean lhsValue = lhs.evaluate(object); // boolean rhsValue = rhs.evaluate(object); // // switch (op) { // case AND: // return lhsValue && rhsValue; // case OR: // return lhsValue || rhsValue; // default: // throw new UnsupportedOperationException("Unsupported compound operator: " + op); // } // } // // @Override // public String toString() { // return "(" + lhs + " " + op + " " + rhs + ")"; // } // // @Override // public boolean equals(Object o) { // if (this == o) return true; // if (o == null || getClass() != o.getClass()) return false; // // CompoundPredicate that = (CompoundPredicate) o; // // if (!lhs.equals(that.lhs)) return false; // if (op != that.op) return false; // if (!rhs.equals(that.rhs)) return false; // // return true; // } // // @Override // public int hashCode() { // int result = lhs.hashCode(); // result = 31 * result + rhs.hashCode(); // result = 31 * result + op.hashCode(); // return result; // } // } // // Path: nexusdata/src/main/java/com/github/dkharrat/nexusdata/predicate/Expression.java // public interface Expression<T> { // // public <V> V accept(ExpressionVisitor<V> visitor); // public T evaluate(Object object); // } // Path: nexusdata/src/main/java/com/github/dkharrat/nexusdata/predicate/parser/PredicateParser.java import com.github.dkharrat.nexusdata.predicate.ComparisonPredicate; import com.github.dkharrat.nexusdata.predicate.CompoundPredicate; import com.github.dkharrat.nexusdata.predicate.Expression; import com.github.dkharrat.nexusdata.predicate.Predicate; public static final int POSTFIX = 7; } private final Parser<TokenType,Expression<?>> parser; private final static LexerGrammar<TokenType> lexerGrammar = new LexerGrammar<TokenType>(TokenType.EOF); static { lexerGrammar.add("\\(", TokenType.OPEN_PAREN); lexerGrammar.add("\\)", TokenType.CLOSE_PAREN); lexerGrammar.add("&&", TokenType.AND); lexerGrammar.add("\\|\\|", TokenType.OR); lexerGrammar.add("==", TokenType.EQUAL); lexerGrammar.add("!=", TokenType.NOT_EQUAL); lexerGrammar.add(">=", TokenType.GREATER_THAN_OR_EQUAL); lexerGrammar.add("<=", TokenType.LESS_THAN_OR_EQUAL); lexerGrammar.add(">", TokenType.GREATER_THAN); lexerGrammar.add("<", TokenType.LESS_THAN); lexerGrammar.add("(\"[^\"\\\\\\r\\n]*(?:\\\\.[^\"\\\\\\r\\n]*)*\")|\\d+|true|false|null", TokenType.CONSTANT); lexerGrammar.add("[a-zA-Z][a-zA-Z0-9_]*", TokenType.FIELD_NAME); } public PredicateParser(String text) { Lexer<TokenType> tokenizer = new Lexer<TokenType>(lexerGrammar, text); parser = new Parser<TokenType,Expression<?>>(tokenizer); parser.registerParslets(TokenType.OPEN_PAREN, new GroupParselet()); parser.registerParslets(TokenType.EQUAL, new ComparisonParselet(ComparisonPredicate.Operator.EQUAL, Precedence.EQUALITY)); parser.registerParslets(TokenType.NOT_EQUAL, new ComparisonParselet(ComparisonPredicate.Operator.NOT_EQUAL, Precedence.EQUALITY)); parser.registerParslets(TokenType.GREATER_THAN, new ComparisonParselet(ComparisonPredicate.Operator.GREATER_THAN, Precedence.INEQUALITY)); parser.registerParslets(TokenType.GREATER_THAN_OR_EQUAL, new ComparisonParselet(ComparisonPredicate.Operator.GREATER_THAN_OR_EQUAL, Precedence.INEQUALITY)); parser.registerParslets(TokenType.LESS_THAN, new ComparisonParselet(ComparisonPredicate.Operator.LESS_THAN, Precedence.INEQUALITY)); parser.registerParslets(TokenType.LESS_THAN_OR_EQUAL, new ComparisonParselet(ComparisonPredicate.Operator.LESS_THAN_OR_EQUAL, Precedence.INEQUALITY));
parser.registerParslets(TokenType.AND, new LogicalParselet(CompoundPredicate.Operator.AND, Precedence.AND));
dkharrat/NexusData
nexusdata/src/main/java/com/github/dkharrat/nexusdata/core/FetchRequest.java
// Path: nexusdata/src/main/java/com/github/dkharrat/nexusdata/predicate/PredicateBuilder.java // public class PredicateBuilder { // // private final Predicate curPredicate; // private final Expression<?> curExpression; // // PredicateBuilder(Predicate curPredicate) { // this.curPredicate = curPredicate; // this.curExpression = null; // } // // PredicateBuilder(Expression<?> curExpression) { // this.curExpression = curExpression; // this.curPredicate = null; // } // // public Predicate getPredicate() { // return curPredicate; // } // // public static Predicate parse(String expr) { // PredicateParser parser = new PredicateParser(expr); // return parser.parse(); // } // // Expression<?> getExpression() { // return curExpression; // } // // public PredicateBuilder gt(Expression<?> rhs) { // return new PredicateBuilder(new ComparisonPredicate(curExpression, ComparisonPredicate.Operator.GREATER_THAN, rhs)); // } // // public PredicateBuilder gt(ExpressionBuilder rhs) { // return gt(rhs.getExpression()); // } // // public <T> PredicateBuilder gt(T value) { // return gt(new ConstantExpression<T>(value)); // } // // public PredicateBuilder lt(Expression rhs) { // return new PredicateBuilder(new ComparisonPredicate(curExpression, ComparisonPredicate.Operator.LESS_THAN, rhs)); // } // // public PredicateBuilder lt(ExpressionBuilder rhs) { // return lt(rhs.getExpression()); // } // // public <T> PredicateBuilder lt(T value) { // return lt(new ConstantExpression<T>(value)); // } // // public PredicateBuilder eq(Expression<?> rhs) { // return new PredicateBuilder(new ComparisonPredicate(curExpression, ComparisonPredicate.Operator.EQUAL, rhs)); // } // // public PredicateBuilder eq(ExpressionBuilder rhs) { // return eq(rhs.getExpression()); // } // // public <T> PredicateBuilder eq(T value) { // return eq(new ConstantExpression<T>(value)); // } // // public PredicateBuilder notEq(Expression<?> rhs) { // return new PredicateBuilder(new ComparisonPredicate(curExpression, ComparisonPredicate.Operator.NOT_EQUAL, rhs)); // } // // public PredicateBuilder notEq(ExpressionBuilder rhs) { // return notEq(rhs.getExpression()); // } // // public <T> PredicateBuilder notEq(T value) { // return notEq(new ConstantExpression<T>(value)); // } // // public PredicateBuilder isNull() { // return eq(new ConstantExpression<Object>(null)); // } // // public PredicateBuilder isNotNull() { // return notEq(new ConstantExpression<Object>(null)); // } // // public PredicateBuilder and(PredicateBuilder rhs) { // return new PredicateBuilder(new CompoundPredicate(curPredicate, CompoundPredicate.Operator.AND, rhs.getPredicate())); // } // // public PredicateBuilder or(PredicateBuilder rhs) { // return new PredicateBuilder(new CompoundPredicate(curPredicate, CompoundPredicate.Operator.OR, rhs.getPredicate())); // } // }
import java.util.ArrayList; import java.util.List; import com.github.dkharrat.nexusdata.metamodel.Entity; import com.github.dkharrat.nexusdata.predicate.Predicate; import com.github.dkharrat.nexusdata.predicate.PredicateBuilder;
* A builder class that simplifies the creation of a FetchRequest. */ public static class Builder<T extends ManagedObject> { private final FetchRequest<T> fetchRequest; /** * @see FetchRequest#FetchRequest(com.github.dkharrat.nexusdata.metamodel.Entity) */ public static <S extends ManagedObject> Builder<S> forEntity(Entity<S> entity) { return new Builder<S>(new FetchRequest<S>(entity)); } private Builder(FetchRequest<T> fetchRequest) { this.fetchRequest = fetchRequest; } /** * @see FetchRequest#setPredicate(com.github.dkharrat.nexusdata.predicate.Predicate) */ public Builder<T> predicate(Predicate predicate) { fetchRequest.setPredicate(predicate); return this; } /** * Sets the predicate given a string representation. * * @see FetchRequest#setPredicate(com.github.dkharrat.nexusdata.predicate.Predicate) */ public Builder<T> predicate(String predicateToParse) {
// Path: nexusdata/src/main/java/com/github/dkharrat/nexusdata/predicate/PredicateBuilder.java // public class PredicateBuilder { // // private final Predicate curPredicate; // private final Expression<?> curExpression; // // PredicateBuilder(Predicate curPredicate) { // this.curPredicate = curPredicate; // this.curExpression = null; // } // // PredicateBuilder(Expression<?> curExpression) { // this.curExpression = curExpression; // this.curPredicate = null; // } // // public Predicate getPredicate() { // return curPredicate; // } // // public static Predicate parse(String expr) { // PredicateParser parser = new PredicateParser(expr); // return parser.parse(); // } // // Expression<?> getExpression() { // return curExpression; // } // // public PredicateBuilder gt(Expression<?> rhs) { // return new PredicateBuilder(new ComparisonPredicate(curExpression, ComparisonPredicate.Operator.GREATER_THAN, rhs)); // } // // public PredicateBuilder gt(ExpressionBuilder rhs) { // return gt(rhs.getExpression()); // } // // public <T> PredicateBuilder gt(T value) { // return gt(new ConstantExpression<T>(value)); // } // // public PredicateBuilder lt(Expression rhs) { // return new PredicateBuilder(new ComparisonPredicate(curExpression, ComparisonPredicate.Operator.LESS_THAN, rhs)); // } // // public PredicateBuilder lt(ExpressionBuilder rhs) { // return lt(rhs.getExpression()); // } // // public <T> PredicateBuilder lt(T value) { // return lt(new ConstantExpression<T>(value)); // } // // public PredicateBuilder eq(Expression<?> rhs) { // return new PredicateBuilder(new ComparisonPredicate(curExpression, ComparisonPredicate.Operator.EQUAL, rhs)); // } // // public PredicateBuilder eq(ExpressionBuilder rhs) { // return eq(rhs.getExpression()); // } // // public <T> PredicateBuilder eq(T value) { // return eq(new ConstantExpression<T>(value)); // } // // public PredicateBuilder notEq(Expression<?> rhs) { // return new PredicateBuilder(new ComparisonPredicate(curExpression, ComparisonPredicate.Operator.NOT_EQUAL, rhs)); // } // // public PredicateBuilder notEq(ExpressionBuilder rhs) { // return notEq(rhs.getExpression()); // } // // public <T> PredicateBuilder notEq(T value) { // return notEq(new ConstantExpression<T>(value)); // } // // public PredicateBuilder isNull() { // return eq(new ConstantExpression<Object>(null)); // } // // public PredicateBuilder isNotNull() { // return notEq(new ConstantExpression<Object>(null)); // } // // public PredicateBuilder and(PredicateBuilder rhs) { // return new PredicateBuilder(new CompoundPredicate(curPredicate, CompoundPredicate.Operator.AND, rhs.getPredicate())); // } // // public PredicateBuilder or(PredicateBuilder rhs) { // return new PredicateBuilder(new CompoundPredicate(curPredicate, CompoundPredicate.Operator.OR, rhs.getPredicate())); // } // } // Path: nexusdata/src/main/java/com/github/dkharrat/nexusdata/core/FetchRequest.java import java.util.ArrayList; import java.util.List; import com.github.dkharrat.nexusdata.metamodel.Entity; import com.github.dkharrat.nexusdata.predicate.Predicate; import com.github.dkharrat.nexusdata.predicate.PredicateBuilder; * A builder class that simplifies the creation of a FetchRequest. */ public static class Builder<T extends ManagedObject> { private final FetchRequest<T> fetchRequest; /** * @see FetchRequest#FetchRequest(com.github.dkharrat.nexusdata.metamodel.Entity) */ public static <S extends ManagedObject> Builder<S> forEntity(Entity<S> entity) { return new Builder<S>(new FetchRequest<S>(entity)); } private Builder(FetchRequest<T> fetchRequest) { this.fetchRequest = fetchRequest; } /** * @see FetchRequest#setPredicate(com.github.dkharrat.nexusdata.predicate.Predicate) */ public Builder<T> predicate(Predicate predicate) { fetchRequest.setPredicate(predicate); return this; } /** * Sets the predicate given a string representation. * * @see FetchRequest#setPredicate(com.github.dkharrat.nexusdata.predicate.Predicate) */ public Builder<T> predicate(String predicateToParse) {
fetchRequest.setPredicate(PredicateBuilder.parse(predicateToParse));
dkharrat/NexusData
samples/todo/src/main/java/org/example/todo/TodoApp.java
// Path: nexusdata/src/main/java/com/github/dkharrat/nexusdata/metamodel/ObjectModel.java // public class ObjectModel { // private final int version; // private final String name; // private final Map<String,Entity<?>> entities = new HashMap<String,Entity<?>>(); // // /** // * Creates a new object model. // * // * @param name the name of the model // * @param entities the set of entities defined in this model // * @param version the version of this model // */ // public ObjectModel(String name, Collection<Entity<?>> entities, int version) { // this.name = name; // this.version = version; // initEntities(entities); // } // // /** // * Creates a new ObjectModel from a model file // * // * @param modelData the input stream for the model file // * @param includePath path to look under if there are other models to include // * @throws IOException if there was a problem reading from the input stream // */ // public ObjectModel(InputStream modelData, String includePath) throws IOException { // ObjectModelJsonParser.ParsedModel parsedModel = ObjectModelJsonParser.parseJsonModel(this, modelData, includePath); // name = parsedModel.getName(); // version = parsedModel.getVersion(); // initEntities(parsedModel.getEntities()); // } // // /** // * Creates a new ObjectModel from a model file // * // * @param modelData the input stream for the model file // * @throws IOException if there was a problem reading from the input stream // */ // public ObjectModel(InputStream modelData) throws IOException { // this(modelData, ""); // } // // /** // * Merges two unrelated models (as in not referencing each other) together to form a new single model. This is // * useful for organizational purposes, where two unrelated models are stored in separate files. The models must not // * conflict together (e.g. sharing the same entity name). // * // * @param models the set of models to merge // * @param name the name of the newly merged model // * @param version the version of the newly merged model // * // * @return a new ObjectModel from merging the specified models together // */ // public static ObjectModel mergeModels(Set<ObjectModel> models, String name, int version) { // Set<Entity<?>> mergedEntities = new HashSet<>(); // for (ObjectModel model : models) { // mergedEntities.addAll(model.getEntities()); // } // // return new ObjectModel(name, mergedEntities, version); // } // // private void initEntities(Collection<Entity<?>> entities) { // for (Entity<?> entity : entities) { // if (entities.contains(entity.getName())) { // throw new RuntimeException("Entity " + entity.getName() + " already exists in this model."); // } // this.entities.put(entity.getName(), entity); // } // } // // /** // * Returns the model version. Model versions are used to identify different versions of the same semantic model. // * When making changes to a model that has already been published and is in use, make sure to increment the version // * number to have persistence stores using older versions of the model to upgrade. // * // * @return an integer representing the model's version // */ // public int getVersion() { // return version; // } // // /** // * Returns the model's name. // * // * @return the model's name. // */ // public String getName() { // return name; // } // // /** // * Returns the set of entities defined in this model. // * // * @return the set of entities defined in this model // */ // public Set<Entity<?>> getEntities() { // return new HashSet<Entity<?>>(entities.values()); // } // // /** // * Returns the entity in this model by the entity's class type, or NULL if not found. // * // * @param type the class type // */ // @SuppressWarnings("unchecked") // public <T extends ManagedObject> Entity<T> getEntity(Class<T> type) { // return (Entity<T>) getEntity(type.getSimpleName()); // } // // /** // * Returns the entity in this model by the entity's name, or NULL if not found. // * // * @param name the name of the entity // */ // @SuppressWarnings("unchecked") // public <T extends ManagedObject> Entity<T> getEntity(String name) { // return (Entity<T>)entities.get(name); // } // }
import android.app.Application; import android.content.Context; import com.github.dkharrat.nexusdata.core.*; import com.github.dkharrat.nexusdata.metamodel.ObjectModel; import com.github.dkharrat.nexusdata.store.AndroidSqlPersistentStore; import java.io.IOException;
package org.example.todo; public class TodoApp extends Application { private static PersistentStoreCoordinator storeCoordinator; private static ObjectContext mainObjectContext; private static TodoApp app; @Override public void onCreate() { app = this; super.onCreate(); } public static PersistentStoreCoordinator getStoreCoordinator() { if (storeCoordinator == null) {
// Path: nexusdata/src/main/java/com/github/dkharrat/nexusdata/metamodel/ObjectModel.java // public class ObjectModel { // private final int version; // private final String name; // private final Map<String,Entity<?>> entities = new HashMap<String,Entity<?>>(); // // /** // * Creates a new object model. // * // * @param name the name of the model // * @param entities the set of entities defined in this model // * @param version the version of this model // */ // public ObjectModel(String name, Collection<Entity<?>> entities, int version) { // this.name = name; // this.version = version; // initEntities(entities); // } // // /** // * Creates a new ObjectModel from a model file // * // * @param modelData the input stream for the model file // * @param includePath path to look under if there are other models to include // * @throws IOException if there was a problem reading from the input stream // */ // public ObjectModel(InputStream modelData, String includePath) throws IOException { // ObjectModelJsonParser.ParsedModel parsedModel = ObjectModelJsonParser.parseJsonModel(this, modelData, includePath); // name = parsedModel.getName(); // version = parsedModel.getVersion(); // initEntities(parsedModel.getEntities()); // } // // /** // * Creates a new ObjectModel from a model file // * // * @param modelData the input stream for the model file // * @throws IOException if there was a problem reading from the input stream // */ // public ObjectModel(InputStream modelData) throws IOException { // this(modelData, ""); // } // // /** // * Merges two unrelated models (as in not referencing each other) together to form a new single model. This is // * useful for organizational purposes, where two unrelated models are stored in separate files. The models must not // * conflict together (e.g. sharing the same entity name). // * // * @param models the set of models to merge // * @param name the name of the newly merged model // * @param version the version of the newly merged model // * // * @return a new ObjectModel from merging the specified models together // */ // public static ObjectModel mergeModels(Set<ObjectModel> models, String name, int version) { // Set<Entity<?>> mergedEntities = new HashSet<>(); // for (ObjectModel model : models) { // mergedEntities.addAll(model.getEntities()); // } // // return new ObjectModel(name, mergedEntities, version); // } // // private void initEntities(Collection<Entity<?>> entities) { // for (Entity<?> entity : entities) { // if (entities.contains(entity.getName())) { // throw new RuntimeException("Entity " + entity.getName() + " already exists in this model."); // } // this.entities.put(entity.getName(), entity); // } // } // // /** // * Returns the model version. Model versions are used to identify different versions of the same semantic model. // * When making changes to a model that has already been published and is in use, make sure to increment the version // * number to have persistence stores using older versions of the model to upgrade. // * // * @return an integer representing the model's version // */ // public int getVersion() { // return version; // } // // /** // * Returns the model's name. // * // * @return the model's name. // */ // public String getName() { // return name; // } // // /** // * Returns the set of entities defined in this model. // * // * @return the set of entities defined in this model // */ // public Set<Entity<?>> getEntities() { // return new HashSet<Entity<?>>(entities.values()); // } // // /** // * Returns the entity in this model by the entity's class type, or NULL if not found. // * // * @param type the class type // */ // @SuppressWarnings("unchecked") // public <T extends ManagedObject> Entity<T> getEntity(Class<T> type) { // return (Entity<T>) getEntity(type.getSimpleName()); // } // // /** // * Returns the entity in this model by the entity's name, or NULL if not found. // * // * @param name the name of the entity // */ // @SuppressWarnings("unchecked") // public <T extends ManagedObject> Entity<T> getEntity(String name) { // return (Entity<T>)entities.get(name); // } // } // Path: samples/todo/src/main/java/org/example/todo/TodoApp.java import android.app.Application; import android.content.Context; import com.github.dkharrat.nexusdata.core.*; import com.github.dkharrat.nexusdata.metamodel.ObjectModel; import com.github.dkharrat.nexusdata.store.AndroidSqlPersistentStore; import java.io.IOException; package org.example.todo; public class TodoApp extends Application { private static PersistentStoreCoordinator storeCoordinator; private static ObjectContext mainObjectContext; private static TodoApp app; @Override public void onCreate() { app = this; super.onCreate(); } public static PersistentStoreCoordinator getStoreCoordinator() { if (storeCoordinator == null) {
ObjectModel model;
dkharrat/NexusData
nexusdata/src/main/java/com/github/dkharrat/nexusdata/predicate/PredicateBuilder.java
// Path: nexusdata/src/main/java/com/github/dkharrat/nexusdata/predicate/parser/PredicateParser.java // public class PredicateParser { // // public static enum TokenType { // AND, // OR, // OPEN_PAREN, // CLOSE_PAREN, // EQUAL, // GREATER_THAN_OR_EQUAL, // LESS_THAN_OR_EQUAL, // NOT_EQUAL, // GREATER_THAN, // LESS_THAN, // FIELD_NAME, // CONSTANT, // EOF // } // // public static interface Precedence { // public static final int OR = 1; // public static final int AND = 2; // public static final int EQUALITY = 3; // public static final int INEQUALITY = 4; // public static final int NOT = 5; // public static final int PREFIX = 6; // public static final int POSTFIX = 7; // } // // private final Parser<TokenType,Expression<?>> parser; // private final static LexerGrammar<TokenType> lexerGrammar = new LexerGrammar<TokenType>(TokenType.EOF); // static { // lexerGrammar.add("\\(", TokenType.OPEN_PAREN); // lexerGrammar.add("\\)", TokenType.CLOSE_PAREN); // lexerGrammar.add("&&", TokenType.AND); // lexerGrammar.add("\\|\\|", TokenType.OR); // lexerGrammar.add("==", TokenType.EQUAL); // lexerGrammar.add("!=", TokenType.NOT_EQUAL); // lexerGrammar.add(">=", TokenType.GREATER_THAN_OR_EQUAL); // lexerGrammar.add("<=", TokenType.LESS_THAN_OR_EQUAL); // lexerGrammar.add(">", TokenType.GREATER_THAN); // lexerGrammar.add("<", TokenType.LESS_THAN); // lexerGrammar.add("(\"[^\"\\\\\\r\\n]*(?:\\\\.[^\"\\\\\\r\\n]*)*\")|\\d+|true|false|null", TokenType.CONSTANT); // lexerGrammar.add("[a-zA-Z][a-zA-Z0-9_]*", TokenType.FIELD_NAME); // } // // public PredicateParser(String text) { // Lexer<TokenType> tokenizer = new Lexer<TokenType>(lexerGrammar, text); // parser = new Parser<TokenType,Expression<?>>(tokenizer); // parser.registerParslets(TokenType.OPEN_PAREN, new GroupParselet()); // parser.registerParslets(TokenType.EQUAL, new ComparisonParselet(ComparisonPredicate.Operator.EQUAL, Precedence.EQUALITY)); // parser.registerParslets(TokenType.NOT_EQUAL, new ComparisonParselet(ComparisonPredicate.Operator.NOT_EQUAL, Precedence.EQUALITY)); // parser.registerParslets(TokenType.GREATER_THAN, new ComparisonParselet(ComparisonPredicate.Operator.GREATER_THAN, Precedence.INEQUALITY)); // parser.registerParslets(TokenType.GREATER_THAN_OR_EQUAL, new ComparisonParselet(ComparisonPredicate.Operator.GREATER_THAN_OR_EQUAL, Precedence.INEQUALITY)); // parser.registerParslets(TokenType.LESS_THAN, new ComparisonParselet(ComparisonPredicate.Operator.LESS_THAN, Precedence.INEQUALITY)); // parser.registerParslets(TokenType.LESS_THAN_OR_EQUAL, new ComparisonParselet(ComparisonPredicate.Operator.LESS_THAN_OR_EQUAL, Precedence.INEQUALITY)); // parser.registerParslets(TokenType.AND, new LogicalParselet(CompoundPredicate.Operator.AND, Precedence.AND)); // parser.registerParslets(TokenType.OR, new LogicalParselet(CompoundPredicate.Operator.OR, Precedence.OR)); // parser.registerParslets(TokenType.CONSTANT, new ConstantParselet()); // parser.registerParslets(TokenType.FIELD_NAME, new NameParselet()); // } // // public Predicate parse() { // return (Predicate)parser.parse(); // } // }
import com.github.dkharrat.nexusdata.predicate.parser.PredicateParser;
package com.github.dkharrat.nexusdata.predicate; public class PredicateBuilder { private final Predicate curPredicate; private final Expression<?> curExpression; PredicateBuilder(Predicate curPredicate) { this.curPredicate = curPredicate; this.curExpression = null; } PredicateBuilder(Expression<?> curExpression) { this.curExpression = curExpression; this.curPredicate = null; } public Predicate getPredicate() { return curPredicate; } public static Predicate parse(String expr) {
// Path: nexusdata/src/main/java/com/github/dkharrat/nexusdata/predicate/parser/PredicateParser.java // public class PredicateParser { // // public static enum TokenType { // AND, // OR, // OPEN_PAREN, // CLOSE_PAREN, // EQUAL, // GREATER_THAN_OR_EQUAL, // LESS_THAN_OR_EQUAL, // NOT_EQUAL, // GREATER_THAN, // LESS_THAN, // FIELD_NAME, // CONSTANT, // EOF // } // // public static interface Precedence { // public static final int OR = 1; // public static final int AND = 2; // public static final int EQUALITY = 3; // public static final int INEQUALITY = 4; // public static final int NOT = 5; // public static final int PREFIX = 6; // public static final int POSTFIX = 7; // } // // private final Parser<TokenType,Expression<?>> parser; // private final static LexerGrammar<TokenType> lexerGrammar = new LexerGrammar<TokenType>(TokenType.EOF); // static { // lexerGrammar.add("\\(", TokenType.OPEN_PAREN); // lexerGrammar.add("\\)", TokenType.CLOSE_PAREN); // lexerGrammar.add("&&", TokenType.AND); // lexerGrammar.add("\\|\\|", TokenType.OR); // lexerGrammar.add("==", TokenType.EQUAL); // lexerGrammar.add("!=", TokenType.NOT_EQUAL); // lexerGrammar.add(">=", TokenType.GREATER_THAN_OR_EQUAL); // lexerGrammar.add("<=", TokenType.LESS_THAN_OR_EQUAL); // lexerGrammar.add(">", TokenType.GREATER_THAN); // lexerGrammar.add("<", TokenType.LESS_THAN); // lexerGrammar.add("(\"[^\"\\\\\\r\\n]*(?:\\\\.[^\"\\\\\\r\\n]*)*\")|\\d+|true|false|null", TokenType.CONSTANT); // lexerGrammar.add("[a-zA-Z][a-zA-Z0-9_]*", TokenType.FIELD_NAME); // } // // public PredicateParser(String text) { // Lexer<TokenType> tokenizer = new Lexer<TokenType>(lexerGrammar, text); // parser = new Parser<TokenType,Expression<?>>(tokenizer); // parser.registerParslets(TokenType.OPEN_PAREN, new GroupParselet()); // parser.registerParslets(TokenType.EQUAL, new ComparisonParselet(ComparisonPredicate.Operator.EQUAL, Precedence.EQUALITY)); // parser.registerParslets(TokenType.NOT_EQUAL, new ComparisonParselet(ComparisonPredicate.Operator.NOT_EQUAL, Precedence.EQUALITY)); // parser.registerParslets(TokenType.GREATER_THAN, new ComparisonParselet(ComparisonPredicate.Operator.GREATER_THAN, Precedence.INEQUALITY)); // parser.registerParslets(TokenType.GREATER_THAN_OR_EQUAL, new ComparisonParselet(ComparisonPredicate.Operator.GREATER_THAN_OR_EQUAL, Precedence.INEQUALITY)); // parser.registerParslets(TokenType.LESS_THAN, new ComparisonParselet(ComparisonPredicate.Operator.LESS_THAN, Precedence.INEQUALITY)); // parser.registerParslets(TokenType.LESS_THAN_OR_EQUAL, new ComparisonParselet(ComparisonPredicate.Operator.LESS_THAN_OR_EQUAL, Precedence.INEQUALITY)); // parser.registerParslets(TokenType.AND, new LogicalParselet(CompoundPredicate.Operator.AND, Precedence.AND)); // parser.registerParslets(TokenType.OR, new LogicalParselet(CompoundPredicate.Operator.OR, Precedence.OR)); // parser.registerParslets(TokenType.CONSTANT, new ConstantParselet()); // parser.registerParslets(TokenType.FIELD_NAME, new NameParselet()); // } // // public Predicate parse() { // return (Predicate)parser.parse(); // } // } // Path: nexusdata/src/main/java/com/github/dkharrat/nexusdata/predicate/PredicateBuilder.java import com.github.dkharrat.nexusdata.predicate.parser.PredicateParser; package com.github.dkharrat.nexusdata.predicate; public class PredicateBuilder { private final Predicate curPredicate; private final Expression<?> curExpression; PredicateBuilder(Predicate curPredicate) { this.curPredicate = curPredicate; this.curExpression = null; } PredicateBuilder(Expression<?> curExpression) { this.curExpression = curExpression; this.curPredicate = null; } public Predicate getPredicate() { return curPredicate; } public static Predicate parse(String expr) {
PredicateParser parser = new PredicateParser(expr);
dkharrat/NexusData
nexusdata/src/androidTest/java/com/github/dkharrat/nexusdata/test/PredicatesTest.java
// Path: nexusdata/src/main/java/com/github/dkharrat/nexusdata/predicate/ExpressionBuilder.java // public class ExpressionBuilder { // private final Expression curExpression; // // ExpressionBuilder(Expression curExp) { // curExpression = curExp; // } // // public Expression getExpression() { // return curExpression; // } // // public static <T> PredicateBuilder constant(T value) { // return new PredicateBuilder(new ConstantExpression<T>(value)); // } // // public static PredicateBuilder field(String fieldPath) { // return new PredicateBuilder(new FieldPathExpression(fieldPath)); // } // // public static PredicateBuilder self() { // return new PredicateBuilder(new ThisExpression()); // } // }
import junit.framework.TestCase; import com.github.dkharrat.nexusdata.predicate.ExpressionBuilder; import com.github.dkharrat.nexusdata.predicate.Predicate;
package com.github.dkharrat.nexusdata.test; public class PredicatesTest extends TestCase { class Book { String title; String authorName; int pages; Book(String title, int pages) { this.title = title; this.pages = pages; } } @Override protected void setUp() throws Exception { super.setUp(); } @Override protected void tearDown() throws Exception { super.tearDown(); } public void testSimplePredicateTrue() throws Throwable {
// Path: nexusdata/src/main/java/com/github/dkharrat/nexusdata/predicate/ExpressionBuilder.java // public class ExpressionBuilder { // private final Expression curExpression; // // ExpressionBuilder(Expression curExp) { // curExpression = curExp; // } // // public Expression getExpression() { // return curExpression; // } // // public static <T> PredicateBuilder constant(T value) { // return new PredicateBuilder(new ConstantExpression<T>(value)); // } // // public static PredicateBuilder field(String fieldPath) { // return new PredicateBuilder(new FieldPathExpression(fieldPath)); // } // // public static PredicateBuilder self() { // return new PredicateBuilder(new ThisExpression()); // } // } // Path: nexusdata/src/androidTest/java/com/github/dkharrat/nexusdata/test/PredicatesTest.java import junit.framework.TestCase; import com.github.dkharrat.nexusdata.predicate.ExpressionBuilder; import com.github.dkharrat.nexusdata.predicate.Predicate; package com.github.dkharrat.nexusdata.test; public class PredicatesTest extends TestCase { class Book { String title; String authorName; int pages; Book(String title, int pages) { this.title = title; this.pages = pages; } } @Override protected void setUp() throws Exception { super.setUp(); } @Override protected void tearDown() throws Exception { super.tearDown(); } public void testSimplePredicateTrue() throws Throwable {
Predicate p = ExpressionBuilder.constant("1").eq("1").getPredicate();
dkharrat/NexusData
nexusdata/src/main/java/com/github/dkharrat/nexusdata/core/PersistentStore.java
// Path: nexusdata/src/main/java/com/github/dkharrat/nexusdata/metamodel/Relationship.java // public class Relationship extends Property { // /** // * Represents the type of the relationship // */ // public enum Type { // TO_ONE, // TO_MANY, // } // // private final Type relationshipType; // private final Entity<?> destinationEntity; // private Relationship inverse; // // //TODO: look into deducing the 'type' param based on relationshipType // /** // * Creates a new Attribute. // * // * @param entity the associated entity // * @param name the name of the property // * @param type the relationship instance type. For to-one relationships, it must be the same as // * {@code destinationEntity} (i.e. type of the related object. For to-many relationships, // * it must be {@link java.util.Set}. // * @param relationshipType the relationship type (to-one or to-many) // * @param destinationEntity the entity of the object(s) this relationship will store // * @param inverse the relationship in the other direction (from the destination entity to this // * relationship's entity // * @param isRequired if true, property is required to have a value // */ // public Relationship(Entity<?> entity, String name, Class<?> type, Type relationshipType, Entity<?> destinationEntity, Relationship inverse, boolean isRequired) { // super(entity, name, type, isRequired); // this.relationshipType = relationshipType; // this.destinationEntity = destinationEntity; // this.inverse = inverse; // } // // /** // * Returns the relationship type. // * // * @return the relationship type // */ // public Type getRelationshipType() { // return relationshipType; // } // // /** // * Indicates whether this relationship is a to-one relationship or not. // * // * @return true if this relationship is a to-one relationship, or false otherwise // */ // public boolean isToOne() { // return relationshipType == Type.TO_ONE; // } // // /** // * Indicates whether this relationship is a to-many relationship or not. // * // * @return true if this relationship is a to-many relationship, or false otherwise // */ // public boolean isToMany() { // return relationshipType == Type.TO_MANY; // } // // /** // * Returns the entity to which this relationship is related to. // * // * @return the entity to which this relationship is related to // */ // public Entity<?> getDestinationEntity() { // return destinationEntity; // } // // /** // * Returns the inverse relationship (i.e the relationship in the other direction). // * // * @return the inverse relationship // */ // public Relationship getInverse() { // return inverse; // } // // void setInverse(Relationship inverse) { // this.inverse = inverse; // } // // @Override // public boolean isRelationship() { // return true; // } // // @Override // public String toString() { // return super.toString() + "[" // + "destinationEntity=" + (getDestinationEntity() == null ? "<null>" : getDestinationEntity().getName()) // + ", inverseRelationship=" + (getInverse() == null ? "<null>" : getInverse().getName()) // + "]"; // } // }
import java.io.File; import java.net.MalformedURLException; import java.net.URL; import java.util.*; import com.github.dkharrat.nexusdata.metamodel.Entity; import com.github.dkharrat.nexusdata.metamodel.Relationship;
/** * Returns the corresponding ObjectIDs for the specified ManagedObjects. These ObjectIDs must be permanent and must * not be changed after this call. Objects that already have a permanent ObjectID must return the same one. * * @param objects the list of objects that shall get permanent IDs. * * @return the corresponding ObjectIDs of the specified ManagedObjects */ abstract List<ObjectID> getPermanentIDsForObjects(List<ManagedObject> objects); /** * Returns the associated cache node of the specified ObjectID. * * @param objectID the ObjectID * @param context the context to which the data will be returned * * @return the associated cache node of the specified ObjectID, or {@code null} if no such object exists */ abstract StoreCacheNode getObjectValues(ObjectID objectID, ObjectContext context); /** * Returns the ObjectID of the related object for the to-one relationship. * * @param objectID the objectID of the source object for which the relationship is requested * @param relationship the relationship property to retrieve * @param context the context to which the data will be returned * * @return the ObjectID of the related object, or {@code null} if there is no related object */
// Path: nexusdata/src/main/java/com/github/dkharrat/nexusdata/metamodel/Relationship.java // public class Relationship extends Property { // /** // * Represents the type of the relationship // */ // public enum Type { // TO_ONE, // TO_MANY, // } // // private final Type relationshipType; // private final Entity<?> destinationEntity; // private Relationship inverse; // // //TODO: look into deducing the 'type' param based on relationshipType // /** // * Creates a new Attribute. // * // * @param entity the associated entity // * @param name the name of the property // * @param type the relationship instance type. For to-one relationships, it must be the same as // * {@code destinationEntity} (i.e. type of the related object. For to-many relationships, // * it must be {@link java.util.Set}. // * @param relationshipType the relationship type (to-one or to-many) // * @param destinationEntity the entity of the object(s) this relationship will store // * @param inverse the relationship in the other direction (from the destination entity to this // * relationship's entity // * @param isRequired if true, property is required to have a value // */ // public Relationship(Entity<?> entity, String name, Class<?> type, Type relationshipType, Entity<?> destinationEntity, Relationship inverse, boolean isRequired) { // super(entity, name, type, isRequired); // this.relationshipType = relationshipType; // this.destinationEntity = destinationEntity; // this.inverse = inverse; // } // // /** // * Returns the relationship type. // * // * @return the relationship type // */ // public Type getRelationshipType() { // return relationshipType; // } // // /** // * Indicates whether this relationship is a to-one relationship or not. // * // * @return true if this relationship is a to-one relationship, or false otherwise // */ // public boolean isToOne() { // return relationshipType == Type.TO_ONE; // } // // /** // * Indicates whether this relationship is a to-many relationship or not. // * // * @return true if this relationship is a to-many relationship, or false otherwise // */ // public boolean isToMany() { // return relationshipType == Type.TO_MANY; // } // // /** // * Returns the entity to which this relationship is related to. // * // * @return the entity to which this relationship is related to // */ // public Entity<?> getDestinationEntity() { // return destinationEntity; // } // // /** // * Returns the inverse relationship (i.e the relationship in the other direction). // * // * @return the inverse relationship // */ // public Relationship getInverse() { // return inverse; // } // // void setInverse(Relationship inverse) { // this.inverse = inverse; // } // // @Override // public boolean isRelationship() { // return true; // } // // @Override // public String toString() { // return super.toString() + "[" // + "destinationEntity=" + (getDestinationEntity() == null ? "<null>" : getDestinationEntity().getName()) // + ", inverseRelationship=" + (getInverse() == null ? "<null>" : getInverse().getName()) // + "]"; // } // } // Path: nexusdata/src/main/java/com/github/dkharrat/nexusdata/core/PersistentStore.java import java.io.File; import java.net.MalformedURLException; import java.net.URL; import java.util.*; import com.github.dkharrat.nexusdata.metamodel.Entity; import com.github.dkharrat.nexusdata.metamodel.Relationship; /** * Returns the corresponding ObjectIDs for the specified ManagedObjects. These ObjectIDs must be permanent and must * not be changed after this call. Objects that already have a permanent ObjectID must return the same one. * * @param objects the list of objects that shall get permanent IDs. * * @return the corresponding ObjectIDs of the specified ManagedObjects */ abstract List<ObjectID> getPermanentIDsForObjects(List<ManagedObject> objects); /** * Returns the associated cache node of the specified ObjectID. * * @param objectID the ObjectID * @param context the context to which the data will be returned * * @return the associated cache node of the specified ObjectID, or {@code null} if no such object exists */ abstract StoreCacheNode getObjectValues(ObjectID objectID, ObjectContext context); /** * Returns the ObjectID of the related object for the to-one relationship. * * @param objectID the objectID of the source object for which the relationship is requested * @param relationship the relationship property to retrieve * @param context the context to which the data will be returned * * @return the ObjectID of the related object, or {@code null} if there is no related object */
abstract ObjectID getToOneRelationshipValue(ObjectID objectID, Relationship relationship, ObjectContext context);
dkharrat/NexusData
nexusdata/src/main/java/com/github/dkharrat/nexusdata/core/AtomicStore.java
// Path: nexusdata/src/main/java/com/github/dkharrat/nexusdata/metamodel/Relationship.java // public class Relationship extends Property { // /** // * Represents the type of the relationship // */ // public enum Type { // TO_ONE, // TO_MANY, // } // // private final Type relationshipType; // private final Entity<?> destinationEntity; // private Relationship inverse; // // //TODO: look into deducing the 'type' param based on relationshipType // /** // * Creates a new Attribute. // * // * @param entity the associated entity // * @param name the name of the property // * @param type the relationship instance type. For to-one relationships, it must be the same as // * {@code destinationEntity} (i.e. type of the related object. For to-many relationships, // * it must be {@link java.util.Set}. // * @param relationshipType the relationship type (to-one or to-many) // * @param destinationEntity the entity of the object(s) this relationship will store // * @param inverse the relationship in the other direction (from the destination entity to this // * relationship's entity // * @param isRequired if true, property is required to have a value // */ // public Relationship(Entity<?> entity, String name, Class<?> type, Type relationshipType, Entity<?> destinationEntity, Relationship inverse, boolean isRequired) { // super(entity, name, type, isRequired); // this.relationshipType = relationshipType; // this.destinationEntity = destinationEntity; // this.inverse = inverse; // } // // /** // * Returns the relationship type. // * // * @return the relationship type // */ // public Type getRelationshipType() { // return relationshipType; // } // // /** // * Indicates whether this relationship is a to-one relationship or not. // * // * @return true if this relationship is a to-one relationship, or false otherwise // */ // public boolean isToOne() { // return relationshipType == Type.TO_ONE; // } // // /** // * Indicates whether this relationship is a to-many relationship or not. // * // * @return true if this relationship is a to-many relationship, or false otherwise // */ // public boolean isToMany() { // return relationshipType == Type.TO_MANY; // } // // /** // * Returns the entity to which this relationship is related to. // * // * @return the entity to which this relationship is related to // */ // public Entity<?> getDestinationEntity() { // return destinationEntity; // } // // /** // * Returns the inverse relationship (i.e the relationship in the other direction). // * // * @return the inverse relationship // */ // public Relationship getInverse() { // return inverse; // } // // void setInverse(Relationship inverse) { // this.inverse = inverse; // } // // @Override // public boolean isRelationship() { // return true; // } // // @Override // public String toString() { // return super.toString() + "[" // + "destinationEntity=" + (getDestinationEntity() == null ? "<null>" : getDestinationEntity().getName()) // + ", inverseRelationship=" + (getInverse() == null ? "<null>" : getInverse().getName()) // + "]"; // } // }
import java.io.File; import java.net.URL; import java.util.*; import com.github.dkharrat.nexusdata.metamodel.Property; import com.github.dkharrat.nexusdata.metamodel.Relationship; import com.github.dkharrat.nexusdata.utils.ObjectUtil;
package com.github.dkharrat.nexusdata.core; /** * An AtomicStore is a persistence store in which data is loaded and saved all at once. It is useful when the data set * is small enough to fit in memory and good performance is needed. */ public abstract class AtomicStore extends PersistentStore { private final Map<ObjectID, StoreCacheNode> idsToCacheNodes = new HashMap<ObjectID, StoreCacheNode>(); /** * Constructs a new Atomic store * * @param location the location in which to save the data persistence file */ public AtomicStore(URL location) { super(location); } public AtomicStore(File location) { super(location); } public abstract void load(); public abstract void save(); public abstract Object createReferenceObjectForManagedObject(ManagedObject object); @Override protected void loadMetadata() { setUuid(UUID.randomUUID()); } Set<StoreCacheNode> getCacheNodes() { return new HashSet<StoreCacheNode>(idsToCacheNodes.values()); } protected void addCacheNode(StoreCacheNode cacheNode) { idsToCacheNodes.put(cacheNode.getID(), cacheNode); } protected void removeCacheNode(StoreCacheNode cacheNode) { idsToCacheNodes.remove(cacheNode.getID()); } protected void updateCacheNode(StoreCacheNode cacheNode, ManagedObject object) { for(Property property : object.getEntity().getProperties()) { Object value = object.getValue(property.getName()); if (property.isRelationship()) {
// Path: nexusdata/src/main/java/com/github/dkharrat/nexusdata/metamodel/Relationship.java // public class Relationship extends Property { // /** // * Represents the type of the relationship // */ // public enum Type { // TO_ONE, // TO_MANY, // } // // private final Type relationshipType; // private final Entity<?> destinationEntity; // private Relationship inverse; // // //TODO: look into deducing the 'type' param based on relationshipType // /** // * Creates a new Attribute. // * // * @param entity the associated entity // * @param name the name of the property // * @param type the relationship instance type. For to-one relationships, it must be the same as // * {@code destinationEntity} (i.e. type of the related object. For to-many relationships, // * it must be {@link java.util.Set}. // * @param relationshipType the relationship type (to-one or to-many) // * @param destinationEntity the entity of the object(s) this relationship will store // * @param inverse the relationship in the other direction (from the destination entity to this // * relationship's entity // * @param isRequired if true, property is required to have a value // */ // public Relationship(Entity<?> entity, String name, Class<?> type, Type relationshipType, Entity<?> destinationEntity, Relationship inverse, boolean isRequired) { // super(entity, name, type, isRequired); // this.relationshipType = relationshipType; // this.destinationEntity = destinationEntity; // this.inverse = inverse; // } // // /** // * Returns the relationship type. // * // * @return the relationship type // */ // public Type getRelationshipType() { // return relationshipType; // } // // /** // * Indicates whether this relationship is a to-one relationship or not. // * // * @return true if this relationship is a to-one relationship, or false otherwise // */ // public boolean isToOne() { // return relationshipType == Type.TO_ONE; // } // // /** // * Indicates whether this relationship is a to-many relationship or not. // * // * @return true if this relationship is a to-many relationship, or false otherwise // */ // public boolean isToMany() { // return relationshipType == Type.TO_MANY; // } // // /** // * Returns the entity to which this relationship is related to. // * // * @return the entity to which this relationship is related to // */ // public Entity<?> getDestinationEntity() { // return destinationEntity; // } // // /** // * Returns the inverse relationship (i.e the relationship in the other direction). // * // * @return the inverse relationship // */ // public Relationship getInverse() { // return inverse; // } // // void setInverse(Relationship inverse) { // this.inverse = inverse; // } // // @Override // public boolean isRelationship() { // return true; // } // // @Override // public String toString() { // return super.toString() + "[" // + "destinationEntity=" + (getDestinationEntity() == null ? "<null>" : getDestinationEntity().getName()) // + ", inverseRelationship=" + (getInverse() == null ? "<null>" : getInverse().getName()) // + "]"; // } // } // Path: nexusdata/src/main/java/com/github/dkharrat/nexusdata/core/AtomicStore.java import java.io.File; import java.net.URL; import java.util.*; import com.github.dkharrat.nexusdata.metamodel.Property; import com.github.dkharrat.nexusdata.metamodel.Relationship; import com.github.dkharrat.nexusdata.utils.ObjectUtil; package com.github.dkharrat.nexusdata.core; /** * An AtomicStore is a persistence store in which data is loaded and saved all at once. It is useful when the data set * is small enough to fit in memory and good performance is needed. */ public abstract class AtomicStore extends PersistentStore { private final Map<ObjectID, StoreCacheNode> idsToCacheNodes = new HashMap<ObjectID, StoreCacheNode>(); /** * Constructs a new Atomic store * * @param location the location in which to save the data persistence file */ public AtomicStore(URL location) { super(location); } public AtomicStore(File location) { super(location); } public abstract void load(); public abstract void save(); public abstract Object createReferenceObjectForManagedObject(ManagedObject object); @Override protected void loadMetadata() { setUuid(UUID.randomUUID()); } Set<StoreCacheNode> getCacheNodes() { return new HashSet<StoreCacheNode>(idsToCacheNodes.values()); } protected void addCacheNode(StoreCacheNode cacheNode) { idsToCacheNodes.put(cacheNode.getID(), cacheNode); } protected void removeCacheNode(StoreCacheNode cacheNode) { idsToCacheNodes.remove(cacheNode.getID()); } protected void updateCacheNode(StoreCacheNode cacheNode, ManagedObject object) { for(Property property : object.getEntity().getProperties()) { Object value = object.getValue(property.getName()); if (property.isRelationship()) {
Relationship relationship = (Relationship) property;
PistoiaHELM/HELMNotationToolkit
test/org/helm/notation/tools/CalculatorTest.java
// Path: source/org/helm/notation/CalculationException.java // public class CalculationException extends Exception { // // /** // * Creates a new instance of <code>StructureException</code> without detail // * message. // */ // public CalculationException() { // } // // /** // * Constructs an instance of <code>StructureException</code> with the // * specified detail message. // * // * @param msg // * the detail message. // */ // public CalculationException(String msg) { // super(msg); // } // } // // Path: source/org/helm/notation/MonomerException.java // public class MonomerException extends Exception { // // /** // * Creates a new instance of <code>MonomerException</code> without detail // * message. // */ // public MonomerException() { // } // // /** // * Constructs an instance of <code>MonomerException</code> with the // * specified detail message. // * // * @param msg // * the detail message. // */ // public MonomerException(String msg) { // super(msg); // } // // public MonomerException(String msg, Throwable err) { // super(msg, err); // } // } // // Path: source/org/helm/notation/NotationException.java // public class NotationException extends Exception { // // /** // * Creates a new instance of <code>NotationException</code> without detail // * message. // */ // public NotationException() { // } // // /** // * Constructs an instance of <code>NotationException</code> with the // * specified detail message. // * // * @param msg // * the detail message. // */ // public NotationException(String msg) { // super(msg); // } // // public NotationException(String msg, Throwable err) { // super(msg, err); // } // } // // Path: source/org/helm/notation/StructureException.java // public class StructureException extends Exception { // // /** // * Creates a new instance of <code>StructureException</code> without detail // * message. // */ // public StructureException() { // } // // /** // * Constructs an instance of <code>StructureException</code> with the // * specified detail message. // * // * @param msg // * the detail message. // */ // public StructureException(String msg) { // super(msg); // } // // public StructureException(String msg, Throwable err) { // super(msg, err); // } // }
import static org.junit.Assert.assertEquals; import java.io.IOException; import org.helm.notation.CalculationException; import org.helm.notation.MonomerException; import org.helm.notation.NotationException; import org.helm.notation.StructureException; import org.jdom.JDOMException; import org.junit.Before; import org.junit.Test;
package org.helm.notation.tools; public class CalculatorTest { private ExtinctionCoefficientCalculator calculator; @Before
// Path: source/org/helm/notation/CalculationException.java // public class CalculationException extends Exception { // // /** // * Creates a new instance of <code>StructureException</code> without detail // * message. // */ // public CalculationException() { // } // // /** // * Constructs an instance of <code>StructureException</code> with the // * specified detail message. // * // * @param msg // * the detail message. // */ // public CalculationException(String msg) { // super(msg); // } // } // // Path: source/org/helm/notation/MonomerException.java // public class MonomerException extends Exception { // // /** // * Creates a new instance of <code>MonomerException</code> without detail // * message. // */ // public MonomerException() { // } // // /** // * Constructs an instance of <code>MonomerException</code> with the // * specified detail message. // * // * @param msg // * the detail message. // */ // public MonomerException(String msg) { // super(msg); // } // // public MonomerException(String msg, Throwable err) { // super(msg, err); // } // } // // Path: source/org/helm/notation/NotationException.java // public class NotationException extends Exception { // // /** // * Creates a new instance of <code>NotationException</code> without detail // * message. // */ // public NotationException() { // } // // /** // * Constructs an instance of <code>NotationException</code> with the // * specified detail message. // * // * @param msg // * the detail message. // */ // public NotationException(String msg) { // super(msg); // } // // public NotationException(String msg, Throwable err) { // super(msg, err); // } // } // // Path: source/org/helm/notation/StructureException.java // public class StructureException extends Exception { // // /** // * Creates a new instance of <code>StructureException</code> without detail // * message. // */ // public StructureException() { // } // // /** // * Constructs an instance of <code>StructureException</code> with the // * specified detail message. // * // * @param msg // * the detail message. // */ // public StructureException(String msg) { // super(msg); // } // // public StructureException(String msg, Throwable err) { // super(msg, err); // } // } // Path: test/org/helm/notation/tools/CalculatorTest.java import static org.junit.Assert.assertEquals; import java.io.IOException; import org.helm.notation.CalculationException; import org.helm.notation.MonomerException; import org.helm.notation.NotationException; import org.helm.notation.StructureException; import org.jdom.JDOMException; import org.junit.Before; import org.junit.Test; package org.helm.notation.tools; public class CalculatorTest { private ExtinctionCoefficientCalculator calculator; @Before
public void setUp() throws CalculationException {
PistoiaHELM/HELMNotationToolkit
test/org/helm/notation/tools/CalculatorTest.java
// Path: source/org/helm/notation/CalculationException.java // public class CalculationException extends Exception { // // /** // * Creates a new instance of <code>StructureException</code> without detail // * message. // */ // public CalculationException() { // } // // /** // * Constructs an instance of <code>StructureException</code> with the // * specified detail message. // * // * @param msg // * the detail message. // */ // public CalculationException(String msg) { // super(msg); // } // } // // Path: source/org/helm/notation/MonomerException.java // public class MonomerException extends Exception { // // /** // * Creates a new instance of <code>MonomerException</code> without detail // * message. // */ // public MonomerException() { // } // // /** // * Constructs an instance of <code>MonomerException</code> with the // * specified detail message. // * // * @param msg // * the detail message. // */ // public MonomerException(String msg) { // super(msg); // } // // public MonomerException(String msg, Throwable err) { // super(msg, err); // } // } // // Path: source/org/helm/notation/NotationException.java // public class NotationException extends Exception { // // /** // * Creates a new instance of <code>NotationException</code> without detail // * message. // */ // public NotationException() { // } // // /** // * Constructs an instance of <code>NotationException</code> with the // * specified detail message. // * // * @param msg // * the detail message. // */ // public NotationException(String msg) { // super(msg); // } // // public NotationException(String msg, Throwable err) { // super(msg, err); // } // } // // Path: source/org/helm/notation/StructureException.java // public class StructureException extends Exception { // // /** // * Creates a new instance of <code>StructureException</code> without detail // * message. // */ // public StructureException() { // } // // /** // * Constructs an instance of <code>StructureException</code> with the // * specified detail message. // * // * @param msg // * the detail message. // */ // public StructureException(String msg) { // super(msg); // } // // public StructureException(String msg, Throwable err) { // super(msg, err); // } // }
import static org.junit.Assert.assertEquals; import java.io.IOException; import org.helm.notation.CalculationException; import org.helm.notation.MonomerException; import org.helm.notation.NotationException; import org.helm.notation.StructureException; import org.jdom.JDOMException; import org.junit.Before; import org.junit.Test;
package org.helm.notation.tools; public class CalculatorTest { private ExtinctionCoefficientCalculator calculator; @Before public void setUp() throws CalculationException { calculator = ExtinctionCoefficientCalculator.getInstance(); } @Test public void testCalculateFromAminoAcidSequence() throws CalculationException { String input = "AGGDDDDDDDDDDDDDDDDDDFFFFFFFFFFFFF"; float result = calculator.calculateFromAminoAcidSequence(input); assertEquals(result, 0.0, 1e-15); input = "AGGCFFFFFFFFFF"; result = calculator.calculateFromAminoAcidSequence(input); assertEquals(result, 0.0, 62.5); input = "AGGYEEEEEEEEEEEEEEEEEEE"; result = calculator.calculateFromAminoAcidSequence(input); assertEquals(result, 1490.0, 1e-15); input = "AGGWEEEEEEEEEEEEEEEEEEE"; result = calculator.calculateFromAminoAcidSequence(input); assertEquals(result, 5500.0, 1e-15); } @Test public void testCalculateFromPeptidePolymerNotation()
// Path: source/org/helm/notation/CalculationException.java // public class CalculationException extends Exception { // // /** // * Creates a new instance of <code>StructureException</code> without detail // * message. // */ // public CalculationException() { // } // // /** // * Constructs an instance of <code>StructureException</code> with the // * specified detail message. // * // * @param msg // * the detail message. // */ // public CalculationException(String msg) { // super(msg); // } // } // // Path: source/org/helm/notation/MonomerException.java // public class MonomerException extends Exception { // // /** // * Creates a new instance of <code>MonomerException</code> without detail // * message. // */ // public MonomerException() { // } // // /** // * Constructs an instance of <code>MonomerException</code> with the // * specified detail message. // * // * @param msg // * the detail message. // */ // public MonomerException(String msg) { // super(msg); // } // // public MonomerException(String msg, Throwable err) { // super(msg, err); // } // } // // Path: source/org/helm/notation/NotationException.java // public class NotationException extends Exception { // // /** // * Creates a new instance of <code>NotationException</code> without detail // * message. // */ // public NotationException() { // } // // /** // * Constructs an instance of <code>NotationException</code> with the // * specified detail message. // * // * @param msg // * the detail message. // */ // public NotationException(String msg) { // super(msg); // } // // public NotationException(String msg, Throwable err) { // super(msg, err); // } // } // // Path: source/org/helm/notation/StructureException.java // public class StructureException extends Exception { // // /** // * Creates a new instance of <code>StructureException</code> without detail // * message. // */ // public StructureException() { // } // // /** // * Constructs an instance of <code>StructureException</code> with the // * specified detail message. // * // * @param msg // * the detail message. // */ // public StructureException(String msg) { // super(msg); // } // // public StructureException(String msg, Throwable err) { // super(msg, err); // } // } // Path: test/org/helm/notation/tools/CalculatorTest.java import static org.junit.Assert.assertEquals; import java.io.IOException; import org.helm.notation.CalculationException; import org.helm.notation.MonomerException; import org.helm.notation.NotationException; import org.helm.notation.StructureException; import org.jdom.JDOMException; import org.junit.Before; import org.junit.Test; package org.helm.notation.tools; public class CalculatorTest { private ExtinctionCoefficientCalculator calculator; @Before public void setUp() throws CalculationException { calculator = ExtinctionCoefficientCalculator.getInstance(); } @Test public void testCalculateFromAminoAcidSequence() throws CalculationException { String input = "AGGDDDDDDDDDDDDDDDDDDFFFFFFFFFFFFF"; float result = calculator.calculateFromAminoAcidSequence(input); assertEquals(result, 0.0, 1e-15); input = "AGGCFFFFFFFFFF"; result = calculator.calculateFromAminoAcidSequence(input); assertEquals(result, 0.0, 62.5); input = "AGGYEEEEEEEEEEEEEEEEEEE"; result = calculator.calculateFromAminoAcidSequence(input); assertEquals(result, 1490.0, 1e-15); input = "AGGWEEEEEEEEEEEEEEEEEEE"; result = calculator.calculateFromAminoAcidSequence(input); assertEquals(result, 5500.0, 1e-15); } @Test public void testCalculateFromPeptidePolymerNotation()
throws NotationException, MonomerException, CalculationException,
PistoiaHELM/HELMNotationToolkit
test/org/helm/notation/tools/CalculatorTest.java
// Path: source/org/helm/notation/CalculationException.java // public class CalculationException extends Exception { // // /** // * Creates a new instance of <code>StructureException</code> without detail // * message. // */ // public CalculationException() { // } // // /** // * Constructs an instance of <code>StructureException</code> with the // * specified detail message. // * // * @param msg // * the detail message. // */ // public CalculationException(String msg) { // super(msg); // } // } // // Path: source/org/helm/notation/MonomerException.java // public class MonomerException extends Exception { // // /** // * Creates a new instance of <code>MonomerException</code> without detail // * message. // */ // public MonomerException() { // } // // /** // * Constructs an instance of <code>MonomerException</code> with the // * specified detail message. // * // * @param msg // * the detail message. // */ // public MonomerException(String msg) { // super(msg); // } // // public MonomerException(String msg, Throwable err) { // super(msg, err); // } // } // // Path: source/org/helm/notation/NotationException.java // public class NotationException extends Exception { // // /** // * Creates a new instance of <code>NotationException</code> without detail // * message. // */ // public NotationException() { // } // // /** // * Constructs an instance of <code>NotationException</code> with the // * specified detail message. // * // * @param msg // * the detail message. // */ // public NotationException(String msg) { // super(msg); // } // // public NotationException(String msg, Throwable err) { // super(msg, err); // } // } // // Path: source/org/helm/notation/StructureException.java // public class StructureException extends Exception { // // /** // * Creates a new instance of <code>StructureException</code> without detail // * message. // */ // public StructureException() { // } // // /** // * Constructs an instance of <code>StructureException</code> with the // * specified detail message. // * // * @param msg // * the detail message. // */ // public StructureException(String msg) { // super(msg); // } // // public StructureException(String msg, Throwable err) { // super(msg, err); // } // }
import static org.junit.Assert.assertEquals; import java.io.IOException; import org.helm.notation.CalculationException; import org.helm.notation.MonomerException; import org.helm.notation.NotationException; import org.helm.notation.StructureException; import org.jdom.JDOMException; import org.junit.Before; import org.junit.Test;
package org.helm.notation.tools; public class CalculatorTest { private ExtinctionCoefficientCalculator calculator; @Before public void setUp() throws CalculationException { calculator = ExtinctionCoefficientCalculator.getInstance(); } @Test public void testCalculateFromAminoAcidSequence() throws CalculationException { String input = "AGGDDDDDDDDDDDDDDDDDDFFFFFFFFFFFFF"; float result = calculator.calculateFromAminoAcidSequence(input); assertEquals(result, 0.0, 1e-15); input = "AGGCFFFFFFFFFF"; result = calculator.calculateFromAminoAcidSequence(input); assertEquals(result, 0.0, 62.5); input = "AGGYEEEEEEEEEEEEEEEEEEE"; result = calculator.calculateFromAminoAcidSequence(input); assertEquals(result, 1490.0, 1e-15); input = "AGGWEEEEEEEEEEEEEEEEEEE"; result = calculator.calculateFromAminoAcidSequence(input); assertEquals(result, 5500.0, 1e-15); } @Test public void testCalculateFromPeptidePolymerNotation()
// Path: source/org/helm/notation/CalculationException.java // public class CalculationException extends Exception { // // /** // * Creates a new instance of <code>StructureException</code> without detail // * message. // */ // public CalculationException() { // } // // /** // * Constructs an instance of <code>StructureException</code> with the // * specified detail message. // * // * @param msg // * the detail message. // */ // public CalculationException(String msg) { // super(msg); // } // } // // Path: source/org/helm/notation/MonomerException.java // public class MonomerException extends Exception { // // /** // * Creates a new instance of <code>MonomerException</code> without detail // * message. // */ // public MonomerException() { // } // // /** // * Constructs an instance of <code>MonomerException</code> with the // * specified detail message. // * // * @param msg // * the detail message. // */ // public MonomerException(String msg) { // super(msg); // } // // public MonomerException(String msg, Throwable err) { // super(msg, err); // } // } // // Path: source/org/helm/notation/NotationException.java // public class NotationException extends Exception { // // /** // * Creates a new instance of <code>NotationException</code> without detail // * message. // */ // public NotationException() { // } // // /** // * Constructs an instance of <code>NotationException</code> with the // * specified detail message. // * // * @param msg // * the detail message. // */ // public NotationException(String msg) { // super(msg); // } // // public NotationException(String msg, Throwable err) { // super(msg, err); // } // } // // Path: source/org/helm/notation/StructureException.java // public class StructureException extends Exception { // // /** // * Creates a new instance of <code>StructureException</code> without detail // * message. // */ // public StructureException() { // } // // /** // * Constructs an instance of <code>StructureException</code> with the // * specified detail message. // * // * @param msg // * the detail message. // */ // public StructureException(String msg) { // super(msg); // } // // public StructureException(String msg, Throwable err) { // super(msg, err); // } // } // Path: test/org/helm/notation/tools/CalculatorTest.java import static org.junit.Assert.assertEquals; import java.io.IOException; import org.helm.notation.CalculationException; import org.helm.notation.MonomerException; import org.helm.notation.NotationException; import org.helm.notation.StructureException; import org.jdom.JDOMException; import org.junit.Before; import org.junit.Test; package org.helm.notation.tools; public class CalculatorTest { private ExtinctionCoefficientCalculator calculator; @Before public void setUp() throws CalculationException { calculator = ExtinctionCoefficientCalculator.getInstance(); } @Test public void testCalculateFromAminoAcidSequence() throws CalculationException { String input = "AGGDDDDDDDDDDDDDDDDDDFFFFFFFFFFFFF"; float result = calculator.calculateFromAminoAcidSequence(input); assertEquals(result, 0.0, 1e-15); input = "AGGCFFFFFFFFFF"; result = calculator.calculateFromAminoAcidSequence(input); assertEquals(result, 0.0, 62.5); input = "AGGYEEEEEEEEEEEEEEEEEEE"; result = calculator.calculateFromAminoAcidSequence(input); assertEquals(result, 1490.0, 1e-15); input = "AGGWEEEEEEEEEEEEEEEEEEE"; result = calculator.calculateFromAminoAcidSequence(input); assertEquals(result, 5500.0, 1e-15); } @Test public void testCalculateFromPeptidePolymerNotation()
throws NotationException, MonomerException, CalculationException,
PistoiaHELM/HELMNotationToolkit
test/org/helm/notation/tools/CalculatorTest.java
// Path: source/org/helm/notation/CalculationException.java // public class CalculationException extends Exception { // // /** // * Creates a new instance of <code>StructureException</code> without detail // * message. // */ // public CalculationException() { // } // // /** // * Constructs an instance of <code>StructureException</code> with the // * specified detail message. // * // * @param msg // * the detail message. // */ // public CalculationException(String msg) { // super(msg); // } // } // // Path: source/org/helm/notation/MonomerException.java // public class MonomerException extends Exception { // // /** // * Creates a new instance of <code>MonomerException</code> without detail // * message. // */ // public MonomerException() { // } // // /** // * Constructs an instance of <code>MonomerException</code> with the // * specified detail message. // * // * @param msg // * the detail message. // */ // public MonomerException(String msg) { // super(msg); // } // // public MonomerException(String msg, Throwable err) { // super(msg, err); // } // } // // Path: source/org/helm/notation/NotationException.java // public class NotationException extends Exception { // // /** // * Creates a new instance of <code>NotationException</code> without detail // * message. // */ // public NotationException() { // } // // /** // * Constructs an instance of <code>NotationException</code> with the // * specified detail message. // * // * @param msg // * the detail message. // */ // public NotationException(String msg) { // super(msg); // } // // public NotationException(String msg, Throwable err) { // super(msg, err); // } // } // // Path: source/org/helm/notation/StructureException.java // public class StructureException extends Exception { // // /** // * Creates a new instance of <code>StructureException</code> without detail // * message. // */ // public StructureException() { // } // // /** // * Constructs an instance of <code>StructureException</code> with the // * specified detail message. // * // * @param msg // * the detail message. // */ // public StructureException(String msg) { // super(msg); // } // // public StructureException(String msg, Throwable err) { // super(msg, err); // } // }
import static org.junit.Assert.assertEquals; import java.io.IOException; import org.helm.notation.CalculationException; import org.helm.notation.MonomerException; import org.helm.notation.NotationException; import org.helm.notation.StructureException; import org.jdom.JDOMException; import org.junit.Before; import org.junit.Test;
package org.helm.notation.tools; public class CalculatorTest { private ExtinctionCoefficientCalculator calculator; @Before public void setUp() throws CalculationException { calculator = ExtinctionCoefficientCalculator.getInstance(); } @Test public void testCalculateFromAminoAcidSequence() throws CalculationException { String input = "AGGDDDDDDDDDDDDDDDDDDFFFFFFFFFFFFF"; float result = calculator.calculateFromAminoAcidSequence(input); assertEquals(result, 0.0, 1e-15); input = "AGGCFFFFFFFFFF"; result = calculator.calculateFromAminoAcidSequence(input); assertEquals(result, 0.0, 62.5); input = "AGGYEEEEEEEEEEEEEEEEEEE"; result = calculator.calculateFromAminoAcidSequence(input); assertEquals(result, 1490.0, 1e-15); input = "AGGWEEEEEEEEEEEEEEEEEEE"; result = calculator.calculateFromAminoAcidSequence(input); assertEquals(result, 5500.0, 1e-15); } @Test public void testCalculateFromPeptidePolymerNotation() throws NotationException, MonomerException, CalculationException,
// Path: source/org/helm/notation/CalculationException.java // public class CalculationException extends Exception { // // /** // * Creates a new instance of <code>StructureException</code> without detail // * message. // */ // public CalculationException() { // } // // /** // * Constructs an instance of <code>StructureException</code> with the // * specified detail message. // * // * @param msg // * the detail message. // */ // public CalculationException(String msg) { // super(msg); // } // } // // Path: source/org/helm/notation/MonomerException.java // public class MonomerException extends Exception { // // /** // * Creates a new instance of <code>MonomerException</code> without detail // * message. // */ // public MonomerException() { // } // // /** // * Constructs an instance of <code>MonomerException</code> with the // * specified detail message. // * // * @param msg // * the detail message. // */ // public MonomerException(String msg) { // super(msg); // } // // public MonomerException(String msg, Throwable err) { // super(msg, err); // } // } // // Path: source/org/helm/notation/NotationException.java // public class NotationException extends Exception { // // /** // * Creates a new instance of <code>NotationException</code> without detail // * message. // */ // public NotationException() { // } // // /** // * Constructs an instance of <code>NotationException</code> with the // * specified detail message. // * // * @param msg // * the detail message. // */ // public NotationException(String msg) { // super(msg); // } // // public NotationException(String msg, Throwable err) { // super(msg, err); // } // } // // Path: source/org/helm/notation/StructureException.java // public class StructureException extends Exception { // // /** // * Creates a new instance of <code>StructureException</code> without detail // * message. // */ // public StructureException() { // } // // /** // * Constructs an instance of <code>StructureException</code> with the // * specified detail message. // * // * @param msg // * the detail message. // */ // public StructureException(String msg) { // super(msg); // } // // public StructureException(String msg, Throwable err) { // super(msg, err); // } // } // Path: test/org/helm/notation/tools/CalculatorTest.java import static org.junit.Assert.assertEquals; import java.io.IOException; import org.helm.notation.CalculationException; import org.helm.notation.MonomerException; import org.helm.notation.NotationException; import org.helm.notation.StructureException; import org.jdom.JDOMException; import org.junit.Before; import org.junit.Test; package org.helm.notation.tools; public class CalculatorTest { private ExtinctionCoefficientCalculator calculator; @Before public void setUp() throws CalculationException { calculator = ExtinctionCoefficientCalculator.getInstance(); } @Test public void testCalculateFromAminoAcidSequence() throws CalculationException { String input = "AGGDDDDDDDDDDDDDDDDDDFFFFFFFFFFFFF"; float result = calculator.calculateFromAminoAcidSequence(input); assertEquals(result, 0.0, 1e-15); input = "AGGCFFFFFFFFFF"; result = calculator.calculateFromAminoAcidSequence(input); assertEquals(result, 0.0, 62.5); input = "AGGYEEEEEEEEEEEEEEEEEEE"; result = calculator.calculateFromAminoAcidSequence(input); assertEquals(result, 1490.0, 1e-15); input = "AGGWEEEEEEEEEEEEEEEEEEE"; result = calculator.calculateFromAminoAcidSequence(input); assertEquals(result, 5500.0, 1e-15); } @Test public void testCalculateFromPeptidePolymerNotation() throws NotationException, MonomerException, CalculationException,
IOException, JDOMException, StructureException {
PistoiaHELM/HELMNotationToolkit
source/org/helm/notation/tools/StructureParser.java
// Path: source/org/helm/notation/NotationException.java // public class NotationException extends Exception { // // /** // * Creates a new instance of <code>NotationException</code> without detail // * message. // */ // public NotationException() { // } // // /** // * Constructs an instance of <code>NotationException</code> with the // * specified detail message. // * // * @param msg // * the detail message. // */ // public NotationException(String msg) { // super(msg); // } // // public NotationException(String msg, Throwable err) { // super(msg, err); // } // } // // Path: source/org/helm/notation/StructureException.java // public class StructureException extends Exception { // // /** // * Creates a new instance of <code>StructureException</code> without detail // * message. // */ // public StructureException() { // } // // /** // * Constructs an instance of <code>StructureException</code> with the // * specified detail message. // * // * @param msg // * the detail message. // */ // public StructureException(String msg) { // super(msg); // } // // public StructureException(String msg, Throwable err) { // super(msg, err); // } // } // // Path: source/org/helm/notation/model/MoleculeInfo.java // public class MoleculeInfo { // private double molecularWeight; // private String molecularFormula; // private double exactMass; // // public double getMolecularWeight() { // return molecularWeight; // } // // public void setMolecularWeight(double molecularWeight) { // this.molecularWeight = molecularWeight; // } // // public String getMolecularFormula() { // return molecularFormula; // } // // public void setMolecularFormula(String molecularFormula) { // this.molecularFormula = molecularFormula; // } // // public double getExactMass() { // return exactMass; // } // // public void setExactMass(double exactMass) { // this.exactMass = exactMass; // } // }
import org.helm.notation.model.MoleculeInfo; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.TreeMap; import chemaxon.formats.MolImporter; import chemaxon.marvin.calculations.ElementalAnalyserPlugin; import chemaxon.marvin.plugin.PluginException; import chemaxon.struc.MolAtom; import chemaxon.struc.MolBond; import chemaxon.struc.Molecule; import org.helm.notation.NotationException; import org.helm.notation.StructureException;
/******************************************************************************* * Copyright C 2012, The Pistoia Alliance * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ******************************************************************************/ package org.helm.notation.tools; /** * This class provides methods that handle chemical structures * * @author zhangtianhong */ public class StructureParser { public static final String SMILES_EXTENSION_SEPARATOR_REGEX = "\\|"; public static final String SMILES_EXTENSION_SEPARATOR_SYMBOL = "|"; public static final String EXTENSION_COMPONENT_SEPARATOR_REGEX = "\\$"; public static final String EXTENSION_COMPONENT_SEPARATOR_SYMBOL = "$"; public static final String SMILES_MIXTURE_DELIMITER_REGEX = "\\."; public static final String ATOM_POSITION_DELIMITER_REGEX = "\\$|;"; public static final String ATOM_POSITION_DELIMITER_SYMBOL = ";"; public static final String WHITE_SPACE_REGEX = "\\s"; // 2014-05-13 -e :do not include enhanced stereochemistry features public static final String CHEMAXON_EXTENDEND_SMILES_FORMAT = "cxsmiles:u-e"; public static final String UNIQUE_SMILES_FORMAT = "smiles:u"; public static final String SMILES_FORMAT = "smiles"; private static final int CANONICALIZATION_ROUND = 3;
// Path: source/org/helm/notation/NotationException.java // public class NotationException extends Exception { // // /** // * Creates a new instance of <code>NotationException</code> without detail // * message. // */ // public NotationException() { // } // // /** // * Constructs an instance of <code>NotationException</code> with the // * specified detail message. // * // * @param msg // * the detail message. // */ // public NotationException(String msg) { // super(msg); // } // // public NotationException(String msg, Throwable err) { // super(msg, err); // } // } // // Path: source/org/helm/notation/StructureException.java // public class StructureException extends Exception { // // /** // * Creates a new instance of <code>StructureException</code> without detail // * message. // */ // public StructureException() { // } // // /** // * Constructs an instance of <code>StructureException</code> with the // * specified detail message. // * // * @param msg // * the detail message. // */ // public StructureException(String msg) { // super(msg); // } // // public StructureException(String msg, Throwable err) { // super(msg, err); // } // } // // Path: source/org/helm/notation/model/MoleculeInfo.java // public class MoleculeInfo { // private double molecularWeight; // private String molecularFormula; // private double exactMass; // // public double getMolecularWeight() { // return molecularWeight; // } // // public void setMolecularWeight(double molecularWeight) { // this.molecularWeight = molecularWeight; // } // // public String getMolecularFormula() { // return molecularFormula; // } // // public void setMolecularFormula(String molecularFormula) { // this.molecularFormula = molecularFormula; // } // // public double getExactMass() { // return exactMass; // } // // public void setExactMass(double exactMass) { // this.exactMass = exactMass; // } // } // Path: source/org/helm/notation/tools/StructureParser.java import org.helm.notation.model.MoleculeInfo; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.TreeMap; import chemaxon.formats.MolImporter; import chemaxon.marvin.calculations.ElementalAnalyserPlugin; import chemaxon.marvin.plugin.PluginException; import chemaxon.struc.MolAtom; import chemaxon.struc.MolBond; import chemaxon.struc.Molecule; import org.helm.notation.NotationException; import org.helm.notation.StructureException; /******************************************************************************* * Copyright C 2012, The Pistoia Alliance * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ******************************************************************************/ package org.helm.notation.tools; /** * This class provides methods that handle chemical structures * * @author zhangtianhong */ public class StructureParser { public static final String SMILES_EXTENSION_SEPARATOR_REGEX = "\\|"; public static final String SMILES_EXTENSION_SEPARATOR_SYMBOL = "|"; public static final String EXTENSION_COMPONENT_SEPARATOR_REGEX = "\\$"; public static final String EXTENSION_COMPONENT_SEPARATOR_SYMBOL = "$"; public static final String SMILES_MIXTURE_DELIMITER_REGEX = "\\."; public static final String ATOM_POSITION_DELIMITER_REGEX = "\\$|;"; public static final String ATOM_POSITION_DELIMITER_SYMBOL = ";"; public static final String WHITE_SPACE_REGEX = "\\s"; // 2014-05-13 -e :do not include enhanced stereochemistry features public static final String CHEMAXON_EXTENDEND_SMILES_FORMAT = "cxsmiles:u-e"; public static final String UNIQUE_SMILES_FORMAT = "smiles:u"; public static final String SMILES_FORMAT = "smiles"; private static final int CANONICALIZATION_ROUND = 3;
public static MoleculeInfo getMoleculeInfo(String smiles)
PistoiaHELM/HELMNotationToolkit
source/org/helm/notation/tools/StructureParser.java
// Path: source/org/helm/notation/NotationException.java // public class NotationException extends Exception { // // /** // * Creates a new instance of <code>NotationException</code> without detail // * message. // */ // public NotationException() { // } // // /** // * Constructs an instance of <code>NotationException</code> with the // * specified detail message. // * // * @param msg // * the detail message. // */ // public NotationException(String msg) { // super(msg); // } // // public NotationException(String msg, Throwable err) { // super(msg, err); // } // } // // Path: source/org/helm/notation/StructureException.java // public class StructureException extends Exception { // // /** // * Creates a new instance of <code>StructureException</code> without detail // * message. // */ // public StructureException() { // } // // /** // * Constructs an instance of <code>StructureException</code> with the // * specified detail message. // * // * @param msg // * the detail message. // */ // public StructureException(String msg) { // super(msg); // } // // public StructureException(String msg, Throwable err) { // super(msg, err); // } // } // // Path: source/org/helm/notation/model/MoleculeInfo.java // public class MoleculeInfo { // private double molecularWeight; // private String molecularFormula; // private double exactMass; // // public double getMolecularWeight() { // return molecularWeight; // } // // public void setMolecularWeight(double molecularWeight) { // this.molecularWeight = molecularWeight; // } // // public String getMolecularFormula() { // return molecularFormula; // } // // public void setMolecularFormula(String molecularFormula) { // this.molecularFormula = molecularFormula; // } // // public double getExactMass() { // return exactMass; // } // // public void setExactMass(double exactMass) { // this.exactMass = exactMass; // } // }
import org.helm.notation.model.MoleculeInfo; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.TreeMap; import chemaxon.formats.MolImporter; import chemaxon.marvin.calculations.ElementalAnalyserPlugin; import chemaxon.marvin.plugin.PluginException; import chemaxon.struc.MolAtom; import chemaxon.struc.MolBond; import chemaxon.struc.Molecule; import org.helm.notation.NotationException; import org.helm.notation.StructureException;
* * @param smiles * SMILES string to be validated * @return true or false * @throws java.io.IOException */ public static boolean validateSmiles(String smiles) throws IOException { Molecule mol = getMolecule(smiles); for (int i = 0; i < mol.getAtomCount(); i++) { MolAtom a = mol.getAtom(i); a.valenceCheck(); if (a.hasValenceError()) { return false; } } return true; } /** * This method removes everything in ChemAxon Extended SMILES extension, but * Atom Position Input: [*][H].O[*].OC1=CC=C(C[C@H](N[*])C([*])=O)C=C1 * |r,$_R1;;;_R2;;;;;;;;;_R1;;_R2;;;$,c:14,t:3,5| Output: * [*][H].O[*].OC1=CC=C(C[C@H](N[*])C([*])=O)C=C1 * |$_R1;;;_R2;;;;;;;;;_R1;;_R2;;;$| * * @param extendedSMILES * @return simpleExtendedSMILES * @throws org.helm.notation.StructureException */ public static String getSimpleExtendedSMILES(String extendedSMILES)
// Path: source/org/helm/notation/NotationException.java // public class NotationException extends Exception { // // /** // * Creates a new instance of <code>NotationException</code> without detail // * message. // */ // public NotationException() { // } // // /** // * Constructs an instance of <code>NotationException</code> with the // * specified detail message. // * // * @param msg // * the detail message. // */ // public NotationException(String msg) { // super(msg); // } // // public NotationException(String msg, Throwable err) { // super(msg, err); // } // } // // Path: source/org/helm/notation/StructureException.java // public class StructureException extends Exception { // // /** // * Creates a new instance of <code>StructureException</code> without detail // * message. // */ // public StructureException() { // } // // /** // * Constructs an instance of <code>StructureException</code> with the // * specified detail message. // * // * @param msg // * the detail message. // */ // public StructureException(String msg) { // super(msg); // } // // public StructureException(String msg, Throwable err) { // super(msg, err); // } // } // // Path: source/org/helm/notation/model/MoleculeInfo.java // public class MoleculeInfo { // private double molecularWeight; // private String molecularFormula; // private double exactMass; // // public double getMolecularWeight() { // return molecularWeight; // } // // public void setMolecularWeight(double molecularWeight) { // this.molecularWeight = molecularWeight; // } // // public String getMolecularFormula() { // return molecularFormula; // } // // public void setMolecularFormula(String molecularFormula) { // this.molecularFormula = molecularFormula; // } // // public double getExactMass() { // return exactMass; // } // // public void setExactMass(double exactMass) { // this.exactMass = exactMass; // } // } // Path: source/org/helm/notation/tools/StructureParser.java import org.helm.notation.model.MoleculeInfo; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.TreeMap; import chemaxon.formats.MolImporter; import chemaxon.marvin.calculations.ElementalAnalyserPlugin; import chemaxon.marvin.plugin.PluginException; import chemaxon.struc.MolAtom; import chemaxon.struc.MolBond; import chemaxon.struc.Molecule; import org.helm.notation.NotationException; import org.helm.notation.StructureException; * * @param smiles * SMILES string to be validated * @return true or false * @throws java.io.IOException */ public static boolean validateSmiles(String smiles) throws IOException { Molecule mol = getMolecule(smiles); for (int i = 0; i < mol.getAtomCount(); i++) { MolAtom a = mol.getAtom(i); a.valenceCheck(); if (a.hasValenceError()) { return false; } } return true; } /** * This method removes everything in ChemAxon Extended SMILES extension, but * Atom Position Input: [*][H].O[*].OC1=CC=C(C[C@H](N[*])C([*])=O)C=C1 * |r,$_R1;;;_R2;;;;;;;;;_R1;;_R2;;;$,c:14,t:3,5| Output: * [*][H].O[*].OC1=CC=C(C[C@H](N[*])C([*])=O)C=C1 * |$_R1;;;_R2;;;;;;;;;_R1;;_R2;;;$| * * @param extendedSMILES * @return simpleExtendedSMILES * @throws org.helm.notation.StructureException */ public static String getSimpleExtendedSMILES(String extendedSMILES)
throws StructureException {
PistoiaHELM/HELMNotationToolkit
source/org/helm/notation/tools/StructureParser.java
// Path: source/org/helm/notation/NotationException.java // public class NotationException extends Exception { // // /** // * Creates a new instance of <code>NotationException</code> without detail // * message. // */ // public NotationException() { // } // // /** // * Constructs an instance of <code>NotationException</code> with the // * specified detail message. // * // * @param msg // * the detail message. // */ // public NotationException(String msg) { // super(msg); // } // // public NotationException(String msg, Throwable err) { // super(msg, err); // } // } // // Path: source/org/helm/notation/StructureException.java // public class StructureException extends Exception { // // /** // * Creates a new instance of <code>StructureException</code> without detail // * message. // */ // public StructureException() { // } // // /** // * Constructs an instance of <code>StructureException</code> with the // * specified detail message. // * // * @param msg // * the detail message. // */ // public StructureException(String msg) { // super(msg); // } // // public StructureException(String msg, Throwable err) { // super(msg, err); // } // } // // Path: source/org/helm/notation/model/MoleculeInfo.java // public class MoleculeInfo { // private double molecularWeight; // private String molecularFormula; // private double exactMass; // // public double getMolecularWeight() { // return molecularWeight; // } // // public void setMolecularWeight(double molecularWeight) { // this.molecularWeight = molecularWeight; // } // // public String getMolecularFormula() { // return molecularFormula; // } // // public void setMolecularFormula(String molecularFormula) { // this.molecularFormula = molecularFormula; // } // // public double getExactMass() { // return exactMass; // } // // public void setExactMass(double exactMass) { // this.exactMass = exactMass; // } // }
import org.helm.notation.model.MoleculeInfo; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.TreeMap; import chemaxon.formats.MolImporter; import chemaxon.marvin.calculations.ElementalAnalyserPlugin; import chemaxon.marvin.plugin.PluginException; import chemaxon.struc.MolAtom; import chemaxon.struc.MolBond; import chemaxon.struc.Molecule; import org.helm.notation.NotationException; import org.helm.notation.StructureException;
* @return true or false * @throws StructureException */ protected static boolean isSingleStereo(MolAtom rAtom) throws StructureException { int bondCount = rAtom.getBondCount(); if (bondCount != 1) { throw new StructureException("RGroup is allowed to have single connection to other atom"); } MolBond bond = rAtom.getBond(0); int bondType = bond.getFlags() & MolBond.STEREO1_MASK; return bondType == MolBond.UP || bondType == MolBond.DOWN || bondType == MolBond.WAVY; } /** * This method should be used by SimpleNotationParser and * ComplexNotationParser, not exposed to public * * @param chunks * - list of main MoleculeInfo * @param caps * - list of cap MoleculeInfo * @return MoleculeInfo after processing * @throws NotationException */ protected static MoleculeInfo processMoleculeInfo( List<MoleculeInfo> chunks, List<MoleculeInfo> caps)
// Path: source/org/helm/notation/NotationException.java // public class NotationException extends Exception { // // /** // * Creates a new instance of <code>NotationException</code> without detail // * message. // */ // public NotationException() { // } // // /** // * Constructs an instance of <code>NotationException</code> with the // * specified detail message. // * // * @param msg // * the detail message. // */ // public NotationException(String msg) { // super(msg); // } // // public NotationException(String msg, Throwable err) { // super(msg, err); // } // } // // Path: source/org/helm/notation/StructureException.java // public class StructureException extends Exception { // // /** // * Creates a new instance of <code>StructureException</code> without detail // * message. // */ // public StructureException() { // } // // /** // * Constructs an instance of <code>StructureException</code> with the // * specified detail message. // * // * @param msg // * the detail message. // */ // public StructureException(String msg) { // super(msg); // } // // public StructureException(String msg, Throwable err) { // super(msg, err); // } // } // // Path: source/org/helm/notation/model/MoleculeInfo.java // public class MoleculeInfo { // private double molecularWeight; // private String molecularFormula; // private double exactMass; // // public double getMolecularWeight() { // return molecularWeight; // } // // public void setMolecularWeight(double molecularWeight) { // this.molecularWeight = molecularWeight; // } // // public String getMolecularFormula() { // return molecularFormula; // } // // public void setMolecularFormula(String molecularFormula) { // this.molecularFormula = molecularFormula; // } // // public double getExactMass() { // return exactMass; // } // // public void setExactMass(double exactMass) { // this.exactMass = exactMass; // } // } // Path: source/org/helm/notation/tools/StructureParser.java import org.helm.notation.model.MoleculeInfo; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.TreeMap; import chemaxon.formats.MolImporter; import chemaxon.marvin.calculations.ElementalAnalyserPlugin; import chemaxon.marvin.plugin.PluginException; import chemaxon.struc.MolAtom; import chemaxon.struc.MolBond; import chemaxon.struc.Molecule; import org.helm.notation.NotationException; import org.helm.notation.StructureException; * @return true or false * @throws StructureException */ protected static boolean isSingleStereo(MolAtom rAtom) throws StructureException { int bondCount = rAtom.getBondCount(); if (bondCount != 1) { throw new StructureException("RGroup is allowed to have single connection to other atom"); } MolBond bond = rAtom.getBond(0); int bondType = bond.getFlags() & MolBond.STEREO1_MASK; return bondType == MolBond.UP || bondType == MolBond.DOWN || bondType == MolBond.WAVY; } /** * This method should be used by SimpleNotationParser and * ComplexNotationParser, not exposed to public * * @param chunks * - list of main MoleculeInfo * @param caps * - list of cap MoleculeInfo * @return MoleculeInfo after processing * @throws NotationException */ protected static MoleculeInfo processMoleculeInfo( List<MoleculeInfo> chunks, List<MoleculeInfo> caps)
throws NotationException {
FangGet/ORB_SLAM2_Android
ORB_SLAM2_Android/src/orb/slam2/android/FileChooserActivity.java
// Path: ORB_SLAM2_Android/src/orb/slam2/android/FileChooserAdapter.java // static class FileInfo { // private FileType fileType; // private String fileName; // private String filePath; // // public FileInfo(String filePath, String fileName, boolean isDirectory) { // this.filePath = filePath; // this.fileName = fileName; // fileType = isDirectory ? FileType.DIRECTORY : FileType.FILE; // } // // public boolean isDirectory(){ // if(fileType == FileType.DIRECTORY) // return true ; // else // return false ; // } // // public String getFileName() { // return fileName; // } // // public void setFileName(String fileName) { // this.fileName = fileName; // } // // public String getFilePath() { // return filePath; // } // // public void setFilePath(String filePath) { // this.filePath = filePath; // } // // @Override // public String toString() { // return "FileInfo [fileType=" + fileType + ", fileName=" + fileName // + ", filePath=" + filePath + "]"; // } // }
import java.io.File; import java.security.acl.LastOwnerException; import java.util.ArrayList; import orb.slam2.android.FileChooserAdapter.FileInfo; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.os.Environment; import android.view.KeyEvent; import android.view.View; import android.view.WindowManager; import android.view.View.OnClickListener; import android.view.Window; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.GridView; import android.widget.TextView; import android.widget.Toast;
package orb.slam2.android; public class FileChooserActivity extends Activity { private GridView mGridView; private View mBackView; private View mBtExit,mBtOk; private TextView mTvPath ; private String mSdcardRootPath ; //sdcard 根路径 private String mLastFilePath ; //当前显示的路径
// Path: ORB_SLAM2_Android/src/orb/slam2/android/FileChooserAdapter.java // static class FileInfo { // private FileType fileType; // private String fileName; // private String filePath; // // public FileInfo(String filePath, String fileName, boolean isDirectory) { // this.filePath = filePath; // this.fileName = fileName; // fileType = isDirectory ? FileType.DIRECTORY : FileType.FILE; // } // // public boolean isDirectory(){ // if(fileType == FileType.DIRECTORY) // return true ; // else // return false ; // } // // public String getFileName() { // return fileName; // } // // public void setFileName(String fileName) { // this.fileName = fileName; // } // // public String getFilePath() { // return filePath; // } // // public void setFilePath(String filePath) { // this.filePath = filePath; // } // // @Override // public String toString() { // return "FileInfo [fileType=" + fileType + ", fileName=" + fileName // + ", filePath=" + filePath + "]"; // } // } // Path: ORB_SLAM2_Android/src/orb/slam2/android/FileChooserActivity.java import java.io.File; import java.security.acl.LastOwnerException; import java.util.ArrayList; import orb.slam2.android.FileChooserAdapter.FileInfo; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.os.Environment; import android.view.KeyEvent; import android.view.View; import android.view.WindowManager; import android.view.View.OnClickListener; import android.view.Window; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.GridView; import android.widget.TextView; import android.widget.Toast; package orb.slam2.android; public class FileChooserActivity extends Activity { private GridView mGridView; private View mBackView; private View mBtExit,mBtOk; private TextView mTvPath ; private String mSdcardRootPath ; //sdcard 根路径 private String mLastFilePath ; //当前显示的路径
private ArrayList<FileInfo> mFileLists ;
shamanDevel/jME3-OpenCL-Library
src/main/java/org/shaman/jmecl/sorting/BitonicSort.java
// Path: src/main/java/org/shaman/jmecl/OpenCLSettings.java // public class OpenCLSettings { // // private final Context clContext; // private final CommandQueue clCommandQueue; // private final ProgramCache programCache; // private final AssetManager assetManager; // // public OpenCLSettings(Context clContext, CommandQueue clCommandQueue, // ProgramCache programCache, AssetManager assetManager) { // this.clContext = clContext; // this.clCommandQueue = clCommandQueue; // this.programCache = programCache!=null ? programCache : new ProgramCache(); // this.assetManager = assetManager; // } // // public Context getClContext() { // return clContext; // } // // public CommandQueue getClCommandQueue() { // return clCommandQueue; // } // // public ProgramCache getProgramCache() { // return programCache; // } // // public AssetManager getAssetManager() { // return assetManager; // } // // @Override // public int hashCode() { // int hash = 3; // hash = 43 * hash + Objects.hashCode(this.clContext); // hash = 43 * hash + Objects.hashCode(this.clCommandQueue); // return hash; // } // // @Override // public boolean equals(Object obj) { // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // final OpenCLSettings other = (OpenCLSettings) obj; // if (!Objects.equals(this.clContext, other.clContext)) { // return false; // } // if (!Objects.equals(this.clCommandQueue, other.clCommandQueue)) { // return false; // } // return true; // } // // }
import com.jme3.asset.AssetManager; import com.jme3.math.FastMath; import com.jme3.opencl.*;; import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.CyclicBarrier; import java.util.logging.Level; import java.util.logging.Logger; import org.shaman.jmecl.OpenCLSettings;
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.shaman.jmecl.sorting; /** * Bitonic sort. * This is a comparison-based, in-place, non-stable sorting algorithm. * For simplicity and speed, the length of the input array must be a power of two. * * <p> * Peters, H. , Schulz-Hildebrandt, O., Luttenberger, N., "Fast in-place, comparison-based sorting with cuda: a study with bitonic sort," Concurrency and computation, vol. 2011 (23), no. 7, pp. 681-693. * http://onlinelibrary.wiley.com/store/10.1002/cpe.1686/asset/1686 ftp. pdf?v=1&t=ioo1otg2&s=ad0c0650d7248a8d9d943cd0327bbcd7db093c0d * @author shaman */ public class BitonicSort implements Sorter { private static final Logger LOG = Logger.getLogger(BitonicSort.class.getName()); private static final String PROGRAM_FILE = "org/shaman/jmecl/sorting/BitonicSort.cl"; private final Context clContext; private final Device clDevice; private final CommandQueue clQueue; private final Sorter.ComparisonSettings settings; private int sharedMemorySize; private int workGroupSize; private Program program; private Kernel bitonicTrivialKernel; private Kernel bitonicSharedKernel; private final boolean useSharedMemory; /** * Creates a new instance of the bitonic sort algorithm. * @param openCLSettings the OpenCL settings * @param comparisonSettings the comparison settings */
// Path: src/main/java/org/shaman/jmecl/OpenCLSettings.java // public class OpenCLSettings { // // private final Context clContext; // private final CommandQueue clCommandQueue; // private final ProgramCache programCache; // private final AssetManager assetManager; // // public OpenCLSettings(Context clContext, CommandQueue clCommandQueue, // ProgramCache programCache, AssetManager assetManager) { // this.clContext = clContext; // this.clCommandQueue = clCommandQueue; // this.programCache = programCache!=null ? programCache : new ProgramCache(); // this.assetManager = assetManager; // } // // public Context getClContext() { // return clContext; // } // // public CommandQueue getClCommandQueue() { // return clCommandQueue; // } // // public ProgramCache getProgramCache() { // return programCache; // } // // public AssetManager getAssetManager() { // return assetManager; // } // // @Override // public int hashCode() { // int hash = 3; // hash = 43 * hash + Objects.hashCode(this.clContext); // hash = 43 * hash + Objects.hashCode(this.clCommandQueue); // return hash; // } // // @Override // public boolean equals(Object obj) { // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // final OpenCLSettings other = (OpenCLSettings) obj; // if (!Objects.equals(this.clContext, other.clContext)) { // return false; // } // if (!Objects.equals(this.clCommandQueue, other.clCommandQueue)) { // return false; // } // return true; // } // // } // Path: src/main/java/org/shaman/jmecl/sorting/BitonicSort.java import com.jme3.asset.AssetManager; import com.jme3.math.FastMath; import com.jme3.opencl.*;; import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.CyclicBarrier; import java.util.logging.Level; import java.util.logging.Logger; import org.shaman.jmecl.OpenCLSettings; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.shaman.jmecl.sorting; /** * Bitonic sort. * This is a comparison-based, in-place, non-stable sorting algorithm. * For simplicity and speed, the length of the input array must be a power of two. * * <p> * Peters, H. , Schulz-Hildebrandt, O., Luttenberger, N., "Fast in-place, comparison-based sorting with cuda: a study with bitonic sort," Concurrency and computation, vol. 2011 (23), no. 7, pp. 681-693. * http://onlinelibrary.wiley.com/store/10.1002/cpe.1686/asset/1686 ftp. pdf?v=1&t=ioo1otg2&s=ad0c0650d7248a8d9d943cd0327bbcd7db093c0d * @author shaman */ public class BitonicSort implements Sorter { private static final Logger LOG = Logger.getLogger(BitonicSort.class.getName()); private static final String PROGRAM_FILE = "org/shaman/jmecl/sorting/BitonicSort.cl"; private final Context clContext; private final Device clDevice; private final CommandQueue clQueue; private final Sorter.ComparisonSettings settings; private int sharedMemorySize; private int workGroupSize; private Program program; private Kernel bitonicTrivialKernel; private Kernel bitonicSharedKernel; private final boolean useSharedMemory; /** * Creates a new instance of the bitonic sort algorithm. * @param openCLSettings the OpenCL settings * @param comparisonSettings the comparison settings */
public BitonicSort(OpenCLSettings openCLSettings, Sorter.ComparisonSettings comparisonSettings) {
shamanDevel/jME3-OpenCL-Library
src/main/java/org/shaman/jmecl/sorting/RadixSort.java
// Path: src/main/java/org/shaman/jmecl/OpenCLSettings.java // public class OpenCLSettings { // // private final Context clContext; // private final CommandQueue clCommandQueue; // private final ProgramCache programCache; // private final AssetManager assetManager; // // public OpenCLSettings(Context clContext, CommandQueue clCommandQueue, // ProgramCache programCache, AssetManager assetManager) { // this.clContext = clContext; // this.clCommandQueue = clCommandQueue; // this.programCache = programCache!=null ? programCache : new ProgramCache(); // this.assetManager = assetManager; // } // // public Context getClContext() { // return clContext; // } // // public CommandQueue getClCommandQueue() { // return clCommandQueue; // } // // public ProgramCache getProgramCache() { // return programCache; // } // // public AssetManager getAssetManager() { // return assetManager; // } // // @Override // public int hashCode() { // int hash = 3; // hash = 43 * hash + Objects.hashCode(this.clContext); // hash = 43 * hash + Objects.hashCode(this.clCommandQueue); // return hash; // } // // @Override // public boolean equals(Object obj) { // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // final OpenCLSettings other = (OpenCLSettings) obj; // if (!Objects.equals(this.clContext, other.clContext)) { // return false; // } // if (!Objects.equals(this.clCommandQueue, other.clCommandQueue)) { // return false; // } // return true; // } // // }
import com.jme3.asset.AssetManager; import com.jme3.opencl.*; import java.nio.ByteBuffer; import java.util.logging.Level; import java.util.logging.Logger; import org.shaman.jmecl.OpenCLSettings;
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.shaman.jmecl.sorting; /** * Radix sort implementation. * Only integer keys and values are supported. * This is a stable, in-place, non-comparison-based algorithm. * You have to specify the range of bits to be sorted by {@link #setEndBit(int) } * (the start bit is assumed to be zero). * * <p> * A. G. DUANE MERRILL, "High performance and scalable radix sorting: A case study of implementing dynamic parallelism for gpu computing," Parallel processing letters, vol. 2011 (21), no. 2, pp. 245 - 272. * * Geist Software Labs, \libcl: Parallel algorithm library." * http://www.libcl.org * @author shaman */ public class RadixSort implements Sorter { private static final Logger LOG = Logger.getLogger(BitonicSort.class.getName()); private static final String PROGRAM_FILE = "org/shaman/jmecl/sorting/RadixSort.cl"; private final Context clContext; private final Device clDevice; private final CommandQueue clQueue; private final Sorter.ComparisonSettings settings; private final int RS_CBITS = 4; private final int RS_BLOCK_SIZE = 256; private final int RS_BLOCK_SIZE_CUBE = RS_BLOCK_SIZE*RS_BLOCK_SIZE*RS_BLOCK_SIZE; private final long cMaxArraySize = RS_BLOCK_SIZE_CUBE * 4 / (1 << RS_CBITS); private Program program; private final Kernel clBlockSort; private final Kernel clBlockScan; private final Kernel clBlockPrefix; private final Kernel clReorder; private Buffer bfTempKey; private Buffer bfTempVal; private Buffer bfBlockScan; private Buffer bfBlockSum; private Buffer bfBlockOffset; private int endBit = 32; /** * Creates a new instance of the radix sort using ascending sorting on * integer keys and values. * * @param settings the opencl settings */
// Path: src/main/java/org/shaman/jmecl/OpenCLSettings.java // public class OpenCLSettings { // // private final Context clContext; // private final CommandQueue clCommandQueue; // private final ProgramCache programCache; // private final AssetManager assetManager; // // public OpenCLSettings(Context clContext, CommandQueue clCommandQueue, // ProgramCache programCache, AssetManager assetManager) { // this.clContext = clContext; // this.clCommandQueue = clCommandQueue; // this.programCache = programCache!=null ? programCache : new ProgramCache(); // this.assetManager = assetManager; // } // // public Context getClContext() { // return clContext; // } // // public CommandQueue getClCommandQueue() { // return clCommandQueue; // } // // public ProgramCache getProgramCache() { // return programCache; // } // // public AssetManager getAssetManager() { // return assetManager; // } // // @Override // public int hashCode() { // int hash = 3; // hash = 43 * hash + Objects.hashCode(this.clContext); // hash = 43 * hash + Objects.hashCode(this.clCommandQueue); // return hash; // } // // @Override // public boolean equals(Object obj) { // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // final OpenCLSettings other = (OpenCLSettings) obj; // if (!Objects.equals(this.clContext, other.clContext)) { // return false; // } // if (!Objects.equals(this.clCommandQueue, other.clCommandQueue)) { // return false; // } // return true; // } // // } // Path: src/main/java/org/shaman/jmecl/sorting/RadixSort.java import com.jme3.asset.AssetManager; import com.jme3.opencl.*; import java.nio.ByteBuffer; import java.util.logging.Level; import java.util.logging.Logger; import org.shaman.jmecl.OpenCLSettings; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.shaman.jmecl.sorting; /** * Radix sort implementation. * Only integer keys and values are supported. * This is a stable, in-place, non-comparison-based algorithm. * You have to specify the range of bits to be sorted by {@link #setEndBit(int) } * (the start bit is assumed to be zero). * * <p> * A. G. DUANE MERRILL, "High performance and scalable radix sorting: A case study of implementing dynamic parallelism for gpu computing," Parallel processing letters, vol. 2011 (21), no. 2, pp. 245 - 272. * * Geist Software Labs, \libcl: Parallel algorithm library." * http://www.libcl.org * @author shaman */ public class RadixSort implements Sorter { private static final Logger LOG = Logger.getLogger(BitonicSort.class.getName()); private static final String PROGRAM_FILE = "org/shaman/jmecl/sorting/RadixSort.cl"; private final Context clContext; private final Device clDevice; private final CommandQueue clQueue; private final Sorter.ComparisonSettings settings; private final int RS_CBITS = 4; private final int RS_BLOCK_SIZE = 256; private final int RS_BLOCK_SIZE_CUBE = RS_BLOCK_SIZE*RS_BLOCK_SIZE*RS_BLOCK_SIZE; private final long cMaxArraySize = RS_BLOCK_SIZE_CUBE * 4 / (1 << RS_CBITS); private Program program; private final Kernel clBlockSort; private final Kernel clBlockScan; private final Kernel clBlockPrefix; private final Kernel clReorder; private Buffer bfTempKey; private Buffer bfTempVal; private Buffer bfBlockScan; private Buffer bfBlockSum; private Buffer bfBlockOffset; private int endBit = 32; /** * Creates a new instance of the radix sort using ascending sorting on * integer keys and values. * * @param settings the opencl settings */
public RadixSort(OpenCLSettings settings) {
shamanDevel/jME3-OpenCL-Library
src/main/java/org/shaman/jmecl/particles/DefaultAdvectionStrategy.java
// Path: src/main/java/org/shaman/jmecl/OpenCLSettings.java // public class OpenCLSettings { // // private final Context clContext; // private final CommandQueue clCommandQueue; // private final ProgramCache programCache; // private final AssetManager assetManager; // // public OpenCLSettings(Context clContext, CommandQueue clCommandQueue, // ProgramCache programCache, AssetManager assetManager) { // this.clContext = clContext; // this.clCommandQueue = clCommandQueue; // this.programCache = programCache!=null ? programCache : new ProgramCache(); // this.assetManager = assetManager; // } // // public Context getClContext() { // return clContext; // } // // public CommandQueue getClCommandQueue() { // return clCommandQueue; // } // // public ProgramCache getProgramCache() { // return programCache; // } // // public AssetManager getAssetManager() { // return assetManager; // } // // @Override // public int hashCode() { // int hash = 3; // hash = 43 * hash + Objects.hashCode(this.clContext); // hash = 43 * hash + Objects.hashCode(this.clCommandQueue); // return hash; // } // // @Override // public boolean equals(Object obj) { // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // final OpenCLSettings other = (OpenCLSettings) obj; // if (!Objects.equals(this.clContext, other.clContext)) { // return false; // } // if (!Objects.equals(this.clCommandQueue, other.clCommandQueue)) { // return false; // } // return true; // } // // }
import com.jme3.math.Vector3f; import com.jme3.math.Vector4f; import com.jme3.opencl.Buffer; import com.jme3.opencl.CommandQueue; import com.jme3.opencl.Kernel; import com.jme3.opencl.Program; import com.jme3.scene.VertexBuffer; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import org.shaman.jmecl.OpenCLSettings;
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.shaman.jmecl.particles; /** * A default advection strategy. * <p> * Particles can have: * <ul> * <li>a position</li> * <li>a velocity</li> * <li>an acceleration, or a global acceleration</li> * <li>a mass, or a global mass</li> * <li>a color</li> * </ul> * <p> * Deletion by (multiple can be specified): * <ul> * <li>axis aligned bounding box</li> * <li>bounding sphere</li> * <li>lower density threshold</li> * </ul> * <p> * Advection equation: <br> * <code> v = v + dt * (alpha*density*gravity - beta * temperature * gravity + velocity_field(x)/density </code> <br> * <code> x = x + dt * v </code> * <p> * Exponential decay: <br> * <code> temperature = temperature - dt * temperature * lambda </code> <br> * <code> density = density - dt * temperature * mu </code> <br> * It must hold that <code>dt * lambda < 1</code>, <code>dt * my < 1</code> for the largest possible timestep <code>dt</code> */ public class DefaultAdvectionStrategy implements AdvectionStrategy { private static final String SOURCE_FILE = "org/shaman/jmecl/particles/DefaultAdvectionStrategy.cl";
// Path: src/main/java/org/shaman/jmecl/OpenCLSettings.java // public class OpenCLSettings { // // private final Context clContext; // private final CommandQueue clCommandQueue; // private final ProgramCache programCache; // private final AssetManager assetManager; // // public OpenCLSettings(Context clContext, CommandQueue clCommandQueue, // ProgramCache programCache, AssetManager assetManager) { // this.clContext = clContext; // this.clCommandQueue = clCommandQueue; // this.programCache = programCache!=null ? programCache : new ProgramCache(); // this.assetManager = assetManager; // } // // public Context getClContext() { // return clContext; // } // // public CommandQueue getClCommandQueue() { // return clCommandQueue; // } // // public ProgramCache getProgramCache() { // return programCache; // } // // public AssetManager getAssetManager() { // return assetManager; // } // // @Override // public int hashCode() { // int hash = 3; // hash = 43 * hash + Objects.hashCode(this.clContext); // hash = 43 * hash + Objects.hashCode(this.clCommandQueue); // return hash; // } // // @Override // public boolean equals(Object obj) { // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // final OpenCLSettings other = (OpenCLSettings) obj; // if (!Objects.equals(this.clContext, other.clContext)) { // return false; // } // if (!Objects.equals(this.clCommandQueue, other.clCommandQueue)) { // return false; // } // return true; // } // // } // Path: src/main/java/org/shaman/jmecl/particles/DefaultAdvectionStrategy.java import com.jme3.math.Vector3f; import com.jme3.math.Vector4f; import com.jme3.opencl.Buffer; import com.jme3.opencl.CommandQueue; import com.jme3.opencl.Kernel; import com.jme3.opencl.Program; import com.jme3.scene.VertexBuffer; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import org.shaman.jmecl.OpenCLSettings; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.shaman.jmecl.particles; /** * A default advection strategy. * <p> * Particles can have: * <ul> * <li>a position</li> * <li>a velocity</li> * <li>an acceleration, or a global acceleration</li> * <li>a mass, or a global mass</li> * <li>a color</li> * </ul> * <p> * Deletion by (multiple can be specified): * <ul> * <li>axis aligned bounding box</li> * <li>bounding sphere</li> * <li>lower density threshold</li> * </ul> * <p> * Advection equation: <br> * <code> v = v + dt * (alpha*density*gravity - beta * temperature * gravity + velocity_field(x)/density </code> <br> * <code> x = x + dt * v </code> * <p> * Exponential decay: <br> * <code> temperature = temperature - dt * temperature * lambda </code> <br> * <code> density = density - dt * temperature * mu </code> <br> * It must hold that <code>dt * lambda < 1</code>, <code>dt * my < 1</code> for the largest possible timestep <code>dt</code> */ public class DefaultAdvectionStrategy implements AdvectionStrategy { private static final String SOURCE_FILE = "org/shaman/jmecl/particles/DefaultAdvectionStrategy.cl";
private static final Map<OpenCLSettings, Kernels> kernelMap = new HashMap<>();
shamanDevel/jME3-OpenCL-Library
src/main/java/org/shaman/jmecl/fluids/DebugTools.java
// Path: src/main/java/org/shaman/jmecl/utils/SharedTexture.java // public class SharedTexture { // // private Texture texture; // private Image image; // private com.jme3.opencl.Image clImage; // private com.jme3.opencl.Image.ImageDescriptor descriptor; // private Image.Format format; // private GLRenderer renderer; // // /** // * Creates a new shared texture with the specified dimensions, type and format // * @param descriptor specifies dimensions and type // * @param format specifies the format // */ // public SharedTexture(com.jme3.opencl.Image.ImageDescriptor descriptor, Image.Format format) { // if (descriptor == null) { // throw new NullPointerException("descriptor is null"); // } // if (format == null) { // throw new NullPointerException("format is null"); // } // this.descriptor = descriptor; // this.format = format; // } // // /** // * Creates a new shared texture from an already existing jME texture. // * Only the creation of the shared OpenCL image is left // * @param texture // */ // public SharedTexture(Texture texture) { // this.texture = texture; // this.image = texture.getImage(); // } // // /** // * Checks if the image is already initialized. // * @return {@code true} if already initialized // */ // public boolean isInitialized() { // return clImage != null; // } // // /** // * Initializes the shared textures. // * The texture is created (not with the constructor taking the texture as argument), // * uploaded to the GPU and shared with OpenCL. // * Must be called from the jME main thread. // * // * @param renderManager the render manager // * @param clContext the OpenCL context // * @param memoryAccess the allowed memory access to the OpenCL texture // * // * @throws IllegalStateException if it was already initialized // * @throws IllegalArgumentException // * If the underlying renderer implementation is not {@code GLRenderer}, or // * if the OpenCL texture type can't be mapped to a texture type of jME // */ // public void initialize(RenderManager renderManager, Context clContext, MemoryAccess memoryAccess) { // if (isInitialized()) { // throw new IllegalStateException("already initialized"); // } // //get renderer // if (renderManager.getRenderer() instanceof GLRenderer) { // renderer = (GLRenderer) renderManager.getRenderer(); // } else { // throw new IllegalArgumentException("Only GLRenderer supported"); // } // // //create texture // if (texture == null) { // switch (descriptor.type) { // case IMAGE_2D: // texture = new Texture2D((int) descriptor.width, (int) descriptor.height, format); // break; // case IMAGE_2D_ARRAY: // ArrayList<Image> images = new ArrayList<>((int) descriptor.arraySize); // for (int i=0; i<descriptor.arraySize; ++i) { // images.add(new Image(format, (int) descriptor.width, (int) descriptor.height, null, ColorSpace.Linear)); // } // texture = new TextureArray(images); // break; // case IMAGE_3D: // texture = new Texture3D((int) descriptor.width, (int) descriptor.height, (int) descriptor.depth, format); // break; // default: // throw new IllegalArgumentException("unsupported texture type: "+descriptor.type); // } // image = texture.getImage(); // } // // //upload texture to GPU // renderer.updateTexImageData(image, texture.getType(), 0, false); // // //create shared image // clImage = clContext.bindImage(texture, memoryAccess).register(); // } // // /** // * Returns the jME texture. // * @return // */ // public Texture getJMETexture() { // return texture; // } // // /** // * Returns the OpenCL image // * @return // */ // public com.jme3.opencl.Image getCLImage() { // return clImage; // } // }
import com.jme3.math.ColorRGBA; import com.jme3.opencl.Buffer; import com.jme3.opencl.CommandQueue; import com.jme3.opencl.Kernel; import com.jme3.opencl.MappingAccess; import com.jme3.opencl.MemoryAccess; import com.jme3.opencl.Program; import com.jme3.renderer.RenderManager; import com.jme3.texture.Image; import com.jme3.util.BufferUtils; import java.nio.ByteBuffer; import java.nio.FloatBuffer; import java.util.EnumMap; import org.shaman.jmecl.utils.SharedTexture;
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.shaman.jmecl.fluids; /** * Various helper methods for testing the fluid solver. * @author Sebastian */ public class DebugTools { private final FluidSolver solver; private boolean flagCopyInitialized; private Buffer flagColorsBuffer; private Kernel flagCopyKernel; public DebugTools(FluidSolver solver) { this.solver = solver; }
// Path: src/main/java/org/shaman/jmecl/utils/SharedTexture.java // public class SharedTexture { // // private Texture texture; // private Image image; // private com.jme3.opencl.Image clImage; // private com.jme3.opencl.Image.ImageDescriptor descriptor; // private Image.Format format; // private GLRenderer renderer; // // /** // * Creates a new shared texture with the specified dimensions, type and format // * @param descriptor specifies dimensions and type // * @param format specifies the format // */ // public SharedTexture(com.jme3.opencl.Image.ImageDescriptor descriptor, Image.Format format) { // if (descriptor == null) { // throw new NullPointerException("descriptor is null"); // } // if (format == null) { // throw new NullPointerException("format is null"); // } // this.descriptor = descriptor; // this.format = format; // } // // /** // * Creates a new shared texture from an already existing jME texture. // * Only the creation of the shared OpenCL image is left // * @param texture // */ // public SharedTexture(Texture texture) { // this.texture = texture; // this.image = texture.getImage(); // } // // /** // * Checks if the image is already initialized. // * @return {@code true} if already initialized // */ // public boolean isInitialized() { // return clImage != null; // } // // /** // * Initializes the shared textures. // * The texture is created (not with the constructor taking the texture as argument), // * uploaded to the GPU and shared with OpenCL. // * Must be called from the jME main thread. // * // * @param renderManager the render manager // * @param clContext the OpenCL context // * @param memoryAccess the allowed memory access to the OpenCL texture // * // * @throws IllegalStateException if it was already initialized // * @throws IllegalArgumentException // * If the underlying renderer implementation is not {@code GLRenderer}, or // * if the OpenCL texture type can't be mapped to a texture type of jME // */ // public void initialize(RenderManager renderManager, Context clContext, MemoryAccess memoryAccess) { // if (isInitialized()) { // throw new IllegalStateException("already initialized"); // } // //get renderer // if (renderManager.getRenderer() instanceof GLRenderer) { // renderer = (GLRenderer) renderManager.getRenderer(); // } else { // throw new IllegalArgumentException("Only GLRenderer supported"); // } // // //create texture // if (texture == null) { // switch (descriptor.type) { // case IMAGE_2D: // texture = new Texture2D((int) descriptor.width, (int) descriptor.height, format); // break; // case IMAGE_2D_ARRAY: // ArrayList<Image> images = new ArrayList<>((int) descriptor.arraySize); // for (int i=0; i<descriptor.arraySize; ++i) { // images.add(new Image(format, (int) descriptor.width, (int) descriptor.height, null, ColorSpace.Linear)); // } // texture = new TextureArray(images); // break; // case IMAGE_3D: // texture = new Texture3D((int) descriptor.width, (int) descriptor.height, (int) descriptor.depth, format); // break; // default: // throw new IllegalArgumentException("unsupported texture type: "+descriptor.type); // } // image = texture.getImage(); // } // // //upload texture to GPU // renderer.updateTexImageData(image, texture.getType(), 0, false); // // //create shared image // clImage = clContext.bindImage(texture, memoryAccess).register(); // } // // /** // * Returns the jME texture. // * @return // */ // public Texture getJMETexture() { // return texture; // } // // /** // * Returns the OpenCL image // * @return // */ // public com.jme3.opencl.Image getCLImage() { // return clImage; // } // } // Path: src/main/java/org/shaman/jmecl/fluids/DebugTools.java import com.jme3.math.ColorRGBA; import com.jme3.opencl.Buffer; import com.jme3.opencl.CommandQueue; import com.jme3.opencl.Kernel; import com.jme3.opencl.MappingAccess; import com.jme3.opencl.MemoryAccess; import com.jme3.opencl.Program; import com.jme3.renderer.RenderManager; import com.jme3.texture.Image; import com.jme3.util.BufferUtils; import java.nio.ByteBuffer; import java.nio.FloatBuffer; import java.util.EnumMap; import org.shaman.jmecl.utils.SharedTexture; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.shaman.jmecl.fluids; /** * Various helper methods for testing the fluid solver. * @author Sebastian */ public class DebugTools { private final FluidSolver solver; private boolean flagCopyInitialized; private Buffer flagColorsBuffer; private Kernel flagCopyKernel; public DebugTools(FluidSolver solver) { this.solver = solver; }
public SharedTexture createRealTexture2D(RenderManager renderManager) {
shamanDevel/jME3-OpenCL-Library
src/main/java/org/shaman/jmecl/particles/ShapeSeedingStrategy.java
// Path: src/main/java/org/shaman/jmecl/OpenCLSettings.java // public class OpenCLSettings { // // private final Context clContext; // private final CommandQueue clCommandQueue; // private final ProgramCache programCache; // private final AssetManager assetManager; // // public OpenCLSettings(Context clContext, CommandQueue clCommandQueue, // ProgramCache programCache, AssetManager assetManager) { // this.clContext = clContext; // this.clCommandQueue = clCommandQueue; // this.programCache = programCache!=null ? programCache : new ProgramCache(); // this.assetManager = assetManager; // } // // public Context getClContext() { // return clContext; // } // // public CommandQueue getClCommandQueue() { // return clCommandQueue; // } // // public ProgramCache getProgramCache() { // return programCache; // } // // public AssetManager getAssetManager() { // return assetManager; // } // // @Override // public int hashCode() { // int hash = 3; // hash = 43 * hash + Objects.hashCode(this.clContext); // hash = 43 * hash + Objects.hashCode(this.clCommandQueue); // return hash; // } // // @Override // public boolean equals(Object obj) { // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // final OpenCLSettings other = (OpenCLSettings) obj; // if (!Objects.equals(this.clContext, other.clContext)) { // return false; // } // if (!Objects.equals(this.clCommandQueue, other.clCommandQueue)) { // return false; // } // return true; // } // // }
import com.jme3.math.Vector3f; import com.jme3.math.Vector4f; import com.jme3.opencl.Buffer; import com.jme3.opencl.CommandQueue; import com.jme3.opencl.Kernel; import com.jme3.opencl.Program; import com.jme3.scene.VertexBuffer; import com.jme3.util.BufferUtils; import com.jme3.util.TempVars; import java.nio.ByteBuffer; import java.util.HashMap; import java.util.Map; import java.util.Random; import org.shaman.jmecl.OpenCLSettings;
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.shaman.jmecl.particles; /** * * @author Sebastian Weiss */ public class ShapeSeedingStrategy implements SeedingStrategy { private static final int RANDOM_SEED_COUNT = 2048; private static final String SOURCE_FILE = "org/shaman/jmecl/particles/ShapeSeedingStrategy.cl";
// Path: src/main/java/org/shaman/jmecl/OpenCLSettings.java // public class OpenCLSettings { // // private final Context clContext; // private final CommandQueue clCommandQueue; // private final ProgramCache programCache; // private final AssetManager assetManager; // // public OpenCLSettings(Context clContext, CommandQueue clCommandQueue, // ProgramCache programCache, AssetManager assetManager) { // this.clContext = clContext; // this.clCommandQueue = clCommandQueue; // this.programCache = programCache!=null ? programCache : new ProgramCache(); // this.assetManager = assetManager; // } // // public Context getClContext() { // return clContext; // } // // public CommandQueue getClCommandQueue() { // return clCommandQueue; // } // // public ProgramCache getProgramCache() { // return programCache; // } // // public AssetManager getAssetManager() { // return assetManager; // } // // @Override // public int hashCode() { // int hash = 3; // hash = 43 * hash + Objects.hashCode(this.clContext); // hash = 43 * hash + Objects.hashCode(this.clCommandQueue); // return hash; // } // // @Override // public boolean equals(Object obj) { // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // final OpenCLSettings other = (OpenCLSettings) obj; // if (!Objects.equals(this.clContext, other.clContext)) { // return false; // } // if (!Objects.equals(this.clCommandQueue, other.clCommandQueue)) { // return false; // } // return true; // } // // } // Path: src/main/java/org/shaman/jmecl/particles/ShapeSeedingStrategy.java import com.jme3.math.Vector3f; import com.jme3.math.Vector4f; import com.jme3.opencl.Buffer; import com.jme3.opencl.CommandQueue; import com.jme3.opencl.Kernel; import com.jme3.opencl.Program; import com.jme3.scene.VertexBuffer; import com.jme3.util.BufferUtils; import com.jme3.util.TempVars; import java.nio.ByteBuffer; import java.util.HashMap; import java.util.Map; import java.util.Random; import org.shaman.jmecl.OpenCLSettings; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.shaman.jmecl.particles; /** * * @author Sebastian Weiss */ public class ShapeSeedingStrategy implements SeedingStrategy { private static final int RANDOM_SEED_COUNT = 2048; private static final String SOURCE_FILE = "org/shaman/jmecl/particles/ShapeSeedingStrategy.cl";
private static final Map<OpenCLSettings, Kernels> kernelMap = new HashMap<>();
shamanDevel/jME3-OpenCL-Library
src/main/java/org/shaman/jmecl/utils/CLBlas.java
// Path: src/main/java/org/shaman/jmecl/OpenCLSettings.java // public class OpenCLSettings { // // private final Context clContext; // private final CommandQueue clCommandQueue; // private final ProgramCache programCache; // private final AssetManager assetManager; // // public OpenCLSettings(Context clContext, CommandQueue clCommandQueue, // ProgramCache programCache, AssetManager assetManager) { // this.clContext = clContext; // this.clCommandQueue = clCommandQueue; // this.programCache = programCache!=null ? programCache : new ProgramCache(); // this.assetManager = assetManager; // } // // public Context getClContext() { // return clContext; // } // // public CommandQueue getClCommandQueue() { // return clCommandQueue; // } // // public ProgramCache getProgramCache() { // return programCache; // } // // public AssetManager getAssetManager() { // return assetManager; // } // // @Override // public int hashCode() { // int hash = 3; // hash = 43 * hash + Objects.hashCode(this.clContext); // hash = 43 * hash + Objects.hashCode(this.clCommandQueue); // return hash; // } // // @Override // public boolean equals(Object obj) { // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // final OpenCLSettings other = (OpenCLSettings) obj; // if (!Objects.equals(this.clContext, other.clContext)) { // return false; // } // if (!Objects.equals(this.clCommandQueue, other.clCommandQueue)) { // return false; // } // return true; // } // // }
import com.jme3.opencl.*; import java.nio.ByteBuffer; import java.util.AbstractMap; import java.util.EnumMap; import java.util.HashMap; import java.util.Map; import java.util.logging.Logger; import org.shaman.jmecl.OpenCLSettings;
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.shaman.jmecl.utils; /** * Collection of utitlity and blas-level-1 routines on primitive types. * <p> * All operations take the following arguments: * <ul> * <li>{@code size} the size or number of elements that the operation should process </li> * <li>{@code step} the step size in the array, must be non-zero </li> * <li>{@code offset} the offset into the array, must be non-negative </li> * </ul> * The passed buffers are adressed as they would be arrays of type {@code T}: * {@code T val = buffer[index * step + offset]} with {@code index} ranging from {@code 0} * to {@code size-1}. <br> * It must be ensured that the passed buffer large enough so that no element outside * the bounds is accessed. * * * @author Sebastian Weiss * @param <T> the number type, Float, Double, Integer and Long are supported */ public final class CLBlas<T extends Number> { private static final Logger LOG = Logger.getLogger(CLBlas.class.getName()); private static final String FILE = "org/shaman/jmecl/utils/CLBlas.cl";
// Path: src/main/java/org/shaman/jmecl/OpenCLSettings.java // public class OpenCLSettings { // // private final Context clContext; // private final CommandQueue clCommandQueue; // private final ProgramCache programCache; // private final AssetManager assetManager; // // public OpenCLSettings(Context clContext, CommandQueue clCommandQueue, // ProgramCache programCache, AssetManager assetManager) { // this.clContext = clContext; // this.clCommandQueue = clCommandQueue; // this.programCache = programCache!=null ? programCache : new ProgramCache(); // this.assetManager = assetManager; // } // // public Context getClContext() { // return clContext; // } // // public CommandQueue getClCommandQueue() { // return clCommandQueue; // } // // public ProgramCache getProgramCache() { // return programCache; // } // // public AssetManager getAssetManager() { // return assetManager; // } // // @Override // public int hashCode() { // int hash = 3; // hash = 43 * hash + Objects.hashCode(this.clContext); // hash = 43 * hash + Objects.hashCode(this.clCommandQueue); // return hash; // } // // @Override // public boolean equals(Object obj) { // if (obj == null) { // return false; // } // if (getClass() != obj.getClass()) { // return false; // } // final OpenCLSettings other = (OpenCLSettings) obj; // if (!Objects.equals(this.clContext, other.clContext)) { // return false; // } // if (!Objects.equals(this.clCommandQueue, other.clCommandQueue)) { // return false; // } // return true; // } // // } // Path: src/main/java/org/shaman/jmecl/utils/CLBlas.java import com.jme3.opencl.*; import java.nio.ByteBuffer; import java.util.AbstractMap; import java.util.EnumMap; import java.util.HashMap; import java.util.Map; import java.util.logging.Logger; import org.shaman.jmecl.OpenCLSettings; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.shaman.jmecl.utils; /** * Collection of utitlity and blas-level-1 routines on primitive types. * <p> * All operations take the following arguments: * <ul> * <li>{@code size} the size or number of elements that the operation should process </li> * <li>{@code step} the step size in the array, must be non-zero </li> * <li>{@code offset} the offset into the array, must be non-negative </li> * </ul> * The passed buffers are adressed as they would be arrays of type {@code T}: * {@code T val = buffer[index * step + offset]} with {@code index} ranging from {@code 0} * to {@code size-1}. <br> * It must be ensured that the passed buffer large enough so that no element outside * the bounds is accessed. * * * @author Sebastian Weiss * @param <T> the number type, Float, Double, Integer and Long are supported */ public final class CLBlas<T extends Number> { private static final Logger LOG = Logger.getLogger(CLBlas.class.getName()); private static final String FILE = "org/shaman/jmecl/utils/CLBlas.cl";
private static final Map<OpenCLSettings, Map<Class<? extends Number>, CLBlas<? extends Number>>> instances
geoparser/geolocator-2.0
geo-locator/src/edu/cmu/geolocator/resource/gazindexing/GazStringStat.java
// Path: geo-locator/src/edu/cmu/geolocator/common/CollectionSorting.java // public class CollectionSorting { // // @SuppressWarnings({ "unchecked", "rawtypes" }) // public static ArrayList<Entry<String, Float>> rankArray(ArrayList<Entry<String, Float>> as) { // // sort by frequency // Collections.sort(as, new Comparator() { // public int compare(Object o1, Object o2) { // Map.Entry e1 = (Map.Entry) o1; // Map.Entry e2 = (Map.Entry) o2; // Float first = (Float) e1.getValue(); // Float second = (Float) e2.getValue(); // return second.compareTo(first); // } // }); // // return as; // } // // @SuppressWarnings({ "unchecked", "rawtypes" }) // public static <T extends Comparable<T>> ArrayList<Entry<String, T>> rankIntArray(ArrayList<Entry<String, T>> as) { // // sort by frequency // Collections.sort(as, new Comparator() { // public int compare(Object o1, Object o2) { // Map.Entry e1 = (Map.Entry) o1; // Map.Entry e2 = (Map.Entry) o2; // T first = (T) e1.getValue(); // T second = (T) e2.getValue(); // return second.compareTo(first); // } // }); // return as; // } // // public static LinkedHashMap sortHashMapByValuesD(HashMap passedMap) { // ArrayList mapKeys = new ArrayList(passedMap.keySet()); // ArrayList mapValues = new ArrayList(passedMap.values()); // Collections.sort(mapValues); // Collections.sort(mapKeys); // // LinkedHashMap sortedMap = new LinkedHashMap(); // // Iterator valueIt = mapValues.iterator(); // while (valueIt.hasNext()) { // Object val = valueIt.next(); // Iterator keyIt = mapKeys.iterator(); // // while (keyIt.hasNext()) { // Object key = keyIt.next(); // String comp1 = passedMap.get(key).toString(); // String comp2 = val.toString(); // // if (comp1.equals(comp2)) { // passedMap.remove(key); // mapKeys.remove(key); // sortedMap.put((String) key, val); // break; // } // // } // // } // return sortedMap; // } // } // // Path: geo-locator/src/edu/cmu/geolocator/io/GetReader.java // public class GetReader { // // public static BufferedReader getUTF8FileReader(String filename) throws FileNotFoundException, // UnsupportedEncodingException { // File file = new File(filename); // BufferedReader bin = new BufferedReader(new InputStreamReader(new FileInputStream(file), // "utf-8")); // return bin; // } // // public static IndexSearcher getIndexSearcherFromWriter(String filename) throws IOException { // IndexWriter iw = GetWriter.getIndexWriter(filename, 1024); // IndexReader ir = IndexReader.open(iw, false); // IndexSearcher searcher = new IndexSearcher(ir); // return searcher; // } // // public static IndexSearcher getIndexSearcher(String filename, String diskOrMem) throws Exception { // IndexReader reader; // Directory d ; // if (diskOrMem.equals("disk")) // d = FSDirectory.open(new File(filename)); // else if (diskOrMem.equals("mmap")) // d= MmapDirectory(new File(filename)); // else // throw new Exception("parameter for directory type not defined."); // // if(OSUtil.isWindows()) // reader = IndexReader.open(FSDirectory.open(new File(filename))); // else // reader = IndexReader.open(NIOFSDirectory.open(new File(filename))); // IndexSearcher searcher = new IndexSearcher(reader); // return searcher; // } // // private static Directory MmapDirectory(File file) { // // TODO Auto-generated method stub // return null; // } // // public static BufferedReader getCommandLineReader() throws UnsupportedEncodingException { // BufferedReader br = new BufferedReader(new InputStreamReader(System.in, "utf-8")); // return br; // } // // }
import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.nio.CharBuffer; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Scanner; import java.util.Map.Entry; import edu.cmu.geolocator.common.CollectionSorting; import edu.cmu.geolocator.io.GetReader;
s.useDelimiter("\t"); int count = 0; int total = 0; while (s.hasNext()) { total++; if (total % 18000000 == 0) System.out.println(total / 18); temp = s.next(); if (count == 1) { // System.out.println(asciiStr); asciiStr = temp.toLowerCase(); } if (count == 14) { // This is for storing the balanced or population prefered. if (true) if (locations.containsKey(asciiStr)) locations.put(asciiStr, locations.get(asciiStr) + Long.parseLong(temp)); else locations.put(asciiStr, Long.parseLong(temp)); //This is for storing the ambiguity prefered locations. if(false) if (locations.containsKey(asciiStr)) locations.put(asciiStr, locations.get(asciiStr)+1); else locations.put(asciiStr, 1L); } count = count % 18; count++; } ArrayList<Entry<String, Long>> as = new ArrayList<Entry<String, Long>>(locations.entrySet());
// Path: geo-locator/src/edu/cmu/geolocator/common/CollectionSorting.java // public class CollectionSorting { // // @SuppressWarnings({ "unchecked", "rawtypes" }) // public static ArrayList<Entry<String, Float>> rankArray(ArrayList<Entry<String, Float>> as) { // // sort by frequency // Collections.sort(as, new Comparator() { // public int compare(Object o1, Object o2) { // Map.Entry e1 = (Map.Entry) o1; // Map.Entry e2 = (Map.Entry) o2; // Float first = (Float) e1.getValue(); // Float second = (Float) e2.getValue(); // return second.compareTo(first); // } // }); // // return as; // } // // @SuppressWarnings({ "unchecked", "rawtypes" }) // public static <T extends Comparable<T>> ArrayList<Entry<String, T>> rankIntArray(ArrayList<Entry<String, T>> as) { // // sort by frequency // Collections.sort(as, new Comparator() { // public int compare(Object o1, Object o2) { // Map.Entry e1 = (Map.Entry) o1; // Map.Entry e2 = (Map.Entry) o2; // T first = (T) e1.getValue(); // T second = (T) e2.getValue(); // return second.compareTo(first); // } // }); // return as; // } // // public static LinkedHashMap sortHashMapByValuesD(HashMap passedMap) { // ArrayList mapKeys = new ArrayList(passedMap.keySet()); // ArrayList mapValues = new ArrayList(passedMap.values()); // Collections.sort(mapValues); // Collections.sort(mapKeys); // // LinkedHashMap sortedMap = new LinkedHashMap(); // // Iterator valueIt = mapValues.iterator(); // while (valueIt.hasNext()) { // Object val = valueIt.next(); // Iterator keyIt = mapKeys.iterator(); // // while (keyIt.hasNext()) { // Object key = keyIt.next(); // String comp1 = passedMap.get(key).toString(); // String comp2 = val.toString(); // // if (comp1.equals(comp2)) { // passedMap.remove(key); // mapKeys.remove(key); // sortedMap.put((String) key, val); // break; // } // // } // // } // return sortedMap; // } // } // // Path: geo-locator/src/edu/cmu/geolocator/io/GetReader.java // public class GetReader { // // public static BufferedReader getUTF8FileReader(String filename) throws FileNotFoundException, // UnsupportedEncodingException { // File file = new File(filename); // BufferedReader bin = new BufferedReader(new InputStreamReader(new FileInputStream(file), // "utf-8")); // return bin; // } // // public static IndexSearcher getIndexSearcherFromWriter(String filename) throws IOException { // IndexWriter iw = GetWriter.getIndexWriter(filename, 1024); // IndexReader ir = IndexReader.open(iw, false); // IndexSearcher searcher = new IndexSearcher(ir); // return searcher; // } // // public static IndexSearcher getIndexSearcher(String filename, String diskOrMem) throws Exception { // IndexReader reader; // Directory d ; // if (diskOrMem.equals("disk")) // d = FSDirectory.open(new File(filename)); // else if (diskOrMem.equals("mmap")) // d= MmapDirectory(new File(filename)); // else // throw new Exception("parameter for directory type not defined."); // // if(OSUtil.isWindows()) // reader = IndexReader.open(FSDirectory.open(new File(filename))); // else // reader = IndexReader.open(NIOFSDirectory.open(new File(filename))); // IndexSearcher searcher = new IndexSearcher(reader); // return searcher; // } // // private static Directory MmapDirectory(File file) { // // TODO Auto-generated method stub // return null; // } // // public static BufferedReader getCommandLineReader() throws UnsupportedEncodingException { // BufferedReader br = new BufferedReader(new InputStreamReader(System.in, "utf-8")); // return br; // } // // } // Path: geo-locator/src/edu/cmu/geolocator/resource/gazindexing/GazStringStat.java import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.nio.CharBuffer; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Scanner; import java.util.Map.Entry; import edu.cmu.geolocator.common.CollectionSorting; import edu.cmu.geolocator.io.GetReader; s.useDelimiter("\t"); int count = 0; int total = 0; while (s.hasNext()) { total++; if (total % 18000000 == 0) System.out.println(total / 18); temp = s.next(); if (count == 1) { // System.out.println(asciiStr); asciiStr = temp.toLowerCase(); } if (count == 14) { // This is for storing the balanced or population prefered. if (true) if (locations.containsKey(asciiStr)) locations.put(asciiStr, locations.get(asciiStr) + Long.parseLong(temp)); else locations.put(asciiStr, Long.parseLong(temp)); //This is for storing the ambiguity prefered locations. if(false) if (locations.containsKey(asciiStr)) locations.put(asciiStr, locations.get(asciiStr)+1); else locations.put(asciiStr, 1L); } count = count % 18; count++; } ArrayList<Entry<String, Long>> as = new ArrayList<Entry<String, Long>>(locations.entrySet());
ArrayList<Entry<String, Long>> sortedLocations = CollectionSorting.rankIntArray(as);
geoparser/geolocator-2.0
geo-locator/src/edu/cmu/geolocator/resource/Map/FeatureCode2Map.java
// Path: geo-locator/src/edu/cmu/geolocator/GlobalParam.java // public class GlobalParam { // // public static String gazIndex="GazIndex"; // public static String geoNames="GeoNames"; // public static String getGazIndex() { // return gazIndex; // } // public static void setGazIndex(String gazIndex) { // GlobalParam.gazIndex = gazIndex; // return; // } // public static String getGeoNames() { // return geoNames; // } // public static void setGeoNames(String geoNames) { // GlobalParam.geoNames = geoNames; // return; // } // // } // // Path: geo-locator/src/edu/cmu/geolocator/io/GetReader.java // public class GetReader { // // public static BufferedReader getUTF8FileReader(String filename) throws FileNotFoundException, // UnsupportedEncodingException { // File file = new File(filename); // BufferedReader bin = new BufferedReader(new InputStreamReader(new FileInputStream(file), // "utf-8")); // return bin; // } // // public static IndexSearcher getIndexSearcherFromWriter(String filename) throws IOException { // IndexWriter iw = GetWriter.getIndexWriter(filename, 1024); // IndexReader ir = IndexReader.open(iw, false); // IndexSearcher searcher = new IndexSearcher(ir); // return searcher; // } // // public static IndexSearcher getIndexSearcher(String filename, String diskOrMem) throws Exception { // IndexReader reader; // Directory d ; // if (diskOrMem.equals("disk")) // d = FSDirectory.open(new File(filename)); // else if (diskOrMem.equals("mmap")) // d= MmapDirectory(new File(filename)); // else // throw new Exception("parameter for directory type not defined."); // // if(OSUtil.isWindows()) // reader = IndexReader.open(FSDirectory.open(new File(filename))); // else // reader = IndexReader.open(NIOFSDirectory.open(new File(filename))); // IndexSearcher searcher = new IndexSearcher(reader); // return searcher; // } // // private static Directory MmapDirectory(File file) { // // TODO Auto-generated method stub // return null; // } // // public static BufferedReader getCommandLineReader() throws UnsupportedEncodingException { // BufferedReader br = new BufferedReader(new InputStreamReader(System.in, "utf-8")); // return br; // } // // } // // Path: geo-locator/src/edu/cmu/geolocator/resource/ResourceFactory.java // public class ResourceFactory { // // private static CollaborativeIndex collaborativeIndex = CollaborativeIndex.getInstance(); // // private static AdmCode2GazCandidateMap adminCode2GazCandidateMap = AdmCode2GazCandidateMap // .getInstance(); // // private static CCodeAdj2CTRYtype countryCode2CountryMap = CCodeAdj2CTRYtype // .getInstance(); // // private static FeatureCode2Map featurecode2map = FeatureCode2Map.getInstance(); // /** // * @return the collaborativeIndex // */ // public static CollaborativeIndex getClbIndex() { // return collaborativeIndex; // } // // /** // * return the GazEntryAndInfo type given the admin code. // * @return the adminCode2GazCandidateMap // */ // public static AdmCode2GazCandidateMap getAdminCode2GazCandidateMap() { // return adminCode2GazCandidateMap; // } // // /** // * return the Country type given the country code. // * @return the countryCode2CountryMap // * // */ // public static CCodeAdj2CTRYtype getCountryCode2CountryMap() { // return countryCode2CountryMap; // } // // public static FeatureCode2Map getFeatureCode2Map() { // // TODO Auto-generated method stub // return featurecode2map; // } // }
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.HashMap; import edu.cmu.geolocator.GlobalParam; import edu.cmu.geolocator.io.GetReader; import edu.cmu.geolocator.resource.ResourceFactory;
package edu.cmu.geolocator.resource.Map; public class FeatureCode2Map { HashMap<String,Integer> codemap; public FeatureCode2Map() { // TODO Auto-generated constructor stub codemap = new HashMap<String,Integer>(); } public static void main(String args[]) {
// Path: geo-locator/src/edu/cmu/geolocator/GlobalParam.java // public class GlobalParam { // // public static String gazIndex="GazIndex"; // public static String geoNames="GeoNames"; // public static String getGazIndex() { // return gazIndex; // } // public static void setGazIndex(String gazIndex) { // GlobalParam.gazIndex = gazIndex; // return; // } // public static String getGeoNames() { // return geoNames; // } // public static void setGeoNames(String geoNames) { // GlobalParam.geoNames = geoNames; // return; // } // // } // // Path: geo-locator/src/edu/cmu/geolocator/io/GetReader.java // public class GetReader { // // public static BufferedReader getUTF8FileReader(String filename) throws FileNotFoundException, // UnsupportedEncodingException { // File file = new File(filename); // BufferedReader bin = new BufferedReader(new InputStreamReader(new FileInputStream(file), // "utf-8")); // return bin; // } // // public static IndexSearcher getIndexSearcherFromWriter(String filename) throws IOException { // IndexWriter iw = GetWriter.getIndexWriter(filename, 1024); // IndexReader ir = IndexReader.open(iw, false); // IndexSearcher searcher = new IndexSearcher(ir); // return searcher; // } // // public static IndexSearcher getIndexSearcher(String filename, String diskOrMem) throws Exception { // IndexReader reader; // Directory d ; // if (diskOrMem.equals("disk")) // d = FSDirectory.open(new File(filename)); // else if (diskOrMem.equals("mmap")) // d= MmapDirectory(new File(filename)); // else // throw new Exception("parameter for directory type not defined."); // // if(OSUtil.isWindows()) // reader = IndexReader.open(FSDirectory.open(new File(filename))); // else // reader = IndexReader.open(NIOFSDirectory.open(new File(filename))); // IndexSearcher searcher = new IndexSearcher(reader); // return searcher; // } // // private static Directory MmapDirectory(File file) { // // TODO Auto-generated method stub // return null; // } // // public static BufferedReader getCommandLineReader() throws UnsupportedEncodingException { // BufferedReader br = new BufferedReader(new InputStreamReader(System.in, "utf-8")); // return br; // } // // } // // Path: geo-locator/src/edu/cmu/geolocator/resource/ResourceFactory.java // public class ResourceFactory { // // private static CollaborativeIndex collaborativeIndex = CollaborativeIndex.getInstance(); // // private static AdmCode2GazCandidateMap adminCode2GazCandidateMap = AdmCode2GazCandidateMap // .getInstance(); // // private static CCodeAdj2CTRYtype countryCode2CountryMap = CCodeAdj2CTRYtype // .getInstance(); // // private static FeatureCode2Map featurecode2map = FeatureCode2Map.getInstance(); // /** // * @return the collaborativeIndex // */ // public static CollaborativeIndex getClbIndex() { // return collaborativeIndex; // } // // /** // * return the GazEntryAndInfo type given the admin code. // * @return the adminCode2GazCandidateMap // */ // public static AdmCode2GazCandidateMap getAdminCode2GazCandidateMap() { // return adminCode2GazCandidateMap; // } // // /** // * return the Country type given the country code. // * @return the countryCode2CountryMap // * // */ // public static CCodeAdj2CTRYtype getCountryCode2CountryMap() { // return countryCode2CountryMap; // } // // public static FeatureCode2Map getFeatureCode2Map() { // // TODO Auto-generated method stub // return featurecode2map; // } // } // Path: geo-locator/src/edu/cmu/geolocator/resource/Map/FeatureCode2Map.java import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.HashMap; import edu.cmu.geolocator.GlobalParam; import edu.cmu.geolocator.io.GetReader; import edu.cmu.geolocator.resource.ResourceFactory; package edu.cmu.geolocator.resource.Map; public class FeatureCode2Map { HashMap<String,Integer> codemap; public FeatureCode2Map() { // TODO Auto-generated constructor stub codemap = new HashMap<String,Integer>(); } public static void main(String args[]) {
FeatureCode2Map fm = ResourceFactory.getFeatureCode2Map().getInstance();
geoparser/geolocator-2.0
geo-locator/src/edu/cmu/geolocator/resource/Map/FeatureCode2Map.java
// Path: geo-locator/src/edu/cmu/geolocator/GlobalParam.java // public class GlobalParam { // // public static String gazIndex="GazIndex"; // public static String geoNames="GeoNames"; // public static String getGazIndex() { // return gazIndex; // } // public static void setGazIndex(String gazIndex) { // GlobalParam.gazIndex = gazIndex; // return; // } // public static String getGeoNames() { // return geoNames; // } // public static void setGeoNames(String geoNames) { // GlobalParam.geoNames = geoNames; // return; // } // // } // // Path: geo-locator/src/edu/cmu/geolocator/io/GetReader.java // public class GetReader { // // public static BufferedReader getUTF8FileReader(String filename) throws FileNotFoundException, // UnsupportedEncodingException { // File file = new File(filename); // BufferedReader bin = new BufferedReader(new InputStreamReader(new FileInputStream(file), // "utf-8")); // return bin; // } // // public static IndexSearcher getIndexSearcherFromWriter(String filename) throws IOException { // IndexWriter iw = GetWriter.getIndexWriter(filename, 1024); // IndexReader ir = IndexReader.open(iw, false); // IndexSearcher searcher = new IndexSearcher(ir); // return searcher; // } // // public static IndexSearcher getIndexSearcher(String filename, String diskOrMem) throws Exception { // IndexReader reader; // Directory d ; // if (diskOrMem.equals("disk")) // d = FSDirectory.open(new File(filename)); // else if (diskOrMem.equals("mmap")) // d= MmapDirectory(new File(filename)); // else // throw new Exception("parameter for directory type not defined."); // // if(OSUtil.isWindows()) // reader = IndexReader.open(FSDirectory.open(new File(filename))); // else // reader = IndexReader.open(NIOFSDirectory.open(new File(filename))); // IndexSearcher searcher = new IndexSearcher(reader); // return searcher; // } // // private static Directory MmapDirectory(File file) { // // TODO Auto-generated method stub // return null; // } // // public static BufferedReader getCommandLineReader() throws UnsupportedEncodingException { // BufferedReader br = new BufferedReader(new InputStreamReader(System.in, "utf-8")); // return br; // } // // } // // Path: geo-locator/src/edu/cmu/geolocator/resource/ResourceFactory.java // public class ResourceFactory { // // private static CollaborativeIndex collaborativeIndex = CollaborativeIndex.getInstance(); // // private static AdmCode2GazCandidateMap adminCode2GazCandidateMap = AdmCode2GazCandidateMap // .getInstance(); // // private static CCodeAdj2CTRYtype countryCode2CountryMap = CCodeAdj2CTRYtype // .getInstance(); // // private static FeatureCode2Map featurecode2map = FeatureCode2Map.getInstance(); // /** // * @return the collaborativeIndex // */ // public static CollaborativeIndex getClbIndex() { // return collaborativeIndex; // } // // /** // * return the GazEntryAndInfo type given the admin code. // * @return the adminCode2GazCandidateMap // */ // public static AdmCode2GazCandidateMap getAdminCode2GazCandidateMap() { // return adminCode2GazCandidateMap; // } // // /** // * return the Country type given the country code. // * @return the countryCode2CountryMap // * // */ // public static CCodeAdj2CTRYtype getCountryCode2CountryMap() { // return countryCode2CountryMap; // } // // public static FeatureCode2Map getFeatureCode2Map() { // // TODO Auto-generated method stub // return featurecode2map; // } // }
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.HashMap; import edu.cmu.geolocator.GlobalParam; import edu.cmu.geolocator.io.GetReader; import edu.cmu.geolocator.resource.ResourceFactory;
package edu.cmu.geolocator.resource.Map; public class FeatureCode2Map { HashMap<String,Integer> codemap; public FeatureCode2Map() { // TODO Auto-generated constructor stub codemap = new HashMap<String,Integer>(); } public static void main(String args[]) { FeatureCode2Map fm = ResourceFactory.getFeatureCode2Map().getInstance(); int i = fm.getIndex("ppla"); int size = fm.size(); System.out.println(i); } public int size() { // TODO Auto-generated method stub return codemap.size(); } /** * The string passed into this function should be the feature name, without the single char class. * indexed ppl instead of P.PPL. * * @param string * @return */ public int getIndex(String string) { // TODO Auto-generated method stub string = string.toLowerCase(); return codemap.get(string); } private FeatureCode2Map load(String filename) { BufferedReader br = null; try {
// Path: geo-locator/src/edu/cmu/geolocator/GlobalParam.java // public class GlobalParam { // // public static String gazIndex="GazIndex"; // public static String geoNames="GeoNames"; // public static String getGazIndex() { // return gazIndex; // } // public static void setGazIndex(String gazIndex) { // GlobalParam.gazIndex = gazIndex; // return; // } // public static String getGeoNames() { // return geoNames; // } // public static void setGeoNames(String geoNames) { // GlobalParam.geoNames = geoNames; // return; // } // // } // // Path: geo-locator/src/edu/cmu/geolocator/io/GetReader.java // public class GetReader { // // public static BufferedReader getUTF8FileReader(String filename) throws FileNotFoundException, // UnsupportedEncodingException { // File file = new File(filename); // BufferedReader bin = new BufferedReader(new InputStreamReader(new FileInputStream(file), // "utf-8")); // return bin; // } // // public static IndexSearcher getIndexSearcherFromWriter(String filename) throws IOException { // IndexWriter iw = GetWriter.getIndexWriter(filename, 1024); // IndexReader ir = IndexReader.open(iw, false); // IndexSearcher searcher = new IndexSearcher(ir); // return searcher; // } // // public static IndexSearcher getIndexSearcher(String filename, String diskOrMem) throws Exception { // IndexReader reader; // Directory d ; // if (diskOrMem.equals("disk")) // d = FSDirectory.open(new File(filename)); // else if (diskOrMem.equals("mmap")) // d= MmapDirectory(new File(filename)); // else // throw new Exception("parameter for directory type not defined."); // // if(OSUtil.isWindows()) // reader = IndexReader.open(FSDirectory.open(new File(filename))); // else // reader = IndexReader.open(NIOFSDirectory.open(new File(filename))); // IndexSearcher searcher = new IndexSearcher(reader); // return searcher; // } // // private static Directory MmapDirectory(File file) { // // TODO Auto-generated method stub // return null; // } // // public static BufferedReader getCommandLineReader() throws UnsupportedEncodingException { // BufferedReader br = new BufferedReader(new InputStreamReader(System.in, "utf-8")); // return br; // } // // } // // Path: geo-locator/src/edu/cmu/geolocator/resource/ResourceFactory.java // public class ResourceFactory { // // private static CollaborativeIndex collaborativeIndex = CollaborativeIndex.getInstance(); // // private static AdmCode2GazCandidateMap adminCode2GazCandidateMap = AdmCode2GazCandidateMap // .getInstance(); // // private static CCodeAdj2CTRYtype countryCode2CountryMap = CCodeAdj2CTRYtype // .getInstance(); // // private static FeatureCode2Map featurecode2map = FeatureCode2Map.getInstance(); // /** // * @return the collaborativeIndex // */ // public static CollaborativeIndex getClbIndex() { // return collaborativeIndex; // } // // /** // * return the GazEntryAndInfo type given the admin code. // * @return the adminCode2GazCandidateMap // */ // public static AdmCode2GazCandidateMap getAdminCode2GazCandidateMap() { // return adminCode2GazCandidateMap; // } // // /** // * return the Country type given the country code. // * @return the countryCode2CountryMap // * // */ // public static CCodeAdj2CTRYtype getCountryCode2CountryMap() { // return countryCode2CountryMap; // } // // public static FeatureCode2Map getFeatureCode2Map() { // // TODO Auto-generated method stub // return featurecode2map; // } // } // Path: geo-locator/src/edu/cmu/geolocator/resource/Map/FeatureCode2Map.java import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.HashMap; import edu.cmu.geolocator.GlobalParam; import edu.cmu.geolocator.io.GetReader; import edu.cmu.geolocator.resource.ResourceFactory; package edu.cmu.geolocator.resource.Map; public class FeatureCode2Map { HashMap<String,Integer> codemap; public FeatureCode2Map() { // TODO Auto-generated constructor stub codemap = new HashMap<String,Integer>(); } public static void main(String args[]) { FeatureCode2Map fm = ResourceFactory.getFeatureCode2Map().getInstance(); int i = fm.getIndex("ppla"); int size = fm.size(); System.out.println(i); } public int size() { // TODO Auto-generated method stub return codemap.size(); } /** * The string passed into this function should be the feature name, without the single char class. * indexed ppl instead of P.PPL. * * @param string * @return */ public int getIndex(String string) { // TODO Auto-generated method stub string = string.toLowerCase(); return codemap.get(string); } private FeatureCode2Map load(String filename) { BufferedReader br = null; try {
br = GetReader.getUTF8FileReader(filename);
geoparser/geolocator-2.0
geo-locator/src/edu/cmu/geolocator/io/GetReader.java
// Path: geo-locator/src/edu/cmu/geolocator/common/OSUtil.java // public class OSUtil { // // private static String OS = System.getProperty("os.name").toLowerCase(); // // public static void main(String[] args) { // // System.out.println(OS); // // if (isWindows()) { // System.out.println("This is Windows"); // } else if (isMac()) { // System.out.println("This is Mac"); // } else if (isUnix()) { // System.out.println("This is Unix or Linux"); // } else if (isSolaris()) { // System.out.println("This is Solaris"); // } else { // System.out.println("Your OS is not supported!!"); // } // } // // public static boolean isWindows() { // // return (OS.indexOf("win") >= 0); // // } // // public static boolean isMac() { // // return (OS.indexOf("mac") >= 0); // // } // // public static boolean isUnix() { // // return (OS.indexOf("nix") >= 0 || OS.indexOf("nux") >= 0 || OS.indexOf("aix") > 0 ); // // } // // public static boolean isSolaris() { // // return (OS.indexOf("sunos") >= 0); // // } // // }
import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.store.Directory; import org.apache.lucene.store.FSDirectory; import org.apache.lucene.store.NIOFSDirectory; import edu.cmu.geolocator.common.OSUtil; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException;
/** * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you 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. * * @author Wei Zhang, Language Technology Institute, School of Computer Science, Carnegie-Mellon University. * email: [email protected] * */ package edu.cmu.geolocator.io; public class GetReader { public static BufferedReader getUTF8FileReader(String filename) throws FileNotFoundException, UnsupportedEncodingException { File file = new File(filename); BufferedReader bin = new BufferedReader(new InputStreamReader(new FileInputStream(file), "utf-8")); return bin; } public static IndexSearcher getIndexSearcherFromWriter(String filename) throws IOException { IndexWriter iw = GetWriter.getIndexWriter(filename, 1024); IndexReader ir = IndexReader.open(iw, false); IndexSearcher searcher = new IndexSearcher(ir); return searcher; } public static IndexSearcher getIndexSearcher(String filename, String diskOrMem) throws Exception { IndexReader reader; Directory d ; if (diskOrMem.equals("disk")) d = FSDirectory.open(new File(filename)); else if (diskOrMem.equals("mmap")) d= MmapDirectory(new File(filename)); else throw new Exception("parameter for directory type not defined.");
// Path: geo-locator/src/edu/cmu/geolocator/common/OSUtil.java // public class OSUtil { // // private static String OS = System.getProperty("os.name").toLowerCase(); // // public static void main(String[] args) { // // System.out.println(OS); // // if (isWindows()) { // System.out.println("This is Windows"); // } else if (isMac()) { // System.out.println("This is Mac"); // } else if (isUnix()) { // System.out.println("This is Unix or Linux"); // } else if (isSolaris()) { // System.out.println("This is Solaris"); // } else { // System.out.println("Your OS is not supported!!"); // } // } // // public static boolean isWindows() { // // return (OS.indexOf("win") >= 0); // // } // // public static boolean isMac() { // // return (OS.indexOf("mac") >= 0); // // } // // public static boolean isUnix() { // // return (OS.indexOf("nix") >= 0 || OS.indexOf("nux") >= 0 || OS.indexOf("aix") > 0 ); // // } // // public static boolean isSolaris() { // // return (OS.indexOf("sunos") >= 0); // // } // // } // Path: geo-locator/src/edu/cmu/geolocator/io/GetReader.java import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.store.Directory; import org.apache.lucene.store.FSDirectory; import org.apache.lucene.store.NIOFSDirectory; import edu.cmu.geolocator.common.OSUtil; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; /** * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you 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. * * @author Wei Zhang, Language Technology Institute, School of Computer Science, Carnegie-Mellon University. * email: [email protected] * */ package edu.cmu.geolocator.io; public class GetReader { public static BufferedReader getUTF8FileReader(String filename) throws FileNotFoundException, UnsupportedEncodingException { File file = new File(filename); BufferedReader bin = new BufferedReader(new InputStreamReader(new FileInputStream(file), "utf-8")); return bin; } public static IndexSearcher getIndexSearcherFromWriter(String filename) throws IOException { IndexWriter iw = GetWriter.getIndexWriter(filename, 1024); IndexReader ir = IndexReader.open(iw, false); IndexSearcher searcher = new IndexSearcher(ir); return searcher; } public static IndexSearcher getIndexSearcher(String filename, String diskOrMem) throws Exception { IndexReader reader; Directory d ; if (diskOrMem.equals("disk")) d = FSDirectory.open(new File(filename)); else if (diskOrMem.equals("mmap")) d= MmapDirectory(new File(filename)); else throw new Exception("parameter for directory type not defined.");
if(OSUtil.isWindows())
geoparser/geolocator-2.0
geo-locator/src/edu/cmu/geolocator/io/GetWriter.java
// Path: geo-locator/src/edu/cmu/geolocator/common/OSUtil.java // public class OSUtil { // // private static String OS = System.getProperty("os.name").toLowerCase(); // // public static void main(String[] args) { // // System.out.println(OS); // // if (isWindows()) { // System.out.println("This is Windows"); // } else if (isMac()) { // System.out.println("This is Mac"); // } else if (isUnix()) { // System.out.println("This is Unix or Linux"); // } else if (isSolaris()) { // System.out.println("This is Solaris"); // } else { // System.out.println("Your OS is not supported!!"); // } // } // // public static boolean isWindows() { // // return (OS.indexOf("win") >= 0); // // } // // public static boolean isMac() { // // return (OS.indexOf("mac") >= 0); // // } // // public static boolean isUnix() { // // return (OS.indexOf("nix") >= 0 || OS.indexOf("nux") >= 0 || OS.indexOf("aix") > 0 ); // // } // // public static boolean isSolaris() { // // return (OS.indexOf("sunos") >= 0); // // } // // }
import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.IndexWriterConfig; import org.apache.lucene.index.LogDocMergePolicy; import org.apache.lucene.index.MergePolicy; import org.apache.lucene.index.IndexWriterConfig.OpenMode; import org.apache.lucene.store.Directory; import org.apache.lucene.store.FSDirectory; import org.apache.lucene.store.NIOFSDirectory; import org.apache.lucene.util.Version; import edu.cmu.geolocator.common.OSUtil; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import org.apache.lucene.analysis.Analyzer;
/** * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you 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. * * @author Wei Zhang, Language Technology Institute, School of Computer Science, Carnegie-Mellon University. * email: [email protected] * */ package edu.cmu.geolocator.io; public class GetWriter { public static IndexWriter getIndexWriter(String indexdirectory, double buffersize) throws IOException { Directory dir;
// Path: geo-locator/src/edu/cmu/geolocator/common/OSUtil.java // public class OSUtil { // // private static String OS = System.getProperty("os.name").toLowerCase(); // // public static void main(String[] args) { // // System.out.println(OS); // // if (isWindows()) { // System.out.println("This is Windows"); // } else if (isMac()) { // System.out.println("This is Mac"); // } else if (isUnix()) { // System.out.println("This is Unix or Linux"); // } else if (isSolaris()) { // System.out.println("This is Solaris"); // } else { // System.out.println("Your OS is not supported!!"); // } // } // // public static boolean isWindows() { // // return (OS.indexOf("win") >= 0); // // } // // public static boolean isMac() { // // return (OS.indexOf("mac") >= 0); // // } // // public static boolean isUnix() { // // return (OS.indexOf("nix") >= 0 || OS.indexOf("nux") >= 0 || OS.indexOf("aix") > 0 ); // // } // // public static boolean isSolaris() { // // return (OS.indexOf("sunos") >= 0); // // } // // } // Path: geo-locator/src/edu/cmu/geolocator/io/GetWriter.java import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.IndexWriterConfig; import org.apache.lucene.index.LogDocMergePolicy; import org.apache.lucene.index.MergePolicy; import org.apache.lucene.index.IndexWriterConfig.OpenMode; import org.apache.lucene.store.Directory; import org.apache.lucene.store.FSDirectory; import org.apache.lucene.store.NIOFSDirectory; import org.apache.lucene.util.Version; import edu.cmu.geolocator.common.OSUtil; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import org.apache.lucene.analysis.Analyzer; /** * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you 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. * * @author Wei Zhang, Language Technology Institute, School of Computer Science, Carnegie-Mellon University. * email: [email protected] * */ package edu.cmu.geolocator.io; public class GetWriter { public static IndexWriter getIndexWriter(String indexdirectory, double buffersize) throws IOException { Directory dir;
if (OSUtil.isWindows())
geoparser/geolocator-2.0
geo-locator/src/edu/cmu/geolocator/model/CandidateAndFeature.java
// Path: geo-locator/src/edu/cmu/geolocator/resource/ResourceFactory.java // public class ResourceFactory { // // private static CollaborativeIndex collaborativeIndex = CollaborativeIndex.getInstance(); // // private static AdmCode2GazCandidateMap adminCode2GazCandidateMap = AdmCode2GazCandidateMap // .getInstance(); // // private static CCodeAdj2CTRYtype countryCode2CountryMap = CCodeAdj2CTRYtype // .getInstance(); // // private static FeatureCode2Map featurecode2map = FeatureCode2Map.getInstance(); // /** // * @return the collaborativeIndex // */ // public static CollaborativeIndex getClbIndex() { // return collaborativeIndex; // } // // /** // * return the GazEntryAndInfo type given the admin code. // * @return the adminCode2GazCandidateMap // */ // public static AdmCode2GazCandidateMap getAdminCode2GazCandidateMap() { // return adminCode2GazCandidateMap; // } // // /** // * return the Country type given the country code. // * @return the countryCode2CountryMap // * // */ // public static CCodeAdj2CTRYtype getCountryCode2CountryMap() { // return countryCode2CountryMap; // } // // public static FeatureCode2Map getFeatureCode2Map() { // // TODO Auto-generated method stub // return featurecode2map; // } // } // // Path: geo-locator/src/edu/cmu/geolocator/resource/gazindexing/CollaborativeIndex/InfoFields.java // public class InfoFields { // // public static String id = "ID"; // // public static String name = "ORIGINAL-NAME"; // // public static String alternativeNamesCount = "ALTNAME-COUNT"; // // public static String longitude = "LONGTITUDE"; // // public static String latitude = "LATITUDE"; // // public static String population = "POPULATION"; // // public static String countryCode = "COUNTRY-CODE"; // // public static String adm1Code = "ADM1-CODE"; // // public static String adm2Code = "ADM2-CODE"; // // public static String adm3Code = "ADM3-CODE"; // // public static String adm4Code = "ADM4-CODE"; // // public static String featureClass = "FEATURE-CLASS"; // // public static String feature = "FEATURE"; // // public static String timezone = "TIMEZONE"; // }
import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; import java.util.List; import org.apache.lucene.document.Document; import com.sun.xml.internal.bind.v2.runtime.unmarshaller.IntArrayData; import edu.cmu.geolocator.resource.ResourceFactory; import edu.cmu.geolocator.resource.gazindexing.CollaborativeIndex.InfoFields; import edu.stanford.nlp.util.StringUtils;
/** * @return the f_OtherLocOverlap */ public int getF_OtherLocOverlap() { return f_OtherLocOverlap; } /** * @return the y */ public int getY() { return Y; } /** * @param y * the y to set */ public void setY(int y) { Y = y; } public String getF_featureValue() { // TODO Auto-generated method stub return this.feature; } public void setF_featureVector(String string) { // TODO Auto-generated method stub\
// Path: geo-locator/src/edu/cmu/geolocator/resource/ResourceFactory.java // public class ResourceFactory { // // private static CollaborativeIndex collaborativeIndex = CollaborativeIndex.getInstance(); // // private static AdmCode2GazCandidateMap adminCode2GazCandidateMap = AdmCode2GazCandidateMap // .getInstance(); // // private static CCodeAdj2CTRYtype countryCode2CountryMap = CCodeAdj2CTRYtype // .getInstance(); // // private static FeatureCode2Map featurecode2map = FeatureCode2Map.getInstance(); // /** // * @return the collaborativeIndex // */ // public static CollaborativeIndex getClbIndex() { // return collaborativeIndex; // } // // /** // * return the GazEntryAndInfo type given the admin code. // * @return the adminCode2GazCandidateMap // */ // public static AdmCode2GazCandidateMap getAdminCode2GazCandidateMap() { // return adminCode2GazCandidateMap; // } // // /** // * return the Country type given the country code. // * @return the countryCode2CountryMap // * // */ // public static CCodeAdj2CTRYtype getCountryCode2CountryMap() { // return countryCode2CountryMap; // } // // public static FeatureCode2Map getFeatureCode2Map() { // // TODO Auto-generated method stub // return featurecode2map; // } // } // // Path: geo-locator/src/edu/cmu/geolocator/resource/gazindexing/CollaborativeIndex/InfoFields.java // public class InfoFields { // // public static String id = "ID"; // // public static String name = "ORIGINAL-NAME"; // // public static String alternativeNamesCount = "ALTNAME-COUNT"; // // public static String longitude = "LONGTITUDE"; // // public static String latitude = "LATITUDE"; // // public static String population = "POPULATION"; // // public static String countryCode = "COUNTRY-CODE"; // // public static String adm1Code = "ADM1-CODE"; // // public static String adm2Code = "ADM2-CODE"; // // public static String adm3Code = "ADM3-CODE"; // // public static String adm4Code = "ADM4-CODE"; // // public static String featureClass = "FEATURE-CLASS"; // // public static String feature = "FEATURE"; // // public static String timezone = "TIMEZONE"; // } // Path: geo-locator/src/edu/cmu/geolocator/model/CandidateAndFeature.java import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; import java.util.List; import org.apache.lucene.document.Document; import com.sun.xml.internal.bind.v2.runtime.unmarshaller.IntArrayData; import edu.cmu.geolocator.resource.ResourceFactory; import edu.cmu.geolocator.resource.gazindexing.CollaborativeIndex.InfoFields; import edu.stanford.nlp.util.StringUtils; /** * @return the f_OtherLocOverlap */ public int getF_OtherLocOverlap() { return f_OtherLocOverlap; } /** * @return the y */ public int getY() { return Y; } /** * @param y * the y to set */ public void setY(int y) { Y = y; } public String getF_featureValue() { // TODO Auto-generated method stub return this.feature; } public void setF_featureVector(String string) { // TODO Auto-generated method stub\
this.featureVector = new int[ResourceFactory.getFeatureCode2Map().size()];
geoparser/geolocator-2.0
geo-locator/src/edu/cmu/geolocator/model/CandidateAndFeature.java
// Path: geo-locator/src/edu/cmu/geolocator/resource/ResourceFactory.java // public class ResourceFactory { // // private static CollaborativeIndex collaborativeIndex = CollaborativeIndex.getInstance(); // // private static AdmCode2GazCandidateMap adminCode2GazCandidateMap = AdmCode2GazCandidateMap // .getInstance(); // // private static CCodeAdj2CTRYtype countryCode2CountryMap = CCodeAdj2CTRYtype // .getInstance(); // // private static FeatureCode2Map featurecode2map = FeatureCode2Map.getInstance(); // /** // * @return the collaborativeIndex // */ // public static CollaborativeIndex getClbIndex() { // return collaborativeIndex; // } // // /** // * return the GazEntryAndInfo type given the admin code. // * @return the adminCode2GazCandidateMap // */ // public static AdmCode2GazCandidateMap getAdminCode2GazCandidateMap() { // return adminCode2GazCandidateMap; // } // // /** // * return the Country type given the country code. // * @return the countryCode2CountryMap // * // */ // public static CCodeAdj2CTRYtype getCountryCode2CountryMap() { // return countryCode2CountryMap; // } // // public static FeatureCode2Map getFeatureCode2Map() { // // TODO Auto-generated method stub // return featurecode2map; // } // } // // Path: geo-locator/src/edu/cmu/geolocator/resource/gazindexing/CollaborativeIndex/InfoFields.java // public class InfoFields { // // public static String id = "ID"; // // public static String name = "ORIGINAL-NAME"; // // public static String alternativeNamesCount = "ALTNAME-COUNT"; // // public static String longitude = "LONGTITUDE"; // // public static String latitude = "LATITUDE"; // // public static String population = "POPULATION"; // // public static String countryCode = "COUNTRY-CODE"; // // public static String adm1Code = "ADM1-CODE"; // // public static String adm2Code = "ADM2-CODE"; // // public static String adm3Code = "ADM3-CODE"; // // public static String adm4Code = "ADM4-CODE"; // // public static String featureClass = "FEATURE-CLASS"; // // public static String feature = "FEATURE"; // // public static String timezone = "TIMEZONE"; // }
import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; import java.util.List; import org.apache.lucene.document.Document; import com.sun.xml.internal.bind.v2.runtime.unmarshaller.IntArrayData; import edu.cmu.geolocator.resource.ResourceFactory; import edu.cmu.geolocator.resource.gazindexing.CollaborativeIndex.InfoFields; import edu.stanford.nlp.util.StringUtils;
private boolean f_userLocCountryAgree; private boolean f_userLocStateAgree; public void setF_singleCandidate(boolean b) { // TODO Auto-generated method stub this.f_singleCandidate = b; } public boolean getF_singleCandidate() { // TODO Auto-generated method stub return this.f_singleCandidate; } public boolean getF_isCountry() { // TODO Auto-generated method stub return this.isCountry(); } public void setF_userLocOverlap(ArrayList<ArrayList<Document>>matrixDocs, List<LocEntityAnnotation> userLocs) { // TODO Auto-generated method stub if(userLocs ==null || userLocs.size()==0){ //all default are false. No need to set to false explicitly. return; } for (ArrayList<Document> docs : matrixDocs){ if(docs==null||docs.size()==0) continue; for (Document doc : docs){
// Path: geo-locator/src/edu/cmu/geolocator/resource/ResourceFactory.java // public class ResourceFactory { // // private static CollaborativeIndex collaborativeIndex = CollaborativeIndex.getInstance(); // // private static AdmCode2GazCandidateMap adminCode2GazCandidateMap = AdmCode2GazCandidateMap // .getInstance(); // // private static CCodeAdj2CTRYtype countryCode2CountryMap = CCodeAdj2CTRYtype // .getInstance(); // // private static FeatureCode2Map featurecode2map = FeatureCode2Map.getInstance(); // /** // * @return the collaborativeIndex // */ // public static CollaborativeIndex getClbIndex() { // return collaborativeIndex; // } // // /** // * return the GazEntryAndInfo type given the admin code. // * @return the adminCode2GazCandidateMap // */ // public static AdmCode2GazCandidateMap getAdminCode2GazCandidateMap() { // return adminCode2GazCandidateMap; // } // // /** // * return the Country type given the country code. // * @return the countryCode2CountryMap // * // */ // public static CCodeAdj2CTRYtype getCountryCode2CountryMap() { // return countryCode2CountryMap; // } // // public static FeatureCode2Map getFeatureCode2Map() { // // TODO Auto-generated method stub // return featurecode2map; // } // } // // Path: geo-locator/src/edu/cmu/geolocator/resource/gazindexing/CollaborativeIndex/InfoFields.java // public class InfoFields { // // public static String id = "ID"; // // public static String name = "ORIGINAL-NAME"; // // public static String alternativeNamesCount = "ALTNAME-COUNT"; // // public static String longitude = "LONGTITUDE"; // // public static String latitude = "LATITUDE"; // // public static String population = "POPULATION"; // // public static String countryCode = "COUNTRY-CODE"; // // public static String adm1Code = "ADM1-CODE"; // // public static String adm2Code = "ADM2-CODE"; // // public static String adm3Code = "ADM3-CODE"; // // public static String adm4Code = "ADM4-CODE"; // // public static String featureClass = "FEATURE-CLASS"; // // public static String feature = "FEATURE"; // // public static String timezone = "TIMEZONE"; // } // Path: geo-locator/src/edu/cmu/geolocator/model/CandidateAndFeature.java import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; import java.util.List; import org.apache.lucene.document.Document; import com.sun.xml.internal.bind.v2.runtime.unmarshaller.IntArrayData; import edu.cmu.geolocator.resource.ResourceFactory; import edu.cmu.geolocator.resource.gazindexing.CollaborativeIndex.InfoFields; import edu.stanford.nlp.util.StringUtils; private boolean f_userLocCountryAgree; private boolean f_userLocStateAgree; public void setF_singleCandidate(boolean b) { // TODO Auto-generated method stub this.f_singleCandidate = b; } public boolean getF_singleCandidate() { // TODO Auto-generated method stub return this.f_singleCandidate; } public boolean getF_isCountry() { // TODO Auto-generated method stub return this.isCountry(); } public void setF_userLocOverlap(ArrayList<ArrayList<Document>>matrixDocs, List<LocEntityAnnotation> userLocs) { // TODO Auto-generated method stub if(userLocs ==null || userLocs.size()==0){ //all default are false. No need to set to false explicitly. return; } for (ArrayList<Document> docs : matrixDocs){ if(docs==null||docs.size()==0) continue; for (Document doc : docs){
String dc = doc.get(InfoFields.countryCode);
geoparser/geolocator-2.0
geo-locator/src/edu/cmu/geolocator/nlp/ner/MinorThirdCRF/Tester.java
// Path: geo-locator/src/edu/cmu/geolocator/io/GetReader.java // public class GetReader { // // public static BufferedReader getUTF8FileReader(String filename) throws FileNotFoundException, // UnsupportedEncodingException { // File file = new File(filename); // BufferedReader bin = new BufferedReader(new InputStreamReader(new FileInputStream(file), // "utf-8")); // return bin; // } // // public static IndexSearcher getIndexSearcherFromWriter(String filename) throws IOException { // IndexWriter iw = GetWriter.getIndexWriter(filename, 1024); // IndexReader ir = IndexReader.open(iw, false); // IndexSearcher searcher = new IndexSearcher(ir); // return searcher; // } // // public static IndexSearcher getIndexSearcher(String filename, String diskOrMem) throws Exception { // IndexReader reader; // Directory d ; // if (diskOrMem.equals("disk")) // d = FSDirectory.open(new File(filename)); // else if (diskOrMem.equals("mmap")) // d= MmapDirectory(new File(filename)); // else // throw new Exception("parameter for directory type not defined."); // // if(OSUtil.isWindows()) // reader = IndexReader.open(FSDirectory.open(new File(filename))); // else // reader = IndexReader.open(NIOFSDirectory.open(new File(filename))); // IndexSearcher searcher = new IndexSearcher(reader); // return searcher; // } // // private static Directory MmapDirectory(File file) { // // TODO Auto-generated method stub // return null; // } // // public static BufferedReader getCommandLineReader() throws UnsupportedEncodingException { // BufferedReader br = new BufferedReader(new InputStreamReader(System.in, "utf-8")); // return br; // } // // }
import edu.cmu.minorthird.classify.Feature; import edu.cmu.minorthird.classify.MutableInstance; import edu.cmu.minorthird.classify.sequential.CMM; import edu.cmu.minorthird.util.IOUtil; import java.io.BufferedReader; import java.io.IOException; import java.util.ArrayList; import edu.cmu.geolocator.io.GetReader; import edu.cmu.minorthird.classify.ClassLabel; import edu.cmu.minorthird.classify.Example;
/** * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you 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. * * @author Wei Zhang, Language Technology Institute, School of Computer Science, Carnegie-Mellon University. * email: [email protected] * */ package edu.cmu.geolocator.nlp.ner.MinorThirdCRF; public class Tester { /** * Best options: * * en CRF:iteration = 100. * es CRF: iteration =150. * * en CPL: iteration = 10 (not as good as crf) * es CPL: iteration = 5 (overfit, no recall) * * @param argv * @throws IOException */ public static void main(String argv[]) throws IOException { String lang = "es"; int iteration = 150; String learningalgo = "crf"; String featuretype ="-3tok_.3pres.2cap.3caps.1pos.2pos.1gaz.1gazs.1cty.1ctys.-3-1prep"; // = "ct-1+1"; String crff = lang + "-" + learningalgo + iteration + "-" + featuretype + ".model"; // = "en-crf150-ct-only.model"; // = "en-crf100-all.model"; // = "en-crf100-ct-only.model"; System.out.println("Begin Loading the model: " + crff); CMM model = null; if (learningalgo.equals("cpl")) model = (CMM) IOUtil.loadSerialized(new java.io.File("trainingdata/" + lang + "NER/" + crff)); if (learningalgo.equals("crf")) model = (CMM) IOUtil.loadSerialized(new java.io.File("trainingdata/" + lang + "NER/" + crff)); System.out.println("Model loaded. Tagging test set and Evaluate:"); // usage: // Example[] sequence; // model.classification(sequence);
// Path: geo-locator/src/edu/cmu/geolocator/io/GetReader.java // public class GetReader { // // public static BufferedReader getUTF8FileReader(String filename) throws FileNotFoundException, // UnsupportedEncodingException { // File file = new File(filename); // BufferedReader bin = new BufferedReader(new InputStreamReader(new FileInputStream(file), // "utf-8")); // return bin; // } // // public static IndexSearcher getIndexSearcherFromWriter(String filename) throws IOException { // IndexWriter iw = GetWriter.getIndexWriter(filename, 1024); // IndexReader ir = IndexReader.open(iw, false); // IndexSearcher searcher = new IndexSearcher(ir); // return searcher; // } // // public static IndexSearcher getIndexSearcher(String filename, String diskOrMem) throws Exception { // IndexReader reader; // Directory d ; // if (diskOrMem.equals("disk")) // d = FSDirectory.open(new File(filename)); // else if (diskOrMem.equals("mmap")) // d= MmapDirectory(new File(filename)); // else // throw new Exception("parameter for directory type not defined."); // // if(OSUtil.isWindows()) // reader = IndexReader.open(FSDirectory.open(new File(filename))); // else // reader = IndexReader.open(NIOFSDirectory.open(new File(filename))); // IndexSearcher searcher = new IndexSearcher(reader); // return searcher; // } // // private static Directory MmapDirectory(File file) { // // TODO Auto-generated method stub // return null; // } // // public static BufferedReader getCommandLineReader() throws UnsupportedEncodingException { // BufferedReader br = new BufferedReader(new InputStreamReader(System.in, "utf-8")); // return br; // } // // } // Path: geo-locator/src/edu/cmu/geolocator/nlp/ner/MinorThirdCRF/Tester.java import edu.cmu.minorthird.classify.Feature; import edu.cmu.minorthird.classify.MutableInstance; import edu.cmu.minorthird.classify.sequential.CMM; import edu.cmu.minorthird.util.IOUtil; import java.io.BufferedReader; import java.io.IOException; import java.util.ArrayList; import edu.cmu.geolocator.io.GetReader; import edu.cmu.minorthird.classify.ClassLabel; import edu.cmu.minorthird.classify.Example; /** * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you 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. * * @author Wei Zhang, Language Technology Institute, School of Computer Science, Carnegie-Mellon University. * email: [email protected] * */ package edu.cmu.geolocator.nlp.ner.MinorThirdCRF; public class Tester { /** * Best options: * * en CRF:iteration = 100. * es CRF: iteration =150. * * en CPL: iteration = 10 (not as good as crf) * es CPL: iteration = 5 (overfit, no recall) * * @param argv * @throws IOException */ public static void main(String argv[]) throws IOException { String lang = "es"; int iteration = 150; String learningalgo = "crf"; String featuretype ="-3tok_.3pres.2cap.3caps.1pos.2pos.1gaz.1gazs.1cty.1ctys.-3-1prep"; // = "ct-1+1"; String crff = lang + "-" + learningalgo + iteration + "-" + featuretype + ".model"; // = "en-crf150-ct-only.model"; // = "en-crf100-all.model"; // = "en-crf100-ct-only.model"; System.out.println("Begin Loading the model: " + crff); CMM model = null; if (learningalgo.equals("cpl")) model = (CMM) IOUtil.loadSerialized(new java.io.File("trainingdata/" + lang + "NER/" + crff)); if (learningalgo.equals("crf")) model = (CMM) IOUtil.loadSerialized(new java.io.File("trainingdata/" + lang + "NER/" + crff)); System.out.println("Model loaded. Tagging test set and Evaluate:"); // usage: // Example[] sequence; // model.classification(sequence);
BufferedReader br = GetReader.getUTF8FileReader("trainingdata/" + lang + "NER/test/" + featuretype
geoparser/geolocator-2.0
geo-locator/src/edu/cmu/geolocator/resource/gazindexing/AbbrMapper.java
// Path: geo-locator/src/edu/cmu/geolocator/io/GetReader.java // public class GetReader { // // public static BufferedReader getUTF8FileReader(String filename) throws FileNotFoundException, // UnsupportedEncodingException { // File file = new File(filename); // BufferedReader bin = new BufferedReader(new InputStreamReader(new FileInputStream(file), // "utf-8")); // return bin; // } // // public static IndexSearcher getIndexSearcherFromWriter(String filename) throws IOException { // IndexWriter iw = GetWriter.getIndexWriter(filename, 1024); // IndexReader ir = IndexReader.open(iw, false); // IndexSearcher searcher = new IndexSearcher(ir); // return searcher; // } // // public static IndexSearcher getIndexSearcher(String filename, String diskOrMem) throws Exception { // IndexReader reader; // Directory d ; // if (diskOrMem.equals("disk")) // d = FSDirectory.open(new File(filename)); // else if (diskOrMem.equals("mmap")) // d= MmapDirectory(new File(filename)); // else // throw new Exception("parameter for directory type not defined."); // // if(OSUtil.isWindows()) // reader = IndexReader.open(FSDirectory.open(new File(filename))); // else // reader = IndexReader.open(NIOFSDirectory.open(new File(filename))); // IndexSearcher searcher = new IndexSearcher(reader); // return searcher; // } // // private static Directory MmapDirectory(File file) { // // TODO Auto-generated method stub // return null; // } // // public static BufferedReader getCommandLineReader() throws UnsupportedEncodingException { // BufferedReader br = new BufferedReader(new InputStreamReader(System.in, "utf-8")); // return br; // } // // }
import java.io.BufferedReader; import java.io.IOException; import java.util.HashMap; import edu.cmu.geolocator.io.GetReader;
/** * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you 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. * * @author Wei Zhang, Language Technology Institute, School of Computer Science, Carnegie-Mellon University. * email: [email protected] * */ package edu.cmu.geolocator.resource.gazindexing; public class AbbrMapper { public static HashMap<String, String> load() throws IOException {
// Path: geo-locator/src/edu/cmu/geolocator/io/GetReader.java // public class GetReader { // // public static BufferedReader getUTF8FileReader(String filename) throws FileNotFoundException, // UnsupportedEncodingException { // File file = new File(filename); // BufferedReader bin = new BufferedReader(new InputStreamReader(new FileInputStream(file), // "utf-8")); // return bin; // } // // public static IndexSearcher getIndexSearcherFromWriter(String filename) throws IOException { // IndexWriter iw = GetWriter.getIndexWriter(filename, 1024); // IndexReader ir = IndexReader.open(iw, false); // IndexSearcher searcher = new IndexSearcher(ir); // return searcher; // } // // public static IndexSearcher getIndexSearcher(String filename, String diskOrMem) throws Exception { // IndexReader reader; // Directory d ; // if (diskOrMem.equals("disk")) // d = FSDirectory.open(new File(filename)); // else if (diskOrMem.equals("mmap")) // d= MmapDirectory(new File(filename)); // else // throw new Exception("parameter for directory type not defined."); // // if(OSUtil.isWindows()) // reader = IndexReader.open(FSDirectory.open(new File(filename))); // else // reader = IndexReader.open(NIOFSDirectory.open(new File(filename))); // IndexSearcher searcher = new IndexSearcher(reader); // return searcher; // } // // private static Directory MmapDirectory(File file) { // // TODO Auto-generated method stub // return null; // } // // public static BufferedReader getCommandLineReader() throws UnsupportedEncodingException { // BufferedReader br = new BufferedReader(new InputStreamReader(System.in, "utf-8")); // return br; // } // // } // Path: geo-locator/src/edu/cmu/geolocator/resource/gazindexing/AbbrMapper.java import java.io.BufferedReader; import java.io.IOException; import java.util.HashMap; import edu.cmu.geolocator.io.GetReader; /** * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you 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. * * @author Wei Zhang, Language Technology Institute, School of Computer Science, Carnegie-Mellon University. * email: [email protected] * */ package edu.cmu.geolocator.resource.gazindexing; public class AbbrMapper { public static HashMap<String, String> load() throws IOException {
BufferedReader reader = GetReader.getUTF8FileReader("res/en/state_abbr.txt");
geoparser/geolocator-2.0
geo-locator/src/edu/cmu/geolocator/nlp/ner/MinorThirdCRF/Learner.java
// Path: geo-locator/src/edu/cmu/geolocator/io/GetReader.java // public class GetReader { // // public static BufferedReader getUTF8FileReader(String filename) throws FileNotFoundException, // UnsupportedEncodingException { // File file = new File(filename); // BufferedReader bin = new BufferedReader(new InputStreamReader(new FileInputStream(file), // "utf-8")); // return bin; // } // // public static IndexSearcher getIndexSearcherFromWriter(String filename) throws IOException { // IndexWriter iw = GetWriter.getIndexWriter(filename, 1024); // IndexReader ir = IndexReader.open(iw, false); // IndexSearcher searcher = new IndexSearcher(ir); // return searcher; // } // // public static IndexSearcher getIndexSearcher(String filename, String diskOrMem) throws Exception { // IndexReader reader; // Directory d ; // if (diskOrMem.equals("disk")) // d = FSDirectory.open(new File(filename)); // else if (diskOrMem.equals("mmap")) // d= MmapDirectory(new File(filename)); // else // throw new Exception("parameter for directory type not defined."); // // if(OSUtil.isWindows()) // reader = IndexReader.open(FSDirectory.open(new File(filename))); // else // reader = IndexReader.open(NIOFSDirectory.open(new File(filename))); // IndexSearcher searcher = new IndexSearcher(reader); // return searcher; // } // // private static Directory MmapDirectory(File file) { // // TODO Auto-generated method stub // return null; // } // // public static BufferedReader getCommandLineReader() throws UnsupportedEncodingException { // BufferedReader br = new BufferedReader(new InputStreamReader(System.in, "utf-8")); // return br; // } // // }
import edu.cmu.minorthird.classify.Example; import edu.cmu.minorthird.classify.Feature; import edu.cmu.minorthird.classify.MutableInstance; import edu.cmu.minorthird.classify.sequential.CMM; import edu.cmu.minorthird.classify.sequential.CRFLearner; import edu.cmu.minorthird.classify.sequential.CollinsPerceptronLearner; import edu.cmu.minorthird.classify.sequential.SequenceDataset; import edu.cmu.minorthird.util.IOUtil; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.util.ArrayList; import edu.cmu.geolocator.io.GetReader; import edu.cmu.minorthird.classify.ClassLabel;
/** * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you 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. * * @author Wei Zhang, Language Technology Institute, School of Computer Science, Carnegie-Mellon University. * email: [email protected] * */ package edu.cmu.geolocator.nlp.ner.MinorThirdCRF; public class Learner { public static void main(String argv[]) throws IOException { String lang = "en"; String learner = "crf"; String featuretype // = "ct-only"; = "-3tok*.3pres.2cap.3caps.1pos.2pos.1gaz.1gazs.1cty.1ctys.-3-1prep"; int iter = 150;
// Path: geo-locator/src/edu/cmu/geolocator/io/GetReader.java // public class GetReader { // // public static BufferedReader getUTF8FileReader(String filename) throws FileNotFoundException, // UnsupportedEncodingException { // File file = new File(filename); // BufferedReader bin = new BufferedReader(new InputStreamReader(new FileInputStream(file), // "utf-8")); // return bin; // } // // public static IndexSearcher getIndexSearcherFromWriter(String filename) throws IOException { // IndexWriter iw = GetWriter.getIndexWriter(filename, 1024); // IndexReader ir = IndexReader.open(iw, false); // IndexSearcher searcher = new IndexSearcher(ir); // return searcher; // } // // public static IndexSearcher getIndexSearcher(String filename, String diskOrMem) throws Exception { // IndexReader reader; // Directory d ; // if (diskOrMem.equals("disk")) // d = FSDirectory.open(new File(filename)); // else if (diskOrMem.equals("mmap")) // d= MmapDirectory(new File(filename)); // else // throw new Exception("parameter for directory type not defined."); // // if(OSUtil.isWindows()) // reader = IndexReader.open(FSDirectory.open(new File(filename))); // else // reader = IndexReader.open(NIOFSDirectory.open(new File(filename))); // IndexSearcher searcher = new IndexSearcher(reader); // return searcher; // } // // private static Directory MmapDirectory(File file) { // // TODO Auto-generated method stub // return null; // } // // public static BufferedReader getCommandLineReader() throws UnsupportedEncodingException { // BufferedReader br = new BufferedReader(new InputStreamReader(System.in, "utf-8")); // return br; // } // // } // Path: geo-locator/src/edu/cmu/geolocator/nlp/ner/MinorThirdCRF/Learner.java import edu.cmu.minorthird.classify.Example; import edu.cmu.minorthird.classify.Feature; import edu.cmu.minorthird.classify.MutableInstance; import edu.cmu.minorthird.classify.sequential.CMM; import edu.cmu.minorthird.classify.sequential.CRFLearner; import edu.cmu.minorthird.classify.sequential.CollinsPerceptronLearner; import edu.cmu.minorthird.classify.sequential.SequenceDataset; import edu.cmu.minorthird.util.IOUtil; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.util.ArrayList; import edu.cmu.geolocator.io.GetReader; import edu.cmu.minorthird.classify.ClassLabel; /** * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you 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. * * @author Wei Zhang, Language Technology Institute, School of Computer Science, Carnegie-Mellon University. * email: [email protected] * */ package edu.cmu.geolocator.nlp.ner.MinorThirdCRF; public class Learner { public static void main(String argv[]) throws IOException { String lang = "en"; String learner = "crf"; String featuretype // = "ct-only"; = "-3tok*.3pres.2cap.3caps.1pos.2pos.1gaz.1gazs.1cty.1ctys.-3-1prep"; int iter = 150;
BufferedReader br = GetReader.getUTF8FileReader("trainingdata/" + lang + "NER/train/" + featuretype
geoparser/geolocator-2.0
geo-locator/src/edu/cmu/geolocator/resource/Map/CCodeAdj2CTRYtype.java
// Path: geo-locator/src/edu/cmu/geolocator/io/GetReader.java // public class GetReader { // // public static BufferedReader getUTF8FileReader(String filename) throws FileNotFoundException, // UnsupportedEncodingException { // File file = new File(filename); // BufferedReader bin = new BufferedReader(new InputStreamReader(new FileInputStream(file), // "utf-8")); // return bin; // } // // public static IndexSearcher getIndexSearcherFromWriter(String filename) throws IOException { // IndexWriter iw = GetWriter.getIndexWriter(filename, 1024); // IndexReader ir = IndexReader.open(iw, false); // IndexSearcher searcher = new IndexSearcher(ir); // return searcher; // } // // public static IndexSearcher getIndexSearcher(String filename, String diskOrMem) throws Exception { // IndexReader reader; // Directory d ; // if (diskOrMem.equals("disk")) // d = FSDirectory.open(new File(filename)); // else if (diskOrMem.equals("mmap")) // d= MmapDirectory(new File(filename)); // else // throw new Exception("parameter for directory type not defined."); // // if(OSUtil.isWindows()) // reader = IndexReader.open(FSDirectory.open(new File(filename))); // else // reader = IndexReader.open(NIOFSDirectory.open(new File(filename))); // IndexSearcher searcher = new IndexSearcher(reader); // return searcher; // } // // private static Directory MmapDirectory(File file) { // // TODO Auto-generated method stub // return null; // } // // public static BufferedReader getCommandLineReader() throws UnsupportedEncodingException { // BufferedReader br = new BufferedReader(new InputStreamReader(System.in, "utf-8")); // return br; // } // // } // // Path: geo-locator/src/edu/cmu/geolocator/model/Country.java // public class Country extends CandidateAndFeature implements Comparable<CandidateAndFeature>{ // // // public Country(){ // super(); // } // public String getAbbr() { // return abbr; // } // public Country setAbbr(String abbr) { // this.abbr = abbr; // return this; // } // public String getLang() { // return lang; // } // public Country setLang(String lang) { // this.lang = lang; // return this; // } // public String getRace() { // return race; // } // public Country setRace(String race) { // this.race = race; // return this; // } // // String abbr,lang,race; // @Override // public int compareTo(CandidateAndFeature arg0) { // // TODO Auto-generated method stub // return arg0.getId().compareTo(this.getId()); // } // // } // // Path: geo-locator/src/edu/cmu/geolocator/resource/ResourceFactory.java // public class ResourceFactory { // // private static CollaborativeIndex collaborativeIndex = CollaborativeIndex.getInstance(); // // private static AdmCode2GazCandidateMap adminCode2GazCandidateMap = AdmCode2GazCandidateMap // .getInstance(); // // private static CCodeAdj2CTRYtype countryCode2CountryMap = CCodeAdj2CTRYtype // .getInstance(); // // private static FeatureCode2Map featurecode2map = FeatureCode2Map.getInstance(); // /** // * @return the collaborativeIndex // */ // public static CollaborativeIndex getClbIndex() { // return collaborativeIndex; // } // // /** // * return the GazEntryAndInfo type given the admin code. // * @return the adminCode2GazCandidateMap // */ // public static AdmCode2GazCandidateMap getAdminCode2GazCandidateMap() { // return adminCode2GazCandidateMap; // } // // /** // * return the Country type given the country code. // * @return the countryCode2CountryMap // * // */ // public static CCodeAdj2CTRYtype getCountryCode2CountryMap() { // return countryCode2CountryMap; // } // // public static FeatureCode2Map getFeatureCode2Map() { // // TODO Auto-generated method stub // return featurecode2map; // } // }
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.HashMap; import org.apache.lucene.document.Document; import edu.cmu.geolocator.io.GetReader; import edu.cmu.geolocator.model.Country; import edu.cmu.geolocator.resource.ResourceFactory;
package edu.cmu.geolocator.resource.Map; public class CCodeAdj2CTRYtype extends Map { public static final String name = "res/geonames/countrymapping.txt"; static CCodeAdj2CTRYtype c2cMap;
// Path: geo-locator/src/edu/cmu/geolocator/io/GetReader.java // public class GetReader { // // public static BufferedReader getUTF8FileReader(String filename) throws FileNotFoundException, // UnsupportedEncodingException { // File file = new File(filename); // BufferedReader bin = new BufferedReader(new InputStreamReader(new FileInputStream(file), // "utf-8")); // return bin; // } // // public static IndexSearcher getIndexSearcherFromWriter(String filename) throws IOException { // IndexWriter iw = GetWriter.getIndexWriter(filename, 1024); // IndexReader ir = IndexReader.open(iw, false); // IndexSearcher searcher = new IndexSearcher(ir); // return searcher; // } // // public static IndexSearcher getIndexSearcher(String filename, String diskOrMem) throws Exception { // IndexReader reader; // Directory d ; // if (diskOrMem.equals("disk")) // d = FSDirectory.open(new File(filename)); // else if (diskOrMem.equals("mmap")) // d= MmapDirectory(new File(filename)); // else // throw new Exception("parameter for directory type not defined."); // // if(OSUtil.isWindows()) // reader = IndexReader.open(FSDirectory.open(new File(filename))); // else // reader = IndexReader.open(NIOFSDirectory.open(new File(filename))); // IndexSearcher searcher = new IndexSearcher(reader); // return searcher; // } // // private static Directory MmapDirectory(File file) { // // TODO Auto-generated method stub // return null; // } // // public static BufferedReader getCommandLineReader() throws UnsupportedEncodingException { // BufferedReader br = new BufferedReader(new InputStreamReader(System.in, "utf-8")); // return br; // } // // } // // Path: geo-locator/src/edu/cmu/geolocator/model/Country.java // public class Country extends CandidateAndFeature implements Comparable<CandidateAndFeature>{ // // // public Country(){ // super(); // } // public String getAbbr() { // return abbr; // } // public Country setAbbr(String abbr) { // this.abbr = abbr; // return this; // } // public String getLang() { // return lang; // } // public Country setLang(String lang) { // this.lang = lang; // return this; // } // public String getRace() { // return race; // } // public Country setRace(String race) { // this.race = race; // return this; // } // // String abbr,lang,race; // @Override // public int compareTo(CandidateAndFeature arg0) { // // TODO Auto-generated method stub // return arg0.getId().compareTo(this.getId()); // } // // } // // Path: geo-locator/src/edu/cmu/geolocator/resource/ResourceFactory.java // public class ResourceFactory { // // private static CollaborativeIndex collaborativeIndex = CollaborativeIndex.getInstance(); // // private static AdmCode2GazCandidateMap adminCode2GazCandidateMap = AdmCode2GazCandidateMap // .getInstance(); // // private static CCodeAdj2CTRYtype countryCode2CountryMap = CCodeAdj2CTRYtype // .getInstance(); // // private static FeatureCode2Map featurecode2map = FeatureCode2Map.getInstance(); // /** // * @return the collaborativeIndex // */ // public static CollaborativeIndex getClbIndex() { // return collaborativeIndex; // } // // /** // * return the GazEntryAndInfo type given the admin code. // * @return the adminCode2GazCandidateMap // */ // public static AdmCode2GazCandidateMap getAdminCode2GazCandidateMap() { // return adminCode2GazCandidateMap; // } // // /** // * return the Country type given the country code. // * @return the countryCode2CountryMap // * // */ // public static CCodeAdj2CTRYtype getCountryCode2CountryMap() { // return countryCode2CountryMap; // } // // public static FeatureCode2Map getFeatureCode2Map() { // // TODO Auto-generated method stub // return featurecode2map; // } // } // Path: geo-locator/src/edu/cmu/geolocator/resource/Map/CCodeAdj2CTRYtype.java import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.HashMap; import org.apache.lucene.document.Document; import edu.cmu.geolocator.io.GetReader; import edu.cmu.geolocator.model.Country; import edu.cmu.geolocator.resource.ResourceFactory; package edu.cmu.geolocator.resource.Map; public class CCodeAdj2CTRYtype extends Map { public static final String name = "res/geonames/countrymapping.txt"; static CCodeAdj2CTRYtype c2cMap;
HashMap<String, Country> theMap;
geoparser/geolocator-2.0
geo-locator/src/edu/cmu/geolocator/resource/Map/CCodeAdj2CTRYtype.java
// Path: geo-locator/src/edu/cmu/geolocator/io/GetReader.java // public class GetReader { // // public static BufferedReader getUTF8FileReader(String filename) throws FileNotFoundException, // UnsupportedEncodingException { // File file = new File(filename); // BufferedReader bin = new BufferedReader(new InputStreamReader(new FileInputStream(file), // "utf-8")); // return bin; // } // // public static IndexSearcher getIndexSearcherFromWriter(String filename) throws IOException { // IndexWriter iw = GetWriter.getIndexWriter(filename, 1024); // IndexReader ir = IndexReader.open(iw, false); // IndexSearcher searcher = new IndexSearcher(ir); // return searcher; // } // // public static IndexSearcher getIndexSearcher(String filename, String diskOrMem) throws Exception { // IndexReader reader; // Directory d ; // if (diskOrMem.equals("disk")) // d = FSDirectory.open(new File(filename)); // else if (diskOrMem.equals("mmap")) // d= MmapDirectory(new File(filename)); // else // throw new Exception("parameter for directory type not defined."); // // if(OSUtil.isWindows()) // reader = IndexReader.open(FSDirectory.open(new File(filename))); // else // reader = IndexReader.open(NIOFSDirectory.open(new File(filename))); // IndexSearcher searcher = new IndexSearcher(reader); // return searcher; // } // // private static Directory MmapDirectory(File file) { // // TODO Auto-generated method stub // return null; // } // // public static BufferedReader getCommandLineReader() throws UnsupportedEncodingException { // BufferedReader br = new BufferedReader(new InputStreamReader(System.in, "utf-8")); // return br; // } // // } // // Path: geo-locator/src/edu/cmu/geolocator/model/Country.java // public class Country extends CandidateAndFeature implements Comparable<CandidateAndFeature>{ // // // public Country(){ // super(); // } // public String getAbbr() { // return abbr; // } // public Country setAbbr(String abbr) { // this.abbr = abbr; // return this; // } // public String getLang() { // return lang; // } // public Country setLang(String lang) { // this.lang = lang; // return this; // } // public String getRace() { // return race; // } // public Country setRace(String race) { // this.race = race; // return this; // } // // String abbr,lang,race; // @Override // public int compareTo(CandidateAndFeature arg0) { // // TODO Auto-generated method stub // return arg0.getId().compareTo(this.getId()); // } // // } // // Path: geo-locator/src/edu/cmu/geolocator/resource/ResourceFactory.java // public class ResourceFactory { // // private static CollaborativeIndex collaborativeIndex = CollaborativeIndex.getInstance(); // // private static AdmCode2GazCandidateMap adminCode2GazCandidateMap = AdmCode2GazCandidateMap // .getInstance(); // // private static CCodeAdj2CTRYtype countryCode2CountryMap = CCodeAdj2CTRYtype // .getInstance(); // // private static FeatureCode2Map featurecode2map = FeatureCode2Map.getInstance(); // /** // * @return the collaborativeIndex // */ // public static CollaborativeIndex getClbIndex() { // return collaborativeIndex; // } // // /** // * return the GazEntryAndInfo type given the admin code. // * @return the adminCode2GazCandidateMap // */ // public static AdmCode2GazCandidateMap getAdminCode2GazCandidateMap() { // return adminCode2GazCandidateMap; // } // // /** // * return the Country type given the country code. // * @return the countryCode2CountryMap // * // */ // public static CCodeAdj2CTRYtype getCountryCode2CountryMap() { // return countryCode2CountryMap; // } // // public static FeatureCode2Map getFeatureCode2Map() { // // TODO Auto-generated method stub // return featurecode2map; // } // }
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.HashMap; import org.apache.lucene.document.Document; import edu.cmu.geolocator.io.GetReader; import edu.cmu.geolocator.model.Country; import edu.cmu.geolocator.resource.ResourceFactory;
package edu.cmu.geolocator.resource.Map; public class CCodeAdj2CTRYtype extends Map { public static final String name = "res/geonames/countrymapping.txt"; static CCodeAdj2CTRYtype c2cMap; HashMap<String, Country> theMap; @SuppressWarnings("unchecked") public static CCodeAdj2CTRYtype getInstance() { if (c2cMap == null) return new CCodeAdj2CTRYtype().load(); return c2cMap; } public CCodeAdj2CTRYtype load() { theMap = new HashMap<String, Country>(252); BufferedReader br = null; try {
// Path: geo-locator/src/edu/cmu/geolocator/io/GetReader.java // public class GetReader { // // public static BufferedReader getUTF8FileReader(String filename) throws FileNotFoundException, // UnsupportedEncodingException { // File file = new File(filename); // BufferedReader bin = new BufferedReader(new InputStreamReader(new FileInputStream(file), // "utf-8")); // return bin; // } // // public static IndexSearcher getIndexSearcherFromWriter(String filename) throws IOException { // IndexWriter iw = GetWriter.getIndexWriter(filename, 1024); // IndexReader ir = IndexReader.open(iw, false); // IndexSearcher searcher = new IndexSearcher(ir); // return searcher; // } // // public static IndexSearcher getIndexSearcher(String filename, String diskOrMem) throws Exception { // IndexReader reader; // Directory d ; // if (diskOrMem.equals("disk")) // d = FSDirectory.open(new File(filename)); // else if (diskOrMem.equals("mmap")) // d= MmapDirectory(new File(filename)); // else // throw new Exception("parameter for directory type not defined."); // // if(OSUtil.isWindows()) // reader = IndexReader.open(FSDirectory.open(new File(filename))); // else // reader = IndexReader.open(NIOFSDirectory.open(new File(filename))); // IndexSearcher searcher = new IndexSearcher(reader); // return searcher; // } // // private static Directory MmapDirectory(File file) { // // TODO Auto-generated method stub // return null; // } // // public static BufferedReader getCommandLineReader() throws UnsupportedEncodingException { // BufferedReader br = new BufferedReader(new InputStreamReader(System.in, "utf-8")); // return br; // } // // } // // Path: geo-locator/src/edu/cmu/geolocator/model/Country.java // public class Country extends CandidateAndFeature implements Comparable<CandidateAndFeature>{ // // // public Country(){ // super(); // } // public String getAbbr() { // return abbr; // } // public Country setAbbr(String abbr) { // this.abbr = abbr; // return this; // } // public String getLang() { // return lang; // } // public Country setLang(String lang) { // this.lang = lang; // return this; // } // public String getRace() { // return race; // } // public Country setRace(String race) { // this.race = race; // return this; // } // // String abbr,lang,race; // @Override // public int compareTo(CandidateAndFeature arg0) { // // TODO Auto-generated method stub // return arg0.getId().compareTo(this.getId()); // } // // } // // Path: geo-locator/src/edu/cmu/geolocator/resource/ResourceFactory.java // public class ResourceFactory { // // private static CollaborativeIndex collaborativeIndex = CollaborativeIndex.getInstance(); // // private static AdmCode2GazCandidateMap adminCode2GazCandidateMap = AdmCode2GazCandidateMap // .getInstance(); // // private static CCodeAdj2CTRYtype countryCode2CountryMap = CCodeAdj2CTRYtype // .getInstance(); // // private static FeatureCode2Map featurecode2map = FeatureCode2Map.getInstance(); // /** // * @return the collaborativeIndex // */ // public static CollaborativeIndex getClbIndex() { // return collaborativeIndex; // } // // /** // * return the GazEntryAndInfo type given the admin code. // * @return the adminCode2GazCandidateMap // */ // public static AdmCode2GazCandidateMap getAdminCode2GazCandidateMap() { // return adminCode2GazCandidateMap; // } // // /** // * return the Country type given the country code. // * @return the countryCode2CountryMap // * // */ // public static CCodeAdj2CTRYtype getCountryCode2CountryMap() { // return countryCode2CountryMap; // } // // public static FeatureCode2Map getFeatureCode2Map() { // // TODO Auto-generated method stub // return featurecode2map; // } // } // Path: geo-locator/src/edu/cmu/geolocator/resource/Map/CCodeAdj2CTRYtype.java import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.HashMap; import org.apache.lucene.document.Document; import edu.cmu.geolocator.io.GetReader; import edu.cmu.geolocator.model.Country; import edu.cmu.geolocator.resource.ResourceFactory; package edu.cmu.geolocator.resource.Map; public class CCodeAdj2CTRYtype extends Map { public static final String name = "res/geonames/countrymapping.txt"; static CCodeAdj2CTRYtype c2cMap; HashMap<String, Country> theMap; @SuppressWarnings("unchecked") public static CCodeAdj2CTRYtype getInstance() { if (c2cMap == null) return new CCodeAdj2CTRYtype().load(); return c2cMap; } public CCodeAdj2CTRYtype load() { theMap = new HashMap<String, Country>(252); BufferedReader br = null; try {
br = GetReader.getUTF8FileReader(name);
geoparser/geolocator-2.0
geo-locator/src/edu/cmu/geolocator/resource/Map/CCodeAdj2CTRYtype.java
// Path: geo-locator/src/edu/cmu/geolocator/io/GetReader.java // public class GetReader { // // public static BufferedReader getUTF8FileReader(String filename) throws FileNotFoundException, // UnsupportedEncodingException { // File file = new File(filename); // BufferedReader bin = new BufferedReader(new InputStreamReader(new FileInputStream(file), // "utf-8")); // return bin; // } // // public static IndexSearcher getIndexSearcherFromWriter(String filename) throws IOException { // IndexWriter iw = GetWriter.getIndexWriter(filename, 1024); // IndexReader ir = IndexReader.open(iw, false); // IndexSearcher searcher = new IndexSearcher(ir); // return searcher; // } // // public static IndexSearcher getIndexSearcher(String filename, String diskOrMem) throws Exception { // IndexReader reader; // Directory d ; // if (diskOrMem.equals("disk")) // d = FSDirectory.open(new File(filename)); // else if (diskOrMem.equals("mmap")) // d= MmapDirectory(new File(filename)); // else // throw new Exception("parameter for directory type not defined."); // // if(OSUtil.isWindows()) // reader = IndexReader.open(FSDirectory.open(new File(filename))); // else // reader = IndexReader.open(NIOFSDirectory.open(new File(filename))); // IndexSearcher searcher = new IndexSearcher(reader); // return searcher; // } // // private static Directory MmapDirectory(File file) { // // TODO Auto-generated method stub // return null; // } // // public static BufferedReader getCommandLineReader() throws UnsupportedEncodingException { // BufferedReader br = new BufferedReader(new InputStreamReader(System.in, "utf-8")); // return br; // } // // } // // Path: geo-locator/src/edu/cmu/geolocator/model/Country.java // public class Country extends CandidateAndFeature implements Comparable<CandidateAndFeature>{ // // // public Country(){ // super(); // } // public String getAbbr() { // return abbr; // } // public Country setAbbr(String abbr) { // this.abbr = abbr; // return this; // } // public String getLang() { // return lang; // } // public Country setLang(String lang) { // this.lang = lang; // return this; // } // public String getRace() { // return race; // } // public Country setRace(String race) { // this.race = race; // return this; // } // // String abbr,lang,race; // @Override // public int compareTo(CandidateAndFeature arg0) { // // TODO Auto-generated method stub // return arg0.getId().compareTo(this.getId()); // } // // } // // Path: geo-locator/src/edu/cmu/geolocator/resource/ResourceFactory.java // public class ResourceFactory { // // private static CollaborativeIndex collaborativeIndex = CollaborativeIndex.getInstance(); // // private static AdmCode2GazCandidateMap adminCode2GazCandidateMap = AdmCode2GazCandidateMap // .getInstance(); // // private static CCodeAdj2CTRYtype countryCode2CountryMap = CCodeAdj2CTRYtype // .getInstance(); // // private static FeatureCode2Map featurecode2map = FeatureCode2Map.getInstance(); // /** // * @return the collaborativeIndex // */ // public static CollaborativeIndex getClbIndex() { // return collaborativeIndex; // } // // /** // * return the GazEntryAndInfo type given the admin code. // * @return the adminCode2GazCandidateMap // */ // public static AdmCode2GazCandidateMap getAdminCode2GazCandidateMap() { // return adminCode2GazCandidateMap; // } // // /** // * return the Country type given the country code. // * @return the countryCode2CountryMap // * // */ // public static CCodeAdj2CTRYtype getCountryCode2CountryMap() { // return countryCode2CountryMap; // } // // public static FeatureCode2Map getFeatureCode2Map() { // // TODO Auto-generated method stub // return featurecode2map; // } // }
import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.HashMap; import org.apache.lucene.document.Document; import edu.cmu.geolocator.io.GetReader; import edu.cmu.geolocator.model.Country; import edu.cmu.geolocator.resource.ResourceFactory;
} } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { br.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return this; } @Override public Country getValue(String code) { return theMap.get(code.toLowerCase()); } /** * check if it's a country abbreviation. Case insensitive. Example : US, CN, BR. or us, cn, br. * * @param phrase * @return */ public boolean isInMap(String phrase) { String countryId = null; phrase = phrase.toLowerCase(); // if (phrase.length() != 2) // return false;
// Path: geo-locator/src/edu/cmu/geolocator/io/GetReader.java // public class GetReader { // // public static BufferedReader getUTF8FileReader(String filename) throws FileNotFoundException, // UnsupportedEncodingException { // File file = new File(filename); // BufferedReader bin = new BufferedReader(new InputStreamReader(new FileInputStream(file), // "utf-8")); // return bin; // } // // public static IndexSearcher getIndexSearcherFromWriter(String filename) throws IOException { // IndexWriter iw = GetWriter.getIndexWriter(filename, 1024); // IndexReader ir = IndexReader.open(iw, false); // IndexSearcher searcher = new IndexSearcher(ir); // return searcher; // } // // public static IndexSearcher getIndexSearcher(String filename, String diskOrMem) throws Exception { // IndexReader reader; // Directory d ; // if (diskOrMem.equals("disk")) // d = FSDirectory.open(new File(filename)); // else if (diskOrMem.equals("mmap")) // d= MmapDirectory(new File(filename)); // else // throw new Exception("parameter for directory type not defined."); // // if(OSUtil.isWindows()) // reader = IndexReader.open(FSDirectory.open(new File(filename))); // else // reader = IndexReader.open(NIOFSDirectory.open(new File(filename))); // IndexSearcher searcher = new IndexSearcher(reader); // return searcher; // } // // private static Directory MmapDirectory(File file) { // // TODO Auto-generated method stub // return null; // } // // public static BufferedReader getCommandLineReader() throws UnsupportedEncodingException { // BufferedReader br = new BufferedReader(new InputStreamReader(System.in, "utf-8")); // return br; // } // // } // // Path: geo-locator/src/edu/cmu/geolocator/model/Country.java // public class Country extends CandidateAndFeature implements Comparable<CandidateAndFeature>{ // // // public Country(){ // super(); // } // public String getAbbr() { // return abbr; // } // public Country setAbbr(String abbr) { // this.abbr = abbr; // return this; // } // public String getLang() { // return lang; // } // public Country setLang(String lang) { // this.lang = lang; // return this; // } // public String getRace() { // return race; // } // public Country setRace(String race) { // this.race = race; // return this; // } // // String abbr,lang,race; // @Override // public int compareTo(CandidateAndFeature arg0) { // // TODO Auto-generated method stub // return arg0.getId().compareTo(this.getId()); // } // // } // // Path: geo-locator/src/edu/cmu/geolocator/resource/ResourceFactory.java // public class ResourceFactory { // // private static CollaborativeIndex collaborativeIndex = CollaborativeIndex.getInstance(); // // private static AdmCode2GazCandidateMap adminCode2GazCandidateMap = AdmCode2GazCandidateMap // .getInstance(); // // private static CCodeAdj2CTRYtype countryCode2CountryMap = CCodeAdj2CTRYtype // .getInstance(); // // private static FeatureCode2Map featurecode2map = FeatureCode2Map.getInstance(); // /** // * @return the collaborativeIndex // */ // public static CollaborativeIndex getClbIndex() { // return collaborativeIndex; // } // // /** // * return the GazEntryAndInfo type given the admin code. // * @return the adminCode2GazCandidateMap // */ // public static AdmCode2GazCandidateMap getAdminCode2GazCandidateMap() { // return adminCode2GazCandidateMap; // } // // /** // * return the Country type given the country code. // * @return the countryCode2CountryMap // * // */ // public static CCodeAdj2CTRYtype getCountryCode2CountryMap() { // return countryCode2CountryMap; // } // // public static FeatureCode2Map getFeatureCode2Map() { // // TODO Auto-generated method stub // return featurecode2map; // } // } // Path: geo-locator/src/edu/cmu/geolocator/resource/Map/CCodeAdj2CTRYtype.java import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.HashMap; import org.apache.lucene.document.Document; import edu.cmu.geolocator.io.GetReader; import edu.cmu.geolocator.model.Country; import edu.cmu.geolocator.resource.ResourceFactory; } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { br.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return this; } @Override public Country getValue(String code) { return theMap.get(code.toLowerCase()); } /** * check if it's a country abbreviation. Case insensitive. Example : US, CN, BR. or us, cn, br. * * @param phrase * @return */ public boolean isInMap(String phrase) { String countryId = null; phrase = phrase.toLowerCase(); // if (phrase.length() != 2) // return false;
if (ResourceFactory.getCountryCode2CountryMap().getValue(phrase.toLowerCase()) != null)
tylersuehr7/clean-architecture
app/src/main/java/com/tylersuehr/cleanarchitecture/ui/people/PeopleContract.java
// Path: app/src/main/java/com/tylersuehr/cleanarchitecture/data/models/Person.java // public class Person extends Entity { // private String firstName; // private String lastName; // private String image; // private int age; // // // public Person() {} // // @Override // public String getId() { // return (String)super.getId(); // } // // public String getFirstName() { // return firstName; // } // // public void setFirstName(String firstName) { // this.firstName = firstName; // } // // public String getLastName() { // return lastName; // } // // public void setLastName(String lastName) { // this.lastName = lastName; // } // // public int getAge() { // return age; // } // // public void setAge(int age) { // this.age = age; // } // // public String getImage() { // return image; // } // // public void setImage(String image) { // this.image = image; // } // } // // Path: app/src/main/java/com/tylersuehr/cleanarchitecture/ui/IBasePresenter.java // public interface IBasePresenter<IView extends IBaseView> { // /** // * Gets the presenter's current view. // * @return {@link IView} // */ // IView getView(); // // /** // * Attaches the given view to the presenter. // * @param view {@link IView} // */ // void attach(IView view); // // /** // * Detaches the presenter's current view. // */ // void detach(); // // /** // * Stops any active or pending use case executions. // */ // void stopTasks(); // } // // Path: app/src/main/java/com/tylersuehr/cleanarchitecture/ui/IBaseView.java // public interface IBaseView { // /** // * Shows a message to the user on the screen. // * @param msg Message to display // */ // void onShowMsg(String msg); // // /** // * Checks if the current device is online. // * @return True if device is online // */ // boolean isDeviceOnline(); // }
import com.tylersuehr.cleanarchitecture.data.models.Person; import com.tylersuehr.cleanarchitecture.ui.IBasePresenter; import com.tylersuehr.cleanarchitecture.ui.IBaseView; import java.util.List;
package com.tylersuehr.cleanarchitecture.ui.people; /** * Copyright © 2017 Tyler Suehr * * A contract to define the decouple presenter and view for conceptual people. * * @author Tyler Suehr * @version 1.0 */ interface PeopleContract { /** * Defines core methods for people presenter. */ interface IPeoplePresenter extends IBasePresenter<IPeopleView> { void loadPeople(); void createPerson(String first, String last, int age); void deleteAllPeople(); } /** * Defines core methods for people view. */
// Path: app/src/main/java/com/tylersuehr/cleanarchitecture/data/models/Person.java // public class Person extends Entity { // private String firstName; // private String lastName; // private String image; // private int age; // // // public Person() {} // // @Override // public String getId() { // return (String)super.getId(); // } // // public String getFirstName() { // return firstName; // } // // public void setFirstName(String firstName) { // this.firstName = firstName; // } // // public String getLastName() { // return lastName; // } // // public void setLastName(String lastName) { // this.lastName = lastName; // } // // public int getAge() { // return age; // } // // public void setAge(int age) { // this.age = age; // } // // public String getImage() { // return image; // } // // public void setImage(String image) { // this.image = image; // } // } // // Path: app/src/main/java/com/tylersuehr/cleanarchitecture/ui/IBasePresenter.java // public interface IBasePresenter<IView extends IBaseView> { // /** // * Gets the presenter's current view. // * @return {@link IView} // */ // IView getView(); // // /** // * Attaches the given view to the presenter. // * @param view {@link IView} // */ // void attach(IView view); // // /** // * Detaches the presenter's current view. // */ // void detach(); // // /** // * Stops any active or pending use case executions. // */ // void stopTasks(); // } // // Path: app/src/main/java/com/tylersuehr/cleanarchitecture/ui/IBaseView.java // public interface IBaseView { // /** // * Shows a message to the user on the screen. // * @param msg Message to display // */ // void onShowMsg(String msg); // // /** // * Checks if the current device is online. // * @return True if device is online // */ // boolean isDeviceOnline(); // } // Path: app/src/main/java/com/tylersuehr/cleanarchitecture/ui/people/PeopleContract.java import com.tylersuehr.cleanarchitecture.data.models.Person; import com.tylersuehr.cleanarchitecture.ui.IBasePresenter; import com.tylersuehr.cleanarchitecture.ui.IBaseView; import java.util.List; package com.tylersuehr.cleanarchitecture.ui.people; /** * Copyright © 2017 Tyler Suehr * * A contract to define the decouple presenter and view for conceptual people. * * @author Tyler Suehr * @version 1.0 */ interface PeopleContract { /** * Defines core methods for people presenter. */ interface IPeoplePresenter extends IBasePresenter<IPeopleView> { void loadPeople(); void createPerson(String first, String last, int age); void deleteAllPeople(); } /** * Defines core methods for people view. */
interface IPeopleView extends IBaseView {
tylersuehr7/clean-architecture
app/src/main/java/com/tylersuehr/cleanarchitecture/ui/people/PeopleContract.java
// Path: app/src/main/java/com/tylersuehr/cleanarchitecture/data/models/Person.java // public class Person extends Entity { // private String firstName; // private String lastName; // private String image; // private int age; // // // public Person() {} // // @Override // public String getId() { // return (String)super.getId(); // } // // public String getFirstName() { // return firstName; // } // // public void setFirstName(String firstName) { // this.firstName = firstName; // } // // public String getLastName() { // return lastName; // } // // public void setLastName(String lastName) { // this.lastName = lastName; // } // // public int getAge() { // return age; // } // // public void setAge(int age) { // this.age = age; // } // // public String getImage() { // return image; // } // // public void setImage(String image) { // this.image = image; // } // } // // Path: app/src/main/java/com/tylersuehr/cleanarchitecture/ui/IBasePresenter.java // public interface IBasePresenter<IView extends IBaseView> { // /** // * Gets the presenter's current view. // * @return {@link IView} // */ // IView getView(); // // /** // * Attaches the given view to the presenter. // * @param view {@link IView} // */ // void attach(IView view); // // /** // * Detaches the presenter's current view. // */ // void detach(); // // /** // * Stops any active or pending use case executions. // */ // void stopTasks(); // } // // Path: app/src/main/java/com/tylersuehr/cleanarchitecture/ui/IBaseView.java // public interface IBaseView { // /** // * Shows a message to the user on the screen. // * @param msg Message to display // */ // void onShowMsg(String msg); // // /** // * Checks if the current device is online. // * @return True if device is online // */ // boolean isDeviceOnline(); // }
import com.tylersuehr.cleanarchitecture.data.models.Person; import com.tylersuehr.cleanarchitecture.ui.IBasePresenter; import com.tylersuehr.cleanarchitecture.ui.IBaseView; import java.util.List;
package com.tylersuehr.cleanarchitecture.ui.people; /** * Copyright © 2017 Tyler Suehr * * A contract to define the decouple presenter and view for conceptual people. * * @author Tyler Suehr * @version 1.0 */ interface PeopleContract { /** * Defines core methods for people presenter. */ interface IPeoplePresenter extends IBasePresenter<IPeopleView> { void loadPeople(); void createPerson(String first, String last, int age); void deleteAllPeople(); } /** * Defines core methods for people view. */ interface IPeopleView extends IBaseView {
// Path: app/src/main/java/com/tylersuehr/cleanarchitecture/data/models/Person.java // public class Person extends Entity { // private String firstName; // private String lastName; // private String image; // private int age; // // // public Person() {} // // @Override // public String getId() { // return (String)super.getId(); // } // // public String getFirstName() { // return firstName; // } // // public void setFirstName(String firstName) { // this.firstName = firstName; // } // // public String getLastName() { // return lastName; // } // // public void setLastName(String lastName) { // this.lastName = lastName; // } // // public int getAge() { // return age; // } // // public void setAge(int age) { // this.age = age; // } // // public String getImage() { // return image; // } // // public void setImage(String image) { // this.image = image; // } // } // // Path: app/src/main/java/com/tylersuehr/cleanarchitecture/ui/IBasePresenter.java // public interface IBasePresenter<IView extends IBaseView> { // /** // * Gets the presenter's current view. // * @return {@link IView} // */ // IView getView(); // // /** // * Attaches the given view to the presenter. // * @param view {@link IView} // */ // void attach(IView view); // // /** // * Detaches the presenter's current view. // */ // void detach(); // // /** // * Stops any active or pending use case executions. // */ // void stopTasks(); // } // // Path: app/src/main/java/com/tylersuehr/cleanarchitecture/ui/IBaseView.java // public interface IBaseView { // /** // * Shows a message to the user on the screen. // * @param msg Message to display // */ // void onShowMsg(String msg); // // /** // * Checks if the current device is online. // * @return True if device is online // */ // boolean isDeviceOnline(); // } // Path: app/src/main/java/com/tylersuehr/cleanarchitecture/ui/people/PeopleContract.java import com.tylersuehr.cleanarchitecture.data.models.Person; import com.tylersuehr.cleanarchitecture.ui.IBasePresenter; import com.tylersuehr.cleanarchitecture.ui.IBaseView; import java.util.List; package com.tylersuehr.cleanarchitecture.ui.people; /** * Copyright © 2017 Tyler Suehr * * A contract to define the decouple presenter and view for conceptual people. * * @author Tyler Suehr * @version 1.0 */ interface PeopleContract { /** * Defines core methods for people presenter. */ interface IPeoplePresenter extends IBasePresenter<IPeopleView> { void loadPeople(); void createPerson(String first, String last, int age); void deleteAllPeople(); } /** * Defines core methods for people view. */ interface IPeopleView extends IBaseView {
void onPeopleReady(List<Person> people);
tylersuehr7/clean-architecture
app/src/main/java/com/tylersuehr/cleanarchitecture/data/repositories/people/PersonRepository.java
// Path: app/src/main/java/com/tylersuehr/cleanarchitecture/data/models/Person.java // public class Person extends Entity { // private String firstName; // private String lastName; // private String image; // private int age; // // // public Person() {} // // @Override // public String getId() { // return (String)super.getId(); // } // // public String getFirstName() { // return firstName; // } // // public void setFirstName(String firstName) { // this.firstName = firstName; // } // // public String getLastName() { // return lastName; // } // // public void setLastName(String lastName) { // this.lastName = lastName; // } // // public int getAge() { // return age; // } // // public void setAge(int age) { // this.age = age; // } // // public String getImage() { // return image; // } // // public void setImage(String image) { // this.image = image; // } // } // // Path: app/src/main/java/com/tylersuehr/cleanarchitecture/data/repositories/Callbacks.java // public interface Callbacks { // /** // * Defines an interface for handling an error callback. // */ // interface IError { // void onNotAvailable(Exception ex); // } // // /** // * Defines an interface for handling a single response callback. // */ // interface ISingle<T extends Entity> extends IError { // void onSingleLoaded(T value); // } // // /** // * Defines an interface for handling a list response callback. // */ // interface IList<T extends Entity> extends IError { // void onListLoaded(List<T> values); // } // }
import com.tylersuehr.cleanarchitecture.data.models.Person; import com.tylersuehr.cleanarchitecture.data.repositories.Callbacks; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map;
package com.tylersuehr.cleanarchitecture.data.repositories.people; /** * Copyright 2017 Tyler Suehr * * This manages all data sources for {@link IPersonRepository}. * Note: you can make as many repositories as needed for different data sources. * * @author Tyler Suehr * @version 1.0 */ public final class PersonRepository implements IPersonRepository { private static volatile PersonRepository instance; private final IPersonRepository local; private boolean invalidCache = false;
// Path: app/src/main/java/com/tylersuehr/cleanarchitecture/data/models/Person.java // public class Person extends Entity { // private String firstName; // private String lastName; // private String image; // private int age; // // // public Person() {} // // @Override // public String getId() { // return (String)super.getId(); // } // // public String getFirstName() { // return firstName; // } // // public void setFirstName(String firstName) { // this.firstName = firstName; // } // // public String getLastName() { // return lastName; // } // // public void setLastName(String lastName) { // this.lastName = lastName; // } // // public int getAge() { // return age; // } // // public void setAge(int age) { // this.age = age; // } // // public String getImage() { // return image; // } // // public void setImage(String image) { // this.image = image; // } // } // // Path: app/src/main/java/com/tylersuehr/cleanarchitecture/data/repositories/Callbacks.java // public interface Callbacks { // /** // * Defines an interface for handling an error callback. // */ // interface IError { // void onNotAvailable(Exception ex); // } // // /** // * Defines an interface for handling a single response callback. // */ // interface ISingle<T extends Entity> extends IError { // void onSingleLoaded(T value); // } // // /** // * Defines an interface for handling a list response callback. // */ // interface IList<T extends Entity> extends IError { // void onListLoaded(List<T> values); // } // } // Path: app/src/main/java/com/tylersuehr/cleanarchitecture/data/repositories/people/PersonRepository.java import com.tylersuehr.cleanarchitecture.data.models.Person; import com.tylersuehr.cleanarchitecture.data.repositories.Callbacks; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; package com.tylersuehr.cleanarchitecture.data.repositories.people; /** * Copyright 2017 Tyler Suehr * * This manages all data sources for {@link IPersonRepository}. * Note: you can make as many repositories as needed for different data sources. * * @author Tyler Suehr * @version 1.0 */ public final class PersonRepository implements IPersonRepository { private static volatile PersonRepository instance; private final IPersonRepository local; private boolean invalidCache = false;
private Map<String, Person> cache;
tylersuehr7/clean-architecture
app/src/main/java/com/tylersuehr/cleanarchitecture/data/repositories/people/PersonRepository.java
// Path: app/src/main/java/com/tylersuehr/cleanarchitecture/data/models/Person.java // public class Person extends Entity { // private String firstName; // private String lastName; // private String image; // private int age; // // // public Person() {} // // @Override // public String getId() { // return (String)super.getId(); // } // // public String getFirstName() { // return firstName; // } // // public void setFirstName(String firstName) { // this.firstName = firstName; // } // // public String getLastName() { // return lastName; // } // // public void setLastName(String lastName) { // this.lastName = lastName; // } // // public int getAge() { // return age; // } // // public void setAge(int age) { // this.age = age; // } // // public String getImage() { // return image; // } // // public void setImage(String image) { // this.image = image; // } // } // // Path: app/src/main/java/com/tylersuehr/cleanarchitecture/data/repositories/Callbacks.java // public interface Callbacks { // /** // * Defines an interface for handling an error callback. // */ // interface IError { // void onNotAvailable(Exception ex); // } // // /** // * Defines an interface for handling a single response callback. // */ // interface ISingle<T extends Entity> extends IError { // void onSingleLoaded(T value); // } // // /** // * Defines an interface for handling a list response callback. // */ // interface IList<T extends Entity> extends IError { // void onListLoaded(List<T> values); // } // }
import com.tylersuehr.cleanarchitecture.data.models.Person; import com.tylersuehr.cleanarchitecture.data.repositories.Callbacks; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map;
private PersonRepository(IPersonRepository local) { this.local = local; } public static PersonRepository getInstance(IPersonRepository local) { if (instance == null) { synchronized (PersonRepository.class) { if (instance == null) { instance = new PersonRepository(local); } } } return instance; } @Override public void createPerson(Person person) throws Exception { this.local.createPerson(person); addToCache(person); } @Override public void deletePerson(Person person) throws Exception { this.local.deletePerson(person); if (cache != null && person != null) { this.cache.remove(person.getId()); } } @Override
// Path: app/src/main/java/com/tylersuehr/cleanarchitecture/data/models/Person.java // public class Person extends Entity { // private String firstName; // private String lastName; // private String image; // private int age; // // // public Person() {} // // @Override // public String getId() { // return (String)super.getId(); // } // // public String getFirstName() { // return firstName; // } // // public void setFirstName(String firstName) { // this.firstName = firstName; // } // // public String getLastName() { // return lastName; // } // // public void setLastName(String lastName) { // this.lastName = lastName; // } // // public int getAge() { // return age; // } // // public void setAge(int age) { // this.age = age; // } // // public String getImage() { // return image; // } // // public void setImage(String image) { // this.image = image; // } // } // // Path: app/src/main/java/com/tylersuehr/cleanarchitecture/data/repositories/Callbacks.java // public interface Callbacks { // /** // * Defines an interface for handling an error callback. // */ // interface IError { // void onNotAvailable(Exception ex); // } // // /** // * Defines an interface for handling a single response callback. // */ // interface ISingle<T extends Entity> extends IError { // void onSingleLoaded(T value); // } // // /** // * Defines an interface for handling a list response callback. // */ // interface IList<T extends Entity> extends IError { // void onListLoaded(List<T> values); // } // } // Path: app/src/main/java/com/tylersuehr/cleanarchitecture/data/repositories/people/PersonRepository.java import com.tylersuehr.cleanarchitecture.data.models.Person; import com.tylersuehr.cleanarchitecture.data.repositories.Callbacks; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; private PersonRepository(IPersonRepository local) { this.local = local; } public static PersonRepository getInstance(IPersonRepository local) { if (instance == null) { synchronized (PersonRepository.class) { if (instance == null) { instance = new PersonRepository(local); } } } return instance; } @Override public void createPerson(Person person) throws Exception { this.local.createPerson(person); addToCache(person); } @Override public void deletePerson(Person person) throws Exception { this.local.deletePerson(person); if (cache != null && person != null) { this.cache.remove(person.getId()); } } @Override
public void findAllPeople(final Callbacks.IList<Person> callback) {
tylersuehr7/clean-architecture
app/src/main/java/com/tylersuehr/cleanarchitecture/data/repositories/SQLQuery.java
// Path: app/src/main/java/com/tylersuehr/cleanarchitecture/data/mappers/IEntityMapper.java // public interface IEntityMapper<T extends Entity> { // /** // * Maps {@link Cursor} data to an {@link Entity} object. // * @param c {@link Cursor} // * @return {@link Entity} object // */ // T map(Cursor c); // // /** // * Maps an {@link Entity} object to {@link ContentValues} to store in SQLite database. // * @param entity {@link Entity} object // * @return {@link ContentValues} // */ // ContentValues map(T entity); // } // // Path: app/src/main/java/com/tylersuehr/cleanarchitecture/data/models/Entity.java // public abstract class Entity { // private Object id; // // // @Override // public boolean equals(Object obj) { // return (this == obj) || (obj instanceof Entity && ((Entity)obj).id.equals(id)); // } // // @Override // public String toString() { // return "Entity {'" + id + "'}"; // } // // public Object getId() { // return id; // } // // public void setId(Object id) { // this.id = id; // } // }
import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import com.tylersuehr.cleanarchitecture.data.mappers.IEntityMapper; import com.tylersuehr.cleanarchitecture.data.models.Entity; import java.util.ArrayList; import java.util.List;
package com.tylersuehr.cleanarchitecture.data.repositories; /** * Copyright 2017 Tyler Suehr * * Utility to help with querying the local SQLite database. * * @author Tyler Suehr * @version 1.0 */ public final class SQLQuery { /** * Queries the SQLite database for a single object. * @param db {@link SQLiteDatabase} * @param mapper {@link IEntityMapper} * @param table Table name * @param where Where clause * @param callback {@link Callbacks.ISingle} */ public static <T extends Entity> void query( SQLiteDatabase db,
// Path: app/src/main/java/com/tylersuehr/cleanarchitecture/data/mappers/IEntityMapper.java // public interface IEntityMapper<T extends Entity> { // /** // * Maps {@link Cursor} data to an {@link Entity} object. // * @param c {@link Cursor} // * @return {@link Entity} object // */ // T map(Cursor c); // // /** // * Maps an {@link Entity} object to {@link ContentValues} to store in SQLite database. // * @param entity {@link Entity} object // * @return {@link ContentValues} // */ // ContentValues map(T entity); // } // // Path: app/src/main/java/com/tylersuehr/cleanarchitecture/data/models/Entity.java // public abstract class Entity { // private Object id; // // // @Override // public boolean equals(Object obj) { // return (this == obj) || (obj instanceof Entity && ((Entity)obj).id.equals(id)); // } // // @Override // public String toString() { // return "Entity {'" + id + "'}"; // } // // public Object getId() { // return id; // } // // public void setId(Object id) { // this.id = id; // } // } // Path: app/src/main/java/com/tylersuehr/cleanarchitecture/data/repositories/SQLQuery.java import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import com.tylersuehr.cleanarchitecture.data.mappers.IEntityMapper; import com.tylersuehr.cleanarchitecture.data.models.Entity; import java.util.ArrayList; import java.util.List; package com.tylersuehr.cleanarchitecture.data.repositories; /** * Copyright 2017 Tyler Suehr * * Utility to help with querying the local SQLite database. * * @author Tyler Suehr * @version 1.0 */ public final class SQLQuery { /** * Queries the SQLite database for a single object. * @param db {@link SQLiteDatabase} * @param mapper {@link IEntityMapper} * @param table Table name * @param where Where clause * @param callback {@link Callbacks.ISingle} */ public static <T extends Entity> void query( SQLiteDatabase db,
IEntityMapper<T> mapper,
tylersuehr7/clean-architecture
app/src/main/java/com/tylersuehr/cleanarchitecture/data/mappers/PersonMapper.java
// Path: app/src/main/java/com/tylersuehr/cleanarchitecture/data/models/Person.java // public class Person extends Entity { // private String firstName; // private String lastName; // private String image; // private int age; // // // public Person() {} // // @Override // public String getId() { // return (String)super.getId(); // } // // public String getFirstName() { // return firstName; // } // // public void setFirstName(String firstName) { // this.firstName = firstName; // } // // public String getLastName() { // return lastName; // } // // public void setLastName(String lastName) { // this.lastName = lastName; // } // // public int getAge() { // return age; // } // // public void setAge(int age) { // this.age = age; // } // // public String getImage() { // return image; // } // // public void setImage(String image) { // this.image = image; // } // } // // Path: app/src/main/java/com/tylersuehr/cleanarchitecture/data/repositories/DatabaseContract.java // public static abstract class People { // public static final String NAME = "people"; // public static final String COL_ID = "pId"; // public static final String COL_FIRST_NAME = "pFirst"; // public static final String COL_LAST_NAME = "pLast"; // public static final String COL_IMAGE = "pImage"; // public static final String COL_AGE = "pAge"; // }
import android.content.ContentValues; import android.database.Cursor; import com.tylersuehr.cleanarchitecture.data.models.Person; import static com.tylersuehr.cleanarchitecture.data.repositories.DatabaseContract.People;
package com.tylersuehr.cleanarchitecture.data.mappers; /** * Copyright 2017 Tyler Suehr * * Concrete implementation of {@link IEntityMapper} for {@link Person} model. * * @author Tyler Suehr * @version 1.0 */ public class PersonMapper implements IEntityMapper<Person> { @Override public Person map(Cursor c) { Person person = new Person();
// Path: app/src/main/java/com/tylersuehr/cleanarchitecture/data/models/Person.java // public class Person extends Entity { // private String firstName; // private String lastName; // private String image; // private int age; // // // public Person() {} // // @Override // public String getId() { // return (String)super.getId(); // } // // public String getFirstName() { // return firstName; // } // // public void setFirstName(String firstName) { // this.firstName = firstName; // } // // public String getLastName() { // return lastName; // } // // public void setLastName(String lastName) { // this.lastName = lastName; // } // // public int getAge() { // return age; // } // // public void setAge(int age) { // this.age = age; // } // // public String getImage() { // return image; // } // // public void setImage(String image) { // this.image = image; // } // } // // Path: app/src/main/java/com/tylersuehr/cleanarchitecture/data/repositories/DatabaseContract.java // public static abstract class People { // public static final String NAME = "people"; // public static final String COL_ID = "pId"; // public static final String COL_FIRST_NAME = "pFirst"; // public static final String COL_LAST_NAME = "pLast"; // public static final String COL_IMAGE = "pImage"; // public static final String COL_AGE = "pAge"; // } // Path: app/src/main/java/com/tylersuehr/cleanarchitecture/data/mappers/PersonMapper.java import android.content.ContentValues; import android.database.Cursor; import com.tylersuehr.cleanarchitecture.data.models.Person; import static com.tylersuehr.cleanarchitecture.data.repositories.DatabaseContract.People; package com.tylersuehr.cleanarchitecture.data.mappers; /** * Copyright 2017 Tyler Suehr * * Concrete implementation of {@link IEntityMapper} for {@link Person} model. * * @author Tyler Suehr * @version 1.0 */ public class PersonMapper implements IEntityMapper<Person> { @Override public Person map(Cursor c) { Person person = new Person();
person.setId(c.getString(c.getColumnIndex(People.COL_ID)));