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 |
|---|---|---|---|---|---|---|
wseemann/ServeStream | app/src/main/java/net/sourceforge/servestream/activity/UriEditorActivity.java | // Path: app/src/main/java/net/sourceforge/servestream/preference/UserPreferences.java
// public class UserPreferences implements
// SharedPreferences.OnSharedPreferenceChangeListener {
// private static UserPreferences instance;
// private final Context mContext;
//
// // Preferences
// private int mTheme;
//
// private UserPreferences(Context context) {
// mContext = context;
// loadPreferences();
// }
//
// /**
// * Sets up the UserPreferences class.
// *
// * @throws IllegalArgumentException
// * if context is null
// * */
// public static void createInstance(Context context) {
// if (context == null)
// throw new IllegalArgumentException("Context must not be null");
// instance = new UserPreferences(context);
//
// PreferenceManager.getDefaultSharedPreferences(context)
// .registerOnSharedPreferenceChangeListener(instance);
//
// }
//
// private void loadPreferences() {
// SharedPreferences sp = PreferenceManager
// .getDefaultSharedPreferences(mContext);
// //mTheme = readThemeValue(sp.getString(PreferenceConstants.THEME, "0"));
// mTheme = R.style.Theme_ServeStream_DarkActionBar;;
// }
//
// private int readThemeValue(String valueFromPrefs) {
// switch (Integer.parseInt(valueFromPrefs)) {
// case 0:
// return R.style.Theme_ServeStream_DarkActionBar;
// case 1:
// return R.style.Theme_ServeStream_Dark;
// default:
// return R.style.Theme_ServeStream_DarkActionBar;
// }
// }
//
// private static void instanceAvailable() {
// if (instance == null) {
// throw new IllegalStateException(
// "UserPreferences was used before being set up");
// }
// }
//
// public static int getTheme() {
// instanceAvailable();
// return instance.mTheme;
// }
//
// @Override
// public void onSharedPreferenceChanged(SharedPreferences sp, String key) {
// if (key.equals(PreferenceConstants.THEME)) {
// mTheme = readThemeValue(sp.getString(PreferenceConstants.THEME, ""));
// }
// }
// }
| import net.sourceforge.servestream.fragment.UriEditorFragment;
import net.sourceforge.servestream.preference.UserPreferences;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBar;
import android.view.MenuItem; | /*
* ServeStream: A HTTP stream browser/player for Android
* Copyright 2014 William Seemann
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.sourceforge.servestream.activity;
public class UriEditorActivity extends ActionBarActivity {
@Override
public void onCreate(Bundle savedInstanceState) { | // Path: app/src/main/java/net/sourceforge/servestream/preference/UserPreferences.java
// public class UserPreferences implements
// SharedPreferences.OnSharedPreferenceChangeListener {
// private static UserPreferences instance;
// private final Context mContext;
//
// // Preferences
// private int mTheme;
//
// private UserPreferences(Context context) {
// mContext = context;
// loadPreferences();
// }
//
// /**
// * Sets up the UserPreferences class.
// *
// * @throws IllegalArgumentException
// * if context is null
// * */
// public static void createInstance(Context context) {
// if (context == null)
// throw new IllegalArgumentException("Context must not be null");
// instance = new UserPreferences(context);
//
// PreferenceManager.getDefaultSharedPreferences(context)
// .registerOnSharedPreferenceChangeListener(instance);
//
// }
//
// private void loadPreferences() {
// SharedPreferences sp = PreferenceManager
// .getDefaultSharedPreferences(mContext);
// //mTheme = readThemeValue(sp.getString(PreferenceConstants.THEME, "0"));
// mTheme = R.style.Theme_ServeStream_DarkActionBar;;
// }
//
// private int readThemeValue(String valueFromPrefs) {
// switch (Integer.parseInt(valueFromPrefs)) {
// case 0:
// return R.style.Theme_ServeStream_DarkActionBar;
// case 1:
// return R.style.Theme_ServeStream_Dark;
// default:
// return R.style.Theme_ServeStream_DarkActionBar;
// }
// }
//
// private static void instanceAvailable() {
// if (instance == null) {
// throw new IllegalStateException(
// "UserPreferences was used before being set up");
// }
// }
//
// public static int getTheme() {
// instanceAvailable();
// return instance.mTheme;
// }
//
// @Override
// public void onSharedPreferenceChanged(SharedPreferences sp, String key) {
// if (key.equals(PreferenceConstants.THEME)) {
// mTheme = readThemeValue(sp.getString(PreferenceConstants.THEME, ""));
// }
// }
// }
// Path: app/src/main/java/net/sourceforge/servestream/activity/UriEditorActivity.java
import net.sourceforge.servestream.fragment.UriEditorFragment;
import net.sourceforge.servestream.preference.UserPreferences;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBar;
import android.view.MenuItem;
/*
* ServeStream: A HTTP stream browser/player for Android
* Copyright 2014 William Seemann
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.sourceforge.servestream.activity;
public class UriEditorActivity extends ActionBarActivity {
@Override
public void onCreate(Bundle savedInstanceState) { | setTheme(UserPreferences.getTheme()); |
wseemann/ServeStream | app/src/main/java/net/sourceforge/servestream/fragment/AlarmClockFragment.java | // Path: app/src/main/java/net/sourceforge/servestream/activity/SetAlarmActivity.java
// public class SetAlarmActivity extends ActionBarActivity {
//
// @Override
// public void onCreate(Bundle savedInstanceState) {
// setTheme(UserPreferences.getTheme());
// super.onCreate(savedInstanceState);
//
// ActionBar actionBar = getSupportActionBar();
// actionBar.setDisplayHomeAsUpEnabled(true);
//
// if (savedInstanceState == null) {
// FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
// transaction.add(android.R.id.content, new SetAlarmFragment());
// transaction.commit();
// }
// }
//
// @Override
// public boolean onOptionsItemSelected(MenuItem item) {
// switch (item.getItemId()) {
// case android.R.id.home:
// finish();
// return true;
// default:
// break;
// }
// return super.onOptionsItemSelected(item);
// }
//
// @Override
// public void onBackPressed() {
// SetAlarmFragment fragment = (SetAlarmFragment) getSupportFragmentManager().findFragmentById(android.R.id.content);
// fragment.onBackPressed();
// }
// }
| import android.app.AlertDialog;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.app.LoaderManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CheckBox;
import android.widget.CursorAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Calendar;
import net.sourceforge.servestream.R;
import net.sourceforge.servestream.activity.SetAlarmActivity;
import net.sourceforge.servestream.alarm.Alarm;
import net.sourceforge.servestream.alarm.Alarms;
import net.sourceforge.servestream.alarm.DigitalClock;
import net.sourceforge.servestream.alarm.ToastMaster; | }
switch (item.getItemId()) {
case R.id.delete_alarm:
// Confirm that the alarm will be deleted.
new AlertDialog.Builder(getActivity())
.setTitle(getString(R.string.delete_alarm))
.setMessage(getString(R.string.alarm_delete_confirmation_msg))
.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface d,
int w) {
Alarms.deleteAlarm(getActivity(), id);
}
})
.setNegativeButton(android.R.string.cancel, null)
.show();
return true;
case R.id.enable_alarm:
final Cursor c = (Cursor) mAlarmsList.getAdapter()
.getItem(info.position);
final Alarm alarm = new Alarm(c);
Alarms.enableAlarm(getActivity(), alarm.id, !alarm.enabled);
if (!alarm.enabled) {
popAlarmSetToast(getActivity(), alarm.hour, alarm.minutes,
alarm.daysOfWeek);
}
return true;
case R.id.edit_alarm: | // Path: app/src/main/java/net/sourceforge/servestream/activity/SetAlarmActivity.java
// public class SetAlarmActivity extends ActionBarActivity {
//
// @Override
// public void onCreate(Bundle savedInstanceState) {
// setTheme(UserPreferences.getTheme());
// super.onCreate(savedInstanceState);
//
// ActionBar actionBar = getSupportActionBar();
// actionBar.setDisplayHomeAsUpEnabled(true);
//
// if (savedInstanceState == null) {
// FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
// transaction.add(android.R.id.content, new SetAlarmFragment());
// transaction.commit();
// }
// }
//
// @Override
// public boolean onOptionsItemSelected(MenuItem item) {
// switch (item.getItemId()) {
// case android.R.id.home:
// finish();
// return true;
// default:
// break;
// }
// return super.onOptionsItemSelected(item);
// }
//
// @Override
// public void onBackPressed() {
// SetAlarmFragment fragment = (SetAlarmFragment) getSupportFragmentManager().findFragmentById(android.R.id.content);
// fragment.onBackPressed();
// }
// }
// Path: app/src/main/java/net/sourceforge/servestream/fragment/AlarmClockFragment.java
import android.app.AlertDialog;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.app.LoaderManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CheckBox;
import android.widget.CursorAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Calendar;
import net.sourceforge.servestream.R;
import net.sourceforge.servestream.activity.SetAlarmActivity;
import net.sourceforge.servestream.alarm.Alarm;
import net.sourceforge.servestream.alarm.Alarms;
import net.sourceforge.servestream.alarm.DigitalClock;
import net.sourceforge.servestream.alarm.ToastMaster;
}
switch (item.getItemId()) {
case R.id.delete_alarm:
// Confirm that the alarm will be deleted.
new AlertDialog.Builder(getActivity())
.setTitle(getString(R.string.delete_alarm))
.setMessage(getString(R.string.alarm_delete_confirmation_msg))
.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface d,
int w) {
Alarms.deleteAlarm(getActivity(), id);
}
})
.setNegativeButton(android.R.string.cancel, null)
.show();
return true;
case R.id.enable_alarm:
final Cursor c = (Cursor) mAlarmsList.getAdapter()
.getItem(info.position);
final Alarm alarm = new Alarm(c);
Alarms.enableAlarm(getActivity(), alarm.id, !alarm.enabled);
if (!alarm.enabled) {
popAlarmSetToast(getActivity(), alarm.hour, alarm.minutes,
alarm.daysOfWeek);
}
return true;
case R.id.edit_alarm: | Intent intent = new Intent(getActivity(), SetAlarmActivity.class); |
wseemann/ServeStream | app/src/main/java/net/sourceforge/servestream/activity/AboutActivity.java | // Path: app/src/main/java/net/sourceforge/servestream/preference/UserPreferences.java
// public class UserPreferences implements
// SharedPreferences.OnSharedPreferenceChangeListener {
// private static UserPreferences instance;
// private final Context mContext;
//
// // Preferences
// private int mTheme;
//
// private UserPreferences(Context context) {
// mContext = context;
// loadPreferences();
// }
//
// /**
// * Sets up the UserPreferences class.
// *
// * @throws IllegalArgumentException
// * if context is null
// * */
// public static void createInstance(Context context) {
// if (context == null)
// throw new IllegalArgumentException("Context must not be null");
// instance = new UserPreferences(context);
//
// PreferenceManager.getDefaultSharedPreferences(context)
// .registerOnSharedPreferenceChangeListener(instance);
//
// }
//
// private void loadPreferences() {
// SharedPreferences sp = PreferenceManager
// .getDefaultSharedPreferences(mContext);
// //mTheme = readThemeValue(sp.getString(PreferenceConstants.THEME, "0"));
// mTheme = R.style.Theme_ServeStream_DarkActionBar;;
// }
//
// private int readThemeValue(String valueFromPrefs) {
// switch (Integer.parseInt(valueFromPrefs)) {
// case 0:
// return R.style.Theme_ServeStream_DarkActionBar;
// case 1:
// return R.style.Theme_ServeStream_Dark;
// default:
// return R.style.Theme_ServeStream_DarkActionBar;
// }
// }
//
// private static void instanceAvailable() {
// if (instance == null) {
// throw new IllegalStateException(
// "UserPreferences was used before being set up");
// }
// }
//
// public static int getTheme() {
// instanceAvailable();
// return instance.mTheme;
// }
//
// @Override
// public void onSharedPreferenceChanged(SharedPreferences sp, String key) {
// if (key.equals(PreferenceConstants.THEME)) {
// mTheme = readThemeValue(sp.getString(PreferenceConstants.THEME, ""));
// }
// }
// }
| import net.sourceforge.servestream.R;
import net.sourceforge.servestream.preference.UserPreferences;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.view.MenuItem;
import android.webkit.WebView;
import android.webkit.WebViewClient; | /*
* ServeStream: A HTTP stream browser/player for Android
* Copyright 2013 William Seemann
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.sourceforge.servestream.activity;
public class AboutActivity extends ActionBarActivity {
@Override
public void onCreate(Bundle savedInstanceState) { | // Path: app/src/main/java/net/sourceforge/servestream/preference/UserPreferences.java
// public class UserPreferences implements
// SharedPreferences.OnSharedPreferenceChangeListener {
// private static UserPreferences instance;
// private final Context mContext;
//
// // Preferences
// private int mTheme;
//
// private UserPreferences(Context context) {
// mContext = context;
// loadPreferences();
// }
//
// /**
// * Sets up the UserPreferences class.
// *
// * @throws IllegalArgumentException
// * if context is null
// * */
// public static void createInstance(Context context) {
// if (context == null)
// throw new IllegalArgumentException("Context must not be null");
// instance = new UserPreferences(context);
//
// PreferenceManager.getDefaultSharedPreferences(context)
// .registerOnSharedPreferenceChangeListener(instance);
//
// }
//
// private void loadPreferences() {
// SharedPreferences sp = PreferenceManager
// .getDefaultSharedPreferences(mContext);
// //mTheme = readThemeValue(sp.getString(PreferenceConstants.THEME, "0"));
// mTheme = R.style.Theme_ServeStream_DarkActionBar;;
// }
//
// private int readThemeValue(String valueFromPrefs) {
// switch (Integer.parseInt(valueFromPrefs)) {
// case 0:
// return R.style.Theme_ServeStream_DarkActionBar;
// case 1:
// return R.style.Theme_ServeStream_Dark;
// default:
// return R.style.Theme_ServeStream_DarkActionBar;
// }
// }
//
// private static void instanceAvailable() {
// if (instance == null) {
// throw new IllegalStateException(
// "UserPreferences was used before being set up");
// }
// }
//
// public static int getTheme() {
// instanceAvailable();
// return instance.mTheme;
// }
//
// @Override
// public void onSharedPreferenceChanged(SharedPreferences sp, String key) {
// if (key.equals(PreferenceConstants.THEME)) {
// mTheme = readThemeValue(sp.getString(PreferenceConstants.THEME, ""));
// }
// }
// }
// Path: app/src/main/java/net/sourceforge/servestream/activity/AboutActivity.java
import net.sourceforge.servestream.R;
import net.sourceforge.servestream.preference.UserPreferences;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.view.MenuItem;
import android.webkit.WebView;
import android.webkit.WebViewClient;
/*
* ServeStream: A HTTP stream browser/player for Android
* Copyright 2013 William Seemann
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.sourceforge.servestream.activity;
public class AboutActivity extends ActionBarActivity {
@Override
public void onCreate(Bundle savedInstanceState) { | setTheme(UserPreferences.getTheme()); |
wseemann/ServeStream | app/src/main/java/net/sourceforge/servestream/activity/SearchableActivity.java | // Path: app/src/main/java/net/sourceforge/servestream/preference/UserPreferences.java
// public class UserPreferences implements
// SharedPreferences.OnSharedPreferenceChangeListener {
// private static UserPreferences instance;
// private final Context mContext;
//
// // Preferences
// private int mTheme;
//
// private UserPreferences(Context context) {
// mContext = context;
// loadPreferences();
// }
//
// /**
// * Sets up the UserPreferences class.
// *
// * @throws IllegalArgumentException
// * if context is null
// * */
// public static void createInstance(Context context) {
// if (context == null)
// throw new IllegalArgumentException("Context must not be null");
// instance = new UserPreferences(context);
//
// PreferenceManager.getDefaultSharedPreferences(context)
// .registerOnSharedPreferenceChangeListener(instance);
//
// }
//
// private void loadPreferences() {
// SharedPreferences sp = PreferenceManager
// .getDefaultSharedPreferences(mContext);
// //mTheme = readThemeValue(sp.getString(PreferenceConstants.THEME, "0"));
// mTheme = R.style.Theme_ServeStream_DarkActionBar;;
// }
//
// private int readThemeValue(String valueFromPrefs) {
// switch (Integer.parseInt(valueFromPrefs)) {
// case 0:
// return R.style.Theme_ServeStream_DarkActionBar;
// case 1:
// return R.style.Theme_ServeStream_Dark;
// default:
// return R.style.Theme_ServeStream_DarkActionBar;
// }
// }
//
// private static void instanceAvailable() {
// if (instance == null) {
// throw new IllegalStateException(
// "UserPreferences was used before being set up");
// }
// }
//
// public static int getTheme() {
// instanceAvailable();
// return instance.mTheme;
// }
//
// @Override
// public void onSharedPreferenceChanged(SharedPreferences sp, String key) {
// if (key.equals(PreferenceConstants.THEME)) {
// mTheme = readThemeValue(sp.getString(PreferenceConstants.THEME, ""));
// }
// }
// }
| import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import net.sourceforge.servestream.R;
import net.sourceforge.servestream.adapter.SearchAdapter;
import net.sourceforge.servestream.bean.UriBean;
import net.sourceforge.servestream.preference.UserPreferences;
import android.app.SearchManager;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener; | package net.sourceforge.servestream.activity;
public class SearchableActivity extends ActionBarActivity {
private SearchAdapter mAdapter;
@Override
public void onCreate(Bundle savedInstanceState) { | // Path: app/src/main/java/net/sourceforge/servestream/preference/UserPreferences.java
// public class UserPreferences implements
// SharedPreferences.OnSharedPreferenceChangeListener {
// private static UserPreferences instance;
// private final Context mContext;
//
// // Preferences
// private int mTheme;
//
// private UserPreferences(Context context) {
// mContext = context;
// loadPreferences();
// }
//
// /**
// * Sets up the UserPreferences class.
// *
// * @throws IllegalArgumentException
// * if context is null
// * */
// public static void createInstance(Context context) {
// if (context == null)
// throw new IllegalArgumentException("Context must not be null");
// instance = new UserPreferences(context);
//
// PreferenceManager.getDefaultSharedPreferences(context)
// .registerOnSharedPreferenceChangeListener(instance);
//
// }
//
// private void loadPreferences() {
// SharedPreferences sp = PreferenceManager
// .getDefaultSharedPreferences(mContext);
// //mTheme = readThemeValue(sp.getString(PreferenceConstants.THEME, "0"));
// mTheme = R.style.Theme_ServeStream_DarkActionBar;;
// }
//
// private int readThemeValue(String valueFromPrefs) {
// switch (Integer.parseInt(valueFromPrefs)) {
// case 0:
// return R.style.Theme_ServeStream_DarkActionBar;
// case 1:
// return R.style.Theme_ServeStream_Dark;
// default:
// return R.style.Theme_ServeStream_DarkActionBar;
// }
// }
//
// private static void instanceAvailable() {
// if (instance == null) {
// throw new IllegalStateException(
// "UserPreferences was used before being set up");
// }
// }
//
// public static int getTheme() {
// instanceAvailable();
// return instance.mTheme;
// }
//
// @Override
// public void onSharedPreferenceChanged(SharedPreferences sp, String key) {
// if (key.equals(PreferenceConstants.THEME)) {
// mTheme = readThemeValue(sp.getString(PreferenceConstants.THEME, ""));
// }
// }
// }
// Path: app/src/main/java/net/sourceforge/servestream/activity/SearchableActivity.java
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import net.sourceforge.servestream.R;
import net.sourceforge.servestream.adapter.SearchAdapter;
import net.sourceforge.servestream.bean.UriBean;
import net.sourceforge.servestream.preference.UserPreferences;
import android.app.SearchManager;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
package net.sourceforge.servestream.activity;
public class SearchableActivity extends ActionBarActivity {
private SearchAdapter mAdapter;
@Override
public void onCreate(Bundle savedInstanceState) { | setTheme(UserPreferences.getTheme()); |
wseemann/ServeStream | app/src/main/java/net/sourceforge/servestream/activity/ShortcutActivity.java | // Path: app/src/main/java/net/sourceforge/servestream/preference/UserPreferences.java
// public class UserPreferences implements
// SharedPreferences.OnSharedPreferenceChangeListener {
// private static UserPreferences instance;
// private final Context mContext;
//
// // Preferences
// private int mTheme;
//
// private UserPreferences(Context context) {
// mContext = context;
// loadPreferences();
// }
//
// /**
// * Sets up the UserPreferences class.
// *
// * @throws IllegalArgumentException
// * if context is null
// * */
// public static void createInstance(Context context) {
// if (context == null)
// throw new IllegalArgumentException("Context must not be null");
// instance = new UserPreferences(context);
//
// PreferenceManager.getDefaultSharedPreferences(context)
// .registerOnSharedPreferenceChangeListener(instance);
//
// }
//
// private void loadPreferences() {
// SharedPreferences sp = PreferenceManager
// .getDefaultSharedPreferences(mContext);
// //mTheme = readThemeValue(sp.getString(PreferenceConstants.THEME, "0"));
// mTheme = R.style.Theme_ServeStream_DarkActionBar;;
// }
//
// private int readThemeValue(String valueFromPrefs) {
// switch (Integer.parseInt(valueFromPrefs)) {
// case 0:
// return R.style.Theme_ServeStream_DarkActionBar;
// case 1:
// return R.style.Theme_ServeStream_Dark;
// default:
// return R.style.Theme_ServeStream_DarkActionBar;
// }
// }
//
// private static void instanceAvailable() {
// if (instance == null) {
// throw new IllegalStateException(
// "UserPreferences was used before being set up");
// }
// }
//
// public static int getTheme() {
// instanceAvailable();
// return instance.mTheme;
// }
//
// @Override
// public void onSharedPreferenceChanged(SharedPreferences sp, String key) {
// if (key.equals(PreferenceConstants.THEME)) {
// mTheme = readThemeValue(sp.getString(PreferenceConstants.THEME, ""));
// }
// }
// }
| import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
import java.util.ArrayList;
import java.util.List;
import net.sourceforge.servestream.R;
import net.sourceforge.servestream.bean.UriBean;
import net.sourceforge.servestream.database.StreamDatabase;
import net.sourceforge.servestream.preference.UserPreferences;
import android.content.Intent;
import android.content.Intent.ShortcutIconResource;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter; | /*
* ServeStream: A HTTP stream browser/player for Android
* Copyright 2014 William Seemann
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.sourceforge.servestream.activity;
public class ShortcutActivity extends ActionBarActivity {
@Override
public void onCreate(Bundle savedInstanceState) { | // Path: app/src/main/java/net/sourceforge/servestream/preference/UserPreferences.java
// public class UserPreferences implements
// SharedPreferences.OnSharedPreferenceChangeListener {
// private static UserPreferences instance;
// private final Context mContext;
//
// // Preferences
// private int mTheme;
//
// private UserPreferences(Context context) {
// mContext = context;
// loadPreferences();
// }
//
// /**
// * Sets up the UserPreferences class.
// *
// * @throws IllegalArgumentException
// * if context is null
// * */
// public static void createInstance(Context context) {
// if (context == null)
// throw new IllegalArgumentException("Context must not be null");
// instance = new UserPreferences(context);
//
// PreferenceManager.getDefaultSharedPreferences(context)
// .registerOnSharedPreferenceChangeListener(instance);
//
// }
//
// private void loadPreferences() {
// SharedPreferences sp = PreferenceManager
// .getDefaultSharedPreferences(mContext);
// //mTheme = readThemeValue(sp.getString(PreferenceConstants.THEME, "0"));
// mTheme = R.style.Theme_ServeStream_DarkActionBar;;
// }
//
// private int readThemeValue(String valueFromPrefs) {
// switch (Integer.parseInt(valueFromPrefs)) {
// case 0:
// return R.style.Theme_ServeStream_DarkActionBar;
// case 1:
// return R.style.Theme_ServeStream_Dark;
// default:
// return R.style.Theme_ServeStream_DarkActionBar;
// }
// }
//
// private static void instanceAvailable() {
// if (instance == null) {
// throw new IllegalStateException(
// "UserPreferences was used before being set up");
// }
// }
//
// public static int getTheme() {
// instanceAvailable();
// return instance.mTheme;
// }
//
// @Override
// public void onSharedPreferenceChanged(SharedPreferences sp, String key) {
// if (key.equals(PreferenceConstants.THEME)) {
// mTheme = readThemeValue(sp.getString(PreferenceConstants.THEME, ""));
// }
// }
// }
// Path: app/src/main/java/net/sourceforge/servestream/activity/ShortcutActivity.java
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
import java.util.ArrayList;
import java.util.List;
import net.sourceforge.servestream.R;
import net.sourceforge.servestream.bean.UriBean;
import net.sourceforge.servestream.database.StreamDatabase;
import net.sourceforge.servestream.preference.UserPreferences;
import android.content.Intent;
import android.content.Intent.ShortcutIconResource;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
/*
* ServeStream: A HTTP stream browser/player for Android
* Copyright 2014 William Seemann
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.sourceforge.servestream.activity;
public class ShortcutActivity extends ActionBarActivity {
@Override
public void onCreate(Bundle savedInstanceState) { | setTheme(UserPreferences.getTheme()); |
virsox/cepsim | cepsim-integration/src/main/java/ca/uwo/eng/sel/cepsim/network/FixedDelayNetworkInterface.java | // Path: cepsim-integration/src/main/java/ca/uwo/eng/sel/cepsim/integr/CepSimBroker.java
// public class CepSimBroker extends DatacenterBroker {
//
// private Map<Vertex, Vm> verticesToVm = new HashMap<>();
//
// /** Length of the simulation (in ms)*/
// private double simulationLength;
//
// /** Simulation interval in milliseconds. */
// private double simulationInterval;
//
// public CepSimBroker(String name, double simulationLength, double simulationInterval) throws Exception {
// super(name);
//
// this.simulationLength = simulationLength;
// this.simulationInterval = simulationInterval;
// }
//
//
//
// @Override
// public void processEvent(SimEvent ev) {
//
// switch (ev.getTag()) {
// case CepSimTags.CEP_EVENT_SENT:
// System.out.println(ev.getData());
//
// default:
// super.processEvent(ev);
// break;
// }
//
// }
//
// public Vm getVmAllocation(Vertex v) {
// return verticesToVm.get(v);
// }
//
//
// public Integer getDatacenterId(Vm vm) {
// return getVmsToDatacentersMap().get(vm.getId());
// }
//
// @Override
// protected void submitCloudlets() {
// int vmIndex = 0;
// List<Cloudlet> successfullySubmitted = new ArrayList<Cloudlet>();
// for (Cloudlet cloudlet : getCloudletList()) {
// Vm vm;
// // if user didn't bind this cloudlet and it has not been executed yet
// if (cloudlet.getVmId() == -1) {
// vm = getVmsCreatedList().get(vmIndex);
// } else { // submit to the specific vm
// vm = VmList.getById(getVmsCreatedList(), cloudlet.getVmId());
// if (vm == null) { // vm was not created
// if(!Log.isDisabled()) {
// Log.print(CloudSim.clock() + ": " + getName() + ": Postponing execution of cloudlet " +
// cloudlet.getCloudletId() + ": bount VM not available");
// }
// continue;
// }
// }
//
// if (!Log.isDisabled()) {
// Log.print(CloudSim.clock() + ": " + getName() + ": Sending cloudlet " +
// cloudlet.getCloudletId() + " to VM #" + vm.getId());
// }
//
// cloudlet.setVmId(vm.getId());
// submitCloudlet(vm, cloudlet);
//
// // --------------------------------------------
// // [WAH] - Added - build a map from Vertices to Vms
// if (cloudlet instanceof CepQueryCloudlet) {
// CepQueryCloudlet cepCloudlet = (CepQueryCloudlet) cloudlet;
// for (Vertex v : cepCloudlet.getVertices()) {
// verticesToVm.put(v, vm);
// }
// }
// // --------------------------------------------
//
// cloudletsSubmitted++;
//
//
// vmIndex = (vmIndex + 1) % getVmsCreatedList().size();
// getCloudletSubmittedList().add(cloudlet);
// successfullySubmitted.add(cloudlet);
// }
//
// // remove submitted cloudlets from waiting list
// getCloudletList().removeAll(successfullySubmitted);
// }
//
// public void submitCloudlet(Vm vm, Cloudlet cloudlet) {
// sendNow(getVmsToDatacentersMap().get(vm.getId()), CloudSimTags.CLOUDLET_SUBMIT, cloudlet);
// }
//
// @Override
// protected void processOtherEvent(final SimEvent ev) {
// switch (ev.getTag()) {
// default:
// super.processOtherEvent(ev);
// }
// }
//
//
// }
//
// Path: cepsim-integration/src/main/java/ca/uwo/eng/sel/cepsim/integr/CepSimTags.java
// public class CepSimTags {
//
// public static final int BASE_VALUE = 99900;
//
// public static final int CEP_EVENT_SENT = BASE_VALUE + 10;
//
//
// }
| import ca.uwo.eng.sel.cepsim.integr.CepSimBroker;
import ca.uwo.eng.sel.cepsim.integr.CepSimTags;
import ca.uwo.eng.sel.cepsim.event.EventSet;
import ca.uwo.eng.sel.cepsim.query.InputVertex;
import ca.uwo.eng.sel.cepsim.query.OutputVertex;
import org.cloudbus.cloudsim.Vm; | package ca.uwo.eng.sel.cepsim.network;
/**
* Created by virso on 2014-11-10.
*/
public class FixedDelayNetworkInterface implements NetworkInterface {
private CepSimBroker broker;
private double delay; // in seconds
public FixedDelayNetworkInterface(CepSimBroker broker, double delay) {
this.broker = broker;
this.delay = delay;
}
@Override
public void sendMessage(double timestamp, OutputVertex orig, InputVertex dest, EventSet eventSet) {
Vm destVm = broker.getVmAllocation(dest);
Integer datacenterId = broker.getDatacenterId(destVm);
double start = timestamp / 1000.0; // transform to seconds
// destination, delay, tag, content | // Path: cepsim-integration/src/main/java/ca/uwo/eng/sel/cepsim/integr/CepSimBroker.java
// public class CepSimBroker extends DatacenterBroker {
//
// private Map<Vertex, Vm> verticesToVm = new HashMap<>();
//
// /** Length of the simulation (in ms)*/
// private double simulationLength;
//
// /** Simulation interval in milliseconds. */
// private double simulationInterval;
//
// public CepSimBroker(String name, double simulationLength, double simulationInterval) throws Exception {
// super(name);
//
// this.simulationLength = simulationLength;
// this.simulationInterval = simulationInterval;
// }
//
//
//
// @Override
// public void processEvent(SimEvent ev) {
//
// switch (ev.getTag()) {
// case CepSimTags.CEP_EVENT_SENT:
// System.out.println(ev.getData());
//
// default:
// super.processEvent(ev);
// break;
// }
//
// }
//
// public Vm getVmAllocation(Vertex v) {
// return verticesToVm.get(v);
// }
//
//
// public Integer getDatacenterId(Vm vm) {
// return getVmsToDatacentersMap().get(vm.getId());
// }
//
// @Override
// protected void submitCloudlets() {
// int vmIndex = 0;
// List<Cloudlet> successfullySubmitted = new ArrayList<Cloudlet>();
// for (Cloudlet cloudlet : getCloudletList()) {
// Vm vm;
// // if user didn't bind this cloudlet and it has not been executed yet
// if (cloudlet.getVmId() == -1) {
// vm = getVmsCreatedList().get(vmIndex);
// } else { // submit to the specific vm
// vm = VmList.getById(getVmsCreatedList(), cloudlet.getVmId());
// if (vm == null) { // vm was not created
// if(!Log.isDisabled()) {
// Log.print(CloudSim.clock() + ": " + getName() + ": Postponing execution of cloudlet " +
// cloudlet.getCloudletId() + ": bount VM not available");
// }
// continue;
// }
// }
//
// if (!Log.isDisabled()) {
// Log.print(CloudSim.clock() + ": " + getName() + ": Sending cloudlet " +
// cloudlet.getCloudletId() + " to VM #" + vm.getId());
// }
//
// cloudlet.setVmId(vm.getId());
// submitCloudlet(vm, cloudlet);
//
// // --------------------------------------------
// // [WAH] - Added - build a map from Vertices to Vms
// if (cloudlet instanceof CepQueryCloudlet) {
// CepQueryCloudlet cepCloudlet = (CepQueryCloudlet) cloudlet;
// for (Vertex v : cepCloudlet.getVertices()) {
// verticesToVm.put(v, vm);
// }
// }
// // --------------------------------------------
//
// cloudletsSubmitted++;
//
//
// vmIndex = (vmIndex + 1) % getVmsCreatedList().size();
// getCloudletSubmittedList().add(cloudlet);
// successfullySubmitted.add(cloudlet);
// }
//
// // remove submitted cloudlets from waiting list
// getCloudletList().removeAll(successfullySubmitted);
// }
//
// public void submitCloudlet(Vm vm, Cloudlet cloudlet) {
// sendNow(getVmsToDatacentersMap().get(vm.getId()), CloudSimTags.CLOUDLET_SUBMIT, cloudlet);
// }
//
// @Override
// protected void processOtherEvent(final SimEvent ev) {
// switch (ev.getTag()) {
// default:
// super.processOtherEvent(ev);
// }
// }
//
//
// }
//
// Path: cepsim-integration/src/main/java/ca/uwo/eng/sel/cepsim/integr/CepSimTags.java
// public class CepSimTags {
//
// public static final int BASE_VALUE = 99900;
//
// public static final int CEP_EVENT_SENT = BASE_VALUE + 10;
//
//
// }
// Path: cepsim-integration/src/main/java/ca/uwo/eng/sel/cepsim/network/FixedDelayNetworkInterface.java
import ca.uwo.eng.sel.cepsim.integr.CepSimBroker;
import ca.uwo.eng.sel.cepsim.integr.CepSimTags;
import ca.uwo.eng.sel.cepsim.event.EventSet;
import ca.uwo.eng.sel.cepsim.query.InputVertex;
import ca.uwo.eng.sel.cepsim.query.OutputVertex;
import org.cloudbus.cloudsim.Vm;
package ca.uwo.eng.sel.cepsim.network;
/**
* Created by virso on 2014-11-10.
*/
public class FixedDelayNetworkInterface implements NetworkInterface {
private CepSimBroker broker;
private double delay; // in seconds
public FixedDelayNetworkInterface(CepSimBroker broker, double delay) {
this.broker = broker;
this.delay = delay;
}
@Override
public void sendMessage(double timestamp, OutputVertex orig, InputVertex dest, EventSet eventSet) {
Vm destVm = broker.getVmAllocation(dest);
Integer datacenterId = broker.getDatacenterId(destVm);
double start = timestamp / 1000.0; // transform to seconds
// destination, delay, tag, content | broker.schedule(datacenterId, this.delay, CepSimTags.CEP_EVENT_SENT, |
virsox/cepsim | cepsim-integration/src/test/java/ca/uwo/eng/sel/cepsim/integr/CepQueryCloudletTest.java | // Path: cepsim-integration/src/main/java/ca/uwo/eng/sel/cepsim/network/CepNetworkEvent.java
// public class CepNetworkEvent implements Comparable<CepNetworkEvent> {
//
// private double origTimestamp;
// private double destTimestamp;
// private OutputVertex orig;
// private InputVertex dest;
// private EventSet eventSet;
//
// public CepNetworkEvent(double origTimestamp, OutputVertex orig, double destTimestamp, InputVertex dest,
// EventSet eventSet) {
// this.origTimestamp = origTimestamp;
// this.destTimestamp = destTimestamp;
// this.orig = orig;
// this.dest = dest;
// this.eventSet = eventSet;
// }
//
// public double getOrigTimestamp() {
// return origTimestamp;
// }
//
// public OutputVertex getOrig() {
// return orig;
// }
//
// public double getDestTimestamp() {
// return destTimestamp;
// }
//
// public InputVertex getDest() {
// return dest;
// }
//
// public EventSet getEventSet() {
// return eventSet;
// }
//
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// CepNetworkEvent that = (CepNetworkEvent) o;
//
// if (Double.compare(that.destTimestamp, destTimestamp) != 0) return false;
// if (Double.compare(that.origTimestamp, origTimestamp) != 0) return false;
// if (!dest.equals(that.dest)) return false;
// if (!orig.equals(that.orig)) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result;
// long temp;
// temp = Double.doubleToLongBits(origTimestamp);
// result = (int) (temp ^ (temp >>> 32));
// temp = Double.doubleToLongBits(destTimestamp);
// result = 31 * result + (int) (temp ^ (temp >>> 32));
// result = 31 * result + orig.hashCode();
// result = 31 * result + dest.hashCode();
// return result;
// }
//
// @Override
// public int compareTo(CepNetworkEvent o) {
// int ret = Double.compare(this.destTimestamp, o.destTimestamp);
// if (ret != 0) return ret;
//
// ret = Double.compare(this.origTimestamp, o.origTimestamp);
// if (ret != 0) return ret;
//
// ret = this.orig.compare(o.orig);
// if (ret != 0) return ret;
//
// return this.dest.compare(o.dest);
// }
// }
| import ca.uwo.eng.sel.cepsim.PlacementExecutor;
import ca.uwo.eng.sel.cepsim.history.History;
import ca.uwo.eng.sel.cepsim.history.SimEvent;
import ca.uwo.eng.sel.cepsim.event.EventSet;
import ca.uwo.eng.sel.cepsim.metric.MetricCalculator;
import ca.uwo.eng.sel.cepsim.network.CepNetworkEvent;
import ca.uwo.eng.sel.cepsim.network.NetworkInterface;
import ca.uwo.eng.sel.cepsim.placement.Placement;
import ca.uwo.eng.sel.cepsim.query.EventConsumer;
import ca.uwo.eng.sel.cepsim.query.EventProducer;
import ca.uwo.eng.sel.cepsim.query.Operator;
import ca.uwo.eng.sel.cepsim.query.Vertex;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import scala.collection.JavaConversions;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.anyDouble;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when; | when(placementExecutor.run(anyDouble(), anyDouble(), anyDouble())).thenReturn(new History<SimEvent>());
// 1st invocation
CepQueryCloudlet cloudlet = new CepQueryCloudlet(1, placementExecutor, false, calculator);
cloudlet.updateQuery(80_000_000L, 80, 0, 1);
verify(placementExecutor).init(0);
verify(placementExecutor).run(80_000_000L, 0, 1);
assertEquals(20.0, cloudlet.getEstimatedTimeToFinish(), 0.0001);
// 2nd invocation
cloudlet.updateQuery(100_000_000L, 180, 80, 1);
verify(placementExecutor).run(20_000_000L, 80000, 1);
assertEquals(0.0, cloudlet.getEstimatedTimeToFinish(), 0.0001);
assertEquals(0, cloudlet.getRemainingCloudletLength());
}
@Test
public void testUpdateCloudletWithEventsReceived() {
when(placementExecutor.run(anyDouble(), anyDouble(), anyDouble())).thenReturn(new History<SimEvent>());
CepQueryCloudlet cloudlet = new CepQueryCloudlet(1, placementExecutor, false, calculator);
// enqueue network events
EventSet es1 = new EventSet(1000, 1.0, 0.0, Collections.<EventProducer, Object>singletonMap(p1, 1000.0));
EventSet es2 = new EventSet(2000, 1.0, 0.0, Collections.<EventProducer, Object>singletonMap(p1, 2000.0));
EventSet es3 = new EventSet(5000, 1.0, 0.0, Collections.<EventProducer, Object>singletonMap(p1, 5000.0));
| // Path: cepsim-integration/src/main/java/ca/uwo/eng/sel/cepsim/network/CepNetworkEvent.java
// public class CepNetworkEvent implements Comparable<CepNetworkEvent> {
//
// private double origTimestamp;
// private double destTimestamp;
// private OutputVertex orig;
// private InputVertex dest;
// private EventSet eventSet;
//
// public CepNetworkEvent(double origTimestamp, OutputVertex orig, double destTimestamp, InputVertex dest,
// EventSet eventSet) {
// this.origTimestamp = origTimestamp;
// this.destTimestamp = destTimestamp;
// this.orig = orig;
// this.dest = dest;
// this.eventSet = eventSet;
// }
//
// public double getOrigTimestamp() {
// return origTimestamp;
// }
//
// public OutputVertex getOrig() {
// return orig;
// }
//
// public double getDestTimestamp() {
// return destTimestamp;
// }
//
// public InputVertex getDest() {
// return dest;
// }
//
// public EventSet getEventSet() {
// return eventSet;
// }
//
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// CepNetworkEvent that = (CepNetworkEvent) o;
//
// if (Double.compare(that.destTimestamp, destTimestamp) != 0) return false;
// if (Double.compare(that.origTimestamp, origTimestamp) != 0) return false;
// if (!dest.equals(that.dest)) return false;
// if (!orig.equals(that.orig)) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result;
// long temp;
// temp = Double.doubleToLongBits(origTimestamp);
// result = (int) (temp ^ (temp >>> 32));
// temp = Double.doubleToLongBits(destTimestamp);
// result = 31 * result + (int) (temp ^ (temp >>> 32));
// result = 31 * result + orig.hashCode();
// result = 31 * result + dest.hashCode();
// return result;
// }
//
// @Override
// public int compareTo(CepNetworkEvent o) {
// int ret = Double.compare(this.destTimestamp, o.destTimestamp);
// if (ret != 0) return ret;
//
// ret = Double.compare(this.origTimestamp, o.origTimestamp);
// if (ret != 0) return ret;
//
// ret = this.orig.compare(o.orig);
// if (ret != 0) return ret;
//
// return this.dest.compare(o.dest);
// }
// }
// Path: cepsim-integration/src/test/java/ca/uwo/eng/sel/cepsim/integr/CepQueryCloudletTest.java
import ca.uwo.eng.sel.cepsim.PlacementExecutor;
import ca.uwo.eng.sel.cepsim.history.History;
import ca.uwo.eng.sel.cepsim.history.SimEvent;
import ca.uwo.eng.sel.cepsim.event.EventSet;
import ca.uwo.eng.sel.cepsim.metric.MetricCalculator;
import ca.uwo.eng.sel.cepsim.network.CepNetworkEvent;
import ca.uwo.eng.sel.cepsim.network.NetworkInterface;
import ca.uwo.eng.sel.cepsim.placement.Placement;
import ca.uwo.eng.sel.cepsim.query.EventConsumer;
import ca.uwo.eng.sel.cepsim.query.EventProducer;
import ca.uwo.eng.sel.cepsim.query.Operator;
import ca.uwo.eng.sel.cepsim.query.Vertex;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import scala.collection.JavaConversions;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.anyDouble;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
when(placementExecutor.run(anyDouble(), anyDouble(), anyDouble())).thenReturn(new History<SimEvent>());
// 1st invocation
CepQueryCloudlet cloudlet = new CepQueryCloudlet(1, placementExecutor, false, calculator);
cloudlet.updateQuery(80_000_000L, 80, 0, 1);
verify(placementExecutor).init(0);
verify(placementExecutor).run(80_000_000L, 0, 1);
assertEquals(20.0, cloudlet.getEstimatedTimeToFinish(), 0.0001);
// 2nd invocation
cloudlet.updateQuery(100_000_000L, 180, 80, 1);
verify(placementExecutor).run(20_000_000L, 80000, 1);
assertEquals(0.0, cloudlet.getEstimatedTimeToFinish(), 0.0001);
assertEquals(0, cloudlet.getRemainingCloudletLength());
}
@Test
public void testUpdateCloudletWithEventsReceived() {
when(placementExecutor.run(anyDouble(), anyDouble(), anyDouble())).thenReturn(new History<SimEvent>());
CepQueryCloudlet cloudlet = new CepQueryCloudlet(1, placementExecutor, false, calculator);
// enqueue network events
EventSet es1 = new EventSet(1000, 1.0, 0.0, Collections.<EventProducer, Object>singletonMap(p1, 1000.0));
EventSet es2 = new EventSet(2000, 1.0, 0.0, Collections.<EventProducer, Object>singletonMap(p1, 2000.0));
EventSet es3 = new EventSet(5000, 1.0, 0.0, Collections.<EventProducer, Object>singletonMap(p1, 5000.0));
| CepNetworkEvent net1 = new CepNetworkEvent(1.0, p1, 6.0, f1, es1); |
virsox/cepsim | cepsim-integration/src/test/java/ca/uwo/eng/sel/cepsim/network/FixedDelayNetworkInterfaceTest.java | // Path: cepsim-integration/src/main/java/ca/uwo/eng/sel/cepsim/integr/CepSimBroker.java
// public class CepSimBroker extends DatacenterBroker {
//
// private Map<Vertex, Vm> verticesToVm = new HashMap<>();
//
// /** Length of the simulation (in ms)*/
// private double simulationLength;
//
// /** Simulation interval in milliseconds. */
// private double simulationInterval;
//
// public CepSimBroker(String name, double simulationLength, double simulationInterval) throws Exception {
// super(name);
//
// this.simulationLength = simulationLength;
// this.simulationInterval = simulationInterval;
// }
//
//
//
// @Override
// public void processEvent(SimEvent ev) {
//
// switch (ev.getTag()) {
// case CepSimTags.CEP_EVENT_SENT:
// System.out.println(ev.getData());
//
// default:
// super.processEvent(ev);
// break;
// }
//
// }
//
// public Vm getVmAllocation(Vertex v) {
// return verticesToVm.get(v);
// }
//
//
// public Integer getDatacenterId(Vm vm) {
// return getVmsToDatacentersMap().get(vm.getId());
// }
//
// @Override
// protected void submitCloudlets() {
// int vmIndex = 0;
// List<Cloudlet> successfullySubmitted = new ArrayList<Cloudlet>();
// for (Cloudlet cloudlet : getCloudletList()) {
// Vm vm;
// // if user didn't bind this cloudlet and it has not been executed yet
// if (cloudlet.getVmId() == -1) {
// vm = getVmsCreatedList().get(vmIndex);
// } else { // submit to the specific vm
// vm = VmList.getById(getVmsCreatedList(), cloudlet.getVmId());
// if (vm == null) { // vm was not created
// if(!Log.isDisabled()) {
// Log.print(CloudSim.clock() + ": " + getName() + ": Postponing execution of cloudlet " +
// cloudlet.getCloudletId() + ": bount VM not available");
// }
// continue;
// }
// }
//
// if (!Log.isDisabled()) {
// Log.print(CloudSim.clock() + ": " + getName() + ": Sending cloudlet " +
// cloudlet.getCloudletId() + " to VM #" + vm.getId());
// }
//
// cloudlet.setVmId(vm.getId());
// submitCloudlet(vm, cloudlet);
//
// // --------------------------------------------
// // [WAH] - Added - build a map from Vertices to Vms
// if (cloudlet instanceof CepQueryCloudlet) {
// CepQueryCloudlet cepCloudlet = (CepQueryCloudlet) cloudlet;
// for (Vertex v : cepCloudlet.getVertices()) {
// verticesToVm.put(v, vm);
// }
// }
// // --------------------------------------------
//
// cloudletsSubmitted++;
//
//
// vmIndex = (vmIndex + 1) % getVmsCreatedList().size();
// getCloudletSubmittedList().add(cloudlet);
// successfullySubmitted.add(cloudlet);
// }
//
// // remove submitted cloudlets from waiting list
// getCloudletList().removeAll(successfullySubmitted);
// }
//
// public void submitCloudlet(Vm vm, Cloudlet cloudlet) {
// sendNow(getVmsToDatacentersMap().get(vm.getId()), CloudSimTags.CLOUDLET_SUBMIT, cloudlet);
// }
//
// @Override
// protected void processOtherEvent(final SimEvent ev) {
// switch (ev.getTag()) {
// default:
// super.processOtherEvent(ev);
// }
// }
//
//
// }
//
// Path: cepsim-integration/src/main/java/ca/uwo/eng/sel/cepsim/integr/CepSimTags.java
// public class CepSimTags {
//
// public static final int BASE_VALUE = 99900;
//
// public static final int CEP_EVENT_SENT = BASE_VALUE + 10;
//
//
// }
| import ca.uwo.eng.sel.cepsim.integr.CepSimBroker;
import ca.uwo.eng.sel.cepsim.integr.CepSimTags;
import ca.uwo.eng.sel.cepsim.event.EventSet;
import ca.uwo.eng.sel.cepsim.query.EventProducer;
import ca.uwo.eng.sel.cepsim.query.InputVertex;
import ca.uwo.eng.sel.cepsim.query.OutputVertex;
import org.cloudbus.cloudsim.Vm;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import java.util.HashMap;
import java.util.Map;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when; | package ca.uwo.eng.sel.cepsim.network;
/**
* Created by virso on 2014-11-10.
*/
public class FixedDelayNetworkInterfaceTest {
@Mock private EventProducer producer;
@Mock private OutputVertex orig;
@Mock private InputVertex dest;
@Mock private Vm destVm; | // Path: cepsim-integration/src/main/java/ca/uwo/eng/sel/cepsim/integr/CepSimBroker.java
// public class CepSimBroker extends DatacenterBroker {
//
// private Map<Vertex, Vm> verticesToVm = new HashMap<>();
//
// /** Length of the simulation (in ms)*/
// private double simulationLength;
//
// /** Simulation interval in milliseconds. */
// private double simulationInterval;
//
// public CepSimBroker(String name, double simulationLength, double simulationInterval) throws Exception {
// super(name);
//
// this.simulationLength = simulationLength;
// this.simulationInterval = simulationInterval;
// }
//
//
//
// @Override
// public void processEvent(SimEvent ev) {
//
// switch (ev.getTag()) {
// case CepSimTags.CEP_EVENT_SENT:
// System.out.println(ev.getData());
//
// default:
// super.processEvent(ev);
// break;
// }
//
// }
//
// public Vm getVmAllocation(Vertex v) {
// return verticesToVm.get(v);
// }
//
//
// public Integer getDatacenterId(Vm vm) {
// return getVmsToDatacentersMap().get(vm.getId());
// }
//
// @Override
// protected void submitCloudlets() {
// int vmIndex = 0;
// List<Cloudlet> successfullySubmitted = new ArrayList<Cloudlet>();
// for (Cloudlet cloudlet : getCloudletList()) {
// Vm vm;
// // if user didn't bind this cloudlet and it has not been executed yet
// if (cloudlet.getVmId() == -1) {
// vm = getVmsCreatedList().get(vmIndex);
// } else { // submit to the specific vm
// vm = VmList.getById(getVmsCreatedList(), cloudlet.getVmId());
// if (vm == null) { // vm was not created
// if(!Log.isDisabled()) {
// Log.print(CloudSim.clock() + ": " + getName() + ": Postponing execution of cloudlet " +
// cloudlet.getCloudletId() + ": bount VM not available");
// }
// continue;
// }
// }
//
// if (!Log.isDisabled()) {
// Log.print(CloudSim.clock() + ": " + getName() + ": Sending cloudlet " +
// cloudlet.getCloudletId() + " to VM #" + vm.getId());
// }
//
// cloudlet.setVmId(vm.getId());
// submitCloudlet(vm, cloudlet);
//
// // --------------------------------------------
// // [WAH] - Added - build a map from Vertices to Vms
// if (cloudlet instanceof CepQueryCloudlet) {
// CepQueryCloudlet cepCloudlet = (CepQueryCloudlet) cloudlet;
// for (Vertex v : cepCloudlet.getVertices()) {
// verticesToVm.put(v, vm);
// }
// }
// // --------------------------------------------
//
// cloudletsSubmitted++;
//
//
// vmIndex = (vmIndex + 1) % getVmsCreatedList().size();
// getCloudletSubmittedList().add(cloudlet);
// successfullySubmitted.add(cloudlet);
// }
//
// // remove submitted cloudlets from waiting list
// getCloudletList().removeAll(successfullySubmitted);
// }
//
// public void submitCloudlet(Vm vm, Cloudlet cloudlet) {
// sendNow(getVmsToDatacentersMap().get(vm.getId()), CloudSimTags.CLOUDLET_SUBMIT, cloudlet);
// }
//
// @Override
// protected void processOtherEvent(final SimEvent ev) {
// switch (ev.getTag()) {
// default:
// super.processOtherEvent(ev);
// }
// }
//
//
// }
//
// Path: cepsim-integration/src/main/java/ca/uwo/eng/sel/cepsim/integr/CepSimTags.java
// public class CepSimTags {
//
// public static final int BASE_VALUE = 99900;
//
// public static final int CEP_EVENT_SENT = BASE_VALUE + 10;
//
//
// }
// Path: cepsim-integration/src/test/java/ca/uwo/eng/sel/cepsim/network/FixedDelayNetworkInterfaceTest.java
import ca.uwo.eng.sel.cepsim.integr.CepSimBroker;
import ca.uwo.eng.sel.cepsim.integr.CepSimTags;
import ca.uwo.eng.sel.cepsim.event.EventSet;
import ca.uwo.eng.sel.cepsim.query.EventProducer;
import ca.uwo.eng.sel.cepsim.query.InputVertex;
import ca.uwo.eng.sel.cepsim.query.OutputVertex;
import org.cloudbus.cloudsim.Vm;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import java.util.HashMap;
import java.util.Map;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
package ca.uwo.eng.sel.cepsim.network;
/**
* Created by virso on 2014-11-10.
*/
public class FixedDelayNetworkInterfaceTest {
@Mock private EventProducer producer;
@Mock private OutputVertex orig;
@Mock private InputVertex dest;
@Mock private Vm destVm; | @Mock private CepSimBroker broker; |
virsox/cepsim | cepsim-integration/src/test/java/ca/uwo/eng/sel/cepsim/network/FixedDelayNetworkInterfaceTest.java | // Path: cepsim-integration/src/main/java/ca/uwo/eng/sel/cepsim/integr/CepSimBroker.java
// public class CepSimBroker extends DatacenterBroker {
//
// private Map<Vertex, Vm> verticesToVm = new HashMap<>();
//
// /** Length of the simulation (in ms)*/
// private double simulationLength;
//
// /** Simulation interval in milliseconds. */
// private double simulationInterval;
//
// public CepSimBroker(String name, double simulationLength, double simulationInterval) throws Exception {
// super(name);
//
// this.simulationLength = simulationLength;
// this.simulationInterval = simulationInterval;
// }
//
//
//
// @Override
// public void processEvent(SimEvent ev) {
//
// switch (ev.getTag()) {
// case CepSimTags.CEP_EVENT_SENT:
// System.out.println(ev.getData());
//
// default:
// super.processEvent(ev);
// break;
// }
//
// }
//
// public Vm getVmAllocation(Vertex v) {
// return verticesToVm.get(v);
// }
//
//
// public Integer getDatacenterId(Vm vm) {
// return getVmsToDatacentersMap().get(vm.getId());
// }
//
// @Override
// protected void submitCloudlets() {
// int vmIndex = 0;
// List<Cloudlet> successfullySubmitted = new ArrayList<Cloudlet>();
// for (Cloudlet cloudlet : getCloudletList()) {
// Vm vm;
// // if user didn't bind this cloudlet and it has not been executed yet
// if (cloudlet.getVmId() == -1) {
// vm = getVmsCreatedList().get(vmIndex);
// } else { // submit to the specific vm
// vm = VmList.getById(getVmsCreatedList(), cloudlet.getVmId());
// if (vm == null) { // vm was not created
// if(!Log.isDisabled()) {
// Log.print(CloudSim.clock() + ": " + getName() + ": Postponing execution of cloudlet " +
// cloudlet.getCloudletId() + ": bount VM not available");
// }
// continue;
// }
// }
//
// if (!Log.isDisabled()) {
// Log.print(CloudSim.clock() + ": " + getName() + ": Sending cloudlet " +
// cloudlet.getCloudletId() + " to VM #" + vm.getId());
// }
//
// cloudlet.setVmId(vm.getId());
// submitCloudlet(vm, cloudlet);
//
// // --------------------------------------------
// // [WAH] - Added - build a map from Vertices to Vms
// if (cloudlet instanceof CepQueryCloudlet) {
// CepQueryCloudlet cepCloudlet = (CepQueryCloudlet) cloudlet;
// for (Vertex v : cepCloudlet.getVertices()) {
// verticesToVm.put(v, vm);
// }
// }
// // --------------------------------------------
//
// cloudletsSubmitted++;
//
//
// vmIndex = (vmIndex + 1) % getVmsCreatedList().size();
// getCloudletSubmittedList().add(cloudlet);
// successfullySubmitted.add(cloudlet);
// }
//
// // remove submitted cloudlets from waiting list
// getCloudletList().removeAll(successfullySubmitted);
// }
//
// public void submitCloudlet(Vm vm, Cloudlet cloudlet) {
// sendNow(getVmsToDatacentersMap().get(vm.getId()), CloudSimTags.CLOUDLET_SUBMIT, cloudlet);
// }
//
// @Override
// protected void processOtherEvent(final SimEvent ev) {
// switch (ev.getTag()) {
// default:
// super.processOtherEvent(ev);
// }
// }
//
//
// }
//
// Path: cepsim-integration/src/main/java/ca/uwo/eng/sel/cepsim/integr/CepSimTags.java
// public class CepSimTags {
//
// public static final int BASE_VALUE = 99900;
//
// public static final int CEP_EVENT_SENT = BASE_VALUE + 10;
//
//
// }
| import ca.uwo.eng.sel.cepsim.integr.CepSimBroker;
import ca.uwo.eng.sel.cepsim.integr.CepSimTags;
import ca.uwo.eng.sel.cepsim.event.EventSet;
import ca.uwo.eng.sel.cepsim.query.EventProducer;
import ca.uwo.eng.sel.cepsim.query.InputVertex;
import ca.uwo.eng.sel.cepsim.query.OutputVertex;
import org.cloudbus.cloudsim.Vm;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import java.util.HashMap;
import java.util.Map;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when; | package ca.uwo.eng.sel.cepsim.network;
/**
* Created by virso on 2014-11-10.
*/
public class FixedDelayNetworkInterfaceTest {
@Mock private EventProducer producer;
@Mock private OutputVertex orig;
@Mock private InputVertex dest;
@Mock private Vm destVm;
@Mock private CepSimBroker broker;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
}
@Test
public void testSendMessage() {
when(broker.getVmAllocation(dest)).thenReturn(destVm);
when(broker.getDatacenterId(destVm)).thenReturn(1);
Map<EventProducer, Object> totals = new HashMap<>();
totals.put(producer, 5000.0);
EventSet es = new EventSet(5000.0, 10.0, 1.0, totals);
FixedDelayNetworkInterface ni = new FixedDelayNetworkInterface(broker, 0.5); // 500 ms
// this is invoked by CEPSim core - so, it is in ms
ni.sendMessage(100, orig, dest, es);
CepNetworkEvent expected = new CepNetworkEvent(0.1, orig, 0.6, dest, es); | // Path: cepsim-integration/src/main/java/ca/uwo/eng/sel/cepsim/integr/CepSimBroker.java
// public class CepSimBroker extends DatacenterBroker {
//
// private Map<Vertex, Vm> verticesToVm = new HashMap<>();
//
// /** Length of the simulation (in ms)*/
// private double simulationLength;
//
// /** Simulation interval in milliseconds. */
// private double simulationInterval;
//
// public CepSimBroker(String name, double simulationLength, double simulationInterval) throws Exception {
// super(name);
//
// this.simulationLength = simulationLength;
// this.simulationInterval = simulationInterval;
// }
//
//
//
// @Override
// public void processEvent(SimEvent ev) {
//
// switch (ev.getTag()) {
// case CepSimTags.CEP_EVENT_SENT:
// System.out.println(ev.getData());
//
// default:
// super.processEvent(ev);
// break;
// }
//
// }
//
// public Vm getVmAllocation(Vertex v) {
// return verticesToVm.get(v);
// }
//
//
// public Integer getDatacenterId(Vm vm) {
// return getVmsToDatacentersMap().get(vm.getId());
// }
//
// @Override
// protected void submitCloudlets() {
// int vmIndex = 0;
// List<Cloudlet> successfullySubmitted = new ArrayList<Cloudlet>();
// for (Cloudlet cloudlet : getCloudletList()) {
// Vm vm;
// // if user didn't bind this cloudlet and it has not been executed yet
// if (cloudlet.getVmId() == -1) {
// vm = getVmsCreatedList().get(vmIndex);
// } else { // submit to the specific vm
// vm = VmList.getById(getVmsCreatedList(), cloudlet.getVmId());
// if (vm == null) { // vm was not created
// if(!Log.isDisabled()) {
// Log.print(CloudSim.clock() + ": " + getName() + ": Postponing execution of cloudlet " +
// cloudlet.getCloudletId() + ": bount VM not available");
// }
// continue;
// }
// }
//
// if (!Log.isDisabled()) {
// Log.print(CloudSim.clock() + ": " + getName() + ": Sending cloudlet " +
// cloudlet.getCloudletId() + " to VM #" + vm.getId());
// }
//
// cloudlet.setVmId(vm.getId());
// submitCloudlet(vm, cloudlet);
//
// // --------------------------------------------
// // [WAH] - Added - build a map from Vertices to Vms
// if (cloudlet instanceof CepQueryCloudlet) {
// CepQueryCloudlet cepCloudlet = (CepQueryCloudlet) cloudlet;
// for (Vertex v : cepCloudlet.getVertices()) {
// verticesToVm.put(v, vm);
// }
// }
// // --------------------------------------------
//
// cloudletsSubmitted++;
//
//
// vmIndex = (vmIndex + 1) % getVmsCreatedList().size();
// getCloudletSubmittedList().add(cloudlet);
// successfullySubmitted.add(cloudlet);
// }
//
// // remove submitted cloudlets from waiting list
// getCloudletList().removeAll(successfullySubmitted);
// }
//
// public void submitCloudlet(Vm vm, Cloudlet cloudlet) {
// sendNow(getVmsToDatacentersMap().get(vm.getId()), CloudSimTags.CLOUDLET_SUBMIT, cloudlet);
// }
//
// @Override
// protected void processOtherEvent(final SimEvent ev) {
// switch (ev.getTag()) {
// default:
// super.processOtherEvent(ev);
// }
// }
//
//
// }
//
// Path: cepsim-integration/src/main/java/ca/uwo/eng/sel/cepsim/integr/CepSimTags.java
// public class CepSimTags {
//
// public static final int BASE_VALUE = 99900;
//
// public static final int CEP_EVENT_SENT = BASE_VALUE + 10;
//
//
// }
// Path: cepsim-integration/src/test/java/ca/uwo/eng/sel/cepsim/network/FixedDelayNetworkInterfaceTest.java
import ca.uwo.eng.sel.cepsim.integr.CepSimBroker;
import ca.uwo.eng.sel.cepsim.integr.CepSimTags;
import ca.uwo.eng.sel.cepsim.event.EventSet;
import ca.uwo.eng.sel.cepsim.query.EventProducer;
import ca.uwo.eng.sel.cepsim.query.InputVertex;
import ca.uwo.eng.sel.cepsim.query.OutputVertex;
import org.cloudbus.cloudsim.Vm;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import java.util.HashMap;
import java.util.Map;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
package ca.uwo.eng.sel.cepsim.network;
/**
* Created by virso on 2014-11-10.
*/
public class FixedDelayNetworkInterfaceTest {
@Mock private EventProducer producer;
@Mock private OutputVertex orig;
@Mock private InputVertex dest;
@Mock private Vm destVm;
@Mock private CepSimBroker broker;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
}
@Test
public void testSendMessage() {
when(broker.getVmAllocation(dest)).thenReturn(destVm);
when(broker.getDatacenterId(destVm)).thenReturn(1);
Map<EventProducer, Object> totals = new HashMap<>();
totals.put(producer, 5000.0);
EventSet es = new EventSet(5000.0, 10.0, 1.0, totals);
FixedDelayNetworkInterface ni = new FixedDelayNetworkInterface(broker, 0.5); // 500 ms
// this is invoked by CEPSim core - so, it is in ms
ni.sendMessage(100, orig, dest, es);
CepNetworkEvent expected = new CepNetworkEvent(0.1, orig, 0.6, dest, es); | verify(broker).schedule(1, 0.5, CepSimTags.CEP_EVENT_SENT, expected); |
virsox/cepsim | cepsim-integration/src/main/java/ca/uwo/eng/sel/cepsim/integr/CepSimDatacenter.java | // Path: cepsim-integration/src/main/java/ca/uwo/eng/sel/cepsim/network/CepNetworkEvent.java
// public class CepNetworkEvent implements Comparable<CepNetworkEvent> {
//
// private double origTimestamp;
// private double destTimestamp;
// private OutputVertex orig;
// private InputVertex dest;
// private EventSet eventSet;
//
// public CepNetworkEvent(double origTimestamp, OutputVertex orig, double destTimestamp, InputVertex dest,
// EventSet eventSet) {
// this.origTimestamp = origTimestamp;
// this.destTimestamp = destTimestamp;
// this.orig = orig;
// this.dest = dest;
// this.eventSet = eventSet;
// }
//
// public double getOrigTimestamp() {
// return origTimestamp;
// }
//
// public OutputVertex getOrig() {
// return orig;
// }
//
// public double getDestTimestamp() {
// return destTimestamp;
// }
//
// public InputVertex getDest() {
// return dest;
// }
//
// public EventSet getEventSet() {
// return eventSet;
// }
//
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// CepNetworkEvent that = (CepNetworkEvent) o;
//
// if (Double.compare(that.destTimestamp, destTimestamp) != 0) return false;
// if (Double.compare(that.origTimestamp, origTimestamp) != 0) return false;
// if (!dest.equals(that.dest)) return false;
// if (!orig.equals(that.orig)) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result;
// long temp;
// temp = Double.doubleToLongBits(origTimestamp);
// result = (int) (temp ^ (temp >>> 32));
// temp = Double.doubleToLongBits(destTimestamp);
// result = 31 * result + (int) (temp ^ (temp >>> 32));
// result = 31 * result + orig.hashCode();
// result = 31 * result + dest.hashCode();
// return result;
// }
//
// @Override
// public int compareTo(CepNetworkEvent o) {
// int ret = Double.compare(this.destTimestamp, o.destTimestamp);
// if (ret != 0) return ret;
//
// ret = Double.compare(this.origTimestamp, o.origTimestamp);
// if (ret != 0) return ret;
//
// ret = this.orig.compare(o.orig);
// if (ret != 0) return ret;
//
// return this.dest.compare(o.dest);
// }
// }
| import java.util.HashMap;
import java.util.List;
import java.util.Map;
import ca.uwo.eng.sel.cepsim.network.CepNetworkEvent;
import ca.uwo.eng.sel.cepsim.query.Vertex;
import org.cloudbus.cloudsim.Cloudlet;
import org.cloudbus.cloudsim.CloudletScheduler;
import org.cloudbus.cloudsim.Datacenter;
import org.cloudbus.cloudsim.DatacenterCharacteristics;
import org.cloudbus.cloudsim.Host;
import org.cloudbus.cloudsim.Log;
import org.cloudbus.cloudsim.Storage;
import org.cloudbus.cloudsim.Vm;
import org.cloudbus.cloudsim.VmAllocationPolicy;
import org.cloudbus.cloudsim.core.CloudSim;
import org.cloudbus.cloudsim.core.CloudSimTags;
import org.cloudbus.cloudsim.core.SimEvent; | package ca.uwo.eng.sel.cepsim.integr;
public class CepSimDatacenter extends Datacenter {
private Map<Vertex, CepQueryCloudlet> vertexToCloudlet = new HashMap<>();
public CepSimDatacenter(String name,
DatacenterCharacteristics characteristics,
VmAllocationPolicy vmAllocationPolicy,
List<Storage> storageList,
double schedulingInterval) throws Exception {
super(name, characteristics, vmAllocationPolicy, storageList, schedulingInterval);
}
@Override
protected void processOtherEvent(SimEvent ev) {
switch (ev.getTag()) {
case CepSimTags.CEP_EVENT_SENT:
this.processCepEventSent(ev);
break;
default:
super.processOtherEvent(ev);
break;
}
}
private void processCepEventSent(SimEvent ev) { | // Path: cepsim-integration/src/main/java/ca/uwo/eng/sel/cepsim/network/CepNetworkEvent.java
// public class CepNetworkEvent implements Comparable<CepNetworkEvent> {
//
// private double origTimestamp;
// private double destTimestamp;
// private OutputVertex orig;
// private InputVertex dest;
// private EventSet eventSet;
//
// public CepNetworkEvent(double origTimestamp, OutputVertex orig, double destTimestamp, InputVertex dest,
// EventSet eventSet) {
// this.origTimestamp = origTimestamp;
// this.destTimestamp = destTimestamp;
// this.orig = orig;
// this.dest = dest;
// this.eventSet = eventSet;
// }
//
// public double getOrigTimestamp() {
// return origTimestamp;
// }
//
// public OutputVertex getOrig() {
// return orig;
// }
//
// public double getDestTimestamp() {
// return destTimestamp;
// }
//
// public InputVertex getDest() {
// return dest;
// }
//
// public EventSet getEventSet() {
// return eventSet;
// }
//
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// CepNetworkEvent that = (CepNetworkEvent) o;
//
// if (Double.compare(that.destTimestamp, destTimestamp) != 0) return false;
// if (Double.compare(that.origTimestamp, origTimestamp) != 0) return false;
// if (!dest.equals(that.dest)) return false;
// if (!orig.equals(that.orig)) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result;
// long temp;
// temp = Double.doubleToLongBits(origTimestamp);
// result = (int) (temp ^ (temp >>> 32));
// temp = Double.doubleToLongBits(destTimestamp);
// result = 31 * result + (int) (temp ^ (temp >>> 32));
// result = 31 * result + orig.hashCode();
// result = 31 * result + dest.hashCode();
// return result;
// }
//
// @Override
// public int compareTo(CepNetworkEvent o) {
// int ret = Double.compare(this.destTimestamp, o.destTimestamp);
// if (ret != 0) return ret;
//
// ret = Double.compare(this.origTimestamp, o.origTimestamp);
// if (ret != 0) return ret;
//
// ret = this.orig.compare(o.orig);
// if (ret != 0) return ret;
//
// return this.dest.compare(o.dest);
// }
// }
// Path: cepsim-integration/src/main/java/ca/uwo/eng/sel/cepsim/integr/CepSimDatacenter.java
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import ca.uwo.eng.sel.cepsim.network.CepNetworkEvent;
import ca.uwo.eng.sel.cepsim.query.Vertex;
import org.cloudbus.cloudsim.Cloudlet;
import org.cloudbus.cloudsim.CloudletScheduler;
import org.cloudbus.cloudsim.Datacenter;
import org.cloudbus.cloudsim.DatacenterCharacteristics;
import org.cloudbus.cloudsim.Host;
import org.cloudbus.cloudsim.Log;
import org.cloudbus.cloudsim.Storage;
import org.cloudbus.cloudsim.Vm;
import org.cloudbus.cloudsim.VmAllocationPolicy;
import org.cloudbus.cloudsim.core.CloudSim;
import org.cloudbus.cloudsim.core.CloudSimTags;
import org.cloudbus.cloudsim.core.SimEvent;
package ca.uwo.eng.sel.cepsim.integr;
public class CepSimDatacenter extends Datacenter {
private Map<Vertex, CepQueryCloudlet> vertexToCloudlet = new HashMap<>();
public CepSimDatacenter(String name,
DatacenterCharacteristics characteristics,
VmAllocationPolicy vmAllocationPolicy,
List<Storage> storageList,
double schedulingInterval) throws Exception {
super(name, characteristics, vmAllocationPolicy, storageList, schedulingInterval);
}
@Override
protected void processOtherEvent(SimEvent ev) {
switch (ev.getTag()) {
case CepSimTags.CEP_EVENT_SENT:
this.processCepEventSent(ev);
break;
default:
super.processOtherEvent(ev);
break;
}
}
private void processCepEventSent(SimEvent ev) { | CepNetworkEvent netEvent = (CepNetworkEvent) ev.getData(); |
virsox/cepsim | cepsim-integration/src/main/java/ca/uwo/eng/sel/cepsim/integr/CepQueryCloudlet.java | // Path: cepsim-integration/src/main/java/ca/uwo/eng/sel/cepsim/network/CepNetworkEvent.java
// public class CepNetworkEvent implements Comparable<CepNetworkEvent> {
//
// private double origTimestamp;
// private double destTimestamp;
// private OutputVertex orig;
// private InputVertex dest;
// private EventSet eventSet;
//
// public CepNetworkEvent(double origTimestamp, OutputVertex orig, double destTimestamp, InputVertex dest,
// EventSet eventSet) {
// this.origTimestamp = origTimestamp;
// this.destTimestamp = destTimestamp;
// this.orig = orig;
// this.dest = dest;
// this.eventSet = eventSet;
// }
//
// public double getOrigTimestamp() {
// return origTimestamp;
// }
//
// public OutputVertex getOrig() {
// return orig;
// }
//
// public double getDestTimestamp() {
// return destTimestamp;
// }
//
// public InputVertex getDest() {
// return dest;
// }
//
// public EventSet getEventSet() {
// return eventSet;
// }
//
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// CepNetworkEvent that = (CepNetworkEvent) o;
//
// if (Double.compare(that.destTimestamp, destTimestamp) != 0) return false;
// if (Double.compare(that.origTimestamp, origTimestamp) != 0) return false;
// if (!dest.equals(that.dest)) return false;
// if (!orig.equals(that.orig)) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result;
// long temp;
// temp = Double.doubleToLongBits(origTimestamp);
// result = (int) (temp ^ (temp >>> 32));
// temp = Double.doubleToLongBits(destTimestamp);
// result = 31 * result + (int) (temp ^ (temp >>> 32));
// result = 31 * result + orig.hashCode();
// result = 31 * result + dest.hashCode();
// return result;
// }
//
// @Override
// public int compareTo(CepNetworkEvent o) {
// int ret = Double.compare(this.destTimestamp, o.destTimestamp);
// if (ret != 0) return ret;
//
// ret = Double.compare(this.origTimestamp, o.origTimestamp);
// if (ret != 0) return ret;
//
// ret = this.orig.compare(o.orig);
// if (ret != 0) return ret;
//
// return this.dest.compare(o.dest);
// }
// }
| import ca.uwo.eng.sel.cepsim.PlacementExecutor;
import ca.uwo.eng.sel.cepsim.history.History;
import ca.uwo.eng.sel.cepsim.history.SimEvent;
import ca.uwo.eng.sel.cepsim.metric.LatencyMetric;
import ca.uwo.eng.sel.cepsim.metric.LatencyThroughputCalculator;
import ca.uwo.eng.sel.cepsim.metric.MetricCalculator;
import ca.uwo.eng.sel.cepsim.metric.ThroughputMetric;
import ca.uwo.eng.sel.cepsim.network.CepNetworkEvent;
import ca.uwo.eng.sel.cepsim.query.Query;
import ca.uwo.eng.sel.cepsim.query.Vertex;
import org.cloudbus.cloudsim.Cloudlet;
import org.cloudbus.cloudsim.UtilizationModelFull;
import scala.Option;
import scala.collection.JavaConversions;
import java.util.*; | package ca.uwo.eng.sel.cepsim.integr;
public class CepQueryCloudlet extends Cloudlet {
private static final UtilizationModelFull UTIL_MODEL_FULL = new UtilizationModelFull();
private PlacementExecutor executor;
private History<SimEvent> history; | // Path: cepsim-integration/src/main/java/ca/uwo/eng/sel/cepsim/network/CepNetworkEvent.java
// public class CepNetworkEvent implements Comparable<CepNetworkEvent> {
//
// private double origTimestamp;
// private double destTimestamp;
// private OutputVertex orig;
// private InputVertex dest;
// private EventSet eventSet;
//
// public CepNetworkEvent(double origTimestamp, OutputVertex orig, double destTimestamp, InputVertex dest,
// EventSet eventSet) {
// this.origTimestamp = origTimestamp;
// this.destTimestamp = destTimestamp;
// this.orig = orig;
// this.dest = dest;
// this.eventSet = eventSet;
// }
//
// public double getOrigTimestamp() {
// return origTimestamp;
// }
//
// public OutputVertex getOrig() {
// return orig;
// }
//
// public double getDestTimestamp() {
// return destTimestamp;
// }
//
// public InputVertex getDest() {
// return dest;
// }
//
// public EventSet getEventSet() {
// return eventSet;
// }
//
//
// @Override
// public boolean equals(Object o) {
// if (this == o) return true;
// if (o == null || getClass() != o.getClass()) return false;
//
// CepNetworkEvent that = (CepNetworkEvent) o;
//
// if (Double.compare(that.destTimestamp, destTimestamp) != 0) return false;
// if (Double.compare(that.origTimestamp, origTimestamp) != 0) return false;
// if (!dest.equals(that.dest)) return false;
// if (!orig.equals(that.orig)) return false;
//
// return true;
// }
//
// @Override
// public int hashCode() {
// int result;
// long temp;
// temp = Double.doubleToLongBits(origTimestamp);
// result = (int) (temp ^ (temp >>> 32));
// temp = Double.doubleToLongBits(destTimestamp);
// result = 31 * result + (int) (temp ^ (temp >>> 32));
// result = 31 * result + orig.hashCode();
// result = 31 * result + dest.hashCode();
// return result;
// }
//
// @Override
// public int compareTo(CepNetworkEvent o) {
// int ret = Double.compare(this.destTimestamp, o.destTimestamp);
// if (ret != 0) return ret;
//
// ret = Double.compare(this.origTimestamp, o.origTimestamp);
// if (ret != 0) return ret;
//
// ret = this.orig.compare(o.orig);
// if (ret != 0) return ret;
//
// return this.dest.compare(o.dest);
// }
// }
// Path: cepsim-integration/src/main/java/ca/uwo/eng/sel/cepsim/integr/CepQueryCloudlet.java
import ca.uwo.eng.sel.cepsim.PlacementExecutor;
import ca.uwo.eng.sel.cepsim.history.History;
import ca.uwo.eng.sel.cepsim.history.SimEvent;
import ca.uwo.eng.sel.cepsim.metric.LatencyMetric;
import ca.uwo.eng.sel.cepsim.metric.LatencyThroughputCalculator;
import ca.uwo.eng.sel.cepsim.metric.MetricCalculator;
import ca.uwo.eng.sel.cepsim.metric.ThroughputMetric;
import ca.uwo.eng.sel.cepsim.network.CepNetworkEvent;
import ca.uwo.eng.sel.cepsim.query.Query;
import ca.uwo.eng.sel.cepsim.query.Vertex;
import org.cloudbus.cloudsim.Cloudlet;
import org.cloudbus.cloudsim.UtilizationModelFull;
import scala.Option;
import scala.collection.JavaConversions;
import java.util.*;
package ca.uwo.eng.sel.cepsim.integr;
public class CepQueryCloudlet extends Cloudlet {
private static final UtilizationModelFull UTIL_MODEL_FULL = new UtilizationModelFull();
private PlacementExecutor executor;
private History<SimEvent> history; | private Queue<CepNetworkEvent> networkEvents; |
tzaeschke/TinSpin | src/main/java/org/tinspin/data/hdf5/HDF5BlockSBHeader.java | // Path: src/main/java/org/tinspin/data/hdf5/HDF5BlockSNOD.java
// static class SymbolTableEntry extends HDF5Block {
// static final int SIZE = 40;
//
// //Link Name OffsetO
// long l0LinkNameOffsetO;
//
// //Object Header AddressO
// int l8ObjectHeaderAddressO;
//
// //Cache Type
// long i16CachedType;
//
// //Reserved (zero)
// long i20Zero;
//
// //Scratch-pad Space (16 bytes)
//
// //CT 1: Address of B-treeO
// long l24ct1addressBTreeO;
//
// //CT 1: Address of Name HeapO
// long l32ct1addressNameHeapO;
//
// //CT 2: Offset to Link Value (4 bytes)
// long i24ct2offsetToLink;
//
// public SymbolTableEntry(int offset, int version) {
// super(offset, version);
// }
//
// @Override
// public String toString() {
// String ret =
// "SymTE(" + getOffset() + ")" + Reader.L +
// //Link Name OffsetO
// "LinkNameOffset=" + l0LinkNameOffsetO + Reader.L +
//
// //Object Header AddressO
// "ObjectHeaderAddress=" + l8ObjectHeaderAddressO + Reader.L +
//
// //Cache Type
// "CachedType=" + i16CachedType + Reader.L;
//
// //Reserved (zero)
// //"Zero=" + i12Zero + Reader.L;
//
// //Scratch-pad Space (16 bytes)
//
// if (i16CachedType == 1) {
// ret +=
// //CT 1: Address of B-treeO
// "ct1addressBTreeO=" + l24ct1addressBTreeO + Reader.L +
//
// //CT 1: Address of Name HeapO
// "ct1addressNameHeapO=" + l32ct1addressNameHeapO;
// } else if (i16CachedType == 2) {
// ret +=
// //CT 2: Offset to Link Value (4 bytes)
// "ct2offsetToLink=" + i24ct2offsetToLink;
// }
// return ret;
// }
//
// public int getOffsetTREE() {
// if (i16CachedType == 1) {
// return (int) l24ct1addressBTreeO;
// } else if (i16CachedType == 2) {
// // ret +=
// // //CT 2: Offset to Link Value (4 bytes)
// // "ct2offsetToLink=" + i24ct2offsetToLink;
// }
// throw new UnsupportedOperationException();
// }
//
// public int getOffsetHEAP() {
// if (i16CachedType == 1) {
// return (int) l32ct1addressNameHeapO;
// } else if (i16CachedType == 2) {
// // ret +=
// // //CT 2: Offset to Link Value (4 bytes)
// // "ct2offsetToLink=" + i24ct2offsetToLink;
// }
// throw new UnsupportedOperationException();
// }
// }
| import org.tinspin.data.hdf5.HDF5BlockSNOD.SymbolTableEntry; | /*
* Copyright 2018 Tilmann Zäschke. All Rights Reserved.
*
* This software is the proprietary information of Tilmann Zäschke.
* Use is subject to license terms.
*/
package org.tinspin.data.hdf5;
/**
*/
class HDF5BlockSBHeader extends HDF5Block {
//Version # of Superblock
//int b8sbVersion;
//Version # of File's Free Space Storage
int b9ffssVersion;
//Version # of Root Group Symbol Table Entry
int b10rgsteVersion;
//Reserved (zero)
int b11zero;
//Version Number of Shared Header Message Format
int b12nshmfVersion;
//Size of Offsets
int b13sizeOfOffsets;
//Size of Lengths
int b14sizeOfLength;
//Reserved (zero)
int b15zero;
//b2 Group Leaf Node K
int s16gLeafNodeK;
//b2 Group Internal Node K
int s18gIntNodeK;
//b4 File Consistency Flags
int i20fcf;
//b2 Indexed Storage Internal Node K1
int s24isIntNodeK;
//b2 Reserved (zero)1
int s26zero;
//b8 Base AddressO
long l28baseAddrO;
//b8 Address of File Free space InfoO
long l36addrFFSIO;
//b8 End of File AddressO
long l44eofAddrO;
//b8 Driver Information Block AddressO
long l52dibAddrO;
//b4 Root Group Symbol Table Entry
//int i60rootGSTE;
//Root Group Symbol Table Entry | // Path: src/main/java/org/tinspin/data/hdf5/HDF5BlockSNOD.java
// static class SymbolTableEntry extends HDF5Block {
// static final int SIZE = 40;
//
// //Link Name OffsetO
// long l0LinkNameOffsetO;
//
// //Object Header AddressO
// int l8ObjectHeaderAddressO;
//
// //Cache Type
// long i16CachedType;
//
// //Reserved (zero)
// long i20Zero;
//
// //Scratch-pad Space (16 bytes)
//
// //CT 1: Address of B-treeO
// long l24ct1addressBTreeO;
//
// //CT 1: Address of Name HeapO
// long l32ct1addressNameHeapO;
//
// //CT 2: Offset to Link Value (4 bytes)
// long i24ct2offsetToLink;
//
// public SymbolTableEntry(int offset, int version) {
// super(offset, version);
// }
//
// @Override
// public String toString() {
// String ret =
// "SymTE(" + getOffset() + ")" + Reader.L +
// //Link Name OffsetO
// "LinkNameOffset=" + l0LinkNameOffsetO + Reader.L +
//
// //Object Header AddressO
// "ObjectHeaderAddress=" + l8ObjectHeaderAddressO + Reader.L +
//
// //Cache Type
// "CachedType=" + i16CachedType + Reader.L;
//
// //Reserved (zero)
// //"Zero=" + i12Zero + Reader.L;
//
// //Scratch-pad Space (16 bytes)
//
// if (i16CachedType == 1) {
// ret +=
// //CT 1: Address of B-treeO
// "ct1addressBTreeO=" + l24ct1addressBTreeO + Reader.L +
//
// //CT 1: Address of Name HeapO
// "ct1addressNameHeapO=" + l32ct1addressNameHeapO;
// } else if (i16CachedType == 2) {
// ret +=
// //CT 2: Offset to Link Value (4 bytes)
// "ct2offsetToLink=" + i24ct2offsetToLink;
// }
// return ret;
// }
//
// public int getOffsetTREE() {
// if (i16CachedType == 1) {
// return (int) l24ct1addressBTreeO;
// } else if (i16CachedType == 2) {
// // ret +=
// // //CT 2: Offset to Link Value (4 bytes)
// // "ct2offsetToLink=" + i24ct2offsetToLink;
// }
// throw new UnsupportedOperationException();
// }
//
// public int getOffsetHEAP() {
// if (i16CachedType == 1) {
// return (int) l32ct1addressNameHeapO;
// } else if (i16CachedType == 2) {
// // ret +=
// // //CT 2: Offset to Link Value (4 bytes)
// // "ct2offsetToLink=" + i24ct2offsetToLink;
// }
// throw new UnsupportedOperationException();
// }
// }
// Path: src/main/java/org/tinspin/data/hdf5/HDF5BlockSBHeader.java
import org.tinspin.data.hdf5.HDF5BlockSNOD.SymbolTableEntry;
/*
* Copyright 2018 Tilmann Zäschke. All Rights Reserved.
*
* This software is the proprietary information of Tilmann Zäschke.
* Use is subject to license terms.
*/
package org.tinspin.data.hdf5;
/**
*/
class HDF5BlockSBHeader extends HDF5Block {
//Version # of Superblock
//int b8sbVersion;
//Version # of File's Free Space Storage
int b9ffssVersion;
//Version # of Root Group Symbol Table Entry
int b10rgsteVersion;
//Reserved (zero)
int b11zero;
//Version Number of Shared Header Message Format
int b12nshmfVersion;
//Size of Offsets
int b13sizeOfOffsets;
//Size of Lengths
int b14sizeOfLength;
//Reserved (zero)
int b15zero;
//b2 Group Leaf Node K
int s16gLeafNodeK;
//b2 Group Internal Node K
int s18gIntNodeK;
//b4 File Consistency Flags
int i20fcf;
//b2 Indexed Storage Internal Node K1
int s24isIntNodeK;
//b2 Reserved (zero)1
int s26zero;
//b8 Base AddressO
long l28baseAddrO;
//b8 Address of File Free space InfoO
long l36addrFFSIO;
//b8 End of File AddressO
long l44eofAddrO;
//b8 Driver Information Block AddressO
long l52dibAddrO;
//b4 Root Group Symbol Table Entry
//int i60rootGSTE;
//Root Group Symbol Table Entry | SymbolTableEntry rootGroupSymbolTableEntry; |
tzaeschke/TinSpin | src/main/java/ch/ethz/globis/tinspin/util/rmi/TestManagerRMI.java | // Path: src/main/java/ch/ethz/globis/tinspin/util/rmi/TestRunnerLocal.java
// static class NoSecurityManager extends SecurityManager {
// @Override
// public void checkConnect (String host, int port) {}
// @Override
// public void checkConnect (String host, int port, Object context) {}
// @Override
// public void checkPropertyAccess(String key) {};
// @Override
// public void checkPermission(Permission perm) {};
// @Override
// public void checkPermission(Permission perm, Object context) {};
// @Override
// public void checkAccept(String host, int port) {};
// }
| import java.rmi.ConnectException;
import java.rmi.NotBoundException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import ch.ethz.globis.tinspin.TestStats;
import ch.ethz.globis.tinspin.util.rmi.TestRunnerLocal.NoSecurityManager; | /*
* Copyright 2011-2016 ETH Zurich. All Rights Reserved.
*
* This software is the proprietary information of ETH Zurich.
* Use is subject to license terms.
*/
package ch.ethz.globis.tinspin.util.rmi;
public class TestManagerRMI {
public static String PROCESS_OPTIONS = "-Xmx24G -XX:+UseConcMarkSweepGC";
private static final boolean USE_RMI = true;
static final String RMI_NAME = "TestRunnerRMI";
private static TestStats runRmiTest(TestStats stats0) {
TestProcessLauncher.launchRmiRegistry();
//Check whether there are already tests running
try {
Registry registry = LocateRegistry.getRegistry();
TestRunnerAPI comp = (TestRunnerAPI) registry.lookup(RMI_NAME);
if (comp.isAlive()) {
throw new IllegalStateException("Test process already running!");
}
} catch (NotBoundException e) {
//good!
} catch (ConnectException e) {
//good!
} catch (Exception e) {
throw new RuntimeException(e);
}
// start test process
System.out.println("Manager: starting task.");
//TestProcessLauncher.launchProcess("rmigegistry", new String[]{}); | // Path: src/main/java/ch/ethz/globis/tinspin/util/rmi/TestRunnerLocal.java
// static class NoSecurityManager extends SecurityManager {
// @Override
// public void checkConnect (String host, int port) {}
// @Override
// public void checkConnect (String host, int port, Object context) {}
// @Override
// public void checkPropertyAccess(String key) {};
// @Override
// public void checkPermission(Permission perm) {};
// @Override
// public void checkPermission(Permission perm, Object context) {};
// @Override
// public void checkAccept(String host, int port) {};
// }
// Path: src/main/java/ch/ethz/globis/tinspin/util/rmi/TestManagerRMI.java
import java.rmi.ConnectException;
import java.rmi.NotBoundException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import ch.ethz.globis.tinspin.TestStats;
import ch.ethz.globis.tinspin.util.rmi.TestRunnerLocal.NoSecurityManager;
/*
* Copyright 2011-2016 ETH Zurich. All Rights Reserved.
*
* This software is the proprietary information of ETH Zurich.
* Use is subject to license terms.
*/
package ch.ethz.globis.tinspin.util.rmi;
public class TestManagerRMI {
public static String PROCESS_OPTIONS = "-Xmx24G -XX:+UseConcMarkSweepGC";
private static final boolean USE_RMI = true;
static final String RMI_NAME = "TestRunnerRMI";
private static TestStats runRmiTest(TestStats stats0) {
TestProcessLauncher.launchRmiRegistry();
//Check whether there are already tests running
try {
Registry registry = LocateRegistry.getRegistry();
TestRunnerAPI comp = (TestRunnerAPI) registry.lookup(RMI_NAME);
if (comp.isAlive()) {
throw new IllegalStateException("Test process already running!");
}
} catch (NotBoundException e) {
//good!
} catch (ConnectException e) {
//good!
} catch (Exception e) {
throw new RuntimeException(e);
}
// start test process
System.out.println("Manager: starting task.");
//TestProcessLauncher.launchProcess("rmigegistry", new String[]{}); | System.setSecurityManager (new NoSecurityManager()); |
tzaeschke/TinSpin | src/main/java/org/tinspin/data/hdf5/Reader.java | // Path: src/main/java/org/tinspin/data/hdf5/HDF5BlockSNOD.java
// static class SymbolTableEntry extends HDF5Block {
// static final int SIZE = 40;
//
// //Link Name OffsetO
// long l0LinkNameOffsetO;
//
// //Object Header AddressO
// int l8ObjectHeaderAddressO;
//
// //Cache Type
// long i16CachedType;
//
// //Reserved (zero)
// long i20Zero;
//
// //Scratch-pad Space (16 bytes)
//
// //CT 1: Address of B-treeO
// long l24ct1addressBTreeO;
//
// //CT 1: Address of Name HeapO
// long l32ct1addressNameHeapO;
//
// //CT 2: Offset to Link Value (4 bytes)
// long i24ct2offsetToLink;
//
// public SymbolTableEntry(int offset, int version) {
// super(offset, version);
// }
//
// @Override
// public String toString() {
// String ret =
// "SymTE(" + getOffset() + ")" + Reader.L +
// //Link Name OffsetO
// "LinkNameOffset=" + l0LinkNameOffsetO + Reader.L +
//
// //Object Header AddressO
// "ObjectHeaderAddress=" + l8ObjectHeaderAddressO + Reader.L +
//
// //Cache Type
// "CachedType=" + i16CachedType + Reader.L;
//
// //Reserved (zero)
// //"Zero=" + i12Zero + Reader.L;
//
// //Scratch-pad Space (16 bytes)
//
// if (i16CachedType == 1) {
// ret +=
// //CT 1: Address of B-treeO
// "ct1addressBTreeO=" + l24ct1addressBTreeO + Reader.L +
//
// //CT 1: Address of Name HeapO
// "ct1addressNameHeapO=" + l32ct1addressNameHeapO;
// } else if (i16CachedType == 2) {
// ret +=
// //CT 2: Offset to Link Value (4 bytes)
// "ct2offsetToLink=" + i24ct2offsetToLink;
// }
// return ret;
// }
//
// public int getOffsetTREE() {
// if (i16CachedType == 1) {
// return (int) l24ct1addressBTreeO;
// } else if (i16CachedType == 2) {
// // ret +=
// // //CT 2: Offset to Link Value (4 bytes)
// // "ct2offsetToLink=" + i24ct2offsetToLink;
// }
// throw new UnsupportedOperationException();
// }
//
// public int getOffsetHEAP() {
// if (i16CachedType == 1) {
// return (int) l32ct1addressNameHeapO;
// } else if (i16CachedType == 2) {
// // ret +=
// // //CT 2: Offset to Link Value (4 bytes)
// // "ct2offsetToLink=" + i24ct2offsetToLink;
// }
// throw new UnsupportedOperationException();
// }
// }
| import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.Objects;
import org.tinspin.data.hdf5.HDF5BlockSNOD.SymbolTableEntry; |
sb.rootGroupSymbolTableEntry = readSymbolTableEntry(bb, sLen, sOffs);
//sb.i60rootGSTE = read4(bb);
//sb.rootGroupSymbolTableEntryHEADER = readDOHeaderPrefix(bb, sb.rootGroupSymbolTableEntry.l8ObjectHeaderAddressO);
skipTo(bb, sb.rootGroupSymbolTableEntry.l8ObjectHeaderAddressO);
sb.rootGroupSymbolTableEntryHEADER = readDOHeaderPrefix(bb, sb);
//Not specified, but appears to be the case...
alignPos8(bb);
Group rootGroup = new Group();
skipTo(bb, sb.rootGroupSymbolTableEntry.getOffsetTREE());
readSignature(bb, BLOCK_ID_TREE);
rootGroup.tree = readTREE(bb, sLen, sOffs, sb);
skipTo(bb, sb.rootGroupSymbolTableEntry.getOffsetHEAP());
readSignature(bb, BLOCK_ID_HEAP);
rootGroup.heap = readHEAP(bb, sLen, sOffs);
alignPos8(bb);
// readAny(bb, sb, 1_200);
//read B-Tree SNOD
skipTo(bb, (int) rootGroup.tree.childPointers[0]);
readSignature(bb, BLOCK_ID_SNOD);
HDF5BlockSNOD rootSNOD = readSNOD(bb, sLen, sOffs, sb);
ArrayList<HDF5Dataset> data = new ArrayList<>();
for (int i = 0; i < rootSNOD.symbols.length; i++) { | // Path: src/main/java/org/tinspin/data/hdf5/HDF5BlockSNOD.java
// static class SymbolTableEntry extends HDF5Block {
// static final int SIZE = 40;
//
// //Link Name OffsetO
// long l0LinkNameOffsetO;
//
// //Object Header AddressO
// int l8ObjectHeaderAddressO;
//
// //Cache Type
// long i16CachedType;
//
// //Reserved (zero)
// long i20Zero;
//
// //Scratch-pad Space (16 bytes)
//
// //CT 1: Address of B-treeO
// long l24ct1addressBTreeO;
//
// //CT 1: Address of Name HeapO
// long l32ct1addressNameHeapO;
//
// //CT 2: Offset to Link Value (4 bytes)
// long i24ct2offsetToLink;
//
// public SymbolTableEntry(int offset, int version) {
// super(offset, version);
// }
//
// @Override
// public String toString() {
// String ret =
// "SymTE(" + getOffset() + ")" + Reader.L +
// //Link Name OffsetO
// "LinkNameOffset=" + l0LinkNameOffsetO + Reader.L +
//
// //Object Header AddressO
// "ObjectHeaderAddress=" + l8ObjectHeaderAddressO + Reader.L +
//
// //Cache Type
// "CachedType=" + i16CachedType + Reader.L;
//
// //Reserved (zero)
// //"Zero=" + i12Zero + Reader.L;
//
// //Scratch-pad Space (16 bytes)
//
// if (i16CachedType == 1) {
// ret +=
// //CT 1: Address of B-treeO
// "ct1addressBTreeO=" + l24ct1addressBTreeO + Reader.L +
//
// //CT 1: Address of Name HeapO
// "ct1addressNameHeapO=" + l32ct1addressNameHeapO;
// } else if (i16CachedType == 2) {
// ret +=
// //CT 2: Offset to Link Value (4 bytes)
// "ct2offsetToLink=" + i24ct2offsetToLink;
// }
// return ret;
// }
//
// public int getOffsetTREE() {
// if (i16CachedType == 1) {
// return (int) l24ct1addressBTreeO;
// } else if (i16CachedType == 2) {
// // ret +=
// // //CT 2: Offset to Link Value (4 bytes)
// // "ct2offsetToLink=" + i24ct2offsetToLink;
// }
// throw new UnsupportedOperationException();
// }
//
// public int getOffsetHEAP() {
// if (i16CachedType == 1) {
// return (int) l32ct1addressNameHeapO;
// } else if (i16CachedType == 2) {
// // ret +=
// // //CT 2: Offset to Link Value (4 bytes)
// // "ct2offsetToLink=" + i24ct2offsetToLink;
// }
// throw new UnsupportedOperationException();
// }
// }
// Path: src/main/java/org/tinspin/data/hdf5/Reader.java
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.Objects;
import org.tinspin.data.hdf5.HDF5BlockSNOD.SymbolTableEntry;
sb.rootGroupSymbolTableEntry = readSymbolTableEntry(bb, sLen, sOffs);
//sb.i60rootGSTE = read4(bb);
//sb.rootGroupSymbolTableEntryHEADER = readDOHeaderPrefix(bb, sb.rootGroupSymbolTableEntry.l8ObjectHeaderAddressO);
skipTo(bb, sb.rootGroupSymbolTableEntry.l8ObjectHeaderAddressO);
sb.rootGroupSymbolTableEntryHEADER = readDOHeaderPrefix(bb, sb);
//Not specified, but appears to be the case...
alignPos8(bb);
Group rootGroup = new Group();
skipTo(bb, sb.rootGroupSymbolTableEntry.getOffsetTREE());
readSignature(bb, BLOCK_ID_TREE);
rootGroup.tree = readTREE(bb, sLen, sOffs, sb);
skipTo(bb, sb.rootGroupSymbolTableEntry.getOffsetHEAP());
readSignature(bb, BLOCK_ID_HEAP);
rootGroup.heap = readHEAP(bb, sLen, sOffs);
alignPos8(bb);
// readAny(bb, sb, 1_200);
//read B-Tree SNOD
skipTo(bb, (int) rootGroup.tree.childPointers[0]);
readSignature(bb, BLOCK_ID_SNOD);
HDF5BlockSNOD rootSNOD = readSNOD(bb, sLen, sOffs, sb);
ArrayList<HDF5Dataset> data = new ArrayList<>();
for (int i = 0; i < rootSNOD.symbols.length; i++) { | SymbolTableEntry ste = rootSNOD.symbols[i]; |
tzaeschke/TinSpin | src/main/java/org/tinspin/data/hdf5/HDF5BlockHEAP.java | // Path: src/main/java/org/tinspin/data/hdf5/HDF5BlockSNOD.java
// static class SymbolTableEntry extends HDF5Block {
// static final int SIZE = 40;
//
// //Link Name OffsetO
// long l0LinkNameOffsetO;
//
// //Object Header AddressO
// int l8ObjectHeaderAddressO;
//
// //Cache Type
// long i16CachedType;
//
// //Reserved (zero)
// long i20Zero;
//
// //Scratch-pad Space (16 bytes)
//
// //CT 1: Address of B-treeO
// long l24ct1addressBTreeO;
//
// //CT 1: Address of Name HeapO
// long l32ct1addressNameHeapO;
//
// //CT 2: Offset to Link Value (4 bytes)
// long i24ct2offsetToLink;
//
// public SymbolTableEntry(int offset, int version) {
// super(offset, version);
// }
//
// @Override
// public String toString() {
// String ret =
// "SymTE(" + getOffset() + ")" + Reader.L +
// //Link Name OffsetO
// "LinkNameOffset=" + l0LinkNameOffsetO + Reader.L +
//
// //Object Header AddressO
// "ObjectHeaderAddress=" + l8ObjectHeaderAddressO + Reader.L +
//
// //Cache Type
// "CachedType=" + i16CachedType + Reader.L;
//
// //Reserved (zero)
// //"Zero=" + i12Zero + Reader.L;
//
// //Scratch-pad Space (16 bytes)
//
// if (i16CachedType == 1) {
// ret +=
// //CT 1: Address of B-treeO
// "ct1addressBTreeO=" + l24ct1addressBTreeO + Reader.L +
//
// //CT 1: Address of Name HeapO
// "ct1addressNameHeapO=" + l32ct1addressNameHeapO;
// } else if (i16CachedType == 2) {
// ret +=
// //CT 2: Offset to Link Value (4 bytes)
// "ct2offsetToLink=" + i24ct2offsetToLink;
// }
// return ret;
// }
//
// public int getOffsetTREE() {
// if (i16CachedType == 1) {
// return (int) l24ct1addressBTreeO;
// } else if (i16CachedType == 2) {
// // ret +=
// // //CT 2: Offset to Link Value (4 bytes)
// // "ct2offsetToLink=" + i24ct2offsetToLink;
// }
// throw new UnsupportedOperationException();
// }
//
// public int getOffsetHEAP() {
// if (i16CachedType == 1) {
// return (int) l32ct1addressNameHeapO;
// } else if (i16CachedType == 2) {
// // ret +=
// // //CT 2: Offset to Link Value (4 bytes)
// // "ct2offsetToLink=" + i24ct2offsetToLink;
// }
// throw new UnsupportedOperationException();
// }
// }
| import java.util.Arrays;
import org.tinspin.data.hdf5.HDF5BlockSNOD.SymbolTableEntry; | /*
* Copyright 2018 Tilmann Zäschke. All Rights Reserved.
*
* This software is the proprietary information of Tilmann Zäschke.
* Use is subject to license terms.
*/
package org.tinspin.data.hdf5;
class HDF5BlockHEAP extends HDF5Block {
//Signature
int i0Signature;
//Version
//int b4Version;
//Reserved (zero)
int b5Zero;
int b6Zero;
int b7Zero;
//Data Segment SizeL
long l8dataSegmentSize;
//Offset to Head of Free-listL
long l16freeListOffset;
//Address of Data SegmentO
long l24dataSegementOffset;
String[] heap;
int[] heapOffset;
int heapSize = 0;
public HDF5BlockHEAP(int offset, int version) {
super(offset, version);
}
@Override
public String toString() {
return "HEAP(" + getOffset() + ")" + Reader.L +
// //Signature
// "Signature=" + i0Signature + Reader.L +
//Version
"Version=" + getVersion() + Reader.L +
//Reserved (zero)
//"" + b5Zero + L +
//"" + b6Zero + L +
//"" + b7Zero + L +
//Data Segment SizeL
"dataSegmentSize=" + l8dataSegmentSize + Reader.L +
//Offset to Head of Free-listL
"freeListOffset=" + l16freeListOffset + Reader.L +
//Address of Data SegmentO
"dataSegementOffset=" + l24dataSegementOffset;
}
| // Path: src/main/java/org/tinspin/data/hdf5/HDF5BlockSNOD.java
// static class SymbolTableEntry extends HDF5Block {
// static final int SIZE = 40;
//
// //Link Name OffsetO
// long l0LinkNameOffsetO;
//
// //Object Header AddressO
// int l8ObjectHeaderAddressO;
//
// //Cache Type
// long i16CachedType;
//
// //Reserved (zero)
// long i20Zero;
//
// //Scratch-pad Space (16 bytes)
//
// //CT 1: Address of B-treeO
// long l24ct1addressBTreeO;
//
// //CT 1: Address of Name HeapO
// long l32ct1addressNameHeapO;
//
// //CT 2: Offset to Link Value (4 bytes)
// long i24ct2offsetToLink;
//
// public SymbolTableEntry(int offset, int version) {
// super(offset, version);
// }
//
// @Override
// public String toString() {
// String ret =
// "SymTE(" + getOffset() + ")" + Reader.L +
// //Link Name OffsetO
// "LinkNameOffset=" + l0LinkNameOffsetO + Reader.L +
//
// //Object Header AddressO
// "ObjectHeaderAddress=" + l8ObjectHeaderAddressO + Reader.L +
//
// //Cache Type
// "CachedType=" + i16CachedType + Reader.L;
//
// //Reserved (zero)
// //"Zero=" + i12Zero + Reader.L;
//
// //Scratch-pad Space (16 bytes)
//
// if (i16CachedType == 1) {
// ret +=
// //CT 1: Address of B-treeO
// "ct1addressBTreeO=" + l24ct1addressBTreeO + Reader.L +
//
// //CT 1: Address of Name HeapO
// "ct1addressNameHeapO=" + l32ct1addressNameHeapO;
// } else if (i16CachedType == 2) {
// ret +=
// //CT 2: Offset to Link Value (4 bytes)
// "ct2offsetToLink=" + i24ct2offsetToLink;
// }
// return ret;
// }
//
// public int getOffsetTREE() {
// if (i16CachedType == 1) {
// return (int) l24ct1addressBTreeO;
// } else if (i16CachedType == 2) {
// // ret +=
// // //CT 2: Offset to Link Value (4 bytes)
// // "ct2offsetToLink=" + i24ct2offsetToLink;
// }
// throw new UnsupportedOperationException();
// }
//
// public int getOffsetHEAP() {
// if (i16CachedType == 1) {
// return (int) l32ct1addressNameHeapO;
// } else if (i16CachedType == 2) {
// // ret +=
// // //CT 2: Offset to Link Value (4 bytes)
// // "ct2offsetToLink=" + i24ct2offsetToLink;
// }
// throw new UnsupportedOperationException();
// }
// }
// Path: src/main/java/org/tinspin/data/hdf5/HDF5BlockHEAP.java
import java.util.Arrays;
import org.tinspin.data.hdf5.HDF5BlockSNOD.SymbolTableEntry;
/*
* Copyright 2018 Tilmann Zäschke. All Rights Reserved.
*
* This software is the proprietary information of Tilmann Zäschke.
* Use is subject to license terms.
*/
package org.tinspin.data.hdf5;
class HDF5BlockHEAP extends HDF5Block {
//Signature
int i0Signature;
//Version
//int b4Version;
//Reserved (zero)
int b5Zero;
int b6Zero;
int b7Zero;
//Data Segment SizeL
long l8dataSegmentSize;
//Offset to Head of Free-listL
long l16freeListOffset;
//Address of Data SegmentO
long l24dataSegementOffset;
String[] heap;
int[] heapOffset;
int heapSize = 0;
public HDF5BlockHEAP(int offset, int version) {
super(offset, version);
}
@Override
public String toString() {
return "HEAP(" + getOffset() + ")" + Reader.L +
// //Signature
// "Signature=" + i0Signature + Reader.L +
//Version
"Version=" + getVersion() + Reader.L +
//Reserved (zero)
//"" + b5Zero + L +
//"" + b6Zero + L +
//"" + b7Zero + L +
//Data Segment SizeL
"dataSegmentSize=" + l8dataSegmentSize + Reader.L +
//Offset to Head of Free-listL
"freeListOffset=" + l16freeListOffset + Reader.L +
//Address of Data SegmentO
"dataSegementOffset=" + l24dataSegementOffset;
}
| public String getLinkName(SymbolTableEntry ste) { |
jcgay/send-notification | send-notification/src/main/java/fr/jcgay/notification/notifier/additional/AdditionalNotifier.java | // Path: send-notification/src/main/java/fr/jcgay/notification/DiscoverableNotifier.java
// public interface DiscoverableNotifier extends Notifier {
//
// /**
// * Initialize before usage. <br>
// * This method must be called before trying to send a notification. <br>
// * Calling {@code init()} multiple time should not fail. <br>
// *
// * For example a notifier can open a connection to register the application, or it can do nothing.
// *
// * @return a usable initiated {@link Notifier} to send notification(s)
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// Notifier init();
//
// boolean tryInit();
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/MultipleSendNotificationException.java
// public class MultipleSendNotificationException extends SendNotificationException {
//
// private List<Exception> errors;
//
// public MultipleSendNotificationException(List<Exception> errors) {
// super(messages(checkNotNull(errors)));
// this.errors = errors;
// }
//
// public List<Exception> getErrors() {
// return Collections.unmodifiableList(errors);
// }
//
// private static String messages(List<Exception> errors) {
// Iterator<Exception> iterator = errors.iterator();
// StringBuilder messages = new StringBuilder(iterator.next().getMessage());
// while (iterator.hasNext()) {
// Exception error = iterator.next();
// if (error.getMessage() != null) {
// messages.append(String.format("%n%s", error.getMessage()));
// }
// }
// return messages.toString();
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notification.java
// @AutoValue
// public abstract class Notification {
//
// /**
// * Indicate notification priority.
// */
// public enum Level {INFO, WARNING, ERROR}
//
// /**
// * Notification message.
// *
// * @return message.
// */
// public abstract String message();
//
// /**
// * Notification title.
// *
// * @return title.
// */
// public abstract String title();
//
// /**
// * Notification subtitle. <br>
// * Not available for all notifier implementation.
// *
// * @return subtitle.
// */
// @Nullable
// public abstract String subtitle();
//
// /**
// * Notification icon.
// *
// * @return icon.
// */
// public abstract Icon icon();
//
// /**
// * Indicate the notification priority type.
// *
// * @return type
// */
// public abstract Level level();
//
// Notification() {
// // prevent external subclasses
// }
//
// public static Builder builder(String title, String message, Icon icon) {
// return builder()
// .title(title)
// .message(message)
// .icon(icon);
// }
//
// public static Builder builder() {
// return new AutoValue_Notification.Builder().level(INFO);
// }
//
// @AutoValue.Builder
// public interface Builder {
// Builder title(String title);
// Builder message(String message);
// Builder icon(Icon icon);
// Builder subtitle(String subtitle);
// Builder level(Level level);
// Notification build();
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notifier.java
// public interface Notifier {
//
// /**
// * Send a notification.
// *
// * @param notification a notification.
// *
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// void send(Notification notification);
//
// /**
// * Close the notifier. <br>
// * This method must be called to release resources when the notifier is not needed anymore.
// */
// void close();
//
// /**
// * Indicate if the notifier is always displayed somewhere (menu/task bar, etc).
// * @return {@code true} if the notifier is persistent.
// */
// boolean isPersistent();
// }
| import com.google.common.base.MoreObjects;
import com.google.common.base.Objects;
import fr.jcgay.notification.DiscoverableNotifier;
import fr.jcgay.notification.MultipleSendNotificationException;
import fr.jcgay.notification.Notification;
import fr.jcgay.notification.Notifier;
import org.slf4j.Logger;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static org.slf4j.LoggerFactory.getLogger; | package fr.jcgay.notification.notifier.additional;
public class AdditionalNotifier implements DiscoverableNotifier {
private static final Logger LOGGER = getLogger(AdditionalNotifier.class);
private final Set<DiscoverableNotifier> secondary;
private final DiscoverableNotifier primary;
private final boolean notifyWithSecondaryNotifiers;
public AdditionalNotifier(DiscoverableNotifier primary, Set<DiscoverableNotifier> secondary) {
checkArgument(!secondary.isEmpty());
this.primary = checkNotNull(primary);
this.secondary = secondary;
this.notifyWithSecondaryNotifiers = Boolean.valueOf(System.getProperty("notifyAll"));
}
@Override | // Path: send-notification/src/main/java/fr/jcgay/notification/DiscoverableNotifier.java
// public interface DiscoverableNotifier extends Notifier {
//
// /**
// * Initialize before usage. <br>
// * This method must be called before trying to send a notification. <br>
// * Calling {@code init()} multiple time should not fail. <br>
// *
// * For example a notifier can open a connection to register the application, or it can do nothing.
// *
// * @return a usable initiated {@link Notifier} to send notification(s)
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// Notifier init();
//
// boolean tryInit();
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/MultipleSendNotificationException.java
// public class MultipleSendNotificationException extends SendNotificationException {
//
// private List<Exception> errors;
//
// public MultipleSendNotificationException(List<Exception> errors) {
// super(messages(checkNotNull(errors)));
// this.errors = errors;
// }
//
// public List<Exception> getErrors() {
// return Collections.unmodifiableList(errors);
// }
//
// private static String messages(List<Exception> errors) {
// Iterator<Exception> iterator = errors.iterator();
// StringBuilder messages = new StringBuilder(iterator.next().getMessage());
// while (iterator.hasNext()) {
// Exception error = iterator.next();
// if (error.getMessage() != null) {
// messages.append(String.format("%n%s", error.getMessage()));
// }
// }
// return messages.toString();
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notification.java
// @AutoValue
// public abstract class Notification {
//
// /**
// * Indicate notification priority.
// */
// public enum Level {INFO, WARNING, ERROR}
//
// /**
// * Notification message.
// *
// * @return message.
// */
// public abstract String message();
//
// /**
// * Notification title.
// *
// * @return title.
// */
// public abstract String title();
//
// /**
// * Notification subtitle. <br>
// * Not available for all notifier implementation.
// *
// * @return subtitle.
// */
// @Nullable
// public abstract String subtitle();
//
// /**
// * Notification icon.
// *
// * @return icon.
// */
// public abstract Icon icon();
//
// /**
// * Indicate the notification priority type.
// *
// * @return type
// */
// public abstract Level level();
//
// Notification() {
// // prevent external subclasses
// }
//
// public static Builder builder(String title, String message, Icon icon) {
// return builder()
// .title(title)
// .message(message)
// .icon(icon);
// }
//
// public static Builder builder() {
// return new AutoValue_Notification.Builder().level(INFO);
// }
//
// @AutoValue.Builder
// public interface Builder {
// Builder title(String title);
// Builder message(String message);
// Builder icon(Icon icon);
// Builder subtitle(String subtitle);
// Builder level(Level level);
// Notification build();
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notifier.java
// public interface Notifier {
//
// /**
// * Send a notification.
// *
// * @param notification a notification.
// *
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// void send(Notification notification);
//
// /**
// * Close the notifier. <br>
// * This method must be called to release resources when the notifier is not needed anymore.
// */
// void close();
//
// /**
// * Indicate if the notifier is always displayed somewhere (menu/task bar, etc).
// * @return {@code true} if the notifier is persistent.
// */
// boolean isPersistent();
// }
// Path: send-notification/src/main/java/fr/jcgay/notification/notifier/additional/AdditionalNotifier.java
import com.google.common.base.MoreObjects;
import com.google.common.base.Objects;
import fr.jcgay.notification.DiscoverableNotifier;
import fr.jcgay.notification.MultipleSendNotificationException;
import fr.jcgay.notification.Notification;
import fr.jcgay.notification.Notifier;
import org.slf4j.Logger;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static org.slf4j.LoggerFactory.getLogger;
package fr.jcgay.notification.notifier.additional;
public class AdditionalNotifier implements DiscoverableNotifier {
private static final Logger LOGGER = getLogger(AdditionalNotifier.class);
private final Set<DiscoverableNotifier> secondary;
private final DiscoverableNotifier primary;
private final boolean notifyWithSecondaryNotifiers;
public AdditionalNotifier(DiscoverableNotifier primary, Set<DiscoverableNotifier> secondary) {
checkArgument(!secondary.isEmpty());
this.primary = checkNotNull(primary);
this.secondary = secondary;
this.notifyWithSecondaryNotifiers = Boolean.valueOf(System.getProperty("notifyAll"));
}
@Override | public Notifier init() { |
jcgay/send-notification | send-notification/src/main/java/fr/jcgay/notification/notifier/additional/AdditionalNotifier.java | // Path: send-notification/src/main/java/fr/jcgay/notification/DiscoverableNotifier.java
// public interface DiscoverableNotifier extends Notifier {
//
// /**
// * Initialize before usage. <br>
// * This method must be called before trying to send a notification. <br>
// * Calling {@code init()} multiple time should not fail. <br>
// *
// * For example a notifier can open a connection to register the application, or it can do nothing.
// *
// * @return a usable initiated {@link Notifier} to send notification(s)
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// Notifier init();
//
// boolean tryInit();
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/MultipleSendNotificationException.java
// public class MultipleSendNotificationException extends SendNotificationException {
//
// private List<Exception> errors;
//
// public MultipleSendNotificationException(List<Exception> errors) {
// super(messages(checkNotNull(errors)));
// this.errors = errors;
// }
//
// public List<Exception> getErrors() {
// return Collections.unmodifiableList(errors);
// }
//
// private static String messages(List<Exception> errors) {
// Iterator<Exception> iterator = errors.iterator();
// StringBuilder messages = new StringBuilder(iterator.next().getMessage());
// while (iterator.hasNext()) {
// Exception error = iterator.next();
// if (error.getMessage() != null) {
// messages.append(String.format("%n%s", error.getMessage()));
// }
// }
// return messages.toString();
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notification.java
// @AutoValue
// public abstract class Notification {
//
// /**
// * Indicate notification priority.
// */
// public enum Level {INFO, WARNING, ERROR}
//
// /**
// * Notification message.
// *
// * @return message.
// */
// public abstract String message();
//
// /**
// * Notification title.
// *
// * @return title.
// */
// public abstract String title();
//
// /**
// * Notification subtitle. <br>
// * Not available for all notifier implementation.
// *
// * @return subtitle.
// */
// @Nullable
// public abstract String subtitle();
//
// /**
// * Notification icon.
// *
// * @return icon.
// */
// public abstract Icon icon();
//
// /**
// * Indicate the notification priority type.
// *
// * @return type
// */
// public abstract Level level();
//
// Notification() {
// // prevent external subclasses
// }
//
// public static Builder builder(String title, String message, Icon icon) {
// return builder()
// .title(title)
// .message(message)
// .icon(icon);
// }
//
// public static Builder builder() {
// return new AutoValue_Notification.Builder().level(INFO);
// }
//
// @AutoValue.Builder
// public interface Builder {
// Builder title(String title);
// Builder message(String message);
// Builder icon(Icon icon);
// Builder subtitle(String subtitle);
// Builder level(Level level);
// Notification build();
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notifier.java
// public interface Notifier {
//
// /**
// * Send a notification.
// *
// * @param notification a notification.
// *
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// void send(Notification notification);
//
// /**
// * Close the notifier. <br>
// * This method must be called to release resources when the notifier is not needed anymore.
// */
// void close();
//
// /**
// * Indicate if the notifier is always displayed somewhere (menu/task bar, etc).
// * @return {@code true} if the notifier is persistent.
// */
// boolean isPersistent();
// }
| import com.google.common.base.MoreObjects;
import com.google.common.base.Objects;
import fr.jcgay.notification.DiscoverableNotifier;
import fr.jcgay.notification.MultipleSendNotificationException;
import fr.jcgay.notification.Notification;
import fr.jcgay.notification.Notifier;
import org.slf4j.Logger;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static org.slf4j.LoggerFactory.getLogger; | package fr.jcgay.notification.notifier.additional;
public class AdditionalNotifier implements DiscoverableNotifier {
private static final Logger LOGGER = getLogger(AdditionalNotifier.class);
private final Set<DiscoverableNotifier> secondary;
private final DiscoverableNotifier primary;
private final boolean notifyWithSecondaryNotifiers;
public AdditionalNotifier(DiscoverableNotifier primary, Set<DiscoverableNotifier> secondary) {
checkArgument(!secondary.isEmpty());
this.primary = checkNotNull(primary);
this.secondary = secondary;
this.notifyWithSecondaryNotifiers = Boolean.valueOf(System.getProperty("notifyAll"));
}
@Override
public Notifier init() {
List<Exception> errors = new ArrayList<>();
safeInit(primary, errors);
if (notifyWithSecondaryNotifiers) {
for (DiscoverableNotifier notifier : secondary) {
safeInit(notifier, errors);
}
}
failIfNotEmpty(errors);
return this;
}
@Override
public boolean tryInit() {
return false;
}
@Override | // Path: send-notification/src/main/java/fr/jcgay/notification/DiscoverableNotifier.java
// public interface DiscoverableNotifier extends Notifier {
//
// /**
// * Initialize before usage. <br>
// * This method must be called before trying to send a notification. <br>
// * Calling {@code init()} multiple time should not fail. <br>
// *
// * For example a notifier can open a connection to register the application, or it can do nothing.
// *
// * @return a usable initiated {@link Notifier} to send notification(s)
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// Notifier init();
//
// boolean tryInit();
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/MultipleSendNotificationException.java
// public class MultipleSendNotificationException extends SendNotificationException {
//
// private List<Exception> errors;
//
// public MultipleSendNotificationException(List<Exception> errors) {
// super(messages(checkNotNull(errors)));
// this.errors = errors;
// }
//
// public List<Exception> getErrors() {
// return Collections.unmodifiableList(errors);
// }
//
// private static String messages(List<Exception> errors) {
// Iterator<Exception> iterator = errors.iterator();
// StringBuilder messages = new StringBuilder(iterator.next().getMessage());
// while (iterator.hasNext()) {
// Exception error = iterator.next();
// if (error.getMessage() != null) {
// messages.append(String.format("%n%s", error.getMessage()));
// }
// }
// return messages.toString();
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notification.java
// @AutoValue
// public abstract class Notification {
//
// /**
// * Indicate notification priority.
// */
// public enum Level {INFO, WARNING, ERROR}
//
// /**
// * Notification message.
// *
// * @return message.
// */
// public abstract String message();
//
// /**
// * Notification title.
// *
// * @return title.
// */
// public abstract String title();
//
// /**
// * Notification subtitle. <br>
// * Not available for all notifier implementation.
// *
// * @return subtitle.
// */
// @Nullable
// public abstract String subtitle();
//
// /**
// * Notification icon.
// *
// * @return icon.
// */
// public abstract Icon icon();
//
// /**
// * Indicate the notification priority type.
// *
// * @return type
// */
// public abstract Level level();
//
// Notification() {
// // prevent external subclasses
// }
//
// public static Builder builder(String title, String message, Icon icon) {
// return builder()
// .title(title)
// .message(message)
// .icon(icon);
// }
//
// public static Builder builder() {
// return new AutoValue_Notification.Builder().level(INFO);
// }
//
// @AutoValue.Builder
// public interface Builder {
// Builder title(String title);
// Builder message(String message);
// Builder icon(Icon icon);
// Builder subtitle(String subtitle);
// Builder level(Level level);
// Notification build();
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notifier.java
// public interface Notifier {
//
// /**
// * Send a notification.
// *
// * @param notification a notification.
// *
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// void send(Notification notification);
//
// /**
// * Close the notifier. <br>
// * This method must be called to release resources when the notifier is not needed anymore.
// */
// void close();
//
// /**
// * Indicate if the notifier is always displayed somewhere (menu/task bar, etc).
// * @return {@code true} if the notifier is persistent.
// */
// boolean isPersistent();
// }
// Path: send-notification/src/main/java/fr/jcgay/notification/notifier/additional/AdditionalNotifier.java
import com.google.common.base.MoreObjects;
import com.google.common.base.Objects;
import fr.jcgay.notification.DiscoverableNotifier;
import fr.jcgay.notification.MultipleSendNotificationException;
import fr.jcgay.notification.Notification;
import fr.jcgay.notification.Notifier;
import org.slf4j.Logger;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static org.slf4j.LoggerFactory.getLogger;
package fr.jcgay.notification.notifier.additional;
public class AdditionalNotifier implements DiscoverableNotifier {
private static final Logger LOGGER = getLogger(AdditionalNotifier.class);
private final Set<DiscoverableNotifier> secondary;
private final DiscoverableNotifier primary;
private final boolean notifyWithSecondaryNotifiers;
public AdditionalNotifier(DiscoverableNotifier primary, Set<DiscoverableNotifier> secondary) {
checkArgument(!secondary.isEmpty());
this.primary = checkNotNull(primary);
this.secondary = secondary;
this.notifyWithSecondaryNotifiers = Boolean.valueOf(System.getProperty("notifyAll"));
}
@Override
public Notifier init() {
List<Exception> errors = new ArrayList<>();
safeInit(primary, errors);
if (notifyWithSecondaryNotifiers) {
for (DiscoverableNotifier notifier : secondary) {
safeInit(notifier, errors);
}
}
failIfNotEmpty(errors);
return this;
}
@Override
public boolean tryInit() {
return false;
}
@Override | public void send(Notification notification) { |
jcgay/send-notification | send-notification/src/main/java/fr/jcgay/notification/notifier/additional/AdditionalNotifier.java | // Path: send-notification/src/main/java/fr/jcgay/notification/DiscoverableNotifier.java
// public interface DiscoverableNotifier extends Notifier {
//
// /**
// * Initialize before usage. <br>
// * This method must be called before trying to send a notification. <br>
// * Calling {@code init()} multiple time should not fail. <br>
// *
// * For example a notifier can open a connection to register the application, or it can do nothing.
// *
// * @return a usable initiated {@link Notifier} to send notification(s)
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// Notifier init();
//
// boolean tryInit();
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/MultipleSendNotificationException.java
// public class MultipleSendNotificationException extends SendNotificationException {
//
// private List<Exception> errors;
//
// public MultipleSendNotificationException(List<Exception> errors) {
// super(messages(checkNotNull(errors)));
// this.errors = errors;
// }
//
// public List<Exception> getErrors() {
// return Collections.unmodifiableList(errors);
// }
//
// private static String messages(List<Exception> errors) {
// Iterator<Exception> iterator = errors.iterator();
// StringBuilder messages = new StringBuilder(iterator.next().getMessage());
// while (iterator.hasNext()) {
// Exception error = iterator.next();
// if (error.getMessage() != null) {
// messages.append(String.format("%n%s", error.getMessage()));
// }
// }
// return messages.toString();
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notification.java
// @AutoValue
// public abstract class Notification {
//
// /**
// * Indicate notification priority.
// */
// public enum Level {INFO, WARNING, ERROR}
//
// /**
// * Notification message.
// *
// * @return message.
// */
// public abstract String message();
//
// /**
// * Notification title.
// *
// * @return title.
// */
// public abstract String title();
//
// /**
// * Notification subtitle. <br>
// * Not available for all notifier implementation.
// *
// * @return subtitle.
// */
// @Nullable
// public abstract String subtitle();
//
// /**
// * Notification icon.
// *
// * @return icon.
// */
// public abstract Icon icon();
//
// /**
// * Indicate the notification priority type.
// *
// * @return type
// */
// public abstract Level level();
//
// Notification() {
// // prevent external subclasses
// }
//
// public static Builder builder(String title, String message, Icon icon) {
// return builder()
// .title(title)
// .message(message)
// .icon(icon);
// }
//
// public static Builder builder() {
// return new AutoValue_Notification.Builder().level(INFO);
// }
//
// @AutoValue.Builder
// public interface Builder {
// Builder title(String title);
// Builder message(String message);
// Builder icon(Icon icon);
// Builder subtitle(String subtitle);
// Builder level(Level level);
// Notification build();
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notifier.java
// public interface Notifier {
//
// /**
// * Send a notification.
// *
// * @param notification a notification.
// *
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// void send(Notification notification);
//
// /**
// * Close the notifier. <br>
// * This method must be called to release resources when the notifier is not needed anymore.
// */
// void close();
//
// /**
// * Indicate if the notifier is always displayed somewhere (menu/task bar, etc).
// * @return {@code true} if the notifier is persistent.
// */
// boolean isPersistent();
// }
| import com.google.common.base.MoreObjects;
import com.google.common.base.Objects;
import fr.jcgay.notification.DiscoverableNotifier;
import fr.jcgay.notification.MultipleSendNotificationException;
import fr.jcgay.notification.Notification;
import fr.jcgay.notification.Notifier;
import org.slf4j.Logger;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static org.slf4j.LoggerFactory.getLogger; | safeClose(notifier, errors);
}
}
failIfNotEmpty(errors);
}
@Override
public boolean isPersistent() {
if (notifyWithSecondaryNotifiers) {
boolean result = primary.isPersistent();
for (DiscoverableNotifier notifier : secondary) {
result |= notifier.isPersistent();
}
return result;
}
return primary.isPersistent();
}
public static void safeClose(DiscoverableNotifier notifier, List<Exception> errors) {
try {
notifier.close();
} catch (RuntimeException e) {
LOGGER.debug("Error closing {}.", notifier, e);
errors.add(e);
}
}
private static void failIfNotEmpty(List<Exception> errors) {
if (!errors.isEmpty()) { | // Path: send-notification/src/main/java/fr/jcgay/notification/DiscoverableNotifier.java
// public interface DiscoverableNotifier extends Notifier {
//
// /**
// * Initialize before usage. <br>
// * This method must be called before trying to send a notification. <br>
// * Calling {@code init()} multiple time should not fail. <br>
// *
// * For example a notifier can open a connection to register the application, or it can do nothing.
// *
// * @return a usable initiated {@link Notifier} to send notification(s)
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// Notifier init();
//
// boolean tryInit();
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/MultipleSendNotificationException.java
// public class MultipleSendNotificationException extends SendNotificationException {
//
// private List<Exception> errors;
//
// public MultipleSendNotificationException(List<Exception> errors) {
// super(messages(checkNotNull(errors)));
// this.errors = errors;
// }
//
// public List<Exception> getErrors() {
// return Collections.unmodifiableList(errors);
// }
//
// private static String messages(List<Exception> errors) {
// Iterator<Exception> iterator = errors.iterator();
// StringBuilder messages = new StringBuilder(iterator.next().getMessage());
// while (iterator.hasNext()) {
// Exception error = iterator.next();
// if (error.getMessage() != null) {
// messages.append(String.format("%n%s", error.getMessage()));
// }
// }
// return messages.toString();
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notification.java
// @AutoValue
// public abstract class Notification {
//
// /**
// * Indicate notification priority.
// */
// public enum Level {INFO, WARNING, ERROR}
//
// /**
// * Notification message.
// *
// * @return message.
// */
// public abstract String message();
//
// /**
// * Notification title.
// *
// * @return title.
// */
// public abstract String title();
//
// /**
// * Notification subtitle. <br>
// * Not available for all notifier implementation.
// *
// * @return subtitle.
// */
// @Nullable
// public abstract String subtitle();
//
// /**
// * Notification icon.
// *
// * @return icon.
// */
// public abstract Icon icon();
//
// /**
// * Indicate the notification priority type.
// *
// * @return type
// */
// public abstract Level level();
//
// Notification() {
// // prevent external subclasses
// }
//
// public static Builder builder(String title, String message, Icon icon) {
// return builder()
// .title(title)
// .message(message)
// .icon(icon);
// }
//
// public static Builder builder() {
// return new AutoValue_Notification.Builder().level(INFO);
// }
//
// @AutoValue.Builder
// public interface Builder {
// Builder title(String title);
// Builder message(String message);
// Builder icon(Icon icon);
// Builder subtitle(String subtitle);
// Builder level(Level level);
// Notification build();
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notifier.java
// public interface Notifier {
//
// /**
// * Send a notification.
// *
// * @param notification a notification.
// *
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// void send(Notification notification);
//
// /**
// * Close the notifier. <br>
// * This method must be called to release resources when the notifier is not needed anymore.
// */
// void close();
//
// /**
// * Indicate if the notifier is always displayed somewhere (menu/task bar, etc).
// * @return {@code true} if the notifier is persistent.
// */
// boolean isPersistent();
// }
// Path: send-notification/src/main/java/fr/jcgay/notification/notifier/additional/AdditionalNotifier.java
import com.google.common.base.MoreObjects;
import com.google.common.base.Objects;
import fr.jcgay.notification.DiscoverableNotifier;
import fr.jcgay.notification.MultipleSendNotificationException;
import fr.jcgay.notification.Notification;
import fr.jcgay.notification.Notifier;
import org.slf4j.Logger;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static org.slf4j.LoggerFactory.getLogger;
safeClose(notifier, errors);
}
}
failIfNotEmpty(errors);
}
@Override
public boolean isPersistent() {
if (notifyWithSecondaryNotifiers) {
boolean result = primary.isPersistent();
for (DiscoverableNotifier notifier : secondary) {
result |= notifier.isPersistent();
}
return result;
}
return primary.isPersistent();
}
public static void safeClose(DiscoverableNotifier notifier, List<Exception> errors) {
try {
notifier.close();
} catch (RuntimeException e) {
LOGGER.debug("Error closing {}.", notifier, e);
errors.add(e);
}
}
private static void failIfNotEmpty(List<Exception> errors) {
if (!errors.isEmpty()) { | throw new MultipleSendNotificationException(errors); |
jcgay/send-notification | send-notification/src/main/java/fr/jcgay/notification/notifier/notificationcenter/TerminalNotifier.java | // Path: send-notification/src/main/java/fr/jcgay/notification/Application.java
// @AutoValue
// public abstract class Application {
//
// /**
// * Uniquely identify an application. <br>
// * In order to ensure your application's signature is unique, the recommendation is to follow the Internet Media
// * type (also known as MIME content type) format as defined in IETF <a href="http://tools.ietf.org/html/rfc2046">RFC 2046</a>
// * which contains the application vendor's name - specifically: {@code application/x-vnd-some_vendor.some_app}. <br>
// * The signature must not contain spaces. <br>
// * Some examples of acceptable signatures:
// * <ul>
// * <li>{@code application/x-vnd-acme.hello_world}</li>
// * <li>{@code application/x-vnd-fullphat.snaRSS}</li>
// * </ul>
// *
// * @return unique identifier.
// */
// public abstract String id();
//
// /**
// * A name that will identify the application for the user. <br>
// * Examples:
// * <ul>
// * <li>Maven</li>
// * <li>Gradle</li>
// * </ul>
// *
// * @return application name.
// */
// public abstract String name();
//
// /**
// * A timeout to wait for before cancelling application registration or notification sending.
// *
// * @return timeout in milliseconds, or {@code -1} if not specified.
// */
// public abstract long timeout();
//
// /**
// * The application icon.
// *
// * @return application icon.
// */
// public abstract Icon icon();
//
// Application() {
// // prevent external subclasses
// }
//
// public static Builder builder() {
// return new AutoValue_Application.Builder()
// .timeout(-1);
// }
//
// public static Builder builder(String id, String name, Icon icon) {
// return builder()
// .id(id)
// .name(name)
// .icon(icon);
// }
//
// @AutoValue.Builder
// public interface Builder {
// Builder id(String id);
// Builder name(String name);
// Builder icon(Icon icon);
// Builder timeout(long timeout);
// Application build();
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/DiscoverableNotifier.java
// public interface DiscoverableNotifier extends Notifier {
//
// /**
// * Initialize before usage. <br>
// * This method must be called before trying to send a notification. <br>
// * Calling {@code init()} multiple time should not fail. <br>
// *
// * For example a notifier can open a connection to register the application, or it can do nothing.
// *
// * @return a usable initiated {@link Notifier} to send notification(s)
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// Notifier init();
//
// boolean tryInit();
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notification.java
// @AutoValue
// public abstract class Notification {
//
// /**
// * Indicate notification priority.
// */
// public enum Level {INFO, WARNING, ERROR}
//
// /**
// * Notification message.
// *
// * @return message.
// */
// public abstract String message();
//
// /**
// * Notification title.
// *
// * @return title.
// */
// public abstract String title();
//
// /**
// * Notification subtitle. <br>
// * Not available for all notifier implementation.
// *
// * @return subtitle.
// */
// @Nullable
// public abstract String subtitle();
//
// /**
// * Notification icon.
// *
// * @return icon.
// */
// public abstract Icon icon();
//
// /**
// * Indicate the notification priority type.
// *
// * @return type
// */
// public abstract Level level();
//
// Notification() {
// // prevent external subclasses
// }
//
// public static Builder builder(String title, String message, Icon icon) {
// return builder()
// .title(title)
// .message(message)
// .icon(icon);
// }
//
// public static Builder builder() {
// return new AutoValue_Notification.Builder().level(INFO);
// }
//
// @AutoValue.Builder
// public interface Builder {
// Builder title(String title);
// Builder message(String message);
// Builder icon(Icon icon);
// Builder subtitle(String subtitle);
// Builder level(Level level);
// Notification build();
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notifier.java
// public interface Notifier {
//
// /**
// * Send a notification.
// *
// * @param notification a notification.
// *
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// void send(Notification notification);
//
// /**
// * Close the notifier. <br>
// * This method must be called to release resources when the notifier is not needed anymore.
// */
// void close();
//
// /**
// * Indicate if the notifier is always displayed somewhere (menu/task bar, etc).
// * @return {@code true} if the notifier is persistent.
// */
// boolean isPersistent();
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/notifier/executor/Executor.java
// public interface Executor {
// void exec(String[] command);
// boolean tryExec(String[] command);
// void close();
// }
| import com.google.common.base.MoreObjects;
import com.google.common.base.Objects;
import fr.jcgay.notification.Application;
import fr.jcgay.notification.DiscoverableNotifier;
import fr.jcgay.notification.Notification;
import fr.jcgay.notification.Notifier;
import fr.jcgay.notification.notifier.executor.Executor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List; | package fr.jcgay.notification.notifier.notificationcenter;
public class TerminalNotifier implements DiscoverableNotifier {
private static final Logger LOGGER = LoggerFactory.getLogger(TerminalNotifier.class);
| // Path: send-notification/src/main/java/fr/jcgay/notification/Application.java
// @AutoValue
// public abstract class Application {
//
// /**
// * Uniquely identify an application. <br>
// * In order to ensure your application's signature is unique, the recommendation is to follow the Internet Media
// * type (also known as MIME content type) format as defined in IETF <a href="http://tools.ietf.org/html/rfc2046">RFC 2046</a>
// * which contains the application vendor's name - specifically: {@code application/x-vnd-some_vendor.some_app}. <br>
// * The signature must not contain spaces. <br>
// * Some examples of acceptable signatures:
// * <ul>
// * <li>{@code application/x-vnd-acme.hello_world}</li>
// * <li>{@code application/x-vnd-fullphat.snaRSS}</li>
// * </ul>
// *
// * @return unique identifier.
// */
// public abstract String id();
//
// /**
// * A name that will identify the application for the user. <br>
// * Examples:
// * <ul>
// * <li>Maven</li>
// * <li>Gradle</li>
// * </ul>
// *
// * @return application name.
// */
// public abstract String name();
//
// /**
// * A timeout to wait for before cancelling application registration or notification sending.
// *
// * @return timeout in milliseconds, or {@code -1} if not specified.
// */
// public abstract long timeout();
//
// /**
// * The application icon.
// *
// * @return application icon.
// */
// public abstract Icon icon();
//
// Application() {
// // prevent external subclasses
// }
//
// public static Builder builder() {
// return new AutoValue_Application.Builder()
// .timeout(-1);
// }
//
// public static Builder builder(String id, String name, Icon icon) {
// return builder()
// .id(id)
// .name(name)
// .icon(icon);
// }
//
// @AutoValue.Builder
// public interface Builder {
// Builder id(String id);
// Builder name(String name);
// Builder icon(Icon icon);
// Builder timeout(long timeout);
// Application build();
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/DiscoverableNotifier.java
// public interface DiscoverableNotifier extends Notifier {
//
// /**
// * Initialize before usage. <br>
// * This method must be called before trying to send a notification. <br>
// * Calling {@code init()} multiple time should not fail. <br>
// *
// * For example a notifier can open a connection to register the application, or it can do nothing.
// *
// * @return a usable initiated {@link Notifier} to send notification(s)
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// Notifier init();
//
// boolean tryInit();
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notification.java
// @AutoValue
// public abstract class Notification {
//
// /**
// * Indicate notification priority.
// */
// public enum Level {INFO, WARNING, ERROR}
//
// /**
// * Notification message.
// *
// * @return message.
// */
// public abstract String message();
//
// /**
// * Notification title.
// *
// * @return title.
// */
// public abstract String title();
//
// /**
// * Notification subtitle. <br>
// * Not available for all notifier implementation.
// *
// * @return subtitle.
// */
// @Nullable
// public abstract String subtitle();
//
// /**
// * Notification icon.
// *
// * @return icon.
// */
// public abstract Icon icon();
//
// /**
// * Indicate the notification priority type.
// *
// * @return type
// */
// public abstract Level level();
//
// Notification() {
// // prevent external subclasses
// }
//
// public static Builder builder(String title, String message, Icon icon) {
// return builder()
// .title(title)
// .message(message)
// .icon(icon);
// }
//
// public static Builder builder() {
// return new AutoValue_Notification.Builder().level(INFO);
// }
//
// @AutoValue.Builder
// public interface Builder {
// Builder title(String title);
// Builder message(String message);
// Builder icon(Icon icon);
// Builder subtitle(String subtitle);
// Builder level(Level level);
// Notification build();
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notifier.java
// public interface Notifier {
//
// /**
// * Send a notification.
// *
// * @param notification a notification.
// *
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// void send(Notification notification);
//
// /**
// * Close the notifier. <br>
// * This method must be called to release resources when the notifier is not needed anymore.
// */
// void close();
//
// /**
// * Indicate if the notifier is always displayed somewhere (menu/task bar, etc).
// * @return {@code true} if the notifier is persistent.
// */
// boolean isPersistent();
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/notifier/executor/Executor.java
// public interface Executor {
// void exec(String[] command);
// boolean tryExec(String[] command);
// void close();
// }
// Path: send-notification/src/main/java/fr/jcgay/notification/notifier/notificationcenter/TerminalNotifier.java
import com.google.common.base.MoreObjects;
import com.google.common.base.Objects;
import fr.jcgay.notification.Application;
import fr.jcgay.notification.DiscoverableNotifier;
import fr.jcgay.notification.Notification;
import fr.jcgay.notification.Notifier;
import fr.jcgay.notification.notifier.executor.Executor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
package fr.jcgay.notification.notifier.notificationcenter;
public class TerminalNotifier implements DiscoverableNotifier {
private static final Logger LOGGER = LoggerFactory.getLogger(TerminalNotifier.class);
| private final Application application; |
jcgay/send-notification | send-notification/src/main/java/fr/jcgay/notification/notifier/notificationcenter/TerminalNotifier.java | // Path: send-notification/src/main/java/fr/jcgay/notification/Application.java
// @AutoValue
// public abstract class Application {
//
// /**
// * Uniquely identify an application. <br>
// * In order to ensure your application's signature is unique, the recommendation is to follow the Internet Media
// * type (also known as MIME content type) format as defined in IETF <a href="http://tools.ietf.org/html/rfc2046">RFC 2046</a>
// * which contains the application vendor's name - specifically: {@code application/x-vnd-some_vendor.some_app}. <br>
// * The signature must not contain spaces. <br>
// * Some examples of acceptable signatures:
// * <ul>
// * <li>{@code application/x-vnd-acme.hello_world}</li>
// * <li>{@code application/x-vnd-fullphat.snaRSS}</li>
// * </ul>
// *
// * @return unique identifier.
// */
// public abstract String id();
//
// /**
// * A name that will identify the application for the user. <br>
// * Examples:
// * <ul>
// * <li>Maven</li>
// * <li>Gradle</li>
// * </ul>
// *
// * @return application name.
// */
// public abstract String name();
//
// /**
// * A timeout to wait for before cancelling application registration or notification sending.
// *
// * @return timeout in milliseconds, or {@code -1} if not specified.
// */
// public abstract long timeout();
//
// /**
// * The application icon.
// *
// * @return application icon.
// */
// public abstract Icon icon();
//
// Application() {
// // prevent external subclasses
// }
//
// public static Builder builder() {
// return new AutoValue_Application.Builder()
// .timeout(-1);
// }
//
// public static Builder builder(String id, String name, Icon icon) {
// return builder()
// .id(id)
// .name(name)
// .icon(icon);
// }
//
// @AutoValue.Builder
// public interface Builder {
// Builder id(String id);
// Builder name(String name);
// Builder icon(Icon icon);
// Builder timeout(long timeout);
// Application build();
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/DiscoverableNotifier.java
// public interface DiscoverableNotifier extends Notifier {
//
// /**
// * Initialize before usage. <br>
// * This method must be called before trying to send a notification. <br>
// * Calling {@code init()} multiple time should not fail. <br>
// *
// * For example a notifier can open a connection to register the application, or it can do nothing.
// *
// * @return a usable initiated {@link Notifier} to send notification(s)
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// Notifier init();
//
// boolean tryInit();
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notification.java
// @AutoValue
// public abstract class Notification {
//
// /**
// * Indicate notification priority.
// */
// public enum Level {INFO, WARNING, ERROR}
//
// /**
// * Notification message.
// *
// * @return message.
// */
// public abstract String message();
//
// /**
// * Notification title.
// *
// * @return title.
// */
// public abstract String title();
//
// /**
// * Notification subtitle. <br>
// * Not available for all notifier implementation.
// *
// * @return subtitle.
// */
// @Nullable
// public abstract String subtitle();
//
// /**
// * Notification icon.
// *
// * @return icon.
// */
// public abstract Icon icon();
//
// /**
// * Indicate the notification priority type.
// *
// * @return type
// */
// public abstract Level level();
//
// Notification() {
// // prevent external subclasses
// }
//
// public static Builder builder(String title, String message, Icon icon) {
// return builder()
// .title(title)
// .message(message)
// .icon(icon);
// }
//
// public static Builder builder() {
// return new AutoValue_Notification.Builder().level(INFO);
// }
//
// @AutoValue.Builder
// public interface Builder {
// Builder title(String title);
// Builder message(String message);
// Builder icon(Icon icon);
// Builder subtitle(String subtitle);
// Builder level(Level level);
// Notification build();
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notifier.java
// public interface Notifier {
//
// /**
// * Send a notification.
// *
// * @param notification a notification.
// *
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// void send(Notification notification);
//
// /**
// * Close the notifier. <br>
// * This method must be called to release resources when the notifier is not needed anymore.
// */
// void close();
//
// /**
// * Indicate if the notifier is always displayed somewhere (menu/task bar, etc).
// * @return {@code true} if the notifier is persistent.
// */
// boolean isPersistent();
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/notifier/executor/Executor.java
// public interface Executor {
// void exec(String[] command);
// boolean tryExec(String[] command);
// void close();
// }
| import com.google.common.base.MoreObjects;
import com.google.common.base.Objects;
import fr.jcgay.notification.Application;
import fr.jcgay.notification.DiscoverableNotifier;
import fr.jcgay.notification.Notification;
import fr.jcgay.notification.Notifier;
import fr.jcgay.notification.notifier.executor.Executor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List; | package fr.jcgay.notification.notifier.notificationcenter;
public class TerminalNotifier implements DiscoverableNotifier {
private static final Logger LOGGER = LoggerFactory.getLogger(TerminalNotifier.class);
private final Application application;
private final TerminalNotifierConfiguration configuration; | // Path: send-notification/src/main/java/fr/jcgay/notification/Application.java
// @AutoValue
// public abstract class Application {
//
// /**
// * Uniquely identify an application. <br>
// * In order to ensure your application's signature is unique, the recommendation is to follow the Internet Media
// * type (also known as MIME content type) format as defined in IETF <a href="http://tools.ietf.org/html/rfc2046">RFC 2046</a>
// * which contains the application vendor's name - specifically: {@code application/x-vnd-some_vendor.some_app}. <br>
// * The signature must not contain spaces. <br>
// * Some examples of acceptable signatures:
// * <ul>
// * <li>{@code application/x-vnd-acme.hello_world}</li>
// * <li>{@code application/x-vnd-fullphat.snaRSS}</li>
// * </ul>
// *
// * @return unique identifier.
// */
// public abstract String id();
//
// /**
// * A name that will identify the application for the user. <br>
// * Examples:
// * <ul>
// * <li>Maven</li>
// * <li>Gradle</li>
// * </ul>
// *
// * @return application name.
// */
// public abstract String name();
//
// /**
// * A timeout to wait for before cancelling application registration or notification sending.
// *
// * @return timeout in milliseconds, or {@code -1} if not specified.
// */
// public abstract long timeout();
//
// /**
// * The application icon.
// *
// * @return application icon.
// */
// public abstract Icon icon();
//
// Application() {
// // prevent external subclasses
// }
//
// public static Builder builder() {
// return new AutoValue_Application.Builder()
// .timeout(-1);
// }
//
// public static Builder builder(String id, String name, Icon icon) {
// return builder()
// .id(id)
// .name(name)
// .icon(icon);
// }
//
// @AutoValue.Builder
// public interface Builder {
// Builder id(String id);
// Builder name(String name);
// Builder icon(Icon icon);
// Builder timeout(long timeout);
// Application build();
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/DiscoverableNotifier.java
// public interface DiscoverableNotifier extends Notifier {
//
// /**
// * Initialize before usage. <br>
// * This method must be called before trying to send a notification. <br>
// * Calling {@code init()} multiple time should not fail. <br>
// *
// * For example a notifier can open a connection to register the application, or it can do nothing.
// *
// * @return a usable initiated {@link Notifier} to send notification(s)
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// Notifier init();
//
// boolean tryInit();
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notification.java
// @AutoValue
// public abstract class Notification {
//
// /**
// * Indicate notification priority.
// */
// public enum Level {INFO, WARNING, ERROR}
//
// /**
// * Notification message.
// *
// * @return message.
// */
// public abstract String message();
//
// /**
// * Notification title.
// *
// * @return title.
// */
// public abstract String title();
//
// /**
// * Notification subtitle. <br>
// * Not available for all notifier implementation.
// *
// * @return subtitle.
// */
// @Nullable
// public abstract String subtitle();
//
// /**
// * Notification icon.
// *
// * @return icon.
// */
// public abstract Icon icon();
//
// /**
// * Indicate the notification priority type.
// *
// * @return type
// */
// public abstract Level level();
//
// Notification() {
// // prevent external subclasses
// }
//
// public static Builder builder(String title, String message, Icon icon) {
// return builder()
// .title(title)
// .message(message)
// .icon(icon);
// }
//
// public static Builder builder() {
// return new AutoValue_Notification.Builder().level(INFO);
// }
//
// @AutoValue.Builder
// public interface Builder {
// Builder title(String title);
// Builder message(String message);
// Builder icon(Icon icon);
// Builder subtitle(String subtitle);
// Builder level(Level level);
// Notification build();
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notifier.java
// public interface Notifier {
//
// /**
// * Send a notification.
// *
// * @param notification a notification.
// *
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// void send(Notification notification);
//
// /**
// * Close the notifier. <br>
// * This method must be called to release resources when the notifier is not needed anymore.
// */
// void close();
//
// /**
// * Indicate if the notifier is always displayed somewhere (menu/task bar, etc).
// * @return {@code true} if the notifier is persistent.
// */
// boolean isPersistent();
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/notifier/executor/Executor.java
// public interface Executor {
// void exec(String[] command);
// boolean tryExec(String[] command);
// void close();
// }
// Path: send-notification/src/main/java/fr/jcgay/notification/notifier/notificationcenter/TerminalNotifier.java
import com.google.common.base.MoreObjects;
import com.google.common.base.Objects;
import fr.jcgay.notification.Application;
import fr.jcgay.notification.DiscoverableNotifier;
import fr.jcgay.notification.Notification;
import fr.jcgay.notification.Notifier;
import fr.jcgay.notification.notifier.executor.Executor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
package fr.jcgay.notification.notifier.notificationcenter;
public class TerminalNotifier implements DiscoverableNotifier {
private static final Logger LOGGER = LoggerFactory.getLogger(TerminalNotifier.class);
private final Application application;
private final TerminalNotifierConfiguration configuration; | private final Executor executor; |
jcgay/send-notification | send-notification/src/main/java/fr/jcgay/notification/notifier/notifu/NotifuNotifier.java | // Path: send-notification/src/main/java/fr/jcgay/notification/Application.java
// @AutoValue
// public abstract class Application {
//
// /**
// * Uniquely identify an application. <br>
// * In order to ensure your application's signature is unique, the recommendation is to follow the Internet Media
// * type (also known as MIME content type) format as defined in IETF <a href="http://tools.ietf.org/html/rfc2046">RFC 2046</a>
// * which contains the application vendor's name - specifically: {@code application/x-vnd-some_vendor.some_app}. <br>
// * The signature must not contain spaces. <br>
// * Some examples of acceptable signatures:
// * <ul>
// * <li>{@code application/x-vnd-acme.hello_world}</li>
// * <li>{@code application/x-vnd-fullphat.snaRSS}</li>
// * </ul>
// *
// * @return unique identifier.
// */
// public abstract String id();
//
// /**
// * A name that will identify the application for the user. <br>
// * Examples:
// * <ul>
// * <li>Maven</li>
// * <li>Gradle</li>
// * </ul>
// *
// * @return application name.
// */
// public abstract String name();
//
// /**
// * A timeout to wait for before cancelling application registration or notification sending.
// *
// * @return timeout in milliseconds, or {@code -1} if not specified.
// */
// public abstract long timeout();
//
// /**
// * The application icon.
// *
// * @return application icon.
// */
// public abstract Icon icon();
//
// Application() {
// // prevent external subclasses
// }
//
// public static Builder builder() {
// return new AutoValue_Application.Builder()
// .timeout(-1);
// }
//
// public static Builder builder(String id, String name, Icon icon) {
// return builder()
// .id(id)
// .name(name)
// .icon(icon);
// }
//
// @AutoValue.Builder
// public interface Builder {
// Builder id(String id);
// Builder name(String name);
// Builder icon(Icon icon);
// Builder timeout(long timeout);
// Application build();
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/DiscoverableNotifier.java
// public interface DiscoverableNotifier extends Notifier {
//
// /**
// * Initialize before usage. <br>
// * This method must be called before trying to send a notification. <br>
// * Calling {@code init()} multiple time should not fail. <br>
// *
// * For example a notifier can open a connection to register the application, or it can do nothing.
// *
// * @return a usable initiated {@link Notifier} to send notification(s)
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// Notifier init();
//
// boolean tryInit();
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notification.java
// @AutoValue
// public abstract class Notification {
//
// /**
// * Indicate notification priority.
// */
// public enum Level {INFO, WARNING, ERROR}
//
// /**
// * Notification message.
// *
// * @return message.
// */
// public abstract String message();
//
// /**
// * Notification title.
// *
// * @return title.
// */
// public abstract String title();
//
// /**
// * Notification subtitle. <br>
// * Not available for all notifier implementation.
// *
// * @return subtitle.
// */
// @Nullable
// public abstract String subtitle();
//
// /**
// * Notification icon.
// *
// * @return icon.
// */
// public abstract Icon icon();
//
// /**
// * Indicate the notification priority type.
// *
// * @return type
// */
// public abstract Level level();
//
// Notification() {
// // prevent external subclasses
// }
//
// public static Builder builder(String title, String message, Icon icon) {
// return builder()
// .title(title)
// .message(message)
// .icon(icon);
// }
//
// public static Builder builder() {
// return new AutoValue_Notification.Builder().level(INFO);
// }
//
// @AutoValue.Builder
// public interface Builder {
// Builder title(String title);
// Builder message(String message);
// Builder icon(Icon icon);
// Builder subtitle(String subtitle);
// Builder level(Level level);
// Notification build();
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notifier.java
// public interface Notifier {
//
// /**
// * Send a notification.
// *
// * @param notification a notification.
// *
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// void send(Notification notification);
//
// /**
// * Close the notifier. <br>
// * This method must be called to release resources when the notifier is not needed anymore.
// */
// void close();
//
// /**
// * Indicate if the notifier is always displayed somewhere (menu/task bar, etc).
// * @return {@code true} if the notifier is persistent.
// */
// boolean isPersistent();
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/notifier/executor/Executor.java
// public interface Executor {
// void exec(String[] command);
// boolean tryExec(String[] command);
// void close();
// }
| import com.google.common.base.MoreObjects;
import com.google.common.base.Objects;
import fr.jcgay.notification.Application;
import fr.jcgay.notification.DiscoverableNotifier;
import fr.jcgay.notification.Notification;
import fr.jcgay.notification.Notifier;
import fr.jcgay.notification.notifier.executor.Executor;
import org.slf4j.Logger;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import static org.slf4j.LoggerFactory.getLogger; | package fr.jcgay.notification.notifier.notifu;
public class NotifuNotifier implements DiscoverableNotifier {
private static final Logger LOGGER = getLogger(NotifuNotifier.class);
| // Path: send-notification/src/main/java/fr/jcgay/notification/Application.java
// @AutoValue
// public abstract class Application {
//
// /**
// * Uniquely identify an application. <br>
// * In order to ensure your application's signature is unique, the recommendation is to follow the Internet Media
// * type (also known as MIME content type) format as defined in IETF <a href="http://tools.ietf.org/html/rfc2046">RFC 2046</a>
// * which contains the application vendor's name - specifically: {@code application/x-vnd-some_vendor.some_app}. <br>
// * The signature must not contain spaces. <br>
// * Some examples of acceptable signatures:
// * <ul>
// * <li>{@code application/x-vnd-acme.hello_world}</li>
// * <li>{@code application/x-vnd-fullphat.snaRSS}</li>
// * </ul>
// *
// * @return unique identifier.
// */
// public abstract String id();
//
// /**
// * A name that will identify the application for the user. <br>
// * Examples:
// * <ul>
// * <li>Maven</li>
// * <li>Gradle</li>
// * </ul>
// *
// * @return application name.
// */
// public abstract String name();
//
// /**
// * A timeout to wait for before cancelling application registration or notification sending.
// *
// * @return timeout in milliseconds, or {@code -1} if not specified.
// */
// public abstract long timeout();
//
// /**
// * The application icon.
// *
// * @return application icon.
// */
// public abstract Icon icon();
//
// Application() {
// // prevent external subclasses
// }
//
// public static Builder builder() {
// return new AutoValue_Application.Builder()
// .timeout(-1);
// }
//
// public static Builder builder(String id, String name, Icon icon) {
// return builder()
// .id(id)
// .name(name)
// .icon(icon);
// }
//
// @AutoValue.Builder
// public interface Builder {
// Builder id(String id);
// Builder name(String name);
// Builder icon(Icon icon);
// Builder timeout(long timeout);
// Application build();
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/DiscoverableNotifier.java
// public interface DiscoverableNotifier extends Notifier {
//
// /**
// * Initialize before usage. <br>
// * This method must be called before trying to send a notification. <br>
// * Calling {@code init()} multiple time should not fail. <br>
// *
// * For example a notifier can open a connection to register the application, or it can do nothing.
// *
// * @return a usable initiated {@link Notifier} to send notification(s)
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// Notifier init();
//
// boolean tryInit();
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notification.java
// @AutoValue
// public abstract class Notification {
//
// /**
// * Indicate notification priority.
// */
// public enum Level {INFO, WARNING, ERROR}
//
// /**
// * Notification message.
// *
// * @return message.
// */
// public abstract String message();
//
// /**
// * Notification title.
// *
// * @return title.
// */
// public abstract String title();
//
// /**
// * Notification subtitle. <br>
// * Not available for all notifier implementation.
// *
// * @return subtitle.
// */
// @Nullable
// public abstract String subtitle();
//
// /**
// * Notification icon.
// *
// * @return icon.
// */
// public abstract Icon icon();
//
// /**
// * Indicate the notification priority type.
// *
// * @return type
// */
// public abstract Level level();
//
// Notification() {
// // prevent external subclasses
// }
//
// public static Builder builder(String title, String message, Icon icon) {
// return builder()
// .title(title)
// .message(message)
// .icon(icon);
// }
//
// public static Builder builder() {
// return new AutoValue_Notification.Builder().level(INFO);
// }
//
// @AutoValue.Builder
// public interface Builder {
// Builder title(String title);
// Builder message(String message);
// Builder icon(Icon icon);
// Builder subtitle(String subtitle);
// Builder level(Level level);
// Notification build();
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notifier.java
// public interface Notifier {
//
// /**
// * Send a notification.
// *
// * @param notification a notification.
// *
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// void send(Notification notification);
//
// /**
// * Close the notifier. <br>
// * This method must be called to release resources when the notifier is not needed anymore.
// */
// void close();
//
// /**
// * Indicate if the notifier is always displayed somewhere (menu/task bar, etc).
// * @return {@code true} if the notifier is persistent.
// */
// boolean isPersistent();
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/notifier/executor/Executor.java
// public interface Executor {
// void exec(String[] command);
// boolean tryExec(String[] command);
// void close();
// }
// Path: send-notification/src/main/java/fr/jcgay/notification/notifier/notifu/NotifuNotifier.java
import com.google.common.base.MoreObjects;
import com.google.common.base.Objects;
import fr.jcgay.notification.Application;
import fr.jcgay.notification.DiscoverableNotifier;
import fr.jcgay.notification.Notification;
import fr.jcgay.notification.Notifier;
import fr.jcgay.notification.notifier.executor.Executor;
import org.slf4j.Logger;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import static org.slf4j.LoggerFactory.getLogger;
package fr.jcgay.notification.notifier.notifu;
public class NotifuNotifier implements DiscoverableNotifier {
private static final Logger LOGGER = getLogger(NotifuNotifier.class);
| private final Application application; |
jcgay/send-notification | send-notification/src/main/java/fr/jcgay/notification/notifier/notifu/NotifuNotifier.java | // Path: send-notification/src/main/java/fr/jcgay/notification/Application.java
// @AutoValue
// public abstract class Application {
//
// /**
// * Uniquely identify an application. <br>
// * In order to ensure your application's signature is unique, the recommendation is to follow the Internet Media
// * type (also known as MIME content type) format as defined in IETF <a href="http://tools.ietf.org/html/rfc2046">RFC 2046</a>
// * which contains the application vendor's name - specifically: {@code application/x-vnd-some_vendor.some_app}. <br>
// * The signature must not contain spaces. <br>
// * Some examples of acceptable signatures:
// * <ul>
// * <li>{@code application/x-vnd-acme.hello_world}</li>
// * <li>{@code application/x-vnd-fullphat.snaRSS}</li>
// * </ul>
// *
// * @return unique identifier.
// */
// public abstract String id();
//
// /**
// * A name that will identify the application for the user. <br>
// * Examples:
// * <ul>
// * <li>Maven</li>
// * <li>Gradle</li>
// * </ul>
// *
// * @return application name.
// */
// public abstract String name();
//
// /**
// * A timeout to wait for before cancelling application registration or notification sending.
// *
// * @return timeout in milliseconds, or {@code -1} if not specified.
// */
// public abstract long timeout();
//
// /**
// * The application icon.
// *
// * @return application icon.
// */
// public abstract Icon icon();
//
// Application() {
// // prevent external subclasses
// }
//
// public static Builder builder() {
// return new AutoValue_Application.Builder()
// .timeout(-1);
// }
//
// public static Builder builder(String id, String name, Icon icon) {
// return builder()
// .id(id)
// .name(name)
// .icon(icon);
// }
//
// @AutoValue.Builder
// public interface Builder {
// Builder id(String id);
// Builder name(String name);
// Builder icon(Icon icon);
// Builder timeout(long timeout);
// Application build();
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/DiscoverableNotifier.java
// public interface DiscoverableNotifier extends Notifier {
//
// /**
// * Initialize before usage. <br>
// * This method must be called before trying to send a notification. <br>
// * Calling {@code init()} multiple time should not fail. <br>
// *
// * For example a notifier can open a connection to register the application, or it can do nothing.
// *
// * @return a usable initiated {@link Notifier} to send notification(s)
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// Notifier init();
//
// boolean tryInit();
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notification.java
// @AutoValue
// public abstract class Notification {
//
// /**
// * Indicate notification priority.
// */
// public enum Level {INFO, WARNING, ERROR}
//
// /**
// * Notification message.
// *
// * @return message.
// */
// public abstract String message();
//
// /**
// * Notification title.
// *
// * @return title.
// */
// public abstract String title();
//
// /**
// * Notification subtitle. <br>
// * Not available for all notifier implementation.
// *
// * @return subtitle.
// */
// @Nullable
// public abstract String subtitle();
//
// /**
// * Notification icon.
// *
// * @return icon.
// */
// public abstract Icon icon();
//
// /**
// * Indicate the notification priority type.
// *
// * @return type
// */
// public abstract Level level();
//
// Notification() {
// // prevent external subclasses
// }
//
// public static Builder builder(String title, String message, Icon icon) {
// return builder()
// .title(title)
// .message(message)
// .icon(icon);
// }
//
// public static Builder builder() {
// return new AutoValue_Notification.Builder().level(INFO);
// }
//
// @AutoValue.Builder
// public interface Builder {
// Builder title(String title);
// Builder message(String message);
// Builder icon(Icon icon);
// Builder subtitle(String subtitle);
// Builder level(Level level);
// Notification build();
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notifier.java
// public interface Notifier {
//
// /**
// * Send a notification.
// *
// * @param notification a notification.
// *
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// void send(Notification notification);
//
// /**
// * Close the notifier. <br>
// * This method must be called to release resources when the notifier is not needed anymore.
// */
// void close();
//
// /**
// * Indicate if the notifier is always displayed somewhere (menu/task bar, etc).
// * @return {@code true} if the notifier is persistent.
// */
// boolean isPersistent();
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/notifier/executor/Executor.java
// public interface Executor {
// void exec(String[] command);
// boolean tryExec(String[] command);
// void close();
// }
| import com.google.common.base.MoreObjects;
import com.google.common.base.Objects;
import fr.jcgay.notification.Application;
import fr.jcgay.notification.DiscoverableNotifier;
import fr.jcgay.notification.Notification;
import fr.jcgay.notification.Notifier;
import fr.jcgay.notification.notifier.executor.Executor;
import org.slf4j.Logger;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import static org.slf4j.LoggerFactory.getLogger; | package fr.jcgay.notification.notifier.notifu;
public class NotifuNotifier implements DiscoverableNotifier {
private static final Logger LOGGER = getLogger(NotifuNotifier.class);
private final Application application;
private final NotifuConfiguration configuration; | // Path: send-notification/src/main/java/fr/jcgay/notification/Application.java
// @AutoValue
// public abstract class Application {
//
// /**
// * Uniquely identify an application. <br>
// * In order to ensure your application's signature is unique, the recommendation is to follow the Internet Media
// * type (also known as MIME content type) format as defined in IETF <a href="http://tools.ietf.org/html/rfc2046">RFC 2046</a>
// * which contains the application vendor's name - specifically: {@code application/x-vnd-some_vendor.some_app}. <br>
// * The signature must not contain spaces. <br>
// * Some examples of acceptable signatures:
// * <ul>
// * <li>{@code application/x-vnd-acme.hello_world}</li>
// * <li>{@code application/x-vnd-fullphat.snaRSS}</li>
// * </ul>
// *
// * @return unique identifier.
// */
// public abstract String id();
//
// /**
// * A name that will identify the application for the user. <br>
// * Examples:
// * <ul>
// * <li>Maven</li>
// * <li>Gradle</li>
// * </ul>
// *
// * @return application name.
// */
// public abstract String name();
//
// /**
// * A timeout to wait for before cancelling application registration or notification sending.
// *
// * @return timeout in milliseconds, or {@code -1} if not specified.
// */
// public abstract long timeout();
//
// /**
// * The application icon.
// *
// * @return application icon.
// */
// public abstract Icon icon();
//
// Application() {
// // prevent external subclasses
// }
//
// public static Builder builder() {
// return new AutoValue_Application.Builder()
// .timeout(-1);
// }
//
// public static Builder builder(String id, String name, Icon icon) {
// return builder()
// .id(id)
// .name(name)
// .icon(icon);
// }
//
// @AutoValue.Builder
// public interface Builder {
// Builder id(String id);
// Builder name(String name);
// Builder icon(Icon icon);
// Builder timeout(long timeout);
// Application build();
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/DiscoverableNotifier.java
// public interface DiscoverableNotifier extends Notifier {
//
// /**
// * Initialize before usage. <br>
// * This method must be called before trying to send a notification. <br>
// * Calling {@code init()} multiple time should not fail. <br>
// *
// * For example a notifier can open a connection to register the application, or it can do nothing.
// *
// * @return a usable initiated {@link Notifier} to send notification(s)
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// Notifier init();
//
// boolean tryInit();
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notification.java
// @AutoValue
// public abstract class Notification {
//
// /**
// * Indicate notification priority.
// */
// public enum Level {INFO, WARNING, ERROR}
//
// /**
// * Notification message.
// *
// * @return message.
// */
// public abstract String message();
//
// /**
// * Notification title.
// *
// * @return title.
// */
// public abstract String title();
//
// /**
// * Notification subtitle. <br>
// * Not available for all notifier implementation.
// *
// * @return subtitle.
// */
// @Nullable
// public abstract String subtitle();
//
// /**
// * Notification icon.
// *
// * @return icon.
// */
// public abstract Icon icon();
//
// /**
// * Indicate the notification priority type.
// *
// * @return type
// */
// public abstract Level level();
//
// Notification() {
// // prevent external subclasses
// }
//
// public static Builder builder(String title, String message, Icon icon) {
// return builder()
// .title(title)
// .message(message)
// .icon(icon);
// }
//
// public static Builder builder() {
// return new AutoValue_Notification.Builder().level(INFO);
// }
//
// @AutoValue.Builder
// public interface Builder {
// Builder title(String title);
// Builder message(String message);
// Builder icon(Icon icon);
// Builder subtitle(String subtitle);
// Builder level(Level level);
// Notification build();
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notifier.java
// public interface Notifier {
//
// /**
// * Send a notification.
// *
// * @param notification a notification.
// *
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// void send(Notification notification);
//
// /**
// * Close the notifier. <br>
// * This method must be called to release resources when the notifier is not needed anymore.
// */
// void close();
//
// /**
// * Indicate if the notifier is always displayed somewhere (menu/task bar, etc).
// * @return {@code true} if the notifier is persistent.
// */
// boolean isPersistent();
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/notifier/executor/Executor.java
// public interface Executor {
// void exec(String[] command);
// boolean tryExec(String[] command);
// void close();
// }
// Path: send-notification/src/main/java/fr/jcgay/notification/notifier/notifu/NotifuNotifier.java
import com.google.common.base.MoreObjects;
import com.google.common.base.Objects;
import fr.jcgay.notification.Application;
import fr.jcgay.notification.DiscoverableNotifier;
import fr.jcgay.notification.Notification;
import fr.jcgay.notification.Notifier;
import fr.jcgay.notification.notifier.executor.Executor;
import org.slf4j.Logger;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import static org.slf4j.LoggerFactory.getLogger;
package fr.jcgay.notification.notifier.notifu;
public class NotifuNotifier implements DiscoverableNotifier {
private static final Logger LOGGER = getLogger(NotifuNotifier.class);
private final Application application;
private final NotifuConfiguration configuration; | private final Executor executor; |
jcgay/send-notification | send-notification/src/main/java/fr/jcgay/notification/notifier/growl/GntpSlf4jListener.java | // Path: send-notification/src/main/java/fr/jcgay/notification/configuration/OperatingSystem.java
// public class OperatingSystem {
//
// private final String currentOs;
//
// public OperatingSystem() {
// currentOs = System.getProperty("os.name").toLowerCase();
// }
//
// public OperatingSystem(String currentOs) {
// this.currentOs = currentOs.toLowerCase();
// }
//
// public boolean isMac() {
// return currentOs.contains("mac");
// }
//
// public boolean isWindows() {
// return currentOs.contains("win");
// }
//
// @Override
// public String toString() {
// return "OperatingSystem{" +
// "currentOs='" + currentOs + '\'' +
// '}';
// }
// }
| import com.google.code.jgntp.GntpErrorStatus;
import com.google.code.jgntp.GntpListener;
import com.google.code.jgntp.GntpNotification;
import fr.jcgay.notification.configuration.OperatingSystem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; | @Override
public void onNotificationError(GntpNotification notification, GntpErrorStatus status, String description) {
LOGGER.error(error("Growl notification has failed.\n {}: {}\n {}"), status, description, notification);
}
@Override
public void onCommunicationError(Throwable t) {
LOGGER.error(error("Cannot communicate with Growl."), t);
}
},
DEBUG {
@Override
public void onRegistrationError(GntpErrorStatus status, String description) {
LOGGER.debug(error("Growl registration has failed.\n {}: {}"), status, description);
}
@Override
public void onNotificationError(GntpNotification notification, GntpErrorStatus status, String description) {
LOGGER.debug(error("Growl notification has failed.\n {}: {}\n {}"), status, description, notification);
}
@Override
public void onCommunicationError(Throwable t) {
LOGGER.debug(error("Cannot communicate with Growl."), t);
}
};
private static final Logger LOGGER = LoggerFactory.getLogger(GntpSlf4jListener.class);
private static final String OSX_URL = "https://github.com/jcgay/send-notification/wiki/Growl-(OS-X)";
private static final String WINDOWS_URL = "https://github.com/jcgay/send-notification/wiki/Growl-(Windows)"; | // Path: send-notification/src/main/java/fr/jcgay/notification/configuration/OperatingSystem.java
// public class OperatingSystem {
//
// private final String currentOs;
//
// public OperatingSystem() {
// currentOs = System.getProperty("os.name").toLowerCase();
// }
//
// public OperatingSystem(String currentOs) {
// this.currentOs = currentOs.toLowerCase();
// }
//
// public boolean isMac() {
// return currentOs.contains("mac");
// }
//
// public boolean isWindows() {
// return currentOs.contains("win");
// }
//
// @Override
// public String toString() {
// return "OperatingSystem{" +
// "currentOs='" + currentOs + '\'' +
// '}';
// }
// }
// Path: send-notification/src/main/java/fr/jcgay/notification/notifier/growl/GntpSlf4jListener.java
import com.google.code.jgntp.GntpErrorStatus;
import com.google.code.jgntp.GntpListener;
import com.google.code.jgntp.GntpNotification;
import fr.jcgay.notification.configuration.OperatingSystem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Override
public void onNotificationError(GntpNotification notification, GntpErrorStatus status, String description) {
LOGGER.error(error("Growl notification has failed.\n {}: {}\n {}"), status, description, notification);
}
@Override
public void onCommunicationError(Throwable t) {
LOGGER.error(error("Cannot communicate with Growl."), t);
}
},
DEBUG {
@Override
public void onRegistrationError(GntpErrorStatus status, String description) {
LOGGER.debug(error("Growl registration has failed.\n {}: {}"), status, description);
}
@Override
public void onNotificationError(GntpNotification notification, GntpErrorStatus status, String description) {
LOGGER.debug(error("Growl notification has failed.\n {}: {}\n {}"), status, description, notification);
}
@Override
public void onCommunicationError(Throwable t) {
LOGGER.debug(error("Cannot communicate with Growl."), t);
}
};
private static final Logger LOGGER = LoggerFactory.getLogger(GntpSlf4jListener.class);
private static final String OSX_URL = "https://github.com/jcgay/send-notification/wiki/Growl-(OS-X)";
private static final String WINDOWS_URL = "https://github.com/jcgay/send-notification/wiki/Growl-(Windows)"; | private static final OperatingSystem currentOs = new OperatingSystem(); |
jcgay/send-notification | send-notification/src/main/java/fr/jcgay/notification/notifier/DoNothingNotifier.java | // Path: send-notification/src/main/java/fr/jcgay/notification/DiscoverableNotifier.java
// public interface DiscoverableNotifier extends Notifier {
//
// /**
// * Initialize before usage. <br>
// * This method must be called before trying to send a notification. <br>
// * Calling {@code init()} multiple time should not fail. <br>
// *
// * For example a notifier can open a connection to register the application, or it can do nothing.
// *
// * @return a usable initiated {@link Notifier} to send notification(s)
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// Notifier init();
//
// boolean tryInit();
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notification.java
// @AutoValue
// public abstract class Notification {
//
// /**
// * Indicate notification priority.
// */
// public enum Level {INFO, WARNING, ERROR}
//
// /**
// * Notification message.
// *
// * @return message.
// */
// public abstract String message();
//
// /**
// * Notification title.
// *
// * @return title.
// */
// public abstract String title();
//
// /**
// * Notification subtitle. <br>
// * Not available for all notifier implementation.
// *
// * @return subtitle.
// */
// @Nullable
// public abstract String subtitle();
//
// /**
// * Notification icon.
// *
// * @return icon.
// */
// public abstract Icon icon();
//
// /**
// * Indicate the notification priority type.
// *
// * @return type
// */
// public abstract Level level();
//
// Notification() {
// // prevent external subclasses
// }
//
// public static Builder builder(String title, String message, Icon icon) {
// return builder()
// .title(title)
// .message(message)
// .icon(icon);
// }
//
// public static Builder builder() {
// return new AutoValue_Notification.Builder().level(INFO);
// }
//
// @AutoValue.Builder
// public interface Builder {
// Builder title(String title);
// Builder message(String message);
// Builder icon(Icon icon);
// Builder subtitle(String subtitle);
// Builder level(Level level);
// Notification build();
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notifier.java
// public interface Notifier {
//
// /**
// * Send a notification.
// *
// * @param notification a notification.
// *
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// void send(Notification notification);
//
// /**
// * Close the notifier. <br>
// * This method must be called to release resources when the notifier is not needed anymore.
// */
// void close();
//
// /**
// * Indicate if the notifier is always displayed somewhere (menu/task bar, etc).
// * @return {@code true} if the notifier is persistent.
// */
// boolean isPersistent();
// }
| import fr.jcgay.notification.DiscoverableNotifier;
import fr.jcgay.notification.Notification;
import fr.jcgay.notification.Notifier; | package fr.jcgay.notification.notifier;
public class DoNothingNotifier implements DiscoverableNotifier {
private static final DoNothingNotifier INSTANCE = new DoNothingNotifier();
public static DoNothingNotifier doNothing() {
return INSTANCE;
}
private DoNothingNotifier() {
}
@Override | // Path: send-notification/src/main/java/fr/jcgay/notification/DiscoverableNotifier.java
// public interface DiscoverableNotifier extends Notifier {
//
// /**
// * Initialize before usage. <br>
// * This method must be called before trying to send a notification. <br>
// * Calling {@code init()} multiple time should not fail. <br>
// *
// * For example a notifier can open a connection to register the application, or it can do nothing.
// *
// * @return a usable initiated {@link Notifier} to send notification(s)
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// Notifier init();
//
// boolean tryInit();
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notification.java
// @AutoValue
// public abstract class Notification {
//
// /**
// * Indicate notification priority.
// */
// public enum Level {INFO, WARNING, ERROR}
//
// /**
// * Notification message.
// *
// * @return message.
// */
// public abstract String message();
//
// /**
// * Notification title.
// *
// * @return title.
// */
// public abstract String title();
//
// /**
// * Notification subtitle. <br>
// * Not available for all notifier implementation.
// *
// * @return subtitle.
// */
// @Nullable
// public abstract String subtitle();
//
// /**
// * Notification icon.
// *
// * @return icon.
// */
// public abstract Icon icon();
//
// /**
// * Indicate the notification priority type.
// *
// * @return type
// */
// public abstract Level level();
//
// Notification() {
// // prevent external subclasses
// }
//
// public static Builder builder(String title, String message, Icon icon) {
// return builder()
// .title(title)
// .message(message)
// .icon(icon);
// }
//
// public static Builder builder() {
// return new AutoValue_Notification.Builder().level(INFO);
// }
//
// @AutoValue.Builder
// public interface Builder {
// Builder title(String title);
// Builder message(String message);
// Builder icon(Icon icon);
// Builder subtitle(String subtitle);
// Builder level(Level level);
// Notification build();
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notifier.java
// public interface Notifier {
//
// /**
// * Send a notification.
// *
// * @param notification a notification.
// *
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// void send(Notification notification);
//
// /**
// * Close the notifier. <br>
// * This method must be called to release resources when the notifier is not needed anymore.
// */
// void close();
//
// /**
// * Indicate if the notifier is always displayed somewhere (menu/task bar, etc).
// * @return {@code true} if the notifier is persistent.
// */
// boolean isPersistent();
// }
// Path: send-notification/src/main/java/fr/jcgay/notification/notifier/DoNothingNotifier.java
import fr.jcgay.notification.DiscoverableNotifier;
import fr.jcgay.notification.Notification;
import fr.jcgay.notification.Notifier;
package fr.jcgay.notification.notifier;
public class DoNothingNotifier implements DiscoverableNotifier {
private static final DoNothingNotifier INSTANCE = new DoNothingNotifier();
public static DoNothingNotifier doNothing() {
return INSTANCE;
}
private DoNothingNotifier() {
}
@Override | public Notifier init() { |
jcgay/send-notification | send-notification/src/main/java/fr/jcgay/notification/notifier/DoNothingNotifier.java | // Path: send-notification/src/main/java/fr/jcgay/notification/DiscoverableNotifier.java
// public interface DiscoverableNotifier extends Notifier {
//
// /**
// * Initialize before usage. <br>
// * This method must be called before trying to send a notification. <br>
// * Calling {@code init()} multiple time should not fail. <br>
// *
// * For example a notifier can open a connection to register the application, or it can do nothing.
// *
// * @return a usable initiated {@link Notifier} to send notification(s)
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// Notifier init();
//
// boolean tryInit();
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notification.java
// @AutoValue
// public abstract class Notification {
//
// /**
// * Indicate notification priority.
// */
// public enum Level {INFO, WARNING, ERROR}
//
// /**
// * Notification message.
// *
// * @return message.
// */
// public abstract String message();
//
// /**
// * Notification title.
// *
// * @return title.
// */
// public abstract String title();
//
// /**
// * Notification subtitle. <br>
// * Not available for all notifier implementation.
// *
// * @return subtitle.
// */
// @Nullable
// public abstract String subtitle();
//
// /**
// * Notification icon.
// *
// * @return icon.
// */
// public abstract Icon icon();
//
// /**
// * Indicate the notification priority type.
// *
// * @return type
// */
// public abstract Level level();
//
// Notification() {
// // prevent external subclasses
// }
//
// public static Builder builder(String title, String message, Icon icon) {
// return builder()
// .title(title)
// .message(message)
// .icon(icon);
// }
//
// public static Builder builder() {
// return new AutoValue_Notification.Builder().level(INFO);
// }
//
// @AutoValue.Builder
// public interface Builder {
// Builder title(String title);
// Builder message(String message);
// Builder icon(Icon icon);
// Builder subtitle(String subtitle);
// Builder level(Level level);
// Notification build();
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notifier.java
// public interface Notifier {
//
// /**
// * Send a notification.
// *
// * @param notification a notification.
// *
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// void send(Notification notification);
//
// /**
// * Close the notifier. <br>
// * This method must be called to release resources when the notifier is not needed anymore.
// */
// void close();
//
// /**
// * Indicate if the notifier is always displayed somewhere (menu/task bar, etc).
// * @return {@code true} if the notifier is persistent.
// */
// boolean isPersistent();
// }
| import fr.jcgay.notification.DiscoverableNotifier;
import fr.jcgay.notification.Notification;
import fr.jcgay.notification.Notifier; | package fr.jcgay.notification.notifier;
public class DoNothingNotifier implements DiscoverableNotifier {
private static final DoNothingNotifier INSTANCE = new DoNothingNotifier();
public static DoNothingNotifier doNothing() {
return INSTANCE;
}
private DoNothingNotifier() {
}
@Override
public Notifier init() {
return this;
}
@Override | // Path: send-notification/src/main/java/fr/jcgay/notification/DiscoverableNotifier.java
// public interface DiscoverableNotifier extends Notifier {
//
// /**
// * Initialize before usage. <br>
// * This method must be called before trying to send a notification. <br>
// * Calling {@code init()} multiple time should not fail. <br>
// *
// * For example a notifier can open a connection to register the application, or it can do nothing.
// *
// * @return a usable initiated {@link Notifier} to send notification(s)
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// Notifier init();
//
// boolean tryInit();
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notification.java
// @AutoValue
// public abstract class Notification {
//
// /**
// * Indicate notification priority.
// */
// public enum Level {INFO, WARNING, ERROR}
//
// /**
// * Notification message.
// *
// * @return message.
// */
// public abstract String message();
//
// /**
// * Notification title.
// *
// * @return title.
// */
// public abstract String title();
//
// /**
// * Notification subtitle. <br>
// * Not available for all notifier implementation.
// *
// * @return subtitle.
// */
// @Nullable
// public abstract String subtitle();
//
// /**
// * Notification icon.
// *
// * @return icon.
// */
// public abstract Icon icon();
//
// /**
// * Indicate the notification priority type.
// *
// * @return type
// */
// public abstract Level level();
//
// Notification() {
// // prevent external subclasses
// }
//
// public static Builder builder(String title, String message, Icon icon) {
// return builder()
// .title(title)
// .message(message)
// .icon(icon);
// }
//
// public static Builder builder() {
// return new AutoValue_Notification.Builder().level(INFO);
// }
//
// @AutoValue.Builder
// public interface Builder {
// Builder title(String title);
// Builder message(String message);
// Builder icon(Icon icon);
// Builder subtitle(String subtitle);
// Builder level(Level level);
// Notification build();
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notifier.java
// public interface Notifier {
//
// /**
// * Send a notification.
// *
// * @param notification a notification.
// *
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// void send(Notification notification);
//
// /**
// * Close the notifier. <br>
// * This method must be called to release resources when the notifier is not needed anymore.
// */
// void close();
//
// /**
// * Indicate if the notifier is always displayed somewhere (menu/task bar, etc).
// * @return {@code true} if the notifier is persistent.
// */
// boolean isPersistent();
// }
// Path: send-notification/src/main/java/fr/jcgay/notification/notifier/DoNothingNotifier.java
import fr.jcgay.notification.DiscoverableNotifier;
import fr.jcgay.notification.Notification;
import fr.jcgay.notification.Notifier;
package fr.jcgay.notification.notifier;
public class DoNothingNotifier implements DiscoverableNotifier {
private static final DoNothingNotifier INSTANCE = new DoNothingNotifier();
public static DoNothingNotifier doNothing() {
return INSTANCE;
}
private DoNothingNotifier() {
}
@Override
public Notifier init() {
return this;
}
@Override | public void send(Notification notification) { |
jcgay/send-notification | send-notification/src/main/java/fr/jcgay/notification/notifier/systemtray/SystemTrayNotifier.java | // Path: send-notification/src/main/java/fr/jcgay/notification/Application.java
// @AutoValue
// public abstract class Application {
//
// /**
// * Uniquely identify an application. <br>
// * In order to ensure your application's signature is unique, the recommendation is to follow the Internet Media
// * type (also known as MIME content type) format as defined in IETF <a href="http://tools.ietf.org/html/rfc2046">RFC 2046</a>
// * which contains the application vendor's name - specifically: {@code application/x-vnd-some_vendor.some_app}. <br>
// * The signature must not contain spaces. <br>
// * Some examples of acceptable signatures:
// * <ul>
// * <li>{@code application/x-vnd-acme.hello_world}</li>
// * <li>{@code application/x-vnd-fullphat.snaRSS}</li>
// * </ul>
// *
// * @return unique identifier.
// */
// public abstract String id();
//
// /**
// * A name that will identify the application for the user. <br>
// * Examples:
// * <ul>
// * <li>Maven</li>
// * <li>Gradle</li>
// * </ul>
// *
// * @return application name.
// */
// public abstract String name();
//
// /**
// * A timeout to wait for before cancelling application registration or notification sending.
// *
// * @return timeout in milliseconds, or {@code -1} if not specified.
// */
// public abstract long timeout();
//
// /**
// * The application icon.
// *
// * @return application icon.
// */
// public abstract Icon icon();
//
// Application() {
// // prevent external subclasses
// }
//
// public static Builder builder() {
// return new AutoValue_Application.Builder()
// .timeout(-1);
// }
//
// public static Builder builder(String id, String name, Icon icon) {
// return builder()
// .id(id)
// .name(name)
// .icon(icon);
// }
//
// @AutoValue.Builder
// public interface Builder {
// Builder id(String id);
// Builder name(String name);
// Builder icon(Icon icon);
// Builder timeout(long timeout);
// Application build();
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/DiscoverableNotifier.java
// public interface DiscoverableNotifier extends Notifier {
//
// /**
// * Initialize before usage. <br>
// * This method must be called before trying to send a notification. <br>
// * Calling {@code init()} multiple time should not fail. <br>
// *
// * For example a notifier can open a connection to register the application, or it can do nothing.
// *
// * @return a usable initiated {@link Notifier} to send notification(s)
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// Notifier init();
//
// boolean tryInit();
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notification.java
// @AutoValue
// public abstract class Notification {
//
// /**
// * Indicate notification priority.
// */
// public enum Level {INFO, WARNING, ERROR}
//
// /**
// * Notification message.
// *
// * @return message.
// */
// public abstract String message();
//
// /**
// * Notification title.
// *
// * @return title.
// */
// public abstract String title();
//
// /**
// * Notification subtitle. <br>
// * Not available for all notifier implementation.
// *
// * @return subtitle.
// */
// @Nullable
// public abstract String subtitle();
//
// /**
// * Notification icon.
// *
// * @return icon.
// */
// public abstract Icon icon();
//
// /**
// * Indicate the notification priority type.
// *
// * @return type
// */
// public abstract Level level();
//
// Notification() {
// // prevent external subclasses
// }
//
// public static Builder builder(String title, String message, Icon icon) {
// return builder()
// .title(title)
// .message(message)
// .icon(icon);
// }
//
// public static Builder builder() {
// return new AutoValue_Notification.Builder().level(INFO);
// }
//
// @AutoValue.Builder
// public interface Builder {
// Builder title(String title);
// Builder message(String message);
// Builder icon(Icon icon);
// Builder subtitle(String subtitle);
// Builder level(Level level);
// Notification build();
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notifier.java
// public interface Notifier {
//
// /**
// * Send a notification.
// *
// * @param notification a notification.
// *
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// void send(Notification notification);
//
// /**
// * Close the notifier. <br>
// * This method must be called to release resources when the notifier is not needed anymore.
// */
// void close();
//
// /**
// * Indicate if the notifier is always displayed somewhere (menu/task bar, etc).
// * @return {@code true} if the notifier is persistent.
// */
// boolean isPersistent();
// }
| import com.google.common.base.MoreObjects;
import com.google.common.base.Objects;
import fr.jcgay.notification.Application;
import fr.jcgay.notification.DiscoverableNotifier;
import fr.jcgay.notification.Notification;
import fr.jcgay.notification.Notifier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.awt.*;
import java.awt.TrayIcon.MessageType;
import static java.util.concurrent.TimeUnit.SECONDS; | package fr.jcgay.notification.notifier.systemtray;
public class SystemTrayNotifier implements DiscoverableNotifier {
private static final Logger LOGGER = LoggerFactory.getLogger(SystemTrayNotifier.class);
| // Path: send-notification/src/main/java/fr/jcgay/notification/Application.java
// @AutoValue
// public abstract class Application {
//
// /**
// * Uniquely identify an application. <br>
// * In order to ensure your application's signature is unique, the recommendation is to follow the Internet Media
// * type (also known as MIME content type) format as defined in IETF <a href="http://tools.ietf.org/html/rfc2046">RFC 2046</a>
// * which contains the application vendor's name - specifically: {@code application/x-vnd-some_vendor.some_app}. <br>
// * The signature must not contain spaces. <br>
// * Some examples of acceptable signatures:
// * <ul>
// * <li>{@code application/x-vnd-acme.hello_world}</li>
// * <li>{@code application/x-vnd-fullphat.snaRSS}</li>
// * </ul>
// *
// * @return unique identifier.
// */
// public abstract String id();
//
// /**
// * A name that will identify the application for the user. <br>
// * Examples:
// * <ul>
// * <li>Maven</li>
// * <li>Gradle</li>
// * </ul>
// *
// * @return application name.
// */
// public abstract String name();
//
// /**
// * A timeout to wait for before cancelling application registration or notification sending.
// *
// * @return timeout in milliseconds, or {@code -1} if not specified.
// */
// public abstract long timeout();
//
// /**
// * The application icon.
// *
// * @return application icon.
// */
// public abstract Icon icon();
//
// Application() {
// // prevent external subclasses
// }
//
// public static Builder builder() {
// return new AutoValue_Application.Builder()
// .timeout(-1);
// }
//
// public static Builder builder(String id, String name, Icon icon) {
// return builder()
// .id(id)
// .name(name)
// .icon(icon);
// }
//
// @AutoValue.Builder
// public interface Builder {
// Builder id(String id);
// Builder name(String name);
// Builder icon(Icon icon);
// Builder timeout(long timeout);
// Application build();
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/DiscoverableNotifier.java
// public interface DiscoverableNotifier extends Notifier {
//
// /**
// * Initialize before usage. <br>
// * This method must be called before trying to send a notification. <br>
// * Calling {@code init()} multiple time should not fail. <br>
// *
// * For example a notifier can open a connection to register the application, or it can do nothing.
// *
// * @return a usable initiated {@link Notifier} to send notification(s)
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// Notifier init();
//
// boolean tryInit();
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notification.java
// @AutoValue
// public abstract class Notification {
//
// /**
// * Indicate notification priority.
// */
// public enum Level {INFO, WARNING, ERROR}
//
// /**
// * Notification message.
// *
// * @return message.
// */
// public abstract String message();
//
// /**
// * Notification title.
// *
// * @return title.
// */
// public abstract String title();
//
// /**
// * Notification subtitle. <br>
// * Not available for all notifier implementation.
// *
// * @return subtitle.
// */
// @Nullable
// public abstract String subtitle();
//
// /**
// * Notification icon.
// *
// * @return icon.
// */
// public abstract Icon icon();
//
// /**
// * Indicate the notification priority type.
// *
// * @return type
// */
// public abstract Level level();
//
// Notification() {
// // prevent external subclasses
// }
//
// public static Builder builder(String title, String message, Icon icon) {
// return builder()
// .title(title)
// .message(message)
// .icon(icon);
// }
//
// public static Builder builder() {
// return new AutoValue_Notification.Builder().level(INFO);
// }
//
// @AutoValue.Builder
// public interface Builder {
// Builder title(String title);
// Builder message(String message);
// Builder icon(Icon icon);
// Builder subtitle(String subtitle);
// Builder level(Level level);
// Notification build();
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notifier.java
// public interface Notifier {
//
// /**
// * Send a notification.
// *
// * @param notification a notification.
// *
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// void send(Notification notification);
//
// /**
// * Close the notifier. <br>
// * This method must be called to release resources when the notifier is not needed anymore.
// */
// void close();
//
// /**
// * Indicate if the notifier is always displayed somewhere (menu/task bar, etc).
// * @return {@code true} if the notifier is persistent.
// */
// boolean isPersistent();
// }
// Path: send-notification/src/main/java/fr/jcgay/notification/notifier/systemtray/SystemTrayNotifier.java
import com.google.common.base.MoreObjects;
import com.google.common.base.Objects;
import fr.jcgay.notification.Application;
import fr.jcgay.notification.DiscoverableNotifier;
import fr.jcgay.notification.Notification;
import fr.jcgay.notification.Notifier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.awt.*;
import java.awt.TrayIcon.MessageType;
import static java.util.concurrent.TimeUnit.SECONDS;
package fr.jcgay.notification.notifier.systemtray;
public class SystemTrayNotifier implements DiscoverableNotifier {
private static final Logger LOGGER = LoggerFactory.getLogger(SystemTrayNotifier.class);
| private final Application application; |
jcgay/send-notification | send-notification/src/main/java/fr/jcgay/notification/notifier/systemtray/SystemTrayNotifier.java | // Path: send-notification/src/main/java/fr/jcgay/notification/Application.java
// @AutoValue
// public abstract class Application {
//
// /**
// * Uniquely identify an application. <br>
// * In order to ensure your application's signature is unique, the recommendation is to follow the Internet Media
// * type (also known as MIME content type) format as defined in IETF <a href="http://tools.ietf.org/html/rfc2046">RFC 2046</a>
// * which contains the application vendor's name - specifically: {@code application/x-vnd-some_vendor.some_app}. <br>
// * The signature must not contain spaces. <br>
// * Some examples of acceptable signatures:
// * <ul>
// * <li>{@code application/x-vnd-acme.hello_world}</li>
// * <li>{@code application/x-vnd-fullphat.snaRSS}</li>
// * </ul>
// *
// * @return unique identifier.
// */
// public abstract String id();
//
// /**
// * A name that will identify the application for the user. <br>
// * Examples:
// * <ul>
// * <li>Maven</li>
// * <li>Gradle</li>
// * </ul>
// *
// * @return application name.
// */
// public abstract String name();
//
// /**
// * A timeout to wait for before cancelling application registration or notification sending.
// *
// * @return timeout in milliseconds, or {@code -1} if not specified.
// */
// public abstract long timeout();
//
// /**
// * The application icon.
// *
// * @return application icon.
// */
// public abstract Icon icon();
//
// Application() {
// // prevent external subclasses
// }
//
// public static Builder builder() {
// return new AutoValue_Application.Builder()
// .timeout(-1);
// }
//
// public static Builder builder(String id, String name, Icon icon) {
// return builder()
// .id(id)
// .name(name)
// .icon(icon);
// }
//
// @AutoValue.Builder
// public interface Builder {
// Builder id(String id);
// Builder name(String name);
// Builder icon(Icon icon);
// Builder timeout(long timeout);
// Application build();
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/DiscoverableNotifier.java
// public interface DiscoverableNotifier extends Notifier {
//
// /**
// * Initialize before usage. <br>
// * This method must be called before trying to send a notification. <br>
// * Calling {@code init()} multiple time should not fail. <br>
// *
// * For example a notifier can open a connection to register the application, or it can do nothing.
// *
// * @return a usable initiated {@link Notifier} to send notification(s)
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// Notifier init();
//
// boolean tryInit();
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notification.java
// @AutoValue
// public abstract class Notification {
//
// /**
// * Indicate notification priority.
// */
// public enum Level {INFO, WARNING, ERROR}
//
// /**
// * Notification message.
// *
// * @return message.
// */
// public abstract String message();
//
// /**
// * Notification title.
// *
// * @return title.
// */
// public abstract String title();
//
// /**
// * Notification subtitle. <br>
// * Not available for all notifier implementation.
// *
// * @return subtitle.
// */
// @Nullable
// public abstract String subtitle();
//
// /**
// * Notification icon.
// *
// * @return icon.
// */
// public abstract Icon icon();
//
// /**
// * Indicate the notification priority type.
// *
// * @return type
// */
// public abstract Level level();
//
// Notification() {
// // prevent external subclasses
// }
//
// public static Builder builder(String title, String message, Icon icon) {
// return builder()
// .title(title)
// .message(message)
// .icon(icon);
// }
//
// public static Builder builder() {
// return new AutoValue_Notification.Builder().level(INFO);
// }
//
// @AutoValue.Builder
// public interface Builder {
// Builder title(String title);
// Builder message(String message);
// Builder icon(Icon icon);
// Builder subtitle(String subtitle);
// Builder level(Level level);
// Notification build();
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notifier.java
// public interface Notifier {
//
// /**
// * Send a notification.
// *
// * @param notification a notification.
// *
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// void send(Notification notification);
//
// /**
// * Close the notifier. <br>
// * This method must be called to release resources when the notifier is not needed anymore.
// */
// void close();
//
// /**
// * Indicate if the notifier is always displayed somewhere (menu/task bar, etc).
// * @return {@code true} if the notifier is persistent.
// */
// boolean isPersistent();
// }
| import com.google.common.base.MoreObjects;
import com.google.common.base.Objects;
import fr.jcgay.notification.Application;
import fr.jcgay.notification.DiscoverableNotifier;
import fr.jcgay.notification.Notification;
import fr.jcgay.notification.Notifier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.awt.*;
import java.awt.TrayIcon.MessageType;
import static java.util.concurrent.TimeUnit.SECONDS; | package fr.jcgay.notification.notifier.systemtray;
public class SystemTrayNotifier implements DiscoverableNotifier {
private static final Logger LOGGER = LoggerFactory.getLogger(SystemTrayNotifier.class);
private final Application application;
private boolean skipNotifications;
private TrayIcon icon;
public SystemTrayNotifier(Application application) {
LOGGER.debug("Configuring System Tray for application {}.", application);
this.application = application;
}
@Override | // Path: send-notification/src/main/java/fr/jcgay/notification/Application.java
// @AutoValue
// public abstract class Application {
//
// /**
// * Uniquely identify an application. <br>
// * In order to ensure your application's signature is unique, the recommendation is to follow the Internet Media
// * type (also known as MIME content type) format as defined in IETF <a href="http://tools.ietf.org/html/rfc2046">RFC 2046</a>
// * which contains the application vendor's name - specifically: {@code application/x-vnd-some_vendor.some_app}. <br>
// * The signature must not contain spaces. <br>
// * Some examples of acceptable signatures:
// * <ul>
// * <li>{@code application/x-vnd-acme.hello_world}</li>
// * <li>{@code application/x-vnd-fullphat.snaRSS}</li>
// * </ul>
// *
// * @return unique identifier.
// */
// public abstract String id();
//
// /**
// * A name that will identify the application for the user. <br>
// * Examples:
// * <ul>
// * <li>Maven</li>
// * <li>Gradle</li>
// * </ul>
// *
// * @return application name.
// */
// public abstract String name();
//
// /**
// * A timeout to wait for before cancelling application registration or notification sending.
// *
// * @return timeout in milliseconds, or {@code -1} if not specified.
// */
// public abstract long timeout();
//
// /**
// * The application icon.
// *
// * @return application icon.
// */
// public abstract Icon icon();
//
// Application() {
// // prevent external subclasses
// }
//
// public static Builder builder() {
// return new AutoValue_Application.Builder()
// .timeout(-1);
// }
//
// public static Builder builder(String id, String name, Icon icon) {
// return builder()
// .id(id)
// .name(name)
// .icon(icon);
// }
//
// @AutoValue.Builder
// public interface Builder {
// Builder id(String id);
// Builder name(String name);
// Builder icon(Icon icon);
// Builder timeout(long timeout);
// Application build();
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/DiscoverableNotifier.java
// public interface DiscoverableNotifier extends Notifier {
//
// /**
// * Initialize before usage. <br>
// * This method must be called before trying to send a notification. <br>
// * Calling {@code init()} multiple time should not fail. <br>
// *
// * For example a notifier can open a connection to register the application, or it can do nothing.
// *
// * @return a usable initiated {@link Notifier} to send notification(s)
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// Notifier init();
//
// boolean tryInit();
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notification.java
// @AutoValue
// public abstract class Notification {
//
// /**
// * Indicate notification priority.
// */
// public enum Level {INFO, WARNING, ERROR}
//
// /**
// * Notification message.
// *
// * @return message.
// */
// public abstract String message();
//
// /**
// * Notification title.
// *
// * @return title.
// */
// public abstract String title();
//
// /**
// * Notification subtitle. <br>
// * Not available for all notifier implementation.
// *
// * @return subtitle.
// */
// @Nullable
// public abstract String subtitle();
//
// /**
// * Notification icon.
// *
// * @return icon.
// */
// public abstract Icon icon();
//
// /**
// * Indicate the notification priority type.
// *
// * @return type
// */
// public abstract Level level();
//
// Notification() {
// // prevent external subclasses
// }
//
// public static Builder builder(String title, String message, Icon icon) {
// return builder()
// .title(title)
// .message(message)
// .icon(icon);
// }
//
// public static Builder builder() {
// return new AutoValue_Notification.Builder().level(INFO);
// }
//
// @AutoValue.Builder
// public interface Builder {
// Builder title(String title);
// Builder message(String message);
// Builder icon(Icon icon);
// Builder subtitle(String subtitle);
// Builder level(Level level);
// Notification build();
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notifier.java
// public interface Notifier {
//
// /**
// * Send a notification.
// *
// * @param notification a notification.
// *
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// void send(Notification notification);
//
// /**
// * Close the notifier. <br>
// * This method must be called to release resources when the notifier is not needed anymore.
// */
// void close();
//
// /**
// * Indicate if the notifier is always displayed somewhere (menu/task bar, etc).
// * @return {@code true} if the notifier is persistent.
// */
// boolean isPersistent();
// }
// Path: send-notification/src/main/java/fr/jcgay/notification/notifier/systemtray/SystemTrayNotifier.java
import com.google.common.base.MoreObjects;
import com.google.common.base.Objects;
import fr.jcgay.notification.Application;
import fr.jcgay.notification.DiscoverableNotifier;
import fr.jcgay.notification.Notification;
import fr.jcgay.notification.Notifier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.awt.*;
import java.awt.TrayIcon.MessageType;
import static java.util.concurrent.TimeUnit.SECONDS;
package fr.jcgay.notification.notifier.systemtray;
public class SystemTrayNotifier implements DiscoverableNotifier {
private static final Logger LOGGER = LoggerFactory.getLogger(SystemTrayNotifier.class);
private final Application application;
private boolean skipNotifications;
private TrayIcon icon;
public SystemTrayNotifier(Application application) {
LOGGER.debug("Configuring System Tray for application {}.", application);
this.application = application;
}
@Override | public Notifier init() { |
jcgay/send-notification | send-notification/src/main/java/fr/jcgay/notification/SendNotification.java | // Path: send-notification/src/main/java/fr/jcgay/notification/configuration/ChosenNotifiers.java
// @AutoValue
// public abstract class ChosenNotifiers {
//
// private static final String SEPARATOR = ",";
//
// public abstract String primary();
//
// public abstract Set<String> secondary();
//
// ChosenNotifiers() {
// // prevent external subclasses
// }
//
// public static ChosenNotifiers from(String notifier) {
// checkNotNull(notifier);
//
// if (!notifier.contains(SEPARATOR)) {
// return new AutoValue_ChosenNotifiers(notifier, Collections.emptySet());
// }
//
// String[] notifiers = notifier.split(SEPARATOR);
// Set<String> secondary = new LinkedHashSet<>(asList(notifiers).subList(1, notifiers.length));
// return new AutoValue_ChosenNotifiers(notifiers[0], secondary);
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/configuration/ConfigurationReader.java
// public class ConfigurationReader {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(ConfigurationReader.class);
//
// private final Properties properties;
// private final URL location;
//
// private ConfigurationReader(Properties properties) {
// this(properties, null);
// }
//
// public ConfigurationReader(Properties configuration, URL location) {
// this.properties = configuration;
// this.location = location;
// }
//
// public static ConfigurationReader atPath(String path) {
// try {
// return atUrl(new File(path).toURI().toURL());
// } catch (MalformedURLException e) {
// LOGGER.debug("URL built for path [{}] is malformed will use default configuration.", path, e);
// return new ConfigurationReader(new Properties());
// }
// }
//
// public static ConfigurationReader atUrl(URL url) {
// Properties configuration = new Properties();
// try {
// configuration.load(url.openStream());
// } catch (IOException e) {
// LOGGER.debug("Cannot read configuration at [{}], will use default one.", url, e);
// }
// return new ConfigurationReader(configuration, url);
// }
//
// public Properties get() {
// LOGGER.debug("Notification configuration read from {} is: {}.", location, properties);
// return properties;
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/configuration/OperatingSystem.java
// public class OperatingSystem {
//
// private final String currentOs;
//
// public OperatingSystem() {
// currentOs = System.getProperty("os.name").toLowerCase();
// }
//
// public OperatingSystem(String currentOs) {
// this.currentOs = currentOs.toLowerCase();
// }
//
// public boolean isMac() {
// return currentOs.contains("mac");
// }
//
// public boolean isWindows() {
// return currentOs.contains("win");
// }
//
// @Override
// public String toString() {
// return "OperatingSystem{" +
// "currentOs='" + currentOs + '\'' +
// '}';
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/notifier/DoNothingNotifier.java
// public class DoNothingNotifier implements DiscoverableNotifier {
//
// private static final DoNothingNotifier INSTANCE = new DoNothingNotifier();
//
// public static DoNothingNotifier doNothing() {
// return INSTANCE;
// }
//
// private DoNothingNotifier() {
// }
//
// @Override
// public Notifier init() {
// return this;
// }
//
// @Override
// public void send(Notification notification) {
// // do nothing
// }
//
// @Override
// public void close() {
// // do nothing
// }
//
// @Override
// public boolean isPersistent() {
// return false;
// }
//
// @Override
// public boolean tryInit() {
// return true;
// }
// }
| import com.google.common.annotations.VisibleForTesting;
import fr.jcgay.notification.configuration.ChosenNotifiers;
import fr.jcgay.notification.configuration.ConfigurationReader;
import fr.jcgay.notification.configuration.OperatingSystem;
import fr.jcgay.notification.notifier.DoNothingNotifier;
import org.slf4j.Logger;
import java.util.Properties;
import java.util.Set;
import static com.google.common.base.Preconditions.checkNotNull;
import static org.slf4j.LoggerFactory.getLogger; | package fr.jcgay.notification;
/**
* Fluent builder to create a {@link fr.jcgay.notification.Notifier}. <br>
*
* You'll need a configuration file (by default: {@code {user.home}/.send-notification}
* to select and configure a {@link fr.jcgay.notification.Notifier}. <br>
* This file must be property based (example):
* <pre>{@code
* notifier.implementation = pushbullet
* notifier.message.short = true
* notifier.pushbullet.apikey = 1234
* }</pre>
*
* Then to create a notifier you can use:
* <pre>{@code
* Notifier notifier = new SendNotification()
* .setApplication(application)
* .initNotifier();
* }</pre>
*/
public class SendNotification {
private static final Logger LOGGER = getLogger(SendNotification.class);
private final NotifierProvider provider;
| // Path: send-notification/src/main/java/fr/jcgay/notification/configuration/ChosenNotifiers.java
// @AutoValue
// public abstract class ChosenNotifiers {
//
// private static final String SEPARATOR = ",";
//
// public abstract String primary();
//
// public abstract Set<String> secondary();
//
// ChosenNotifiers() {
// // prevent external subclasses
// }
//
// public static ChosenNotifiers from(String notifier) {
// checkNotNull(notifier);
//
// if (!notifier.contains(SEPARATOR)) {
// return new AutoValue_ChosenNotifiers(notifier, Collections.emptySet());
// }
//
// String[] notifiers = notifier.split(SEPARATOR);
// Set<String> secondary = new LinkedHashSet<>(asList(notifiers).subList(1, notifiers.length));
// return new AutoValue_ChosenNotifiers(notifiers[0], secondary);
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/configuration/ConfigurationReader.java
// public class ConfigurationReader {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(ConfigurationReader.class);
//
// private final Properties properties;
// private final URL location;
//
// private ConfigurationReader(Properties properties) {
// this(properties, null);
// }
//
// public ConfigurationReader(Properties configuration, URL location) {
// this.properties = configuration;
// this.location = location;
// }
//
// public static ConfigurationReader atPath(String path) {
// try {
// return atUrl(new File(path).toURI().toURL());
// } catch (MalformedURLException e) {
// LOGGER.debug("URL built for path [{}] is malformed will use default configuration.", path, e);
// return new ConfigurationReader(new Properties());
// }
// }
//
// public static ConfigurationReader atUrl(URL url) {
// Properties configuration = new Properties();
// try {
// configuration.load(url.openStream());
// } catch (IOException e) {
// LOGGER.debug("Cannot read configuration at [{}], will use default one.", url, e);
// }
// return new ConfigurationReader(configuration, url);
// }
//
// public Properties get() {
// LOGGER.debug("Notification configuration read from {} is: {}.", location, properties);
// return properties;
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/configuration/OperatingSystem.java
// public class OperatingSystem {
//
// private final String currentOs;
//
// public OperatingSystem() {
// currentOs = System.getProperty("os.name").toLowerCase();
// }
//
// public OperatingSystem(String currentOs) {
// this.currentOs = currentOs.toLowerCase();
// }
//
// public boolean isMac() {
// return currentOs.contains("mac");
// }
//
// public boolean isWindows() {
// return currentOs.contains("win");
// }
//
// @Override
// public String toString() {
// return "OperatingSystem{" +
// "currentOs='" + currentOs + '\'' +
// '}';
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/notifier/DoNothingNotifier.java
// public class DoNothingNotifier implements DiscoverableNotifier {
//
// private static final DoNothingNotifier INSTANCE = new DoNothingNotifier();
//
// public static DoNothingNotifier doNothing() {
// return INSTANCE;
// }
//
// private DoNothingNotifier() {
// }
//
// @Override
// public Notifier init() {
// return this;
// }
//
// @Override
// public void send(Notification notification) {
// // do nothing
// }
//
// @Override
// public void close() {
// // do nothing
// }
//
// @Override
// public boolean isPersistent() {
// return false;
// }
//
// @Override
// public boolean tryInit() {
// return true;
// }
// }
// Path: send-notification/src/main/java/fr/jcgay/notification/SendNotification.java
import com.google.common.annotations.VisibleForTesting;
import fr.jcgay.notification.configuration.ChosenNotifiers;
import fr.jcgay.notification.configuration.ConfigurationReader;
import fr.jcgay.notification.configuration.OperatingSystem;
import fr.jcgay.notification.notifier.DoNothingNotifier;
import org.slf4j.Logger;
import java.util.Properties;
import java.util.Set;
import static com.google.common.base.Preconditions.checkNotNull;
import static org.slf4j.LoggerFactory.getLogger;
package fr.jcgay.notification;
/**
* Fluent builder to create a {@link fr.jcgay.notification.Notifier}. <br>
*
* You'll need a configuration file (by default: {@code {user.home}/.send-notification}
* to select and configure a {@link fr.jcgay.notification.Notifier}. <br>
* This file must be property based (example):
* <pre>{@code
* notifier.implementation = pushbullet
* notifier.message.short = true
* notifier.pushbullet.apikey = 1234
* }</pre>
*
* Then to create a notifier you can use:
* <pre>{@code
* Notifier notifier = new SendNotification()
* .setApplication(application)
* .initNotifier();
* }</pre>
*/
public class SendNotification {
private static final Logger LOGGER = getLogger(SendNotification.class);
private final NotifierProvider provider;
| private ConfigurationReader configuration; |
jcgay/send-notification | send-notification/src/main/java/fr/jcgay/notification/SendNotification.java | // Path: send-notification/src/main/java/fr/jcgay/notification/configuration/ChosenNotifiers.java
// @AutoValue
// public abstract class ChosenNotifiers {
//
// private static final String SEPARATOR = ",";
//
// public abstract String primary();
//
// public abstract Set<String> secondary();
//
// ChosenNotifiers() {
// // prevent external subclasses
// }
//
// public static ChosenNotifiers from(String notifier) {
// checkNotNull(notifier);
//
// if (!notifier.contains(SEPARATOR)) {
// return new AutoValue_ChosenNotifiers(notifier, Collections.emptySet());
// }
//
// String[] notifiers = notifier.split(SEPARATOR);
// Set<String> secondary = new LinkedHashSet<>(asList(notifiers).subList(1, notifiers.length));
// return new AutoValue_ChosenNotifiers(notifiers[0], secondary);
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/configuration/ConfigurationReader.java
// public class ConfigurationReader {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(ConfigurationReader.class);
//
// private final Properties properties;
// private final URL location;
//
// private ConfigurationReader(Properties properties) {
// this(properties, null);
// }
//
// public ConfigurationReader(Properties configuration, URL location) {
// this.properties = configuration;
// this.location = location;
// }
//
// public static ConfigurationReader atPath(String path) {
// try {
// return atUrl(new File(path).toURI().toURL());
// } catch (MalformedURLException e) {
// LOGGER.debug("URL built for path [{}] is malformed will use default configuration.", path, e);
// return new ConfigurationReader(new Properties());
// }
// }
//
// public static ConfigurationReader atUrl(URL url) {
// Properties configuration = new Properties();
// try {
// configuration.load(url.openStream());
// } catch (IOException e) {
// LOGGER.debug("Cannot read configuration at [{}], will use default one.", url, e);
// }
// return new ConfigurationReader(configuration, url);
// }
//
// public Properties get() {
// LOGGER.debug("Notification configuration read from {} is: {}.", location, properties);
// return properties;
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/configuration/OperatingSystem.java
// public class OperatingSystem {
//
// private final String currentOs;
//
// public OperatingSystem() {
// currentOs = System.getProperty("os.name").toLowerCase();
// }
//
// public OperatingSystem(String currentOs) {
// this.currentOs = currentOs.toLowerCase();
// }
//
// public boolean isMac() {
// return currentOs.contains("mac");
// }
//
// public boolean isWindows() {
// return currentOs.contains("win");
// }
//
// @Override
// public String toString() {
// return "OperatingSystem{" +
// "currentOs='" + currentOs + '\'' +
// '}';
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/notifier/DoNothingNotifier.java
// public class DoNothingNotifier implements DiscoverableNotifier {
//
// private static final DoNothingNotifier INSTANCE = new DoNothingNotifier();
//
// public static DoNothingNotifier doNothing() {
// return INSTANCE;
// }
//
// private DoNothingNotifier() {
// }
//
// @Override
// public Notifier init() {
// return this;
// }
//
// @Override
// public void send(Notification notification) {
// // do nothing
// }
//
// @Override
// public void close() {
// // do nothing
// }
//
// @Override
// public boolean isPersistent() {
// return false;
// }
//
// @Override
// public boolean tryInit() {
// return true;
// }
// }
| import com.google.common.annotations.VisibleForTesting;
import fr.jcgay.notification.configuration.ChosenNotifiers;
import fr.jcgay.notification.configuration.ConfigurationReader;
import fr.jcgay.notification.configuration.OperatingSystem;
import fr.jcgay.notification.notifier.DoNothingNotifier;
import org.slf4j.Logger;
import java.util.Properties;
import java.util.Set;
import static com.google.common.base.Preconditions.checkNotNull;
import static org.slf4j.LoggerFactory.getLogger; | package fr.jcgay.notification;
/**
* Fluent builder to create a {@link fr.jcgay.notification.Notifier}. <br>
*
* You'll need a configuration file (by default: {@code {user.home}/.send-notification}
* to select and configure a {@link fr.jcgay.notification.Notifier}. <br>
* This file must be property based (example):
* <pre>{@code
* notifier.implementation = pushbullet
* notifier.message.short = true
* notifier.pushbullet.apikey = 1234
* }</pre>
*
* Then to create a notifier you can use:
* <pre>{@code
* Notifier notifier = new SendNotification()
* .setApplication(application)
* .initNotifier();
* }</pre>
*/
public class SendNotification {
private static final Logger LOGGER = getLogger(SendNotification.class);
private final NotifierProvider provider;
private ConfigurationReader configuration; | // Path: send-notification/src/main/java/fr/jcgay/notification/configuration/ChosenNotifiers.java
// @AutoValue
// public abstract class ChosenNotifiers {
//
// private static final String SEPARATOR = ",";
//
// public abstract String primary();
//
// public abstract Set<String> secondary();
//
// ChosenNotifiers() {
// // prevent external subclasses
// }
//
// public static ChosenNotifiers from(String notifier) {
// checkNotNull(notifier);
//
// if (!notifier.contains(SEPARATOR)) {
// return new AutoValue_ChosenNotifiers(notifier, Collections.emptySet());
// }
//
// String[] notifiers = notifier.split(SEPARATOR);
// Set<String> secondary = new LinkedHashSet<>(asList(notifiers).subList(1, notifiers.length));
// return new AutoValue_ChosenNotifiers(notifiers[0], secondary);
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/configuration/ConfigurationReader.java
// public class ConfigurationReader {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(ConfigurationReader.class);
//
// private final Properties properties;
// private final URL location;
//
// private ConfigurationReader(Properties properties) {
// this(properties, null);
// }
//
// public ConfigurationReader(Properties configuration, URL location) {
// this.properties = configuration;
// this.location = location;
// }
//
// public static ConfigurationReader atPath(String path) {
// try {
// return atUrl(new File(path).toURI().toURL());
// } catch (MalformedURLException e) {
// LOGGER.debug("URL built for path [{}] is malformed will use default configuration.", path, e);
// return new ConfigurationReader(new Properties());
// }
// }
//
// public static ConfigurationReader atUrl(URL url) {
// Properties configuration = new Properties();
// try {
// configuration.load(url.openStream());
// } catch (IOException e) {
// LOGGER.debug("Cannot read configuration at [{}], will use default one.", url, e);
// }
// return new ConfigurationReader(configuration, url);
// }
//
// public Properties get() {
// LOGGER.debug("Notification configuration read from {} is: {}.", location, properties);
// return properties;
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/configuration/OperatingSystem.java
// public class OperatingSystem {
//
// private final String currentOs;
//
// public OperatingSystem() {
// currentOs = System.getProperty("os.name").toLowerCase();
// }
//
// public OperatingSystem(String currentOs) {
// this.currentOs = currentOs.toLowerCase();
// }
//
// public boolean isMac() {
// return currentOs.contains("mac");
// }
//
// public boolean isWindows() {
// return currentOs.contains("win");
// }
//
// @Override
// public String toString() {
// return "OperatingSystem{" +
// "currentOs='" + currentOs + '\'' +
// '}';
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/notifier/DoNothingNotifier.java
// public class DoNothingNotifier implements DiscoverableNotifier {
//
// private static final DoNothingNotifier INSTANCE = new DoNothingNotifier();
//
// public static DoNothingNotifier doNothing() {
// return INSTANCE;
// }
//
// private DoNothingNotifier() {
// }
//
// @Override
// public Notifier init() {
// return this;
// }
//
// @Override
// public void send(Notification notification) {
// // do nothing
// }
//
// @Override
// public void close() {
// // do nothing
// }
//
// @Override
// public boolean isPersistent() {
// return false;
// }
//
// @Override
// public boolean tryInit() {
// return true;
// }
// }
// Path: send-notification/src/main/java/fr/jcgay/notification/SendNotification.java
import com.google.common.annotations.VisibleForTesting;
import fr.jcgay.notification.configuration.ChosenNotifiers;
import fr.jcgay.notification.configuration.ConfigurationReader;
import fr.jcgay.notification.configuration.OperatingSystem;
import fr.jcgay.notification.notifier.DoNothingNotifier;
import org.slf4j.Logger;
import java.util.Properties;
import java.util.Set;
import static com.google.common.base.Preconditions.checkNotNull;
import static org.slf4j.LoggerFactory.getLogger;
package fr.jcgay.notification;
/**
* Fluent builder to create a {@link fr.jcgay.notification.Notifier}. <br>
*
* You'll need a configuration file (by default: {@code {user.home}/.send-notification}
* to select and configure a {@link fr.jcgay.notification.Notifier}. <br>
* This file must be property based (example):
* <pre>{@code
* notifier.implementation = pushbullet
* notifier.message.short = true
* notifier.pushbullet.apikey = 1234
* }</pre>
*
* Then to create a notifier you can use:
* <pre>{@code
* Notifier notifier = new SendNotification()
* .setApplication(application)
* .initNotifier();
* }</pre>
*/
public class SendNotification {
private static final Logger LOGGER = getLogger(SendNotification.class);
private final NotifierProvider provider;
private ConfigurationReader configuration; | private ChosenNotifiers chosenNotifiers; |
jcgay/send-notification | send-notification/src/main/java/fr/jcgay/notification/SendNotification.java | // Path: send-notification/src/main/java/fr/jcgay/notification/configuration/ChosenNotifiers.java
// @AutoValue
// public abstract class ChosenNotifiers {
//
// private static final String SEPARATOR = ",";
//
// public abstract String primary();
//
// public abstract Set<String> secondary();
//
// ChosenNotifiers() {
// // prevent external subclasses
// }
//
// public static ChosenNotifiers from(String notifier) {
// checkNotNull(notifier);
//
// if (!notifier.contains(SEPARATOR)) {
// return new AutoValue_ChosenNotifiers(notifier, Collections.emptySet());
// }
//
// String[] notifiers = notifier.split(SEPARATOR);
// Set<String> secondary = new LinkedHashSet<>(asList(notifiers).subList(1, notifiers.length));
// return new AutoValue_ChosenNotifiers(notifiers[0], secondary);
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/configuration/ConfigurationReader.java
// public class ConfigurationReader {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(ConfigurationReader.class);
//
// private final Properties properties;
// private final URL location;
//
// private ConfigurationReader(Properties properties) {
// this(properties, null);
// }
//
// public ConfigurationReader(Properties configuration, URL location) {
// this.properties = configuration;
// this.location = location;
// }
//
// public static ConfigurationReader atPath(String path) {
// try {
// return atUrl(new File(path).toURI().toURL());
// } catch (MalformedURLException e) {
// LOGGER.debug("URL built for path [{}] is malformed will use default configuration.", path, e);
// return new ConfigurationReader(new Properties());
// }
// }
//
// public static ConfigurationReader atUrl(URL url) {
// Properties configuration = new Properties();
// try {
// configuration.load(url.openStream());
// } catch (IOException e) {
// LOGGER.debug("Cannot read configuration at [{}], will use default one.", url, e);
// }
// return new ConfigurationReader(configuration, url);
// }
//
// public Properties get() {
// LOGGER.debug("Notification configuration read from {} is: {}.", location, properties);
// return properties;
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/configuration/OperatingSystem.java
// public class OperatingSystem {
//
// private final String currentOs;
//
// public OperatingSystem() {
// currentOs = System.getProperty("os.name").toLowerCase();
// }
//
// public OperatingSystem(String currentOs) {
// this.currentOs = currentOs.toLowerCase();
// }
//
// public boolean isMac() {
// return currentOs.contains("mac");
// }
//
// public boolean isWindows() {
// return currentOs.contains("win");
// }
//
// @Override
// public String toString() {
// return "OperatingSystem{" +
// "currentOs='" + currentOs + '\'' +
// '}';
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/notifier/DoNothingNotifier.java
// public class DoNothingNotifier implements DiscoverableNotifier {
//
// private static final DoNothingNotifier INSTANCE = new DoNothingNotifier();
//
// public static DoNothingNotifier doNothing() {
// return INSTANCE;
// }
//
// private DoNothingNotifier() {
// }
//
// @Override
// public Notifier init() {
// return this;
// }
//
// @Override
// public void send(Notification notification) {
// // do nothing
// }
//
// @Override
// public void close() {
// // do nothing
// }
//
// @Override
// public boolean isPersistent() {
// return false;
// }
//
// @Override
// public boolean tryInit() {
// return true;
// }
// }
| import com.google.common.annotations.VisibleForTesting;
import fr.jcgay.notification.configuration.ChosenNotifiers;
import fr.jcgay.notification.configuration.ConfigurationReader;
import fr.jcgay.notification.configuration.OperatingSystem;
import fr.jcgay.notification.notifier.DoNothingNotifier;
import org.slf4j.Logger;
import java.util.Properties;
import java.util.Set;
import static com.google.common.base.Preconditions.checkNotNull;
import static org.slf4j.LoggerFactory.getLogger; | package fr.jcgay.notification;
/**
* Fluent builder to create a {@link fr.jcgay.notification.Notifier}. <br>
*
* You'll need a configuration file (by default: {@code {user.home}/.send-notification}
* to select and configure a {@link fr.jcgay.notification.Notifier}. <br>
* This file must be property based (example):
* <pre>{@code
* notifier.implementation = pushbullet
* notifier.message.short = true
* notifier.pushbullet.apikey = 1234
* }</pre>
*
* Then to create a notifier you can use:
* <pre>{@code
* Notifier notifier = new SendNotification()
* .setApplication(application)
* .initNotifier();
* }</pre>
*/
public class SendNotification {
private static final Logger LOGGER = getLogger(SendNotification.class);
private final NotifierProvider provider;
private ConfigurationReader configuration;
private ChosenNotifiers chosenNotifiers;
private Properties additionalConfiguration;
private Application application = Application.builder()
.id("application/x-vnd-jcgay.send-notification-default")
.name("Send Notification (Default)")
.icon(Icon.create(SendNotification.class.getResource("/brochure5.png"), "send-notification"))
.build();
| // Path: send-notification/src/main/java/fr/jcgay/notification/configuration/ChosenNotifiers.java
// @AutoValue
// public abstract class ChosenNotifiers {
//
// private static final String SEPARATOR = ",";
//
// public abstract String primary();
//
// public abstract Set<String> secondary();
//
// ChosenNotifiers() {
// // prevent external subclasses
// }
//
// public static ChosenNotifiers from(String notifier) {
// checkNotNull(notifier);
//
// if (!notifier.contains(SEPARATOR)) {
// return new AutoValue_ChosenNotifiers(notifier, Collections.emptySet());
// }
//
// String[] notifiers = notifier.split(SEPARATOR);
// Set<String> secondary = new LinkedHashSet<>(asList(notifiers).subList(1, notifiers.length));
// return new AutoValue_ChosenNotifiers(notifiers[0], secondary);
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/configuration/ConfigurationReader.java
// public class ConfigurationReader {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(ConfigurationReader.class);
//
// private final Properties properties;
// private final URL location;
//
// private ConfigurationReader(Properties properties) {
// this(properties, null);
// }
//
// public ConfigurationReader(Properties configuration, URL location) {
// this.properties = configuration;
// this.location = location;
// }
//
// public static ConfigurationReader atPath(String path) {
// try {
// return atUrl(new File(path).toURI().toURL());
// } catch (MalformedURLException e) {
// LOGGER.debug("URL built for path [{}] is malformed will use default configuration.", path, e);
// return new ConfigurationReader(new Properties());
// }
// }
//
// public static ConfigurationReader atUrl(URL url) {
// Properties configuration = new Properties();
// try {
// configuration.load(url.openStream());
// } catch (IOException e) {
// LOGGER.debug("Cannot read configuration at [{}], will use default one.", url, e);
// }
// return new ConfigurationReader(configuration, url);
// }
//
// public Properties get() {
// LOGGER.debug("Notification configuration read from {} is: {}.", location, properties);
// return properties;
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/configuration/OperatingSystem.java
// public class OperatingSystem {
//
// private final String currentOs;
//
// public OperatingSystem() {
// currentOs = System.getProperty("os.name").toLowerCase();
// }
//
// public OperatingSystem(String currentOs) {
// this.currentOs = currentOs.toLowerCase();
// }
//
// public boolean isMac() {
// return currentOs.contains("mac");
// }
//
// public boolean isWindows() {
// return currentOs.contains("win");
// }
//
// @Override
// public String toString() {
// return "OperatingSystem{" +
// "currentOs='" + currentOs + '\'' +
// '}';
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/notifier/DoNothingNotifier.java
// public class DoNothingNotifier implements DiscoverableNotifier {
//
// private static final DoNothingNotifier INSTANCE = new DoNothingNotifier();
//
// public static DoNothingNotifier doNothing() {
// return INSTANCE;
// }
//
// private DoNothingNotifier() {
// }
//
// @Override
// public Notifier init() {
// return this;
// }
//
// @Override
// public void send(Notification notification) {
// // do nothing
// }
//
// @Override
// public void close() {
// // do nothing
// }
//
// @Override
// public boolean isPersistent() {
// return false;
// }
//
// @Override
// public boolean tryInit() {
// return true;
// }
// }
// Path: send-notification/src/main/java/fr/jcgay/notification/SendNotification.java
import com.google.common.annotations.VisibleForTesting;
import fr.jcgay.notification.configuration.ChosenNotifiers;
import fr.jcgay.notification.configuration.ConfigurationReader;
import fr.jcgay.notification.configuration.OperatingSystem;
import fr.jcgay.notification.notifier.DoNothingNotifier;
import org.slf4j.Logger;
import java.util.Properties;
import java.util.Set;
import static com.google.common.base.Preconditions.checkNotNull;
import static org.slf4j.LoggerFactory.getLogger;
package fr.jcgay.notification;
/**
* Fluent builder to create a {@link fr.jcgay.notification.Notifier}. <br>
*
* You'll need a configuration file (by default: {@code {user.home}/.send-notification}
* to select and configure a {@link fr.jcgay.notification.Notifier}. <br>
* This file must be property based (example):
* <pre>{@code
* notifier.implementation = pushbullet
* notifier.message.short = true
* notifier.pushbullet.apikey = 1234
* }</pre>
*
* Then to create a notifier you can use:
* <pre>{@code
* Notifier notifier = new SendNotification()
* .setApplication(application)
* .initNotifier();
* }</pre>
*/
public class SendNotification {
private static final Logger LOGGER = getLogger(SendNotification.class);
private final NotifierProvider provider;
private ConfigurationReader configuration;
private ChosenNotifiers chosenNotifiers;
private Properties additionalConfiguration;
private Application application = Application.builder()
.id("application/x-vnd-jcgay.send-notification-default")
.name("Send Notification (Default)")
.icon(Icon.create(SendNotification.class.getResource("/brochure5.png"), "send-notification"))
.build();
| SendNotification(ConfigurationReader configuration, OperatingSystem currentOs) { |
jcgay/send-notification | send-notification/src/main/java/fr/jcgay/notification/SendNotification.java | // Path: send-notification/src/main/java/fr/jcgay/notification/configuration/ChosenNotifiers.java
// @AutoValue
// public abstract class ChosenNotifiers {
//
// private static final String SEPARATOR = ",";
//
// public abstract String primary();
//
// public abstract Set<String> secondary();
//
// ChosenNotifiers() {
// // prevent external subclasses
// }
//
// public static ChosenNotifiers from(String notifier) {
// checkNotNull(notifier);
//
// if (!notifier.contains(SEPARATOR)) {
// return new AutoValue_ChosenNotifiers(notifier, Collections.emptySet());
// }
//
// String[] notifiers = notifier.split(SEPARATOR);
// Set<String> secondary = new LinkedHashSet<>(asList(notifiers).subList(1, notifiers.length));
// return new AutoValue_ChosenNotifiers(notifiers[0], secondary);
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/configuration/ConfigurationReader.java
// public class ConfigurationReader {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(ConfigurationReader.class);
//
// private final Properties properties;
// private final URL location;
//
// private ConfigurationReader(Properties properties) {
// this(properties, null);
// }
//
// public ConfigurationReader(Properties configuration, URL location) {
// this.properties = configuration;
// this.location = location;
// }
//
// public static ConfigurationReader atPath(String path) {
// try {
// return atUrl(new File(path).toURI().toURL());
// } catch (MalformedURLException e) {
// LOGGER.debug("URL built for path [{}] is malformed will use default configuration.", path, e);
// return new ConfigurationReader(new Properties());
// }
// }
//
// public static ConfigurationReader atUrl(URL url) {
// Properties configuration = new Properties();
// try {
// configuration.load(url.openStream());
// } catch (IOException e) {
// LOGGER.debug("Cannot read configuration at [{}], will use default one.", url, e);
// }
// return new ConfigurationReader(configuration, url);
// }
//
// public Properties get() {
// LOGGER.debug("Notification configuration read from {} is: {}.", location, properties);
// return properties;
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/configuration/OperatingSystem.java
// public class OperatingSystem {
//
// private final String currentOs;
//
// public OperatingSystem() {
// currentOs = System.getProperty("os.name").toLowerCase();
// }
//
// public OperatingSystem(String currentOs) {
// this.currentOs = currentOs.toLowerCase();
// }
//
// public boolean isMac() {
// return currentOs.contains("mac");
// }
//
// public boolean isWindows() {
// return currentOs.contains("win");
// }
//
// @Override
// public String toString() {
// return "OperatingSystem{" +
// "currentOs='" + currentOs + '\'' +
// '}';
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/notifier/DoNothingNotifier.java
// public class DoNothingNotifier implements DiscoverableNotifier {
//
// private static final DoNothingNotifier INSTANCE = new DoNothingNotifier();
//
// public static DoNothingNotifier doNothing() {
// return INSTANCE;
// }
//
// private DoNothingNotifier() {
// }
//
// @Override
// public Notifier init() {
// return this;
// }
//
// @Override
// public void send(Notification notification) {
// // do nothing
// }
//
// @Override
// public void close() {
// // do nothing
// }
//
// @Override
// public boolean isPersistent() {
// return false;
// }
//
// @Override
// public boolean tryInit() {
// return true;
// }
// }
| import com.google.common.annotations.VisibleForTesting;
import fr.jcgay.notification.configuration.ChosenNotifiers;
import fr.jcgay.notification.configuration.ConfigurationReader;
import fr.jcgay.notification.configuration.OperatingSystem;
import fr.jcgay.notification.notifier.DoNothingNotifier;
import org.slf4j.Logger;
import java.util.Properties;
import java.util.Set;
import static com.google.common.base.Preconditions.checkNotNull;
import static org.slf4j.LoggerFactory.getLogger; | * @param configurationPath a file path for configuration file.
*
* @return fluent builder.
*/
public SendNotification setConfigurationPath(String configurationPath) {
this.configuration = ConfigurationReader.atPath(configurationPath);
return this;
}
/**
* Add properties that will override existing ones (read from the configuration file).
*
* @param additionalConfiguration configuration (key/value) as {@link java.util.Properties}.
*
* @return fluent builder.
*/
public SendNotification addConfigurationProperties(Properties additionalConfiguration) {
this.additionalConfiguration = additionalConfiguration;
return this;
}
private DiscoverableNotifier defaultNotifier(Properties properties) {
Set<DiscoverableNotifier> all = provider.available(properties, application);
for (DiscoverableNotifier candidate : all) {
boolean isAvailable = candidate.tryInit();
LOGGER.debug("{} is available ? {}.", candidate, isAvailable);
if (isAvailable) {
return candidate;
}
} | // Path: send-notification/src/main/java/fr/jcgay/notification/configuration/ChosenNotifiers.java
// @AutoValue
// public abstract class ChosenNotifiers {
//
// private static final String SEPARATOR = ",";
//
// public abstract String primary();
//
// public abstract Set<String> secondary();
//
// ChosenNotifiers() {
// // prevent external subclasses
// }
//
// public static ChosenNotifiers from(String notifier) {
// checkNotNull(notifier);
//
// if (!notifier.contains(SEPARATOR)) {
// return new AutoValue_ChosenNotifiers(notifier, Collections.emptySet());
// }
//
// String[] notifiers = notifier.split(SEPARATOR);
// Set<String> secondary = new LinkedHashSet<>(asList(notifiers).subList(1, notifiers.length));
// return new AutoValue_ChosenNotifiers(notifiers[0], secondary);
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/configuration/ConfigurationReader.java
// public class ConfigurationReader {
//
// private static final Logger LOGGER = LoggerFactory.getLogger(ConfigurationReader.class);
//
// private final Properties properties;
// private final URL location;
//
// private ConfigurationReader(Properties properties) {
// this(properties, null);
// }
//
// public ConfigurationReader(Properties configuration, URL location) {
// this.properties = configuration;
// this.location = location;
// }
//
// public static ConfigurationReader atPath(String path) {
// try {
// return atUrl(new File(path).toURI().toURL());
// } catch (MalformedURLException e) {
// LOGGER.debug("URL built for path [{}] is malformed will use default configuration.", path, e);
// return new ConfigurationReader(new Properties());
// }
// }
//
// public static ConfigurationReader atUrl(URL url) {
// Properties configuration = new Properties();
// try {
// configuration.load(url.openStream());
// } catch (IOException e) {
// LOGGER.debug("Cannot read configuration at [{}], will use default one.", url, e);
// }
// return new ConfigurationReader(configuration, url);
// }
//
// public Properties get() {
// LOGGER.debug("Notification configuration read from {} is: {}.", location, properties);
// return properties;
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/configuration/OperatingSystem.java
// public class OperatingSystem {
//
// private final String currentOs;
//
// public OperatingSystem() {
// currentOs = System.getProperty("os.name").toLowerCase();
// }
//
// public OperatingSystem(String currentOs) {
// this.currentOs = currentOs.toLowerCase();
// }
//
// public boolean isMac() {
// return currentOs.contains("mac");
// }
//
// public boolean isWindows() {
// return currentOs.contains("win");
// }
//
// @Override
// public String toString() {
// return "OperatingSystem{" +
// "currentOs='" + currentOs + '\'' +
// '}';
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/notifier/DoNothingNotifier.java
// public class DoNothingNotifier implements DiscoverableNotifier {
//
// private static final DoNothingNotifier INSTANCE = new DoNothingNotifier();
//
// public static DoNothingNotifier doNothing() {
// return INSTANCE;
// }
//
// private DoNothingNotifier() {
// }
//
// @Override
// public Notifier init() {
// return this;
// }
//
// @Override
// public void send(Notification notification) {
// // do nothing
// }
//
// @Override
// public void close() {
// // do nothing
// }
//
// @Override
// public boolean isPersistent() {
// return false;
// }
//
// @Override
// public boolean tryInit() {
// return true;
// }
// }
// Path: send-notification/src/main/java/fr/jcgay/notification/SendNotification.java
import com.google.common.annotations.VisibleForTesting;
import fr.jcgay.notification.configuration.ChosenNotifiers;
import fr.jcgay.notification.configuration.ConfigurationReader;
import fr.jcgay.notification.configuration.OperatingSystem;
import fr.jcgay.notification.notifier.DoNothingNotifier;
import org.slf4j.Logger;
import java.util.Properties;
import java.util.Set;
import static com.google.common.base.Preconditions.checkNotNull;
import static org.slf4j.LoggerFactory.getLogger;
* @param configurationPath a file path for configuration file.
*
* @return fluent builder.
*/
public SendNotification setConfigurationPath(String configurationPath) {
this.configuration = ConfigurationReader.atPath(configurationPath);
return this;
}
/**
* Add properties that will override existing ones (read from the configuration file).
*
* @param additionalConfiguration configuration (key/value) as {@link java.util.Properties}.
*
* @return fluent builder.
*/
public SendNotification addConfigurationProperties(Properties additionalConfiguration) {
this.additionalConfiguration = additionalConfiguration;
return this;
}
private DiscoverableNotifier defaultNotifier(Properties properties) {
Set<DiscoverableNotifier> all = provider.available(properties, application);
for (DiscoverableNotifier candidate : all) {
boolean isAvailable = candidate.tryInit();
LOGGER.debug("{} is available ? {}.", candidate, isAvailable);
if (isAvailable) {
return candidate;
}
} | return DoNothingNotifier.doNothing(); |
jcgay/send-notification | send-notification/src/main/java/fr/jcgay/notification/notifier/burnttoast/BurntToastNotifier.java | // Path: send-notification/src/main/java/fr/jcgay/notification/Application.java
// @AutoValue
// public abstract class Application {
//
// /**
// * Uniquely identify an application. <br>
// * In order to ensure your application's signature is unique, the recommendation is to follow the Internet Media
// * type (also known as MIME content type) format as defined in IETF <a href="http://tools.ietf.org/html/rfc2046">RFC 2046</a>
// * which contains the application vendor's name - specifically: {@code application/x-vnd-some_vendor.some_app}. <br>
// * The signature must not contain spaces. <br>
// * Some examples of acceptable signatures:
// * <ul>
// * <li>{@code application/x-vnd-acme.hello_world}</li>
// * <li>{@code application/x-vnd-fullphat.snaRSS}</li>
// * </ul>
// *
// * @return unique identifier.
// */
// public abstract String id();
//
// /**
// * A name that will identify the application for the user. <br>
// * Examples:
// * <ul>
// * <li>Maven</li>
// * <li>Gradle</li>
// * </ul>
// *
// * @return application name.
// */
// public abstract String name();
//
// /**
// * A timeout to wait for before cancelling application registration or notification sending.
// *
// * @return timeout in milliseconds, or {@code -1} if not specified.
// */
// public abstract long timeout();
//
// /**
// * The application icon.
// *
// * @return application icon.
// */
// public abstract Icon icon();
//
// Application() {
// // prevent external subclasses
// }
//
// public static Builder builder() {
// return new AutoValue_Application.Builder()
// .timeout(-1);
// }
//
// public static Builder builder(String id, String name, Icon icon) {
// return builder()
// .id(id)
// .name(name)
// .icon(icon);
// }
//
// @AutoValue.Builder
// public interface Builder {
// Builder id(String id);
// Builder name(String name);
// Builder icon(Icon icon);
// Builder timeout(long timeout);
// Application build();
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/DiscoverableNotifier.java
// public interface DiscoverableNotifier extends Notifier {
//
// /**
// * Initialize before usage. <br>
// * This method must be called before trying to send a notification. <br>
// * Calling {@code init()} multiple time should not fail. <br>
// *
// * For example a notifier can open a connection to register the application, or it can do nothing.
// *
// * @return a usable initiated {@link Notifier} to send notification(s)
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// Notifier init();
//
// boolean tryInit();
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notification.java
// @AutoValue
// public abstract class Notification {
//
// /**
// * Indicate notification priority.
// */
// public enum Level {INFO, WARNING, ERROR}
//
// /**
// * Notification message.
// *
// * @return message.
// */
// public abstract String message();
//
// /**
// * Notification title.
// *
// * @return title.
// */
// public abstract String title();
//
// /**
// * Notification subtitle. <br>
// * Not available for all notifier implementation.
// *
// * @return subtitle.
// */
// @Nullable
// public abstract String subtitle();
//
// /**
// * Notification icon.
// *
// * @return icon.
// */
// public abstract Icon icon();
//
// /**
// * Indicate the notification priority type.
// *
// * @return type
// */
// public abstract Level level();
//
// Notification() {
// // prevent external subclasses
// }
//
// public static Builder builder(String title, String message, Icon icon) {
// return builder()
// .title(title)
// .message(message)
// .icon(icon);
// }
//
// public static Builder builder() {
// return new AutoValue_Notification.Builder().level(INFO);
// }
//
// @AutoValue.Builder
// public interface Builder {
// Builder title(String title);
// Builder message(String message);
// Builder icon(Icon icon);
// Builder subtitle(String subtitle);
// Builder level(Level level);
// Notification build();
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notifier.java
// public interface Notifier {
//
// /**
// * Send a notification.
// *
// * @param notification a notification.
// *
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// void send(Notification notification);
//
// /**
// * Close the notifier. <br>
// * This method must be called to release resources when the notifier is not needed anymore.
// */
// void close();
//
// /**
// * Indicate if the notifier is always displayed somewhere (menu/task bar, etc).
// * @return {@code true} if the notifier is persistent.
// */
// boolean isPersistent();
// }
| import com.google.common.base.MoreObjects;
import com.google.common.base.Objects;
import com.profesorfalken.jpowershell.PowerShell;
import com.profesorfalken.jpowershell.PowerShellResponse;
import fr.jcgay.notification.Application;
import fr.jcgay.notification.DiscoverableNotifier;
import fr.jcgay.notification.Notification;
import fr.jcgay.notification.Notifier;
import org.slf4j.Logger;
import static org.slf4j.LoggerFactory.getLogger; | package fr.jcgay.notification.notifier.burnttoast;
public class BurntToastNotifier implements DiscoverableNotifier {
private static final Logger LOGGER = getLogger(BurntToastNotifier.class);
| // Path: send-notification/src/main/java/fr/jcgay/notification/Application.java
// @AutoValue
// public abstract class Application {
//
// /**
// * Uniquely identify an application. <br>
// * In order to ensure your application's signature is unique, the recommendation is to follow the Internet Media
// * type (also known as MIME content type) format as defined in IETF <a href="http://tools.ietf.org/html/rfc2046">RFC 2046</a>
// * which contains the application vendor's name - specifically: {@code application/x-vnd-some_vendor.some_app}. <br>
// * The signature must not contain spaces. <br>
// * Some examples of acceptable signatures:
// * <ul>
// * <li>{@code application/x-vnd-acme.hello_world}</li>
// * <li>{@code application/x-vnd-fullphat.snaRSS}</li>
// * </ul>
// *
// * @return unique identifier.
// */
// public abstract String id();
//
// /**
// * A name that will identify the application for the user. <br>
// * Examples:
// * <ul>
// * <li>Maven</li>
// * <li>Gradle</li>
// * </ul>
// *
// * @return application name.
// */
// public abstract String name();
//
// /**
// * A timeout to wait for before cancelling application registration or notification sending.
// *
// * @return timeout in milliseconds, or {@code -1} if not specified.
// */
// public abstract long timeout();
//
// /**
// * The application icon.
// *
// * @return application icon.
// */
// public abstract Icon icon();
//
// Application() {
// // prevent external subclasses
// }
//
// public static Builder builder() {
// return new AutoValue_Application.Builder()
// .timeout(-1);
// }
//
// public static Builder builder(String id, String name, Icon icon) {
// return builder()
// .id(id)
// .name(name)
// .icon(icon);
// }
//
// @AutoValue.Builder
// public interface Builder {
// Builder id(String id);
// Builder name(String name);
// Builder icon(Icon icon);
// Builder timeout(long timeout);
// Application build();
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/DiscoverableNotifier.java
// public interface DiscoverableNotifier extends Notifier {
//
// /**
// * Initialize before usage. <br>
// * This method must be called before trying to send a notification. <br>
// * Calling {@code init()} multiple time should not fail. <br>
// *
// * For example a notifier can open a connection to register the application, or it can do nothing.
// *
// * @return a usable initiated {@link Notifier} to send notification(s)
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// Notifier init();
//
// boolean tryInit();
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notification.java
// @AutoValue
// public abstract class Notification {
//
// /**
// * Indicate notification priority.
// */
// public enum Level {INFO, WARNING, ERROR}
//
// /**
// * Notification message.
// *
// * @return message.
// */
// public abstract String message();
//
// /**
// * Notification title.
// *
// * @return title.
// */
// public abstract String title();
//
// /**
// * Notification subtitle. <br>
// * Not available for all notifier implementation.
// *
// * @return subtitle.
// */
// @Nullable
// public abstract String subtitle();
//
// /**
// * Notification icon.
// *
// * @return icon.
// */
// public abstract Icon icon();
//
// /**
// * Indicate the notification priority type.
// *
// * @return type
// */
// public abstract Level level();
//
// Notification() {
// // prevent external subclasses
// }
//
// public static Builder builder(String title, String message, Icon icon) {
// return builder()
// .title(title)
// .message(message)
// .icon(icon);
// }
//
// public static Builder builder() {
// return new AutoValue_Notification.Builder().level(INFO);
// }
//
// @AutoValue.Builder
// public interface Builder {
// Builder title(String title);
// Builder message(String message);
// Builder icon(Icon icon);
// Builder subtitle(String subtitle);
// Builder level(Level level);
// Notification build();
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notifier.java
// public interface Notifier {
//
// /**
// * Send a notification.
// *
// * @param notification a notification.
// *
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// void send(Notification notification);
//
// /**
// * Close the notifier. <br>
// * This method must be called to release resources when the notifier is not needed anymore.
// */
// void close();
//
// /**
// * Indicate if the notifier is always displayed somewhere (menu/task bar, etc).
// * @return {@code true} if the notifier is persistent.
// */
// boolean isPersistent();
// }
// Path: send-notification/src/main/java/fr/jcgay/notification/notifier/burnttoast/BurntToastNotifier.java
import com.google.common.base.MoreObjects;
import com.google.common.base.Objects;
import com.profesorfalken.jpowershell.PowerShell;
import com.profesorfalken.jpowershell.PowerShellResponse;
import fr.jcgay.notification.Application;
import fr.jcgay.notification.DiscoverableNotifier;
import fr.jcgay.notification.Notification;
import fr.jcgay.notification.Notifier;
import org.slf4j.Logger;
import static org.slf4j.LoggerFactory.getLogger;
package fr.jcgay.notification.notifier.burnttoast;
public class BurntToastNotifier implements DiscoverableNotifier {
private static final Logger LOGGER = getLogger(BurntToastNotifier.class);
| private final Application application; |
jcgay/send-notification | send-notification/src/main/java/fr/jcgay/notification/notifier/burnttoast/BurntToastNotifier.java | // Path: send-notification/src/main/java/fr/jcgay/notification/Application.java
// @AutoValue
// public abstract class Application {
//
// /**
// * Uniquely identify an application. <br>
// * In order to ensure your application's signature is unique, the recommendation is to follow the Internet Media
// * type (also known as MIME content type) format as defined in IETF <a href="http://tools.ietf.org/html/rfc2046">RFC 2046</a>
// * which contains the application vendor's name - specifically: {@code application/x-vnd-some_vendor.some_app}. <br>
// * The signature must not contain spaces. <br>
// * Some examples of acceptable signatures:
// * <ul>
// * <li>{@code application/x-vnd-acme.hello_world}</li>
// * <li>{@code application/x-vnd-fullphat.snaRSS}</li>
// * </ul>
// *
// * @return unique identifier.
// */
// public abstract String id();
//
// /**
// * A name that will identify the application for the user. <br>
// * Examples:
// * <ul>
// * <li>Maven</li>
// * <li>Gradle</li>
// * </ul>
// *
// * @return application name.
// */
// public abstract String name();
//
// /**
// * A timeout to wait for before cancelling application registration or notification sending.
// *
// * @return timeout in milliseconds, or {@code -1} if not specified.
// */
// public abstract long timeout();
//
// /**
// * The application icon.
// *
// * @return application icon.
// */
// public abstract Icon icon();
//
// Application() {
// // prevent external subclasses
// }
//
// public static Builder builder() {
// return new AutoValue_Application.Builder()
// .timeout(-1);
// }
//
// public static Builder builder(String id, String name, Icon icon) {
// return builder()
// .id(id)
// .name(name)
// .icon(icon);
// }
//
// @AutoValue.Builder
// public interface Builder {
// Builder id(String id);
// Builder name(String name);
// Builder icon(Icon icon);
// Builder timeout(long timeout);
// Application build();
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/DiscoverableNotifier.java
// public interface DiscoverableNotifier extends Notifier {
//
// /**
// * Initialize before usage. <br>
// * This method must be called before trying to send a notification. <br>
// * Calling {@code init()} multiple time should not fail. <br>
// *
// * For example a notifier can open a connection to register the application, or it can do nothing.
// *
// * @return a usable initiated {@link Notifier} to send notification(s)
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// Notifier init();
//
// boolean tryInit();
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notification.java
// @AutoValue
// public abstract class Notification {
//
// /**
// * Indicate notification priority.
// */
// public enum Level {INFO, WARNING, ERROR}
//
// /**
// * Notification message.
// *
// * @return message.
// */
// public abstract String message();
//
// /**
// * Notification title.
// *
// * @return title.
// */
// public abstract String title();
//
// /**
// * Notification subtitle. <br>
// * Not available for all notifier implementation.
// *
// * @return subtitle.
// */
// @Nullable
// public abstract String subtitle();
//
// /**
// * Notification icon.
// *
// * @return icon.
// */
// public abstract Icon icon();
//
// /**
// * Indicate the notification priority type.
// *
// * @return type
// */
// public abstract Level level();
//
// Notification() {
// // prevent external subclasses
// }
//
// public static Builder builder(String title, String message, Icon icon) {
// return builder()
// .title(title)
// .message(message)
// .icon(icon);
// }
//
// public static Builder builder() {
// return new AutoValue_Notification.Builder().level(INFO);
// }
//
// @AutoValue.Builder
// public interface Builder {
// Builder title(String title);
// Builder message(String message);
// Builder icon(Icon icon);
// Builder subtitle(String subtitle);
// Builder level(Level level);
// Notification build();
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notifier.java
// public interface Notifier {
//
// /**
// * Send a notification.
// *
// * @param notification a notification.
// *
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// void send(Notification notification);
//
// /**
// * Close the notifier. <br>
// * This method must be called to release resources when the notifier is not needed anymore.
// */
// void close();
//
// /**
// * Indicate if the notifier is always displayed somewhere (menu/task bar, etc).
// * @return {@code true} if the notifier is persistent.
// */
// boolean isPersistent();
// }
| import com.google.common.base.MoreObjects;
import com.google.common.base.Objects;
import com.profesorfalken.jpowershell.PowerShell;
import com.profesorfalken.jpowershell.PowerShellResponse;
import fr.jcgay.notification.Application;
import fr.jcgay.notification.DiscoverableNotifier;
import fr.jcgay.notification.Notification;
import fr.jcgay.notification.Notifier;
import org.slf4j.Logger;
import static org.slf4j.LoggerFactory.getLogger; | package fr.jcgay.notification.notifier.burnttoast;
public class BurntToastNotifier implements DiscoverableNotifier {
private static final Logger LOGGER = getLogger(BurntToastNotifier.class);
private final Application application;
private final BurntToastNotifierConfiguration configuration;
public BurntToastNotifier(Application application, BurntToastNotifierConfiguration configuration) {
this.application = application;
this.configuration = configuration;
}
@Override | // Path: send-notification/src/main/java/fr/jcgay/notification/Application.java
// @AutoValue
// public abstract class Application {
//
// /**
// * Uniquely identify an application. <br>
// * In order to ensure your application's signature is unique, the recommendation is to follow the Internet Media
// * type (also known as MIME content type) format as defined in IETF <a href="http://tools.ietf.org/html/rfc2046">RFC 2046</a>
// * which contains the application vendor's name - specifically: {@code application/x-vnd-some_vendor.some_app}. <br>
// * The signature must not contain spaces. <br>
// * Some examples of acceptable signatures:
// * <ul>
// * <li>{@code application/x-vnd-acme.hello_world}</li>
// * <li>{@code application/x-vnd-fullphat.snaRSS}</li>
// * </ul>
// *
// * @return unique identifier.
// */
// public abstract String id();
//
// /**
// * A name that will identify the application for the user. <br>
// * Examples:
// * <ul>
// * <li>Maven</li>
// * <li>Gradle</li>
// * </ul>
// *
// * @return application name.
// */
// public abstract String name();
//
// /**
// * A timeout to wait for before cancelling application registration or notification sending.
// *
// * @return timeout in milliseconds, or {@code -1} if not specified.
// */
// public abstract long timeout();
//
// /**
// * The application icon.
// *
// * @return application icon.
// */
// public abstract Icon icon();
//
// Application() {
// // prevent external subclasses
// }
//
// public static Builder builder() {
// return new AutoValue_Application.Builder()
// .timeout(-1);
// }
//
// public static Builder builder(String id, String name, Icon icon) {
// return builder()
// .id(id)
// .name(name)
// .icon(icon);
// }
//
// @AutoValue.Builder
// public interface Builder {
// Builder id(String id);
// Builder name(String name);
// Builder icon(Icon icon);
// Builder timeout(long timeout);
// Application build();
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/DiscoverableNotifier.java
// public interface DiscoverableNotifier extends Notifier {
//
// /**
// * Initialize before usage. <br>
// * This method must be called before trying to send a notification. <br>
// * Calling {@code init()} multiple time should not fail. <br>
// *
// * For example a notifier can open a connection to register the application, or it can do nothing.
// *
// * @return a usable initiated {@link Notifier} to send notification(s)
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// Notifier init();
//
// boolean tryInit();
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notification.java
// @AutoValue
// public abstract class Notification {
//
// /**
// * Indicate notification priority.
// */
// public enum Level {INFO, WARNING, ERROR}
//
// /**
// * Notification message.
// *
// * @return message.
// */
// public abstract String message();
//
// /**
// * Notification title.
// *
// * @return title.
// */
// public abstract String title();
//
// /**
// * Notification subtitle. <br>
// * Not available for all notifier implementation.
// *
// * @return subtitle.
// */
// @Nullable
// public abstract String subtitle();
//
// /**
// * Notification icon.
// *
// * @return icon.
// */
// public abstract Icon icon();
//
// /**
// * Indicate the notification priority type.
// *
// * @return type
// */
// public abstract Level level();
//
// Notification() {
// // prevent external subclasses
// }
//
// public static Builder builder(String title, String message, Icon icon) {
// return builder()
// .title(title)
// .message(message)
// .icon(icon);
// }
//
// public static Builder builder() {
// return new AutoValue_Notification.Builder().level(INFO);
// }
//
// @AutoValue.Builder
// public interface Builder {
// Builder title(String title);
// Builder message(String message);
// Builder icon(Icon icon);
// Builder subtitle(String subtitle);
// Builder level(Level level);
// Notification build();
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notifier.java
// public interface Notifier {
//
// /**
// * Send a notification.
// *
// * @param notification a notification.
// *
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// void send(Notification notification);
//
// /**
// * Close the notifier. <br>
// * This method must be called to release resources when the notifier is not needed anymore.
// */
// void close();
//
// /**
// * Indicate if the notifier is always displayed somewhere (menu/task bar, etc).
// * @return {@code true} if the notifier is persistent.
// */
// boolean isPersistent();
// }
// Path: send-notification/src/main/java/fr/jcgay/notification/notifier/burnttoast/BurntToastNotifier.java
import com.google.common.base.MoreObjects;
import com.google.common.base.Objects;
import com.profesorfalken.jpowershell.PowerShell;
import com.profesorfalken.jpowershell.PowerShellResponse;
import fr.jcgay.notification.Application;
import fr.jcgay.notification.DiscoverableNotifier;
import fr.jcgay.notification.Notification;
import fr.jcgay.notification.Notifier;
import org.slf4j.Logger;
import static org.slf4j.LoggerFactory.getLogger;
package fr.jcgay.notification.notifier.burnttoast;
public class BurntToastNotifier implements DiscoverableNotifier {
private static final Logger LOGGER = getLogger(BurntToastNotifier.class);
private final Application application;
private final BurntToastNotifierConfiguration configuration;
public BurntToastNotifier(Application application, BurntToastNotifierConfiguration configuration) {
this.application = application;
this.configuration = configuration;
}
@Override | public void send(Notification notification) { |
jcgay/send-notification | send-notification/src/main/java/fr/jcgay/notification/notifier/toaster/ToasterNotifier.java | // Path: send-notification/src/main/java/fr/jcgay/notification/DiscoverableNotifier.java
// public interface DiscoverableNotifier extends Notifier {
//
// /**
// * Initialize before usage. <br>
// * This method must be called before trying to send a notification. <br>
// * Calling {@code init()} multiple time should not fail. <br>
// *
// * For example a notifier can open a connection to register the application, or it can do nothing.
// *
// * @return a usable initiated {@link Notifier} to send notification(s)
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// Notifier init();
//
// boolean tryInit();
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notification.java
// @AutoValue
// public abstract class Notification {
//
// /**
// * Indicate notification priority.
// */
// public enum Level {INFO, WARNING, ERROR}
//
// /**
// * Notification message.
// *
// * @return message.
// */
// public abstract String message();
//
// /**
// * Notification title.
// *
// * @return title.
// */
// public abstract String title();
//
// /**
// * Notification subtitle. <br>
// * Not available for all notifier implementation.
// *
// * @return subtitle.
// */
// @Nullable
// public abstract String subtitle();
//
// /**
// * Notification icon.
// *
// * @return icon.
// */
// public abstract Icon icon();
//
// /**
// * Indicate the notification priority type.
// *
// * @return type
// */
// public abstract Level level();
//
// Notification() {
// // prevent external subclasses
// }
//
// public static Builder builder(String title, String message, Icon icon) {
// return builder()
// .title(title)
// .message(message)
// .icon(icon);
// }
//
// public static Builder builder() {
// return new AutoValue_Notification.Builder().level(INFO);
// }
//
// @AutoValue.Builder
// public interface Builder {
// Builder title(String title);
// Builder message(String message);
// Builder icon(Icon icon);
// Builder subtitle(String subtitle);
// Builder level(Level level);
// Notification build();
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notifier.java
// public interface Notifier {
//
// /**
// * Send a notification.
// *
// * @param notification a notification.
// *
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// void send(Notification notification);
//
// /**
// * Close the notifier. <br>
// * This method must be called to release resources when the notifier is not needed anymore.
// */
// void close();
//
// /**
// * Indicate if the notifier is always displayed somewhere (menu/task bar, etc).
// * @return {@code true} if the notifier is persistent.
// */
// boolean isPersistent();
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/notifier/executor/Executor.java
// public interface Executor {
// void exec(String[] command);
// boolean tryExec(String[] command);
// void close();
// }
| import com.google.common.base.MoreObjects;
import com.google.common.base.Objects;
import fr.jcgay.notification.DiscoverableNotifier;
import fr.jcgay.notification.Notification;
import fr.jcgay.notification.Notifier;
import fr.jcgay.notification.notifier.executor.Executor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List; | package fr.jcgay.notification.notifier.toaster;
public class ToasterNotifier implements DiscoverableNotifier {
private static final Logger LOGGER = LoggerFactory.getLogger(ToasterNotifier.class);
private static final String DOUBLE_QUOTE = "\"";
private final ToasterConfiguration configuration; | // Path: send-notification/src/main/java/fr/jcgay/notification/DiscoverableNotifier.java
// public interface DiscoverableNotifier extends Notifier {
//
// /**
// * Initialize before usage. <br>
// * This method must be called before trying to send a notification. <br>
// * Calling {@code init()} multiple time should not fail. <br>
// *
// * For example a notifier can open a connection to register the application, or it can do nothing.
// *
// * @return a usable initiated {@link Notifier} to send notification(s)
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// Notifier init();
//
// boolean tryInit();
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notification.java
// @AutoValue
// public abstract class Notification {
//
// /**
// * Indicate notification priority.
// */
// public enum Level {INFO, WARNING, ERROR}
//
// /**
// * Notification message.
// *
// * @return message.
// */
// public abstract String message();
//
// /**
// * Notification title.
// *
// * @return title.
// */
// public abstract String title();
//
// /**
// * Notification subtitle. <br>
// * Not available for all notifier implementation.
// *
// * @return subtitle.
// */
// @Nullable
// public abstract String subtitle();
//
// /**
// * Notification icon.
// *
// * @return icon.
// */
// public abstract Icon icon();
//
// /**
// * Indicate the notification priority type.
// *
// * @return type
// */
// public abstract Level level();
//
// Notification() {
// // prevent external subclasses
// }
//
// public static Builder builder(String title, String message, Icon icon) {
// return builder()
// .title(title)
// .message(message)
// .icon(icon);
// }
//
// public static Builder builder() {
// return new AutoValue_Notification.Builder().level(INFO);
// }
//
// @AutoValue.Builder
// public interface Builder {
// Builder title(String title);
// Builder message(String message);
// Builder icon(Icon icon);
// Builder subtitle(String subtitle);
// Builder level(Level level);
// Notification build();
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notifier.java
// public interface Notifier {
//
// /**
// * Send a notification.
// *
// * @param notification a notification.
// *
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// void send(Notification notification);
//
// /**
// * Close the notifier. <br>
// * This method must be called to release resources when the notifier is not needed anymore.
// */
// void close();
//
// /**
// * Indicate if the notifier is always displayed somewhere (menu/task bar, etc).
// * @return {@code true} if the notifier is persistent.
// */
// boolean isPersistent();
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/notifier/executor/Executor.java
// public interface Executor {
// void exec(String[] command);
// boolean tryExec(String[] command);
// void close();
// }
// Path: send-notification/src/main/java/fr/jcgay/notification/notifier/toaster/ToasterNotifier.java
import com.google.common.base.MoreObjects;
import com.google.common.base.Objects;
import fr.jcgay.notification.DiscoverableNotifier;
import fr.jcgay.notification.Notification;
import fr.jcgay.notification.Notifier;
import fr.jcgay.notification.notifier.executor.Executor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
package fr.jcgay.notification.notifier.toaster;
public class ToasterNotifier implements DiscoverableNotifier {
private static final Logger LOGGER = LoggerFactory.getLogger(ToasterNotifier.class);
private static final String DOUBLE_QUOTE = "\"";
private final ToasterConfiguration configuration; | private final Executor executor; |
jcgay/send-notification | send-notification/src/main/java/fr/jcgay/notification/notifier/toaster/ToasterNotifier.java | // Path: send-notification/src/main/java/fr/jcgay/notification/DiscoverableNotifier.java
// public interface DiscoverableNotifier extends Notifier {
//
// /**
// * Initialize before usage. <br>
// * This method must be called before trying to send a notification. <br>
// * Calling {@code init()} multiple time should not fail. <br>
// *
// * For example a notifier can open a connection to register the application, or it can do nothing.
// *
// * @return a usable initiated {@link Notifier} to send notification(s)
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// Notifier init();
//
// boolean tryInit();
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notification.java
// @AutoValue
// public abstract class Notification {
//
// /**
// * Indicate notification priority.
// */
// public enum Level {INFO, WARNING, ERROR}
//
// /**
// * Notification message.
// *
// * @return message.
// */
// public abstract String message();
//
// /**
// * Notification title.
// *
// * @return title.
// */
// public abstract String title();
//
// /**
// * Notification subtitle. <br>
// * Not available for all notifier implementation.
// *
// * @return subtitle.
// */
// @Nullable
// public abstract String subtitle();
//
// /**
// * Notification icon.
// *
// * @return icon.
// */
// public abstract Icon icon();
//
// /**
// * Indicate the notification priority type.
// *
// * @return type
// */
// public abstract Level level();
//
// Notification() {
// // prevent external subclasses
// }
//
// public static Builder builder(String title, String message, Icon icon) {
// return builder()
// .title(title)
// .message(message)
// .icon(icon);
// }
//
// public static Builder builder() {
// return new AutoValue_Notification.Builder().level(INFO);
// }
//
// @AutoValue.Builder
// public interface Builder {
// Builder title(String title);
// Builder message(String message);
// Builder icon(Icon icon);
// Builder subtitle(String subtitle);
// Builder level(Level level);
// Notification build();
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notifier.java
// public interface Notifier {
//
// /**
// * Send a notification.
// *
// * @param notification a notification.
// *
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// void send(Notification notification);
//
// /**
// * Close the notifier. <br>
// * This method must be called to release resources when the notifier is not needed anymore.
// */
// void close();
//
// /**
// * Indicate if the notifier is always displayed somewhere (menu/task bar, etc).
// * @return {@code true} if the notifier is persistent.
// */
// boolean isPersistent();
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/notifier/executor/Executor.java
// public interface Executor {
// void exec(String[] command);
// boolean tryExec(String[] command);
// void close();
// }
| import com.google.common.base.MoreObjects;
import com.google.common.base.Objects;
import fr.jcgay.notification.DiscoverableNotifier;
import fr.jcgay.notification.Notification;
import fr.jcgay.notification.Notifier;
import fr.jcgay.notification.notifier.executor.Executor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List; | package fr.jcgay.notification.notifier.toaster;
public class ToasterNotifier implements DiscoverableNotifier {
private static final Logger LOGGER = LoggerFactory.getLogger(ToasterNotifier.class);
private static final String DOUBLE_QUOTE = "\"";
private final ToasterConfiguration configuration;
private final Executor executor;
public ToasterNotifier(ToasterConfiguration configuration, Executor executor) {
LOGGER.debug("Configuring toaster: {}.", configuration);
this.configuration = configuration;
this.executor = executor;
}
@Override | // Path: send-notification/src/main/java/fr/jcgay/notification/DiscoverableNotifier.java
// public interface DiscoverableNotifier extends Notifier {
//
// /**
// * Initialize before usage. <br>
// * This method must be called before trying to send a notification. <br>
// * Calling {@code init()} multiple time should not fail. <br>
// *
// * For example a notifier can open a connection to register the application, or it can do nothing.
// *
// * @return a usable initiated {@link Notifier} to send notification(s)
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// Notifier init();
//
// boolean tryInit();
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notification.java
// @AutoValue
// public abstract class Notification {
//
// /**
// * Indicate notification priority.
// */
// public enum Level {INFO, WARNING, ERROR}
//
// /**
// * Notification message.
// *
// * @return message.
// */
// public abstract String message();
//
// /**
// * Notification title.
// *
// * @return title.
// */
// public abstract String title();
//
// /**
// * Notification subtitle. <br>
// * Not available for all notifier implementation.
// *
// * @return subtitle.
// */
// @Nullable
// public abstract String subtitle();
//
// /**
// * Notification icon.
// *
// * @return icon.
// */
// public abstract Icon icon();
//
// /**
// * Indicate the notification priority type.
// *
// * @return type
// */
// public abstract Level level();
//
// Notification() {
// // prevent external subclasses
// }
//
// public static Builder builder(String title, String message, Icon icon) {
// return builder()
// .title(title)
// .message(message)
// .icon(icon);
// }
//
// public static Builder builder() {
// return new AutoValue_Notification.Builder().level(INFO);
// }
//
// @AutoValue.Builder
// public interface Builder {
// Builder title(String title);
// Builder message(String message);
// Builder icon(Icon icon);
// Builder subtitle(String subtitle);
// Builder level(Level level);
// Notification build();
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notifier.java
// public interface Notifier {
//
// /**
// * Send a notification.
// *
// * @param notification a notification.
// *
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// void send(Notification notification);
//
// /**
// * Close the notifier. <br>
// * This method must be called to release resources when the notifier is not needed anymore.
// */
// void close();
//
// /**
// * Indicate if the notifier is always displayed somewhere (menu/task bar, etc).
// * @return {@code true} if the notifier is persistent.
// */
// boolean isPersistent();
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/notifier/executor/Executor.java
// public interface Executor {
// void exec(String[] command);
// boolean tryExec(String[] command);
// void close();
// }
// Path: send-notification/src/main/java/fr/jcgay/notification/notifier/toaster/ToasterNotifier.java
import com.google.common.base.MoreObjects;
import com.google.common.base.Objects;
import fr.jcgay.notification.DiscoverableNotifier;
import fr.jcgay.notification.Notification;
import fr.jcgay.notification.Notifier;
import fr.jcgay.notification.notifier.executor.Executor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
package fr.jcgay.notification.notifier.toaster;
public class ToasterNotifier implements DiscoverableNotifier {
private static final Logger LOGGER = LoggerFactory.getLogger(ToasterNotifier.class);
private static final String DOUBLE_QUOTE = "\"";
private final ToasterConfiguration configuration;
private final Executor executor;
public ToasterNotifier(ToasterConfiguration configuration, Executor executor) {
LOGGER.debug("Configuring toaster: {}.", configuration);
this.configuration = configuration;
this.executor = executor;
}
@Override | public Notifier init() { |
jcgay/send-notification | send-notification/src/main/java/fr/jcgay/notification/notifier/toaster/ToasterNotifier.java | // Path: send-notification/src/main/java/fr/jcgay/notification/DiscoverableNotifier.java
// public interface DiscoverableNotifier extends Notifier {
//
// /**
// * Initialize before usage. <br>
// * This method must be called before trying to send a notification. <br>
// * Calling {@code init()} multiple time should not fail. <br>
// *
// * For example a notifier can open a connection to register the application, or it can do nothing.
// *
// * @return a usable initiated {@link Notifier} to send notification(s)
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// Notifier init();
//
// boolean tryInit();
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notification.java
// @AutoValue
// public abstract class Notification {
//
// /**
// * Indicate notification priority.
// */
// public enum Level {INFO, WARNING, ERROR}
//
// /**
// * Notification message.
// *
// * @return message.
// */
// public abstract String message();
//
// /**
// * Notification title.
// *
// * @return title.
// */
// public abstract String title();
//
// /**
// * Notification subtitle. <br>
// * Not available for all notifier implementation.
// *
// * @return subtitle.
// */
// @Nullable
// public abstract String subtitle();
//
// /**
// * Notification icon.
// *
// * @return icon.
// */
// public abstract Icon icon();
//
// /**
// * Indicate the notification priority type.
// *
// * @return type
// */
// public abstract Level level();
//
// Notification() {
// // prevent external subclasses
// }
//
// public static Builder builder(String title, String message, Icon icon) {
// return builder()
// .title(title)
// .message(message)
// .icon(icon);
// }
//
// public static Builder builder() {
// return new AutoValue_Notification.Builder().level(INFO);
// }
//
// @AutoValue.Builder
// public interface Builder {
// Builder title(String title);
// Builder message(String message);
// Builder icon(Icon icon);
// Builder subtitle(String subtitle);
// Builder level(Level level);
// Notification build();
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notifier.java
// public interface Notifier {
//
// /**
// * Send a notification.
// *
// * @param notification a notification.
// *
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// void send(Notification notification);
//
// /**
// * Close the notifier. <br>
// * This method must be called to release resources when the notifier is not needed anymore.
// */
// void close();
//
// /**
// * Indicate if the notifier is always displayed somewhere (menu/task bar, etc).
// * @return {@code true} if the notifier is persistent.
// */
// boolean isPersistent();
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/notifier/executor/Executor.java
// public interface Executor {
// void exec(String[] command);
// boolean tryExec(String[] command);
// void close();
// }
| import com.google.common.base.MoreObjects;
import com.google.common.base.Objects;
import fr.jcgay.notification.DiscoverableNotifier;
import fr.jcgay.notification.Notification;
import fr.jcgay.notification.Notifier;
import fr.jcgay.notification.notifier.executor.Executor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List; | package fr.jcgay.notification.notifier.toaster;
public class ToasterNotifier implements DiscoverableNotifier {
private static final Logger LOGGER = LoggerFactory.getLogger(ToasterNotifier.class);
private static final String DOUBLE_QUOTE = "\"";
private final ToasterConfiguration configuration;
private final Executor executor;
public ToasterNotifier(ToasterConfiguration configuration, Executor executor) {
LOGGER.debug("Configuring toaster: {}.", configuration);
this.configuration = configuration;
this.executor = executor;
}
@Override
public Notifier init() {
return this;
}
@Override | // Path: send-notification/src/main/java/fr/jcgay/notification/DiscoverableNotifier.java
// public interface DiscoverableNotifier extends Notifier {
//
// /**
// * Initialize before usage. <br>
// * This method must be called before trying to send a notification. <br>
// * Calling {@code init()} multiple time should not fail. <br>
// *
// * For example a notifier can open a connection to register the application, or it can do nothing.
// *
// * @return a usable initiated {@link Notifier} to send notification(s)
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// Notifier init();
//
// boolean tryInit();
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notification.java
// @AutoValue
// public abstract class Notification {
//
// /**
// * Indicate notification priority.
// */
// public enum Level {INFO, WARNING, ERROR}
//
// /**
// * Notification message.
// *
// * @return message.
// */
// public abstract String message();
//
// /**
// * Notification title.
// *
// * @return title.
// */
// public abstract String title();
//
// /**
// * Notification subtitle. <br>
// * Not available for all notifier implementation.
// *
// * @return subtitle.
// */
// @Nullable
// public abstract String subtitle();
//
// /**
// * Notification icon.
// *
// * @return icon.
// */
// public abstract Icon icon();
//
// /**
// * Indicate the notification priority type.
// *
// * @return type
// */
// public abstract Level level();
//
// Notification() {
// // prevent external subclasses
// }
//
// public static Builder builder(String title, String message, Icon icon) {
// return builder()
// .title(title)
// .message(message)
// .icon(icon);
// }
//
// public static Builder builder() {
// return new AutoValue_Notification.Builder().level(INFO);
// }
//
// @AutoValue.Builder
// public interface Builder {
// Builder title(String title);
// Builder message(String message);
// Builder icon(Icon icon);
// Builder subtitle(String subtitle);
// Builder level(Level level);
// Notification build();
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notifier.java
// public interface Notifier {
//
// /**
// * Send a notification.
// *
// * @param notification a notification.
// *
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// void send(Notification notification);
//
// /**
// * Close the notifier. <br>
// * This method must be called to release resources when the notifier is not needed anymore.
// */
// void close();
//
// /**
// * Indicate if the notifier is always displayed somewhere (menu/task bar, etc).
// * @return {@code true} if the notifier is persistent.
// */
// boolean isPersistent();
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/notifier/executor/Executor.java
// public interface Executor {
// void exec(String[] command);
// boolean tryExec(String[] command);
// void close();
// }
// Path: send-notification/src/main/java/fr/jcgay/notification/notifier/toaster/ToasterNotifier.java
import com.google.common.base.MoreObjects;
import com.google.common.base.Objects;
import fr.jcgay.notification.DiscoverableNotifier;
import fr.jcgay.notification.Notification;
import fr.jcgay.notification.Notifier;
import fr.jcgay.notification.notifier.executor.Executor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
package fr.jcgay.notification.notifier.toaster;
public class ToasterNotifier implements DiscoverableNotifier {
private static final Logger LOGGER = LoggerFactory.getLogger(ToasterNotifier.class);
private static final String DOUBLE_QUOTE = "\"";
private final ToasterConfiguration configuration;
private final Executor executor;
public ToasterNotifier(ToasterConfiguration configuration, Executor executor) {
LOGGER.debug("Configuring toaster: {}.", configuration);
this.configuration = configuration;
this.executor = executor;
}
@Override
public Notifier init() {
return this;
}
@Override | public void send(Notification notification) { |
jcgay/send-notification | send-notification/src/main/java/fr/jcgay/notification/notifier/snarl/SnarlNotifier.java | // Path: send-notification/src/main/java/fr/jcgay/notification/Application.java
// @AutoValue
// public abstract class Application {
//
// /**
// * Uniquely identify an application. <br>
// * In order to ensure your application's signature is unique, the recommendation is to follow the Internet Media
// * type (also known as MIME content type) format as defined in IETF <a href="http://tools.ietf.org/html/rfc2046">RFC 2046</a>
// * which contains the application vendor's name - specifically: {@code application/x-vnd-some_vendor.some_app}. <br>
// * The signature must not contain spaces. <br>
// * Some examples of acceptable signatures:
// * <ul>
// * <li>{@code application/x-vnd-acme.hello_world}</li>
// * <li>{@code application/x-vnd-fullphat.snaRSS}</li>
// * </ul>
// *
// * @return unique identifier.
// */
// public abstract String id();
//
// /**
// * A name that will identify the application for the user. <br>
// * Examples:
// * <ul>
// * <li>Maven</li>
// * <li>Gradle</li>
// * </ul>
// *
// * @return application name.
// */
// public abstract String name();
//
// /**
// * A timeout to wait for before cancelling application registration or notification sending.
// *
// * @return timeout in milliseconds, or {@code -1} if not specified.
// */
// public abstract long timeout();
//
// /**
// * The application icon.
// *
// * @return application icon.
// */
// public abstract Icon icon();
//
// Application() {
// // prevent external subclasses
// }
//
// public static Builder builder() {
// return new AutoValue_Application.Builder()
// .timeout(-1);
// }
//
// public static Builder builder(String id, String name, Icon icon) {
// return builder()
// .id(id)
// .name(name)
// .icon(icon);
// }
//
// @AutoValue.Builder
// public interface Builder {
// Builder id(String id);
// Builder name(String name);
// Builder icon(Icon icon);
// Builder timeout(long timeout);
// Application build();
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/DiscoverableNotifier.java
// public interface DiscoverableNotifier extends Notifier {
//
// /**
// * Initialize before usage. <br>
// * This method must be called before trying to send a notification. <br>
// * Calling {@code init()} multiple time should not fail. <br>
// *
// * For example a notifier can open a connection to register the application, or it can do nothing.
// *
// * @return a usable initiated {@link Notifier} to send notification(s)
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// Notifier init();
//
// boolean tryInit();
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notification.java
// @AutoValue
// public abstract class Notification {
//
// /**
// * Indicate notification priority.
// */
// public enum Level {INFO, WARNING, ERROR}
//
// /**
// * Notification message.
// *
// * @return message.
// */
// public abstract String message();
//
// /**
// * Notification title.
// *
// * @return title.
// */
// public abstract String title();
//
// /**
// * Notification subtitle. <br>
// * Not available for all notifier implementation.
// *
// * @return subtitle.
// */
// @Nullable
// public abstract String subtitle();
//
// /**
// * Notification icon.
// *
// * @return icon.
// */
// public abstract Icon icon();
//
// /**
// * Indicate the notification priority type.
// *
// * @return type
// */
// public abstract Level level();
//
// Notification() {
// // prevent external subclasses
// }
//
// public static Builder builder(String title, String message, Icon icon) {
// return builder()
// .title(title)
// .message(message)
// .icon(icon);
// }
//
// public static Builder builder() {
// return new AutoValue_Notification.Builder().level(INFO);
// }
//
// @AutoValue.Builder
// public interface Builder {
// Builder title(String title);
// Builder message(String message);
// Builder icon(Icon icon);
// Builder subtitle(String subtitle);
// Builder level(Level level);
// Notification build();
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notifier.java
// public interface Notifier {
//
// /**
// * Send a notification.
// *
// * @param notification a notification.
// *
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// void send(Notification notification);
//
// /**
// * Close the notifier. <br>
// * This method must be called to release resources when the notifier is not needed anymore.
// */
// void close();
//
// /**
// * Indicate if the notifier is always displayed somewhere (menu/task bar, etc).
// * @return {@code true} if the notifier is persistent.
// */
// boolean isPersistent();
// }
| import com.google.common.base.MoreObjects;
import com.google.common.base.Objects;
import com.google.common.io.Closeables;
import fr.jcgay.notification.Application;
import fr.jcgay.notification.DiscoverableNotifier;
import fr.jcgay.notification.Notification;
import fr.jcgay.notification.Notifier;
import fr.jcgay.snp4j.Icon;
import fr.jcgay.snp4j.Server;
import fr.jcgay.snp4j.SnpException;
import fr.jcgay.snp4j.impl.SnpNotifier;
import fr.jcgay.snp4j.request.Priority;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException; | package fr.jcgay.notification.notifier.snarl;
public class SnarlNotifier implements DiscoverableNotifier {
private static final Logger LOGGER = LoggerFactory.getLogger(SnarlNotifier.class);
| // Path: send-notification/src/main/java/fr/jcgay/notification/Application.java
// @AutoValue
// public abstract class Application {
//
// /**
// * Uniquely identify an application. <br>
// * In order to ensure your application's signature is unique, the recommendation is to follow the Internet Media
// * type (also known as MIME content type) format as defined in IETF <a href="http://tools.ietf.org/html/rfc2046">RFC 2046</a>
// * which contains the application vendor's name - specifically: {@code application/x-vnd-some_vendor.some_app}. <br>
// * The signature must not contain spaces. <br>
// * Some examples of acceptable signatures:
// * <ul>
// * <li>{@code application/x-vnd-acme.hello_world}</li>
// * <li>{@code application/x-vnd-fullphat.snaRSS}</li>
// * </ul>
// *
// * @return unique identifier.
// */
// public abstract String id();
//
// /**
// * A name that will identify the application for the user. <br>
// * Examples:
// * <ul>
// * <li>Maven</li>
// * <li>Gradle</li>
// * </ul>
// *
// * @return application name.
// */
// public abstract String name();
//
// /**
// * A timeout to wait for before cancelling application registration or notification sending.
// *
// * @return timeout in milliseconds, or {@code -1} if not specified.
// */
// public abstract long timeout();
//
// /**
// * The application icon.
// *
// * @return application icon.
// */
// public abstract Icon icon();
//
// Application() {
// // prevent external subclasses
// }
//
// public static Builder builder() {
// return new AutoValue_Application.Builder()
// .timeout(-1);
// }
//
// public static Builder builder(String id, String name, Icon icon) {
// return builder()
// .id(id)
// .name(name)
// .icon(icon);
// }
//
// @AutoValue.Builder
// public interface Builder {
// Builder id(String id);
// Builder name(String name);
// Builder icon(Icon icon);
// Builder timeout(long timeout);
// Application build();
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/DiscoverableNotifier.java
// public interface DiscoverableNotifier extends Notifier {
//
// /**
// * Initialize before usage. <br>
// * This method must be called before trying to send a notification. <br>
// * Calling {@code init()} multiple time should not fail. <br>
// *
// * For example a notifier can open a connection to register the application, or it can do nothing.
// *
// * @return a usable initiated {@link Notifier} to send notification(s)
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// Notifier init();
//
// boolean tryInit();
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notification.java
// @AutoValue
// public abstract class Notification {
//
// /**
// * Indicate notification priority.
// */
// public enum Level {INFO, WARNING, ERROR}
//
// /**
// * Notification message.
// *
// * @return message.
// */
// public abstract String message();
//
// /**
// * Notification title.
// *
// * @return title.
// */
// public abstract String title();
//
// /**
// * Notification subtitle. <br>
// * Not available for all notifier implementation.
// *
// * @return subtitle.
// */
// @Nullable
// public abstract String subtitle();
//
// /**
// * Notification icon.
// *
// * @return icon.
// */
// public abstract Icon icon();
//
// /**
// * Indicate the notification priority type.
// *
// * @return type
// */
// public abstract Level level();
//
// Notification() {
// // prevent external subclasses
// }
//
// public static Builder builder(String title, String message, Icon icon) {
// return builder()
// .title(title)
// .message(message)
// .icon(icon);
// }
//
// public static Builder builder() {
// return new AutoValue_Notification.Builder().level(INFO);
// }
//
// @AutoValue.Builder
// public interface Builder {
// Builder title(String title);
// Builder message(String message);
// Builder icon(Icon icon);
// Builder subtitle(String subtitle);
// Builder level(Level level);
// Notification build();
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notifier.java
// public interface Notifier {
//
// /**
// * Send a notification.
// *
// * @param notification a notification.
// *
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// void send(Notification notification);
//
// /**
// * Close the notifier. <br>
// * This method must be called to release resources when the notifier is not needed anymore.
// */
// void close();
//
// /**
// * Indicate if the notifier is always displayed somewhere (menu/task bar, etc).
// * @return {@code true} if the notifier is persistent.
// */
// boolean isPersistent();
// }
// Path: send-notification/src/main/java/fr/jcgay/notification/notifier/snarl/SnarlNotifier.java
import com.google.common.base.MoreObjects;
import com.google.common.base.Objects;
import com.google.common.io.Closeables;
import fr.jcgay.notification.Application;
import fr.jcgay.notification.DiscoverableNotifier;
import fr.jcgay.notification.Notification;
import fr.jcgay.notification.Notifier;
import fr.jcgay.snp4j.Icon;
import fr.jcgay.snp4j.Server;
import fr.jcgay.snp4j.SnpException;
import fr.jcgay.snp4j.impl.SnpNotifier;
import fr.jcgay.snp4j.request.Priority;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
package fr.jcgay.notification.notifier.snarl;
public class SnarlNotifier implements DiscoverableNotifier {
private static final Logger LOGGER = LoggerFactory.getLogger(SnarlNotifier.class);
| private final Application application; |
jcgay/send-notification | send-notification/src/main/java/fr/jcgay/notification/notifier/snarl/SnarlNotifier.java | // Path: send-notification/src/main/java/fr/jcgay/notification/Application.java
// @AutoValue
// public abstract class Application {
//
// /**
// * Uniquely identify an application. <br>
// * In order to ensure your application's signature is unique, the recommendation is to follow the Internet Media
// * type (also known as MIME content type) format as defined in IETF <a href="http://tools.ietf.org/html/rfc2046">RFC 2046</a>
// * which contains the application vendor's name - specifically: {@code application/x-vnd-some_vendor.some_app}. <br>
// * The signature must not contain spaces. <br>
// * Some examples of acceptable signatures:
// * <ul>
// * <li>{@code application/x-vnd-acme.hello_world}</li>
// * <li>{@code application/x-vnd-fullphat.snaRSS}</li>
// * </ul>
// *
// * @return unique identifier.
// */
// public abstract String id();
//
// /**
// * A name that will identify the application for the user. <br>
// * Examples:
// * <ul>
// * <li>Maven</li>
// * <li>Gradle</li>
// * </ul>
// *
// * @return application name.
// */
// public abstract String name();
//
// /**
// * A timeout to wait for before cancelling application registration or notification sending.
// *
// * @return timeout in milliseconds, or {@code -1} if not specified.
// */
// public abstract long timeout();
//
// /**
// * The application icon.
// *
// * @return application icon.
// */
// public abstract Icon icon();
//
// Application() {
// // prevent external subclasses
// }
//
// public static Builder builder() {
// return new AutoValue_Application.Builder()
// .timeout(-1);
// }
//
// public static Builder builder(String id, String name, Icon icon) {
// return builder()
// .id(id)
// .name(name)
// .icon(icon);
// }
//
// @AutoValue.Builder
// public interface Builder {
// Builder id(String id);
// Builder name(String name);
// Builder icon(Icon icon);
// Builder timeout(long timeout);
// Application build();
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/DiscoverableNotifier.java
// public interface DiscoverableNotifier extends Notifier {
//
// /**
// * Initialize before usage. <br>
// * This method must be called before trying to send a notification. <br>
// * Calling {@code init()} multiple time should not fail. <br>
// *
// * For example a notifier can open a connection to register the application, or it can do nothing.
// *
// * @return a usable initiated {@link Notifier} to send notification(s)
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// Notifier init();
//
// boolean tryInit();
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notification.java
// @AutoValue
// public abstract class Notification {
//
// /**
// * Indicate notification priority.
// */
// public enum Level {INFO, WARNING, ERROR}
//
// /**
// * Notification message.
// *
// * @return message.
// */
// public abstract String message();
//
// /**
// * Notification title.
// *
// * @return title.
// */
// public abstract String title();
//
// /**
// * Notification subtitle. <br>
// * Not available for all notifier implementation.
// *
// * @return subtitle.
// */
// @Nullable
// public abstract String subtitle();
//
// /**
// * Notification icon.
// *
// * @return icon.
// */
// public abstract Icon icon();
//
// /**
// * Indicate the notification priority type.
// *
// * @return type
// */
// public abstract Level level();
//
// Notification() {
// // prevent external subclasses
// }
//
// public static Builder builder(String title, String message, Icon icon) {
// return builder()
// .title(title)
// .message(message)
// .icon(icon);
// }
//
// public static Builder builder() {
// return new AutoValue_Notification.Builder().level(INFO);
// }
//
// @AutoValue.Builder
// public interface Builder {
// Builder title(String title);
// Builder message(String message);
// Builder icon(Icon icon);
// Builder subtitle(String subtitle);
// Builder level(Level level);
// Notification build();
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notifier.java
// public interface Notifier {
//
// /**
// * Send a notification.
// *
// * @param notification a notification.
// *
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// void send(Notification notification);
//
// /**
// * Close the notifier. <br>
// * This method must be called to release resources when the notifier is not needed anymore.
// */
// void close();
//
// /**
// * Indicate if the notifier is always displayed somewhere (menu/task bar, etc).
// * @return {@code true} if the notifier is persistent.
// */
// boolean isPersistent();
// }
| import com.google.common.base.MoreObjects;
import com.google.common.base.Objects;
import com.google.common.io.Closeables;
import fr.jcgay.notification.Application;
import fr.jcgay.notification.DiscoverableNotifier;
import fr.jcgay.notification.Notification;
import fr.jcgay.notification.Notifier;
import fr.jcgay.snp4j.Icon;
import fr.jcgay.snp4j.Server;
import fr.jcgay.snp4j.SnpException;
import fr.jcgay.snp4j.impl.SnpNotifier;
import fr.jcgay.snp4j.request.Priority;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException; | package fr.jcgay.notification.notifier.snarl;
public class SnarlNotifier implements DiscoverableNotifier {
private static final Logger LOGGER = LoggerFactory.getLogger(SnarlNotifier.class);
private final Application application;
private final SnarlConfiguration configuration;
private final fr.jcgay.snp4j.Application snarlApplication;
| // Path: send-notification/src/main/java/fr/jcgay/notification/Application.java
// @AutoValue
// public abstract class Application {
//
// /**
// * Uniquely identify an application. <br>
// * In order to ensure your application's signature is unique, the recommendation is to follow the Internet Media
// * type (also known as MIME content type) format as defined in IETF <a href="http://tools.ietf.org/html/rfc2046">RFC 2046</a>
// * which contains the application vendor's name - specifically: {@code application/x-vnd-some_vendor.some_app}. <br>
// * The signature must not contain spaces. <br>
// * Some examples of acceptable signatures:
// * <ul>
// * <li>{@code application/x-vnd-acme.hello_world}</li>
// * <li>{@code application/x-vnd-fullphat.snaRSS}</li>
// * </ul>
// *
// * @return unique identifier.
// */
// public abstract String id();
//
// /**
// * A name that will identify the application for the user. <br>
// * Examples:
// * <ul>
// * <li>Maven</li>
// * <li>Gradle</li>
// * </ul>
// *
// * @return application name.
// */
// public abstract String name();
//
// /**
// * A timeout to wait for before cancelling application registration or notification sending.
// *
// * @return timeout in milliseconds, or {@code -1} if not specified.
// */
// public abstract long timeout();
//
// /**
// * The application icon.
// *
// * @return application icon.
// */
// public abstract Icon icon();
//
// Application() {
// // prevent external subclasses
// }
//
// public static Builder builder() {
// return new AutoValue_Application.Builder()
// .timeout(-1);
// }
//
// public static Builder builder(String id, String name, Icon icon) {
// return builder()
// .id(id)
// .name(name)
// .icon(icon);
// }
//
// @AutoValue.Builder
// public interface Builder {
// Builder id(String id);
// Builder name(String name);
// Builder icon(Icon icon);
// Builder timeout(long timeout);
// Application build();
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/DiscoverableNotifier.java
// public interface DiscoverableNotifier extends Notifier {
//
// /**
// * Initialize before usage. <br>
// * This method must be called before trying to send a notification. <br>
// * Calling {@code init()} multiple time should not fail. <br>
// *
// * For example a notifier can open a connection to register the application, or it can do nothing.
// *
// * @return a usable initiated {@link Notifier} to send notification(s)
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// Notifier init();
//
// boolean tryInit();
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notification.java
// @AutoValue
// public abstract class Notification {
//
// /**
// * Indicate notification priority.
// */
// public enum Level {INFO, WARNING, ERROR}
//
// /**
// * Notification message.
// *
// * @return message.
// */
// public abstract String message();
//
// /**
// * Notification title.
// *
// * @return title.
// */
// public abstract String title();
//
// /**
// * Notification subtitle. <br>
// * Not available for all notifier implementation.
// *
// * @return subtitle.
// */
// @Nullable
// public abstract String subtitle();
//
// /**
// * Notification icon.
// *
// * @return icon.
// */
// public abstract Icon icon();
//
// /**
// * Indicate the notification priority type.
// *
// * @return type
// */
// public abstract Level level();
//
// Notification() {
// // prevent external subclasses
// }
//
// public static Builder builder(String title, String message, Icon icon) {
// return builder()
// .title(title)
// .message(message)
// .icon(icon);
// }
//
// public static Builder builder() {
// return new AutoValue_Notification.Builder().level(INFO);
// }
//
// @AutoValue.Builder
// public interface Builder {
// Builder title(String title);
// Builder message(String message);
// Builder icon(Icon icon);
// Builder subtitle(String subtitle);
// Builder level(Level level);
// Notification build();
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notifier.java
// public interface Notifier {
//
// /**
// * Send a notification.
// *
// * @param notification a notification.
// *
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// void send(Notification notification);
//
// /**
// * Close the notifier. <br>
// * This method must be called to release resources when the notifier is not needed anymore.
// */
// void close();
//
// /**
// * Indicate if the notifier is always displayed somewhere (menu/task bar, etc).
// * @return {@code true} if the notifier is persistent.
// */
// boolean isPersistent();
// }
// Path: send-notification/src/main/java/fr/jcgay/notification/notifier/snarl/SnarlNotifier.java
import com.google.common.base.MoreObjects;
import com.google.common.base.Objects;
import com.google.common.io.Closeables;
import fr.jcgay.notification.Application;
import fr.jcgay.notification.DiscoverableNotifier;
import fr.jcgay.notification.Notification;
import fr.jcgay.notification.Notifier;
import fr.jcgay.snp4j.Icon;
import fr.jcgay.snp4j.Server;
import fr.jcgay.snp4j.SnpException;
import fr.jcgay.snp4j.impl.SnpNotifier;
import fr.jcgay.snp4j.request.Priority;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
package fr.jcgay.notification.notifier.snarl;
public class SnarlNotifier implements DiscoverableNotifier {
private static final Logger LOGGER = LoggerFactory.getLogger(SnarlNotifier.class);
private final Application application;
private final SnarlConfiguration configuration;
private final fr.jcgay.snp4j.Application snarlApplication;
| private fr.jcgay.snp4j.Notifier snarl; |
jcgay/send-notification | send-notification/src/main/java/fr/jcgay/notification/notifier/notifysend/NotifySendNotifier.java | // Path: send-notification/src/main/java/fr/jcgay/notification/Application.java
// @AutoValue
// public abstract class Application {
//
// /**
// * Uniquely identify an application. <br>
// * In order to ensure your application's signature is unique, the recommendation is to follow the Internet Media
// * type (also known as MIME content type) format as defined in IETF <a href="http://tools.ietf.org/html/rfc2046">RFC 2046</a>
// * which contains the application vendor's name - specifically: {@code application/x-vnd-some_vendor.some_app}. <br>
// * The signature must not contain spaces. <br>
// * Some examples of acceptable signatures:
// * <ul>
// * <li>{@code application/x-vnd-acme.hello_world}</li>
// * <li>{@code application/x-vnd-fullphat.snaRSS}</li>
// * </ul>
// *
// * @return unique identifier.
// */
// public abstract String id();
//
// /**
// * A name that will identify the application for the user. <br>
// * Examples:
// * <ul>
// * <li>Maven</li>
// * <li>Gradle</li>
// * </ul>
// *
// * @return application name.
// */
// public abstract String name();
//
// /**
// * A timeout to wait for before cancelling application registration or notification sending.
// *
// * @return timeout in milliseconds, or {@code -1} if not specified.
// */
// public abstract long timeout();
//
// /**
// * The application icon.
// *
// * @return application icon.
// */
// public abstract Icon icon();
//
// Application() {
// // prevent external subclasses
// }
//
// public static Builder builder() {
// return new AutoValue_Application.Builder()
// .timeout(-1);
// }
//
// public static Builder builder(String id, String name, Icon icon) {
// return builder()
// .id(id)
// .name(name)
// .icon(icon);
// }
//
// @AutoValue.Builder
// public interface Builder {
// Builder id(String id);
// Builder name(String name);
// Builder icon(Icon icon);
// Builder timeout(long timeout);
// Application build();
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/DiscoverableNotifier.java
// public interface DiscoverableNotifier extends Notifier {
//
// /**
// * Initialize before usage. <br>
// * This method must be called before trying to send a notification. <br>
// * Calling {@code init()} multiple time should not fail. <br>
// *
// * For example a notifier can open a connection to register the application, or it can do nothing.
// *
// * @return a usable initiated {@link Notifier} to send notification(s)
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// Notifier init();
//
// boolean tryInit();
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notification.java
// @AutoValue
// public abstract class Notification {
//
// /**
// * Indicate notification priority.
// */
// public enum Level {INFO, WARNING, ERROR}
//
// /**
// * Notification message.
// *
// * @return message.
// */
// public abstract String message();
//
// /**
// * Notification title.
// *
// * @return title.
// */
// public abstract String title();
//
// /**
// * Notification subtitle. <br>
// * Not available for all notifier implementation.
// *
// * @return subtitle.
// */
// @Nullable
// public abstract String subtitle();
//
// /**
// * Notification icon.
// *
// * @return icon.
// */
// public abstract Icon icon();
//
// /**
// * Indicate the notification priority type.
// *
// * @return type
// */
// public abstract Level level();
//
// Notification() {
// // prevent external subclasses
// }
//
// public static Builder builder(String title, String message, Icon icon) {
// return builder()
// .title(title)
// .message(message)
// .icon(icon);
// }
//
// public static Builder builder() {
// return new AutoValue_Notification.Builder().level(INFO);
// }
//
// @AutoValue.Builder
// public interface Builder {
// Builder title(String title);
// Builder message(String message);
// Builder icon(Icon icon);
// Builder subtitle(String subtitle);
// Builder level(Level level);
// Notification build();
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notifier.java
// public interface Notifier {
//
// /**
// * Send a notification.
// *
// * @param notification a notification.
// *
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// void send(Notification notification);
//
// /**
// * Close the notifier. <br>
// * This method must be called to release resources when the notifier is not needed anymore.
// */
// void close();
//
// /**
// * Indicate if the notifier is always displayed somewhere (menu/task bar, etc).
// * @return {@code true} if the notifier is persistent.
// */
// boolean isPersistent();
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/notifier/executor/Executor.java
// public interface Executor {
// void exec(String[] command);
// boolean tryExec(String[] command);
// void close();
// }
| import com.google.common.base.MoreObjects;
import com.google.common.base.Objects;
import fr.jcgay.notification.Application;
import fr.jcgay.notification.DiscoverableNotifier;
import fr.jcgay.notification.Notification;
import fr.jcgay.notification.Notifier;
import fr.jcgay.notification.notifier.executor.Executor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List; | package fr.jcgay.notification.notifier.notifysend;
public class NotifySendNotifier implements DiscoverableNotifier {
private static final Logger LOGGER = LoggerFactory.getLogger(NotifySendNotifier.class);
private static final String CMD_TIMEOUT = "-t";
private static final String CMD_ICON = "-i";
private static final String CMD_URGENCY = "-u";
| // Path: send-notification/src/main/java/fr/jcgay/notification/Application.java
// @AutoValue
// public abstract class Application {
//
// /**
// * Uniquely identify an application. <br>
// * In order to ensure your application's signature is unique, the recommendation is to follow the Internet Media
// * type (also known as MIME content type) format as defined in IETF <a href="http://tools.ietf.org/html/rfc2046">RFC 2046</a>
// * which contains the application vendor's name - specifically: {@code application/x-vnd-some_vendor.some_app}. <br>
// * The signature must not contain spaces. <br>
// * Some examples of acceptable signatures:
// * <ul>
// * <li>{@code application/x-vnd-acme.hello_world}</li>
// * <li>{@code application/x-vnd-fullphat.snaRSS}</li>
// * </ul>
// *
// * @return unique identifier.
// */
// public abstract String id();
//
// /**
// * A name that will identify the application for the user. <br>
// * Examples:
// * <ul>
// * <li>Maven</li>
// * <li>Gradle</li>
// * </ul>
// *
// * @return application name.
// */
// public abstract String name();
//
// /**
// * A timeout to wait for before cancelling application registration or notification sending.
// *
// * @return timeout in milliseconds, or {@code -1} if not specified.
// */
// public abstract long timeout();
//
// /**
// * The application icon.
// *
// * @return application icon.
// */
// public abstract Icon icon();
//
// Application() {
// // prevent external subclasses
// }
//
// public static Builder builder() {
// return new AutoValue_Application.Builder()
// .timeout(-1);
// }
//
// public static Builder builder(String id, String name, Icon icon) {
// return builder()
// .id(id)
// .name(name)
// .icon(icon);
// }
//
// @AutoValue.Builder
// public interface Builder {
// Builder id(String id);
// Builder name(String name);
// Builder icon(Icon icon);
// Builder timeout(long timeout);
// Application build();
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/DiscoverableNotifier.java
// public interface DiscoverableNotifier extends Notifier {
//
// /**
// * Initialize before usage. <br>
// * This method must be called before trying to send a notification. <br>
// * Calling {@code init()} multiple time should not fail. <br>
// *
// * For example a notifier can open a connection to register the application, or it can do nothing.
// *
// * @return a usable initiated {@link Notifier} to send notification(s)
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// Notifier init();
//
// boolean tryInit();
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notification.java
// @AutoValue
// public abstract class Notification {
//
// /**
// * Indicate notification priority.
// */
// public enum Level {INFO, WARNING, ERROR}
//
// /**
// * Notification message.
// *
// * @return message.
// */
// public abstract String message();
//
// /**
// * Notification title.
// *
// * @return title.
// */
// public abstract String title();
//
// /**
// * Notification subtitle. <br>
// * Not available for all notifier implementation.
// *
// * @return subtitle.
// */
// @Nullable
// public abstract String subtitle();
//
// /**
// * Notification icon.
// *
// * @return icon.
// */
// public abstract Icon icon();
//
// /**
// * Indicate the notification priority type.
// *
// * @return type
// */
// public abstract Level level();
//
// Notification() {
// // prevent external subclasses
// }
//
// public static Builder builder(String title, String message, Icon icon) {
// return builder()
// .title(title)
// .message(message)
// .icon(icon);
// }
//
// public static Builder builder() {
// return new AutoValue_Notification.Builder().level(INFO);
// }
//
// @AutoValue.Builder
// public interface Builder {
// Builder title(String title);
// Builder message(String message);
// Builder icon(Icon icon);
// Builder subtitle(String subtitle);
// Builder level(Level level);
// Notification build();
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notifier.java
// public interface Notifier {
//
// /**
// * Send a notification.
// *
// * @param notification a notification.
// *
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// void send(Notification notification);
//
// /**
// * Close the notifier. <br>
// * This method must be called to release resources when the notifier is not needed anymore.
// */
// void close();
//
// /**
// * Indicate if the notifier is always displayed somewhere (menu/task bar, etc).
// * @return {@code true} if the notifier is persistent.
// */
// boolean isPersistent();
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/notifier/executor/Executor.java
// public interface Executor {
// void exec(String[] command);
// boolean tryExec(String[] command);
// void close();
// }
// Path: send-notification/src/main/java/fr/jcgay/notification/notifier/notifysend/NotifySendNotifier.java
import com.google.common.base.MoreObjects;
import com.google.common.base.Objects;
import fr.jcgay.notification.Application;
import fr.jcgay.notification.DiscoverableNotifier;
import fr.jcgay.notification.Notification;
import fr.jcgay.notification.Notifier;
import fr.jcgay.notification.notifier.executor.Executor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
package fr.jcgay.notification.notifier.notifysend;
public class NotifySendNotifier implements DiscoverableNotifier {
private static final Logger LOGGER = LoggerFactory.getLogger(NotifySendNotifier.class);
private static final String CMD_TIMEOUT = "-t";
private static final String CMD_ICON = "-i";
private static final String CMD_URGENCY = "-u";
| private final Application application; |
jcgay/send-notification | send-notification/src/main/java/fr/jcgay/notification/notifier/pushbullet/PushbulletNotifier.java | // Path: send-notification/src/main/java/fr/jcgay/notification/Application.java
// @AutoValue
// public abstract class Application {
//
// /**
// * Uniquely identify an application. <br>
// * In order to ensure your application's signature is unique, the recommendation is to follow the Internet Media
// * type (also known as MIME content type) format as defined in IETF <a href="http://tools.ietf.org/html/rfc2046">RFC 2046</a>
// * which contains the application vendor's name - specifically: {@code application/x-vnd-some_vendor.some_app}. <br>
// * The signature must not contain spaces. <br>
// * Some examples of acceptable signatures:
// * <ul>
// * <li>{@code application/x-vnd-acme.hello_world}</li>
// * <li>{@code application/x-vnd-fullphat.snaRSS}</li>
// * </ul>
// *
// * @return unique identifier.
// */
// public abstract String id();
//
// /**
// * A name that will identify the application for the user. <br>
// * Examples:
// * <ul>
// * <li>Maven</li>
// * <li>Gradle</li>
// * </ul>
// *
// * @return application name.
// */
// public abstract String name();
//
// /**
// * A timeout to wait for before cancelling application registration or notification sending.
// *
// * @return timeout in milliseconds, or {@code -1} if not specified.
// */
// public abstract long timeout();
//
// /**
// * The application icon.
// *
// * @return application icon.
// */
// public abstract Icon icon();
//
// Application() {
// // prevent external subclasses
// }
//
// public static Builder builder() {
// return new AutoValue_Application.Builder()
// .timeout(-1);
// }
//
// public static Builder builder(String id, String name, Icon icon) {
// return builder()
// .id(id)
// .name(name)
// .icon(icon);
// }
//
// @AutoValue.Builder
// public interface Builder {
// Builder id(String id);
// Builder name(String name);
// Builder icon(Icon icon);
// Builder timeout(long timeout);
// Application build();
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/DiscoverableNotifier.java
// public interface DiscoverableNotifier extends Notifier {
//
// /**
// * Initialize before usage. <br>
// * This method must be called before trying to send a notification. <br>
// * Calling {@code init()} multiple time should not fail. <br>
// *
// * For example a notifier can open a connection to register the application, or it can do nothing.
// *
// * @return a usable initiated {@link Notifier} to send notification(s)
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// Notifier init();
//
// boolean tryInit();
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notification.java
// @AutoValue
// public abstract class Notification {
//
// /**
// * Indicate notification priority.
// */
// public enum Level {INFO, WARNING, ERROR}
//
// /**
// * Notification message.
// *
// * @return message.
// */
// public abstract String message();
//
// /**
// * Notification title.
// *
// * @return title.
// */
// public abstract String title();
//
// /**
// * Notification subtitle. <br>
// * Not available for all notifier implementation.
// *
// * @return subtitle.
// */
// @Nullable
// public abstract String subtitle();
//
// /**
// * Notification icon.
// *
// * @return icon.
// */
// public abstract Icon icon();
//
// /**
// * Indicate the notification priority type.
// *
// * @return type
// */
// public abstract Level level();
//
// Notification() {
// // prevent external subclasses
// }
//
// public static Builder builder(String title, String message, Icon icon) {
// return builder()
// .title(title)
// .message(message)
// .icon(icon);
// }
//
// public static Builder builder() {
// return new AutoValue_Notification.Builder().level(INFO);
// }
//
// @AutoValue.Builder
// public interface Builder {
// Builder title(String title);
// Builder message(String message);
// Builder icon(Icon icon);
// Builder subtitle(String subtitle);
// Builder level(Level level);
// Notification build();
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notifier.java
// public interface Notifier {
//
// /**
// * Send a notification.
// *
// * @param notification a notification.
// *
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// void send(Notification notification);
//
// /**
// * Close the notifier. <br>
// * This method must be called to release resources when the notifier is not needed anymore.
// */
// void close();
//
// /**
// * Indicate if the notifier is always displayed somewhere (menu/task bar, etc).
// * @return {@code true} if the notifier is persistent.
// */
// boolean isPersistent();
// }
| import com.squareup.mimecraft.FormEncoding;
import com.squareup.okhttp.Authenticator;
import com.squareup.okhttp.Credentials;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;
import fr.jcgay.notification.Application;
import fr.jcgay.notification.DiscoverableNotifier;
import fr.jcgay.notification.Notification;
import fr.jcgay.notification.Notifier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.Proxy; | package fr.jcgay.notification.notifier.pushbullet;
public class PushbulletNotifier implements DiscoverableNotifier {
private static final Logger LOGGER = LoggerFactory.getLogger(PushbulletNotifier.class);
private final PushbulletConfiguration configuration;
private final String url;
private OkHttpClient client;
| // Path: send-notification/src/main/java/fr/jcgay/notification/Application.java
// @AutoValue
// public abstract class Application {
//
// /**
// * Uniquely identify an application. <br>
// * In order to ensure your application's signature is unique, the recommendation is to follow the Internet Media
// * type (also known as MIME content type) format as defined in IETF <a href="http://tools.ietf.org/html/rfc2046">RFC 2046</a>
// * which contains the application vendor's name - specifically: {@code application/x-vnd-some_vendor.some_app}. <br>
// * The signature must not contain spaces. <br>
// * Some examples of acceptable signatures:
// * <ul>
// * <li>{@code application/x-vnd-acme.hello_world}</li>
// * <li>{@code application/x-vnd-fullphat.snaRSS}</li>
// * </ul>
// *
// * @return unique identifier.
// */
// public abstract String id();
//
// /**
// * A name that will identify the application for the user. <br>
// * Examples:
// * <ul>
// * <li>Maven</li>
// * <li>Gradle</li>
// * </ul>
// *
// * @return application name.
// */
// public abstract String name();
//
// /**
// * A timeout to wait for before cancelling application registration or notification sending.
// *
// * @return timeout in milliseconds, or {@code -1} if not specified.
// */
// public abstract long timeout();
//
// /**
// * The application icon.
// *
// * @return application icon.
// */
// public abstract Icon icon();
//
// Application() {
// // prevent external subclasses
// }
//
// public static Builder builder() {
// return new AutoValue_Application.Builder()
// .timeout(-1);
// }
//
// public static Builder builder(String id, String name, Icon icon) {
// return builder()
// .id(id)
// .name(name)
// .icon(icon);
// }
//
// @AutoValue.Builder
// public interface Builder {
// Builder id(String id);
// Builder name(String name);
// Builder icon(Icon icon);
// Builder timeout(long timeout);
// Application build();
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/DiscoverableNotifier.java
// public interface DiscoverableNotifier extends Notifier {
//
// /**
// * Initialize before usage. <br>
// * This method must be called before trying to send a notification. <br>
// * Calling {@code init()} multiple time should not fail. <br>
// *
// * For example a notifier can open a connection to register the application, or it can do nothing.
// *
// * @return a usable initiated {@link Notifier} to send notification(s)
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// Notifier init();
//
// boolean tryInit();
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notification.java
// @AutoValue
// public abstract class Notification {
//
// /**
// * Indicate notification priority.
// */
// public enum Level {INFO, WARNING, ERROR}
//
// /**
// * Notification message.
// *
// * @return message.
// */
// public abstract String message();
//
// /**
// * Notification title.
// *
// * @return title.
// */
// public abstract String title();
//
// /**
// * Notification subtitle. <br>
// * Not available for all notifier implementation.
// *
// * @return subtitle.
// */
// @Nullable
// public abstract String subtitle();
//
// /**
// * Notification icon.
// *
// * @return icon.
// */
// public abstract Icon icon();
//
// /**
// * Indicate the notification priority type.
// *
// * @return type
// */
// public abstract Level level();
//
// Notification() {
// // prevent external subclasses
// }
//
// public static Builder builder(String title, String message, Icon icon) {
// return builder()
// .title(title)
// .message(message)
// .icon(icon);
// }
//
// public static Builder builder() {
// return new AutoValue_Notification.Builder().level(INFO);
// }
//
// @AutoValue.Builder
// public interface Builder {
// Builder title(String title);
// Builder message(String message);
// Builder icon(Icon icon);
// Builder subtitle(String subtitle);
// Builder level(Level level);
// Notification build();
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notifier.java
// public interface Notifier {
//
// /**
// * Send a notification.
// *
// * @param notification a notification.
// *
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// void send(Notification notification);
//
// /**
// * Close the notifier. <br>
// * This method must be called to release resources when the notifier is not needed anymore.
// */
// void close();
//
// /**
// * Indicate if the notifier is always displayed somewhere (menu/task bar, etc).
// * @return {@code true} if the notifier is persistent.
// */
// boolean isPersistent();
// }
// Path: send-notification/src/main/java/fr/jcgay/notification/notifier/pushbullet/PushbulletNotifier.java
import com.squareup.mimecraft.FormEncoding;
import com.squareup.okhttp.Authenticator;
import com.squareup.okhttp.Credentials;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;
import fr.jcgay.notification.Application;
import fr.jcgay.notification.DiscoverableNotifier;
import fr.jcgay.notification.Notification;
import fr.jcgay.notification.Notifier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.Proxy;
package fr.jcgay.notification.notifier.pushbullet;
public class PushbulletNotifier implements DiscoverableNotifier {
private static final Logger LOGGER = LoggerFactory.getLogger(PushbulletNotifier.class);
private final PushbulletConfiguration configuration;
private final String url;
private OkHttpClient client;
| public PushbulletNotifier(Application application, PushbulletConfiguration configuration) { |
jcgay/send-notification | send-notification/src/main/java/fr/jcgay/notification/notifier/notify/NotifyNotifier.java | // Path: send-notification/src/main/java/fr/jcgay/notification/Application.java
// @AutoValue
// public abstract class Application {
//
// /**
// * Uniquely identify an application. <br>
// * In order to ensure your application's signature is unique, the recommendation is to follow the Internet Media
// * type (also known as MIME content type) format as defined in IETF <a href="http://tools.ietf.org/html/rfc2046">RFC 2046</a>
// * which contains the application vendor's name - specifically: {@code application/x-vnd-some_vendor.some_app}. <br>
// * The signature must not contain spaces. <br>
// * Some examples of acceptable signatures:
// * <ul>
// * <li>{@code application/x-vnd-acme.hello_world}</li>
// * <li>{@code application/x-vnd-fullphat.snaRSS}</li>
// * </ul>
// *
// * @return unique identifier.
// */
// public abstract String id();
//
// /**
// * A name that will identify the application for the user. <br>
// * Examples:
// * <ul>
// * <li>Maven</li>
// * <li>Gradle</li>
// * </ul>
// *
// * @return application name.
// */
// public abstract String name();
//
// /**
// * A timeout to wait for before cancelling application registration or notification sending.
// *
// * @return timeout in milliseconds, or {@code -1} if not specified.
// */
// public abstract long timeout();
//
// /**
// * The application icon.
// *
// * @return application icon.
// */
// public abstract Icon icon();
//
// Application() {
// // prevent external subclasses
// }
//
// public static Builder builder() {
// return new AutoValue_Application.Builder()
// .timeout(-1);
// }
//
// public static Builder builder(String id, String name, Icon icon) {
// return builder()
// .id(id)
// .name(name)
// .icon(icon);
// }
//
// @AutoValue.Builder
// public interface Builder {
// Builder id(String id);
// Builder name(String name);
// Builder icon(Icon icon);
// Builder timeout(long timeout);
// Application build();
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/DiscoverableNotifier.java
// public interface DiscoverableNotifier extends Notifier {
//
// /**
// * Initialize before usage. <br>
// * This method must be called before trying to send a notification. <br>
// * Calling {@code init()} multiple time should not fail. <br>
// *
// * For example a notifier can open a connection to register the application, or it can do nothing.
// *
// * @return a usable initiated {@link Notifier} to send notification(s)
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// Notifier init();
//
// boolean tryInit();
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notification.java
// @AutoValue
// public abstract class Notification {
//
// /**
// * Indicate notification priority.
// */
// public enum Level {INFO, WARNING, ERROR}
//
// /**
// * Notification message.
// *
// * @return message.
// */
// public abstract String message();
//
// /**
// * Notification title.
// *
// * @return title.
// */
// public abstract String title();
//
// /**
// * Notification subtitle. <br>
// * Not available for all notifier implementation.
// *
// * @return subtitle.
// */
// @Nullable
// public abstract String subtitle();
//
// /**
// * Notification icon.
// *
// * @return icon.
// */
// public abstract Icon icon();
//
// /**
// * Indicate the notification priority type.
// *
// * @return type
// */
// public abstract Level level();
//
// Notification() {
// // prevent external subclasses
// }
//
// public static Builder builder(String title, String message, Icon icon) {
// return builder()
// .title(title)
// .message(message)
// .icon(icon);
// }
//
// public static Builder builder() {
// return new AutoValue_Notification.Builder().level(INFO);
// }
//
// @AutoValue.Builder
// public interface Builder {
// Builder title(String title);
// Builder message(String message);
// Builder icon(Icon icon);
// Builder subtitle(String subtitle);
// Builder level(Level level);
// Notification build();
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notifier.java
// public interface Notifier {
//
// /**
// * Send a notification.
// *
// * @param notification a notification.
// *
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// void send(Notification notification);
//
// /**
// * Close the notifier. <br>
// * This method must be called to release resources when the notifier is not needed anymore.
// */
// void close();
//
// /**
// * Indicate if the notifier is always displayed somewhere (menu/task bar, etc).
// * @return {@code true} if the notifier is persistent.
// */
// boolean isPersistent();
// }
| import com.google.common.base.MoreObjects;
import com.google.common.base.Objects;
import dorkbox.notify.Notify;
import fr.jcgay.notification.Application;
import fr.jcgay.notification.DiscoverableNotifier;
import fr.jcgay.notification.Notification;
import fr.jcgay.notification.Notifier;
import org.slf4j.Logger;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.slf4j.LoggerFactory.getLogger; | package fr.jcgay.notification.notifier.notify;
public class NotifyNotifier implements DiscoverableNotifier {
private static final Logger LOGGER = getLogger(NotifyNotifier.class);
| // Path: send-notification/src/main/java/fr/jcgay/notification/Application.java
// @AutoValue
// public abstract class Application {
//
// /**
// * Uniquely identify an application. <br>
// * In order to ensure your application's signature is unique, the recommendation is to follow the Internet Media
// * type (also known as MIME content type) format as defined in IETF <a href="http://tools.ietf.org/html/rfc2046">RFC 2046</a>
// * which contains the application vendor's name - specifically: {@code application/x-vnd-some_vendor.some_app}. <br>
// * The signature must not contain spaces. <br>
// * Some examples of acceptable signatures:
// * <ul>
// * <li>{@code application/x-vnd-acme.hello_world}</li>
// * <li>{@code application/x-vnd-fullphat.snaRSS}</li>
// * </ul>
// *
// * @return unique identifier.
// */
// public abstract String id();
//
// /**
// * A name that will identify the application for the user. <br>
// * Examples:
// * <ul>
// * <li>Maven</li>
// * <li>Gradle</li>
// * </ul>
// *
// * @return application name.
// */
// public abstract String name();
//
// /**
// * A timeout to wait for before cancelling application registration or notification sending.
// *
// * @return timeout in milliseconds, or {@code -1} if not specified.
// */
// public abstract long timeout();
//
// /**
// * The application icon.
// *
// * @return application icon.
// */
// public abstract Icon icon();
//
// Application() {
// // prevent external subclasses
// }
//
// public static Builder builder() {
// return new AutoValue_Application.Builder()
// .timeout(-1);
// }
//
// public static Builder builder(String id, String name, Icon icon) {
// return builder()
// .id(id)
// .name(name)
// .icon(icon);
// }
//
// @AutoValue.Builder
// public interface Builder {
// Builder id(String id);
// Builder name(String name);
// Builder icon(Icon icon);
// Builder timeout(long timeout);
// Application build();
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/DiscoverableNotifier.java
// public interface DiscoverableNotifier extends Notifier {
//
// /**
// * Initialize before usage. <br>
// * This method must be called before trying to send a notification. <br>
// * Calling {@code init()} multiple time should not fail. <br>
// *
// * For example a notifier can open a connection to register the application, or it can do nothing.
// *
// * @return a usable initiated {@link Notifier} to send notification(s)
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// Notifier init();
//
// boolean tryInit();
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notification.java
// @AutoValue
// public abstract class Notification {
//
// /**
// * Indicate notification priority.
// */
// public enum Level {INFO, WARNING, ERROR}
//
// /**
// * Notification message.
// *
// * @return message.
// */
// public abstract String message();
//
// /**
// * Notification title.
// *
// * @return title.
// */
// public abstract String title();
//
// /**
// * Notification subtitle. <br>
// * Not available for all notifier implementation.
// *
// * @return subtitle.
// */
// @Nullable
// public abstract String subtitle();
//
// /**
// * Notification icon.
// *
// * @return icon.
// */
// public abstract Icon icon();
//
// /**
// * Indicate the notification priority type.
// *
// * @return type
// */
// public abstract Level level();
//
// Notification() {
// // prevent external subclasses
// }
//
// public static Builder builder(String title, String message, Icon icon) {
// return builder()
// .title(title)
// .message(message)
// .icon(icon);
// }
//
// public static Builder builder() {
// return new AutoValue_Notification.Builder().level(INFO);
// }
//
// @AutoValue.Builder
// public interface Builder {
// Builder title(String title);
// Builder message(String message);
// Builder icon(Icon icon);
// Builder subtitle(String subtitle);
// Builder level(Level level);
// Notification build();
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notifier.java
// public interface Notifier {
//
// /**
// * Send a notification.
// *
// * @param notification a notification.
// *
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// void send(Notification notification);
//
// /**
// * Close the notifier. <br>
// * This method must be called to release resources when the notifier is not needed anymore.
// */
// void close();
//
// /**
// * Indicate if the notifier is always displayed somewhere (menu/task bar, etc).
// * @return {@code true} if the notifier is persistent.
// */
// boolean isPersistent();
// }
// Path: send-notification/src/main/java/fr/jcgay/notification/notifier/notify/NotifyNotifier.java
import com.google.common.base.MoreObjects;
import com.google.common.base.Objects;
import dorkbox.notify.Notify;
import fr.jcgay.notification.Application;
import fr.jcgay.notification.DiscoverableNotifier;
import fr.jcgay.notification.Notification;
import fr.jcgay.notification.Notifier;
import org.slf4j.Logger;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.slf4j.LoggerFactory.getLogger;
package fr.jcgay.notification.notifier.notify;
public class NotifyNotifier implements DiscoverableNotifier {
private static final Logger LOGGER = getLogger(NotifyNotifier.class);
| private final Application application; |
jcgay/send-notification | send-notification/src/main/java/fr/jcgay/notification/notifier/notify/NotifyNotifier.java | // Path: send-notification/src/main/java/fr/jcgay/notification/Application.java
// @AutoValue
// public abstract class Application {
//
// /**
// * Uniquely identify an application. <br>
// * In order to ensure your application's signature is unique, the recommendation is to follow the Internet Media
// * type (also known as MIME content type) format as defined in IETF <a href="http://tools.ietf.org/html/rfc2046">RFC 2046</a>
// * which contains the application vendor's name - specifically: {@code application/x-vnd-some_vendor.some_app}. <br>
// * The signature must not contain spaces. <br>
// * Some examples of acceptable signatures:
// * <ul>
// * <li>{@code application/x-vnd-acme.hello_world}</li>
// * <li>{@code application/x-vnd-fullphat.snaRSS}</li>
// * </ul>
// *
// * @return unique identifier.
// */
// public abstract String id();
//
// /**
// * A name that will identify the application for the user. <br>
// * Examples:
// * <ul>
// * <li>Maven</li>
// * <li>Gradle</li>
// * </ul>
// *
// * @return application name.
// */
// public abstract String name();
//
// /**
// * A timeout to wait for before cancelling application registration or notification sending.
// *
// * @return timeout in milliseconds, or {@code -1} if not specified.
// */
// public abstract long timeout();
//
// /**
// * The application icon.
// *
// * @return application icon.
// */
// public abstract Icon icon();
//
// Application() {
// // prevent external subclasses
// }
//
// public static Builder builder() {
// return new AutoValue_Application.Builder()
// .timeout(-1);
// }
//
// public static Builder builder(String id, String name, Icon icon) {
// return builder()
// .id(id)
// .name(name)
// .icon(icon);
// }
//
// @AutoValue.Builder
// public interface Builder {
// Builder id(String id);
// Builder name(String name);
// Builder icon(Icon icon);
// Builder timeout(long timeout);
// Application build();
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/DiscoverableNotifier.java
// public interface DiscoverableNotifier extends Notifier {
//
// /**
// * Initialize before usage. <br>
// * This method must be called before trying to send a notification. <br>
// * Calling {@code init()} multiple time should not fail. <br>
// *
// * For example a notifier can open a connection to register the application, or it can do nothing.
// *
// * @return a usable initiated {@link Notifier} to send notification(s)
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// Notifier init();
//
// boolean tryInit();
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notification.java
// @AutoValue
// public abstract class Notification {
//
// /**
// * Indicate notification priority.
// */
// public enum Level {INFO, WARNING, ERROR}
//
// /**
// * Notification message.
// *
// * @return message.
// */
// public abstract String message();
//
// /**
// * Notification title.
// *
// * @return title.
// */
// public abstract String title();
//
// /**
// * Notification subtitle. <br>
// * Not available for all notifier implementation.
// *
// * @return subtitle.
// */
// @Nullable
// public abstract String subtitle();
//
// /**
// * Notification icon.
// *
// * @return icon.
// */
// public abstract Icon icon();
//
// /**
// * Indicate the notification priority type.
// *
// * @return type
// */
// public abstract Level level();
//
// Notification() {
// // prevent external subclasses
// }
//
// public static Builder builder(String title, String message, Icon icon) {
// return builder()
// .title(title)
// .message(message)
// .icon(icon);
// }
//
// public static Builder builder() {
// return new AutoValue_Notification.Builder().level(INFO);
// }
//
// @AutoValue.Builder
// public interface Builder {
// Builder title(String title);
// Builder message(String message);
// Builder icon(Icon icon);
// Builder subtitle(String subtitle);
// Builder level(Level level);
// Notification build();
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notifier.java
// public interface Notifier {
//
// /**
// * Send a notification.
// *
// * @param notification a notification.
// *
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// void send(Notification notification);
//
// /**
// * Close the notifier. <br>
// * This method must be called to release resources when the notifier is not needed anymore.
// */
// void close();
//
// /**
// * Indicate if the notifier is always displayed somewhere (menu/task bar, etc).
// * @return {@code true} if the notifier is persistent.
// */
// boolean isPersistent();
// }
| import com.google.common.base.MoreObjects;
import com.google.common.base.Objects;
import dorkbox.notify.Notify;
import fr.jcgay.notification.Application;
import fr.jcgay.notification.DiscoverableNotifier;
import fr.jcgay.notification.Notification;
import fr.jcgay.notification.Notifier;
import org.slf4j.Logger;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.slf4j.LoggerFactory.getLogger; | package fr.jcgay.notification.notifier.notify;
public class NotifyNotifier implements DiscoverableNotifier {
private static final Logger LOGGER = getLogger(NotifyNotifier.class);
private final Application application;
private final NotifyConfiguration configuration;
private boolean skipNotifications;
public NotifyNotifier(Application application, NotifyConfiguration configuration) {
LOGGER.debug("Configuring notify: {}.", configuration);
this.configuration = configuration;
this.application = application;
}
@Override | // Path: send-notification/src/main/java/fr/jcgay/notification/Application.java
// @AutoValue
// public abstract class Application {
//
// /**
// * Uniquely identify an application. <br>
// * In order to ensure your application's signature is unique, the recommendation is to follow the Internet Media
// * type (also known as MIME content type) format as defined in IETF <a href="http://tools.ietf.org/html/rfc2046">RFC 2046</a>
// * which contains the application vendor's name - specifically: {@code application/x-vnd-some_vendor.some_app}. <br>
// * The signature must not contain spaces. <br>
// * Some examples of acceptable signatures:
// * <ul>
// * <li>{@code application/x-vnd-acme.hello_world}</li>
// * <li>{@code application/x-vnd-fullphat.snaRSS}</li>
// * </ul>
// *
// * @return unique identifier.
// */
// public abstract String id();
//
// /**
// * A name that will identify the application for the user. <br>
// * Examples:
// * <ul>
// * <li>Maven</li>
// * <li>Gradle</li>
// * </ul>
// *
// * @return application name.
// */
// public abstract String name();
//
// /**
// * A timeout to wait for before cancelling application registration or notification sending.
// *
// * @return timeout in milliseconds, or {@code -1} if not specified.
// */
// public abstract long timeout();
//
// /**
// * The application icon.
// *
// * @return application icon.
// */
// public abstract Icon icon();
//
// Application() {
// // prevent external subclasses
// }
//
// public static Builder builder() {
// return new AutoValue_Application.Builder()
// .timeout(-1);
// }
//
// public static Builder builder(String id, String name, Icon icon) {
// return builder()
// .id(id)
// .name(name)
// .icon(icon);
// }
//
// @AutoValue.Builder
// public interface Builder {
// Builder id(String id);
// Builder name(String name);
// Builder icon(Icon icon);
// Builder timeout(long timeout);
// Application build();
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/DiscoverableNotifier.java
// public interface DiscoverableNotifier extends Notifier {
//
// /**
// * Initialize before usage. <br>
// * This method must be called before trying to send a notification. <br>
// * Calling {@code init()} multiple time should not fail. <br>
// *
// * For example a notifier can open a connection to register the application, or it can do nothing.
// *
// * @return a usable initiated {@link Notifier} to send notification(s)
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// Notifier init();
//
// boolean tryInit();
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notification.java
// @AutoValue
// public abstract class Notification {
//
// /**
// * Indicate notification priority.
// */
// public enum Level {INFO, WARNING, ERROR}
//
// /**
// * Notification message.
// *
// * @return message.
// */
// public abstract String message();
//
// /**
// * Notification title.
// *
// * @return title.
// */
// public abstract String title();
//
// /**
// * Notification subtitle. <br>
// * Not available for all notifier implementation.
// *
// * @return subtitle.
// */
// @Nullable
// public abstract String subtitle();
//
// /**
// * Notification icon.
// *
// * @return icon.
// */
// public abstract Icon icon();
//
// /**
// * Indicate the notification priority type.
// *
// * @return type
// */
// public abstract Level level();
//
// Notification() {
// // prevent external subclasses
// }
//
// public static Builder builder(String title, String message, Icon icon) {
// return builder()
// .title(title)
// .message(message)
// .icon(icon);
// }
//
// public static Builder builder() {
// return new AutoValue_Notification.Builder().level(INFO);
// }
//
// @AutoValue.Builder
// public interface Builder {
// Builder title(String title);
// Builder message(String message);
// Builder icon(Icon icon);
// Builder subtitle(String subtitle);
// Builder level(Level level);
// Notification build();
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notifier.java
// public interface Notifier {
//
// /**
// * Send a notification.
// *
// * @param notification a notification.
// *
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// void send(Notification notification);
//
// /**
// * Close the notifier. <br>
// * This method must be called to release resources when the notifier is not needed anymore.
// */
// void close();
//
// /**
// * Indicate if the notifier is always displayed somewhere (menu/task bar, etc).
// * @return {@code true} if the notifier is persistent.
// */
// boolean isPersistent();
// }
// Path: send-notification/src/main/java/fr/jcgay/notification/notifier/notify/NotifyNotifier.java
import com.google.common.base.MoreObjects;
import com.google.common.base.Objects;
import dorkbox.notify.Notify;
import fr.jcgay.notification.Application;
import fr.jcgay.notification.DiscoverableNotifier;
import fr.jcgay.notification.Notification;
import fr.jcgay.notification.Notifier;
import org.slf4j.Logger;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.slf4j.LoggerFactory.getLogger;
package fr.jcgay.notification.notifier.notify;
public class NotifyNotifier implements DiscoverableNotifier {
private static final Logger LOGGER = getLogger(NotifyNotifier.class);
private final Application application;
private final NotifyConfiguration configuration;
private boolean skipNotifications;
public NotifyNotifier(Application application, NotifyConfiguration configuration) {
LOGGER.debug("Configuring notify: {}.", configuration);
this.configuration = configuration;
this.application = application;
}
@Override | public Notifier init() { |
jcgay/send-notification | send-notification/src/main/java/fr/jcgay/notification/notifier/kdialog/KdialogNotifier.java | // Path: send-notification/src/main/java/fr/jcgay/notification/Application.java
// @AutoValue
// public abstract class Application {
//
// /**
// * Uniquely identify an application. <br>
// * In order to ensure your application's signature is unique, the recommendation is to follow the Internet Media
// * type (also known as MIME content type) format as defined in IETF <a href="http://tools.ietf.org/html/rfc2046">RFC 2046</a>
// * which contains the application vendor's name - specifically: {@code application/x-vnd-some_vendor.some_app}. <br>
// * The signature must not contain spaces. <br>
// * Some examples of acceptable signatures:
// * <ul>
// * <li>{@code application/x-vnd-acme.hello_world}</li>
// * <li>{@code application/x-vnd-fullphat.snaRSS}</li>
// * </ul>
// *
// * @return unique identifier.
// */
// public abstract String id();
//
// /**
// * A name that will identify the application for the user. <br>
// * Examples:
// * <ul>
// * <li>Maven</li>
// * <li>Gradle</li>
// * </ul>
// *
// * @return application name.
// */
// public abstract String name();
//
// /**
// * A timeout to wait for before cancelling application registration or notification sending.
// *
// * @return timeout in milliseconds, or {@code -1} if not specified.
// */
// public abstract long timeout();
//
// /**
// * The application icon.
// *
// * @return application icon.
// */
// public abstract Icon icon();
//
// Application() {
// // prevent external subclasses
// }
//
// public static Builder builder() {
// return new AutoValue_Application.Builder()
// .timeout(-1);
// }
//
// public static Builder builder(String id, String name, Icon icon) {
// return builder()
// .id(id)
// .name(name)
// .icon(icon);
// }
//
// @AutoValue.Builder
// public interface Builder {
// Builder id(String id);
// Builder name(String name);
// Builder icon(Icon icon);
// Builder timeout(long timeout);
// Application build();
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/DiscoverableNotifier.java
// public interface DiscoverableNotifier extends Notifier {
//
// /**
// * Initialize before usage. <br>
// * This method must be called before trying to send a notification. <br>
// * Calling {@code init()} multiple time should not fail. <br>
// *
// * For example a notifier can open a connection to register the application, or it can do nothing.
// *
// * @return a usable initiated {@link Notifier} to send notification(s)
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// Notifier init();
//
// boolean tryInit();
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notification.java
// @AutoValue
// public abstract class Notification {
//
// /**
// * Indicate notification priority.
// */
// public enum Level {INFO, WARNING, ERROR}
//
// /**
// * Notification message.
// *
// * @return message.
// */
// public abstract String message();
//
// /**
// * Notification title.
// *
// * @return title.
// */
// public abstract String title();
//
// /**
// * Notification subtitle. <br>
// * Not available for all notifier implementation.
// *
// * @return subtitle.
// */
// @Nullable
// public abstract String subtitle();
//
// /**
// * Notification icon.
// *
// * @return icon.
// */
// public abstract Icon icon();
//
// /**
// * Indicate the notification priority type.
// *
// * @return type
// */
// public abstract Level level();
//
// Notification() {
// // prevent external subclasses
// }
//
// public static Builder builder(String title, String message, Icon icon) {
// return builder()
// .title(title)
// .message(message)
// .icon(icon);
// }
//
// public static Builder builder() {
// return new AutoValue_Notification.Builder().level(INFO);
// }
//
// @AutoValue.Builder
// public interface Builder {
// Builder title(String title);
// Builder message(String message);
// Builder icon(Icon icon);
// Builder subtitle(String subtitle);
// Builder level(Level level);
// Notification build();
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notifier.java
// public interface Notifier {
//
// /**
// * Send a notification.
// *
// * @param notification a notification.
// *
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// void send(Notification notification);
//
// /**
// * Close the notifier. <br>
// * This method must be called to release resources when the notifier is not needed anymore.
// */
// void close();
//
// /**
// * Indicate if the notifier is always displayed somewhere (menu/task bar, etc).
// * @return {@code true} if the notifier is persistent.
// */
// boolean isPersistent();
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/notifier/executor/Executor.java
// public interface Executor {
// void exec(String[] command);
// boolean tryExec(String[] command);
// void close();
// }
| import com.google.common.base.MoreObjects;
import com.google.common.base.Objects;
import fr.jcgay.notification.Application;
import fr.jcgay.notification.DiscoverableNotifier;
import fr.jcgay.notification.Notification;
import fr.jcgay.notification.Notifier;
import fr.jcgay.notification.notifier.executor.Executor;
import org.slf4j.Logger;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import static org.slf4j.LoggerFactory.getLogger; | package fr.jcgay.notification.notifier.kdialog;
public class KdialogNotifier implements DiscoverableNotifier {
private static final Logger LOGGER = getLogger(KdialogNotifier.class);
| // Path: send-notification/src/main/java/fr/jcgay/notification/Application.java
// @AutoValue
// public abstract class Application {
//
// /**
// * Uniquely identify an application. <br>
// * In order to ensure your application's signature is unique, the recommendation is to follow the Internet Media
// * type (also known as MIME content type) format as defined in IETF <a href="http://tools.ietf.org/html/rfc2046">RFC 2046</a>
// * which contains the application vendor's name - specifically: {@code application/x-vnd-some_vendor.some_app}. <br>
// * The signature must not contain spaces. <br>
// * Some examples of acceptable signatures:
// * <ul>
// * <li>{@code application/x-vnd-acme.hello_world}</li>
// * <li>{@code application/x-vnd-fullphat.snaRSS}</li>
// * </ul>
// *
// * @return unique identifier.
// */
// public abstract String id();
//
// /**
// * A name that will identify the application for the user. <br>
// * Examples:
// * <ul>
// * <li>Maven</li>
// * <li>Gradle</li>
// * </ul>
// *
// * @return application name.
// */
// public abstract String name();
//
// /**
// * A timeout to wait for before cancelling application registration or notification sending.
// *
// * @return timeout in milliseconds, or {@code -1} if not specified.
// */
// public abstract long timeout();
//
// /**
// * The application icon.
// *
// * @return application icon.
// */
// public abstract Icon icon();
//
// Application() {
// // prevent external subclasses
// }
//
// public static Builder builder() {
// return new AutoValue_Application.Builder()
// .timeout(-1);
// }
//
// public static Builder builder(String id, String name, Icon icon) {
// return builder()
// .id(id)
// .name(name)
// .icon(icon);
// }
//
// @AutoValue.Builder
// public interface Builder {
// Builder id(String id);
// Builder name(String name);
// Builder icon(Icon icon);
// Builder timeout(long timeout);
// Application build();
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/DiscoverableNotifier.java
// public interface DiscoverableNotifier extends Notifier {
//
// /**
// * Initialize before usage. <br>
// * This method must be called before trying to send a notification. <br>
// * Calling {@code init()} multiple time should not fail. <br>
// *
// * For example a notifier can open a connection to register the application, or it can do nothing.
// *
// * @return a usable initiated {@link Notifier} to send notification(s)
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// Notifier init();
//
// boolean tryInit();
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notification.java
// @AutoValue
// public abstract class Notification {
//
// /**
// * Indicate notification priority.
// */
// public enum Level {INFO, WARNING, ERROR}
//
// /**
// * Notification message.
// *
// * @return message.
// */
// public abstract String message();
//
// /**
// * Notification title.
// *
// * @return title.
// */
// public abstract String title();
//
// /**
// * Notification subtitle. <br>
// * Not available for all notifier implementation.
// *
// * @return subtitle.
// */
// @Nullable
// public abstract String subtitle();
//
// /**
// * Notification icon.
// *
// * @return icon.
// */
// public abstract Icon icon();
//
// /**
// * Indicate the notification priority type.
// *
// * @return type
// */
// public abstract Level level();
//
// Notification() {
// // prevent external subclasses
// }
//
// public static Builder builder(String title, String message, Icon icon) {
// return builder()
// .title(title)
// .message(message)
// .icon(icon);
// }
//
// public static Builder builder() {
// return new AutoValue_Notification.Builder().level(INFO);
// }
//
// @AutoValue.Builder
// public interface Builder {
// Builder title(String title);
// Builder message(String message);
// Builder icon(Icon icon);
// Builder subtitle(String subtitle);
// Builder level(Level level);
// Notification build();
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notifier.java
// public interface Notifier {
//
// /**
// * Send a notification.
// *
// * @param notification a notification.
// *
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// void send(Notification notification);
//
// /**
// * Close the notifier. <br>
// * This method must be called to release resources when the notifier is not needed anymore.
// */
// void close();
//
// /**
// * Indicate if the notifier is always displayed somewhere (menu/task bar, etc).
// * @return {@code true} if the notifier is persistent.
// */
// boolean isPersistent();
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/notifier/executor/Executor.java
// public interface Executor {
// void exec(String[] command);
// boolean tryExec(String[] command);
// void close();
// }
// Path: send-notification/src/main/java/fr/jcgay/notification/notifier/kdialog/KdialogNotifier.java
import com.google.common.base.MoreObjects;
import com.google.common.base.Objects;
import fr.jcgay.notification.Application;
import fr.jcgay.notification.DiscoverableNotifier;
import fr.jcgay.notification.Notification;
import fr.jcgay.notification.Notifier;
import fr.jcgay.notification.notifier.executor.Executor;
import org.slf4j.Logger;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import static org.slf4j.LoggerFactory.getLogger;
package fr.jcgay.notification.notifier.kdialog;
public class KdialogNotifier implements DiscoverableNotifier {
private static final Logger LOGGER = getLogger(KdialogNotifier.class);
| private final Application application; |
jcgay/send-notification | send-notification/src/main/java/fr/jcgay/notification/notifier/kdialog/KdialogNotifier.java | // Path: send-notification/src/main/java/fr/jcgay/notification/Application.java
// @AutoValue
// public abstract class Application {
//
// /**
// * Uniquely identify an application. <br>
// * In order to ensure your application's signature is unique, the recommendation is to follow the Internet Media
// * type (also known as MIME content type) format as defined in IETF <a href="http://tools.ietf.org/html/rfc2046">RFC 2046</a>
// * which contains the application vendor's name - specifically: {@code application/x-vnd-some_vendor.some_app}. <br>
// * The signature must not contain spaces. <br>
// * Some examples of acceptable signatures:
// * <ul>
// * <li>{@code application/x-vnd-acme.hello_world}</li>
// * <li>{@code application/x-vnd-fullphat.snaRSS}</li>
// * </ul>
// *
// * @return unique identifier.
// */
// public abstract String id();
//
// /**
// * A name that will identify the application for the user. <br>
// * Examples:
// * <ul>
// * <li>Maven</li>
// * <li>Gradle</li>
// * </ul>
// *
// * @return application name.
// */
// public abstract String name();
//
// /**
// * A timeout to wait for before cancelling application registration or notification sending.
// *
// * @return timeout in milliseconds, or {@code -1} if not specified.
// */
// public abstract long timeout();
//
// /**
// * The application icon.
// *
// * @return application icon.
// */
// public abstract Icon icon();
//
// Application() {
// // prevent external subclasses
// }
//
// public static Builder builder() {
// return new AutoValue_Application.Builder()
// .timeout(-1);
// }
//
// public static Builder builder(String id, String name, Icon icon) {
// return builder()
// .id(id)
// .name(name)
// .icon(icon);
// }
//
// @AutoValue.Builder
// public interface Builder {
// Builder id(String id);
// Builder name(String name);
// Builder icon(Icon icon);
// Builder timeout(long timeout);
// Application build();
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/DiscoverableNotifier.java
// public interface DiscoverableNotifier extends Notifier {
//
// /**
// * Initialize before usage. <br>
// * This method must be called before trying to send a notification. <br>
// * Calling {@code init()} multiple time should not fail. <br>
// *
// * For example a notifier can open a connection to register the application, or it can do nothing.
// *
// * @return a usable initiated {@link Notifier} to send notification(s)
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// Notifier init();
//
// boolean tryInit();
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notification.java
// @AutoValue
// public abstract class Notification {
//
// /**
// * Indicate notification priority.
// */
// public enum Level {INFO, WARNING, ERROR}
//
// /**
// * Notification message.
// *
// * @return message.
// */
// public abstract String message();
//
// /**
// * Notification title.
// *
// * @return title.
// */
// public abstract String title();
//
// /**
// * Notification subtitle. <br>
// * Not available for all notifier implementation.
// *
// * @return subtitle.
// */
// @Nullable
// public abstract String subtitle();
//
// /**
// * Notification icon.
// *
// * @return icon.
// */
// public abstract Icon icon();
//
// /**
// * Indicate the notification priority type.
// *
// * @return type
// */
// public abstract Level level();
//
// Notification() {
// // prevent external subclasses
// }
//
// public static Builder builder(String title, String message, Icon icon) {
// return builder()
// .title(title)
// .message(message)
// .icon(icon);
// }
//
// public static Builder builder() {
// return new AutoValue_Notification.Builder().level(INFO);
// }
//
// @AutoValue.Builder
// public interface Builder {
// Builder title(String title);
// Builder message(String message);
// Builder icon(Icon icon);
// Builder subtitle(String subtitle);
// Builder level(Level level);
// Notification build();
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notifier.java
// public interface Notifier {
//
// /**
// * Send a notification.
// *
// * @param notification a notification.
// *
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// void send(Notification notification);
//
// /**
// * Close the notifier. <br>
// * This method must be called to release resources when the notifier is not needed anymore.
// */
// void close();
//
// /**
// * Indicate if the notifier is always displayed somewhere (menu/task bar, etc).
// * @return {@code true} if the notifier is persistent.
// */
// boolean isPersistent();
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/notifier/executor/Executor.java
// public interface Executor {
// void exec(String[] command);
// boolean tryExec(String[] command);
// void close();
// }
| import com.google.common.base.MoreObjects;
import com.google.common.base.Objects;
import fr.jcgay.notification.Application;
import fr.jcgay.notification.DiscoverableNotifier;
import fr.jcgay.notification.Notification;
import fr.jcgay.notification.Notifier;
import fr.jcgay.notification.notifier.executor.Executor;
import org.slf4j.Logger;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import static org.slf4j.LoggerFactory.getLogger; | package fr.jcgay.notification.notifier.kdialog;
public class KdialogNotifier implements DiscoverableNotifier {
private static final Logger LOGGER = getLogger(KdialogNotifier.class);
private final Application application;
private final KdialogConfiguration configuration; | // Path: send-notification/src/main/java/fr/jcgay/notification/Application.java
// @AutoValue
// public abstract class Application {
//
// /**
// * Uniquely identify an application. <br>
// * In order to ensure your application's signature is unique, the recommendation is to follow the Internet Media
// * type (also known as MIME content type) format as defined in IETF <a href="http://tools.ietf.org/html/rfc2046">RFC 2046</a>
// * which contains the application vendor's name - specifically: {@code application/x-vnd-some_vendor.some_app}. <br>
// * The signature must not contain spaces. <br>
// * Some examples of acceptable signatures:
// * <ul>
// * <li>{@code application/x-vnd-acme.hello_world}</li>
// * <li>{@code application/x-vnd-fullphat.snaRSS}</li>
// * </ul>
// *
// * @return unique identifier.
// */
// public abstract String id();
//
// /**
// * A name that will identify the application for the user. <br>
// * Examples:
// * <ul>
// * <li>Maven</li>
// * <li>Gradle</li>
// * </ul>
// *
// * @return application name.
// */
// public abstract String name();
//
// /**
// * A timeout to wait for before cancelling application registration or notification sending.
// *
// * @return timeout in milliseconds, or {@code -1} if not specified.
// */
// public abstract long timeout();
//
// /**
// * The application icon.
// *
// * @return application icon.
// */
// public abstract Icon icon();
//
// Application() {
// // prevent external subclasses
// }
//
// public static Builder builder() {
// return new AutoValue_Application.Builder()
// .timeout(-1);
// }
//
// public static Builder builder(String id, String name, Icon icon) {
// return builder()
// .id(id)
// .name(name)
// .icon(icon);
// }
//
// @AutoValue.Builder
// public interface Builder {
// Builder id(String id);
// Builder name(String name);
// Builder icon(Icon icon);
// Builder timeout(long timeout);
// Application build();
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/DiscoverableNotifier.java
// public interface DiscoverableNotifier extends Notifier {
//
// /**
// * Initialize before usage. <br>
// * This method must be called before trying to send a notification. <br>
// * Calling {@code init()} multiple time should not fail. <br>
// *
// * For example a notifier can open a connection to register the application, or it can do nothing.
// *
// * @return a usable initiated {@link Notifier} to send notification(s)
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// Notifier init();
//
// boolean tryInit();
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notification.java
// @AutoValue
// public abstract class Notification {
//
// /**
// * Indicate notification priority.
// */
// public enum Level {INFO, WARNING, ERROR}
//
// /**
// * Notification message.
// *
// * @return message.
// */
// public abstract String message();
//
// /**
// * Notification title.
// *
// * @return title.
// */
// public abstract String title();
//
// /**
// * Notification subtitle. <br>
// * Not available for all notifier implementation.
// *
// * @return subtitle.
// */
// @Nullable
// public abstract String subtitle();
//
// /**
// * Notification icon.
// *
// * @return icon.
// */
// public abstract Icon icon();
//
// /**
// * Indicate the notification priority type.
// *
// * @return type
// */
// public abstract Level level();
//
// Notification() {
// // prevent external subclasses
// }
//
// public static Builder builder(String title, String message, Icon icon) {
// return builder()
// .title(title)
// .message(message)
// .icon(icon);
// }
//
// public static Builder builder() {
// return new AutoValue_Notification.Builder().level(INFO);
// }
//
// @AutoValue.Builder
// public interface Builder {
// Builder title(String title);
// Builder message(String message);
// Builder icon(Icon icon);
// Builder subtitle(String subtitle);
// Builder level(Level level);
// Notification build();
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notifier.java
// public interface Notifier {
//
// /**
// * Send a notification.
// *
// * @param notification a notification.
// *
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// void send(Notification notification);
//
// /**
// * Close the notifier. <br>
// * This method must be called to release resources when the notifier is not needed anymore.
// */
// void close();
//
// /**
// * Indicate if the notifier is always displayed somewhere (menu/task bar, etc).
// * @return {@code true} if the notifier is persistent.
// */
// boolean isPersistent();
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/notifier/executor/Executor.java
// public interface Executor {
// void exec(String[] command);
// boolean tryExec(String[] command);
// void close();
// }
// Path: send-notification/src/main/java/fr/jcgay/notification/notifier/kdialog/KdialogNotifier.java
import com.google.common.base.MoreObjects;
import com.google.common.base.Objects;
import fr.jcgay.notification.Application;
import fr.jcgay.notification.DiscoverableNotifier;
import fr.jcgay.notification.Notification;
import fr.jcgay.notification.Notifier;
import fr.jcgay.notification.notifier.executor.Executor;
import org.slf4j.Logger;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import static org.slf4j.LoggerFactory.getLogger;
package fr.jcgay.notification.notifier.kdialog;
public class KdialogNotifier implements DiscoverableNotifier {
private static final Logger LOGGER = getLogger(KdialogNotifier.class);
private final Application application;
private final KdialogConfiguration configuration; | private final Executor executor; |
jcgay/send-notification | send-notification/src/main/java/fr/jcgay/notification/notifier/slack/SlackNotifier.java | // Path: send-notification/src/main/java/fr/jcgay/notification/Application.java
// @AutoValue
// public abstract class Application {
//
// /**
// * Uniquely identify an application. <br>
// * In order to ensure your application's signature is unique, the recommendation is to follow the Internet Media
// * type (also known as MIME content type) format as defined in IETF <a href="http://tools.ietf.org/html/rfc2046">RFC 2046</a>
// * which contains the application vendor's name - specifically: {@code application/x-vnd-some_vendor.some_app}. <br>
// * The signature must not contain spaces. <br>
// * Some examples of acceptable signatures:
// * <ul>
// * <li>{@code application/x-vnd-acme.hello_world}</li>
// * <li>{@code application/x-vnd-fullphat.snaRSS}</li>
// * </ul>
// *
// * @return unique identifier.
// */
// public abstract String id();
//
// /**
// * A name that will identify the application for the user. <br>
// * Examples:
// * <ul>
// * <li>Maven</li>
// * <li>Gradle</li>
// * </ul>
// *
// * @return application name.
// */
// public abstract String name();
//
// /**
// * A timeout to wait for before cancelling application registration or notification sending.
// *
// * @return timeout in milliseconds, or {@code -1} if not specified.
// */
// public abstract long timeout();
//
// /**
// * The application icon.
// *
// * @return application icon.
// */
// public abstract Icon icon();
//
// Application() {
// // prevent external subclasses
// }
//
// public static Builder builder() {
// return new AutoValue_Application.Builder()
// .timeout(-1);
// }
//
// public static Builder builder(String id, String name, Icon icon) {
// return builder()
// .id(id)
// .name(name)
// .icon(icon);
// }
//
// @AutoValue.Builder
// public interface Builder {
// Builder id(String id);
// Builder name(String name);
// Builder icon(Icon icon);
// Builder timeout(long timeout);
// Application build();
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/DiscoverableNotifier.java
// public interface DiscoverableNotifier extends Notifier {
//
// /**
// * Initialize before usage. <br>
// * This method must be called before trying to send a notification. <br>
// * Calling {@code init()} multiple time should not fail. <br>
// *
// * For example a notifier can open a connection to register the application, or it can do nothing.
// *
// * @return a usable initiated {@link Notifier} to send notification(s)
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// Notifier init();
//
// boolean tryInit();
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notification.java
// @AutoValue
// public abstract class Notification {
//
// /**
// * Indicate notification priority.
// */
// public enum Level {INFO, WARNING, ERROR}
//
// /**
// * Notification message.
// *
// * @return message.
// */
// public abstract String message();
//
// /**
// * Notification title.
// *
// * @return title.
// */
// public abstract String title();
//
// /**
// * Notification subtitle. <br>
// * Not available for all notifier implementation.
// *
// * @return subtitle.
// */
// @Nullable
// public abstract String subtitle();
//
// /**
// * Notification icon.
// *
// * @return icon.
// */
// public abstract Icon icon();
//
// /**
// * Indicate the notification priority type.
// *
// * @return type
// */
// public abstract Level level();
//
// Notification() {
// // prevent external subclasses
// }
//
// public static Builder builder(String title, String message, Icon icon) {
// return builder()
// .title(title)
// .message(message)
// .icon(icon);
// }
//
// public static Builder builder() {
// return new AutoValue_Notification.Builder().level(INFO);
// }
//
// @AutoValue.Builder
// public interface Builder {
// Builder title(String title);
// Builder message(String message);
// Builder icon(Icon icon);
// Builder subtitle(String subtitle);
// Builder level(Level level);
// Notification build();
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notifier.java
// public interface Notifier {
//
// /**
// * Send a notification.
// *
// * @param notification a notification.
// *
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// void send(Notification notification);
//
// /**
// * Close the notifier. <br>
// * This method must be called to release resources when the notifier is not needed anymore.
// */
// void close();
//
// /**
// * Indicate if the notifier is always displayed somewhere (menu/task bar, etc).
// * @return {@code true} if the notifier is persistent.
// */
// boolean isPersistent();
// }
| import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import fr.jcgay.notification.Application;
import fr.jcgay.notification.DiscoverableNotifier;
import fr.jcgay.notification.Notification;
import fr.jcgay.notification.Notifier;
import org.slf4j.Logger;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import static org.slf4j.LoggerFactory.getLogger; | package fr.jcgay.notification.notifier.slack;
public class SlackNotifier implements DiscoverableNotifier {
private static final Logger LOGGER = getLogger(SlackNotifier.class);
| // Path: send-notification/src/main/java/fr/jcgay/notification/Application.java
// @AutoValue
// public abstract class Application {
//
// /**
// * Uniquely identify an application. <br>
// * In order to ensure your application's signature is unique, the recommendation is to follow the Internet Media
// * type (also known as MIME content type) format as defined in IETF <a href="http://tools.ietf.org/html/rfc2046">RFC 2046</a>
// * which contains the application vendor's name - specifically: {@code application/x-vnd-some_vendor.some_app}. <br>
// * The signature must not contain spaces. <br>
// * Some examples of acceptable signatures:
// * <ul>
// * <li>{@code application/x-vnd-acme.hello_world}</li>
// * <li>{@code application/x-vnd-fullphat.snaRSS}</li>
// * </ul>
// *
// * @return unique identifier.
// */
// public abstract String id();
//
// /**
// * A name that will identify the application for the user. <br>
// * Examples:
// * <ul>
// * <li>Maven</li>
// * <li>Gradle</li>
// * </ul>
// *
// * @return application name.
// */
// public abstract String name();
//
// /**
// * A timeout to wait for before cancelling application registration or notification sending.
// *
// * @return timeout in milliseconds, or {@code -1} if not specified.
// */
// public abstract long timeout();
//
// /**
// * The application icon.
// *
// * @return application icon.
// */
// public abstract Icon icon();
//
// Application() {
// // prevent external subclasses
// }
//
// public static Builder builder() {
// return new AutoValue_Application.Builder()
// .timeout(-1);
// }
//
// public static Builder builder(String id, String name, Icon icon) {
// return builder()
// .id(id)
// .name(name)
// .icon(icon);
// }
//
// @AutoValue.Builder
// public interface Builder {
// Builder id(String id);
// Builder name(String name);
// Builder icon(Icon icon);
// Builder timeout(long timeout);
// Application build();
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/DiscoverableNotifier.java
// public interface DiscoverableNotifier extends Notifier {
//
// /**
// * Initialize before usage. <br>
// * This method must be called before trying to send a notification. <br>
// * Calling {@code init()} multiple time should not fail. <br>
// *
// * For example a notifier can open a connection to register the application, or it can do nothing.
// *
// * @return a usable initiated {@link Notifier} to send notification(s)
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// Notifier init();
//
// boolean tryInit();
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notification.java
// @AutoValue
// public abstract class Notification {
//
// /**
// * Indicate notification priority.
// */
// public enum Level {INFO, WARNING, ERROR}
//
// /**
// * Notification message.
// *
// * @return message.
// */
// public abstract String message();
//
// /**
// * Notification title.
// *
// * @return title.
// */
// public abstract String title();
//
// /**
// * Notification subtitle. <br>
// * Not available for all notifier implementation.
// *
// * @return subtitle.
// */
// @Nullable
// public abstract String subtitle();
//
// /**
// * Notification icon.
// *
// * @return icon.
// */
// public abstract Icon icon();
//
// /**
// * Indicate the notification priority type.
// *
// * @return type
// */
// public abstract Level level();
//
// Notification() {
// // prevent external subclasses
// }
//
// public static Builder builder(String title, String message, Icon icon) {
// return builder()
// .title(title)
// .message(message)
// .icon(icon);
// }
//
// public static Builder builder() {
// return new AutoValue_Notification.Builder().level(INFO);
// }
//
// @AutoValue.Builder
// public interface Builder {
// Builder title(String title);
// Builder message(String message);
// Builder icon(Icon icon);
// Builder subtitle(String subtitle);
// Builder level(Level level);
// Notification build();
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notifier.java
// public interface Notifier {
//
// /**
// * Send a notification.
// *
// * @param notification a notification.
// *
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// void send(Notification notification);
//
// /**
// * Close the notifier. <br>
// * This method must be called to release resources when the notifier is not needed anymore.
// */
// void close();
//
// /**
// * Indicate if the notifier is always displayed somewhere (menu/task bar, etc).
// * @return {@code true} if the notifier is persistent.
// */
// boolean isPersistent();
// }
// Path: send-notification/src/main/java/fr/jcgay/notification/notifier/slack/SlackNotifier.java
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import fr.jcgay.notification.Application;
import fr.jcgay.notification.DiscoverableNotifier;
import fr.jcgay.notification.Notification;
import fr.jcgay.notification.Notifier;
import org.slf4j.Logger;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import static org.slf4j.LoggerFactory.getLogger;
package fr.jcgay.notification.notifier.slack;
public class SlackNotifier implements DiscoverableNotifier {
private static final Logger LOGGER = getLogger(SlackNotifier.class);
| private final Application application; |
jcgay/send-notification | send-notification/src/main/java/fr/jcgay/notification/notifier/notificationcenter/SimpleNotificationCenterNotifier.java | // Path: send-notification/src/main/java/fr/jcgay/notification/DiscoverableNotifier.java
// public interface DiscoverableNotifier extends Notifier {
//
// /**
// * Initialize before usage. <br>
// * This method must be called before trying to send a notification. <br>
// * Calling {@code init()} multiple time should not fail. <br>
// *
// * For example a notifier can open a connection to register the application, or it can do nothing.
// *
// * @return a usable initiated {@link Notifier} to send notification(s)
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// Notifier init();
//
// boolean tryInit();
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notification.java
// @AutoValue
// public abstract class Notification {
//
// /**
// * Indicate notification priority.
// */
// public enum Level {INFO, WARNING, ERROR}
//
// /**
// * Notification message.
// *
// * @return message.
// */
// public abstract String message();
//
// /**
// * Notification title.
// *
// * @return title.
// */
// public abstract String title();
//
// /**
// * Notification subtitle. <br>
// * Not available for all notifier implementation.
// *
// * @return subtitle.
// */
// @Nullable
// public abstract String subtitle();
//
// /**
// * Notification icon.
// *
// * @return icon.
// */
// public abstract Icon icon();
//
// /**
// * Indicate the notification priority type.
// *
// * @return type
// */
// public abstract Level level();
//
// Notification() {
// // prevent external subclasses
// }
//
// public static Builder builder(String title, String message, Icon icon) {
// return builder()
// .title(title)
// .message(message)
// .icon(icon);
// }
//
// public static Builder builder() {
// return new AutoValue_Notification.Builder().level(INFO);
// }
//
// @AutoValue.Builder
// public interface Builder {
// Builder title(String title);
// Builder message(String message);
// Builder icon(Icon icon);
// Builder subtitle(String subtitle);
// Builder level(Level level);
// Notification build();
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notifier.java
// public interface Notifier {
//
// /**
// * Send a notification.
// *
// * @param notification a notification.
// *
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// void send(Notification notification);
//
// /**
// * Close the notifier. <br>
// * This method must be called to release resources when the notifier is not needed anymore.
// */
// void close();
//
// /**
// * Indicate if the notifier is always displayed somewhere (menu/task bar, etc).
// * @return {@code true} if the notifier is persistent.
// */
// boolean isPersistent();
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/notifier/executor/Executor.java
// public interface Executor {
// void exec(String[] command);
// boolean tryExec(String[] command);
// void close();
// }
| import com.google.common.base.MoreObjects;
import com.google.common.base.Objects;
import fr.jcgay.notification.DiscoverableNotifier;
import fr.jcgay.notification.Notification;
import fr.jcgay.notification.Notifier;
import fr.jcgay.notification.notifier.executor.Executor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List; | package fr.jcgay.notification.notifier.notificationcenter;
public class SimpleNotificationCenterNotifier implements DiscoverableNotifier {
private static final Logger LOGGER = LoggerFactory.getLogger(SimpleNotificationCenterNotifier.class);
private static final String DOUBLE_QUOTE = "\"";
private final TerminalNotifierConfiguration configuration; | // Path: send-notification/src/main/java/fr/jcgay/notification/DiscoverableNotifier.java
// public interface DiscoverableNotifier extends Notifier {
//
// /**
// * Initialize before usage. <br>
// * This method must be called before trying to send a notification. <br>
// * Calling {@code init()} multiple time should not fail. <br>
// *
// * For example a notifier can open a connection to register the application, or it can do nothing.
// *
// * @return a usable initiated {@link Notifier} to send notification(s)
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// Notifier init();
//
// boolean tryInit();
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notification.java
// @AutoValue
// public abstract class Notification {
//
// /**
// * Indicate notification priority.
// */
// public enum Level {INFO, WARNING, ERROR}
//
// /**
// * Notification message.
// *
// * @return message.
// */
// public abstract String message();
//
// /**
// * Notification title.
// *
// * @return title.
// */
// public abstract String title();
//
// /**
// * Notification subtitle. <br>
// * Not available for all notifier implementation.
// *
// * @return subtitle.
// */
// @Nullable
// public abstract String subtitle();
//
// /**
// * Notification icon.
// *
// * @return icon.
// */
// public abstract Icon icon();
//
// /**
// * Indicate the notification priority type.
// *
// * @return type
// */
// public abstract Level level();
//
// Notification() {
// // prevent external subclasses
// }
//
// public static Builder builder(String title, String message, Icon icon) {
// return builder()
// .title(title)
// .message(message)
// .icon(icon);
// }
//
// public static Builder builder() {
// return new AutoValue_Notification.Builder().level(INFO);
// }
//
// @AutoValue.Builder
// public interface Builder {
// Builder title(String title);
// Builder message(String message);
// Builder icon(Icon icon);
// Builder subtitle(String subtitle);
// Builder level(Level level);
// Notification build();
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notifier.java
// public interface Notifier {
//
// /**
// * Send a notification.
// *
// * @param notification a notification.
// *
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// void send(Notification notification);
//
// /**
// * Close the notifier. <br>
// * This method must be called to release resources when the notifier is not needed anymore.
// */
// void close();
//
// /**
// * Indicate if the notifier is always displayed somewhere (menu/task bar, etc).
// * @return {@code true} if the notifier is persistent.
// */
// boolean isPersistent();
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/notifier/executor/Executor.java
// public interface Executor {
// void exec(String[] command);
// boolean tryExec(String[] command);
// void close();
// }
// Path: send-notification/src/main/java/fr/jcgay/notification/notifier/notificationcenter/SimpleNotificationCenterNotifier.java
import com.google.common.base.MoreObjects;
import com.google.common.base.Objects;
import fr.jcgay.notification.DiscoverableNotifier;
import fr.jcgay.notification.Notification;
import fr.jcgay.notification.Notifier;
import fr.jcgay.notification.notifier.executor.Executor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
package fr.jcgay.notification.notifier.notificationcenter;
public class SimpleNotificationCenterNotifier implements DiscoverableNotifier {
private static final Logger LOGGER = LoggerFactory.getLogger(SimpleNotificationCenterNotifier.class);
private static final String DOUBLE_QUOTE = "\"";
private final TerminalNotifierConfiguration configuration; | private final Executor executor; |
jcgay/send-notification | send-notification/src/main/java/fr/jcgay/notification/notifier/notificationcenter/SimpleNotificationCenterNotifier.java | // Path: send-notification/src/main/java/fr/jcgay/notification/DiscoverableNotifier.java
// public interface DiscoverableNotifier extends Notifier {
//
// /**
// * Initialize before usage. <br>
// * This method must be called before trying to send a notification. <br>
// * Calling {@code init()} multiple time should not fail. <br>
// *
// * For example a notifier can open a connection to register the application, or it can do nothing.
// *
// * @return a usable initiated {@link Notifier} to send notification(s)
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// Notifier init();
//
// boolean tryInit();
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notification.java
// @AutoValue
// public abstract class Notification {
//
// /**
// * Indicate notification priority.
// */
// public enum Level {INFO, WARNING, ERROR}
//
// /**
// * Notification message.
// *
// * @return message.
// */
// public abstract String message();
//
// /**
// * Notification title.
// *
// * @return title.
// */
// public abstract String title();
//
// /**
// * Notification subtitle. <br>
// * Not available for all notifier implementation.
// *
// * @return subtitle.
// */
// @Nullable
// public abstract String subtitle();
//
// /**
// * Notification icon.
// *
// * @return icon.
// */
// public abstract Icon icon();
//
// /**
// * Indicate the notification priority type.
// *
// * @return type
// */
// public abstract Level level();
//
// Notification() {
// // prevent external subclasses
// }
//
// public static Builder builder(String title, String message, Icon icon) {
// return builder()
// .title(title)
// .message(message)
// .icon(icon);
// }
//
// public static Builder builder() {
// return new AutoValue_Notification.Builder().level(INFO);
// }
//
// @AutoValue.Builder
// public interface Builder {
// Builder title(String title);
// Builder message(String message);
// Builder icon(Icon icon);
// Builder subtitle(String subtitle);
// Builder level(Level level);
// Notification build();
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notifier.java
// public interface Notifier {
//
// /**
// * Send a notification.
// *
// * @param notification a notification.
// *
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// void send(Notification notification);
//
// /**
// * Close the notifier. <br>
// * This method must be called to release resources when the notifier is not needed anymore.
// */
// void close();
//
// /**
// * Indicate if the notifier is always displayed somewhere (menu/task bar, etc).
// * @return {@code true} if the notifier is persistent.
// */
// boolean isPersistent();
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/notifier/executor/Executor.java
// public interface Executor {
// void exec(String[] command);
// boolean tryExec(String[] command);
// void close();
// }
| import com.google.common.base.MoreObjects;
import com.google.common.base.Objects;
import fr.jcgay.notification.DiscoverableNotifier;
import fr.jcgay.notification.Notification;
import fr.jcgay.notification.Notifier;
import fr.jcgay.notification.notifier.executor.Executor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List; | package fr.jcgay.notification.notifier.notificationcenter;
public class SimpleNotificationCenterNotifier implements DiscoverableNotifier {
private static final Logger LOGGER = LoggerFactory.getLogger(SimpleNotificationCenterNotifier.class);
private static final String DOUBLE_QUOTE = "\"";
private final TerminalNotifierConfiguration configuration;
private final Executor executor;
public SimpleNotificationCenterNotifier(TerminalNotifierConfiguration configuration, Executor executor) {
LOGGER.debug("Configuring notification-center : {}.", configuration);
this.configuration = configuration;
this.executor = executor;
}
@Override | // Path: send-notification/src/main/java/fr/jcgay/notification/DiscoverableNotifier.java
// public interface DiscoverableNotifier extends Notifier {
//
// /**
// * Initialize before usage. <br>
// * This method must be called before trying to send a notification. <br>
// * Calling {@code init()} multiple time should not fail. <br>
// *
// * For example a notifier can open a connection to register the application, or it can do nothing.
// *
// * @return a usable initiated {@link Notifier} to send notification(s)
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// Notifier init();
//
// boolean tryInit();
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notification.java
// @AutoValue
// public abstract class Notification {
//
// /**
// * Indicate notification priority.
// */
// public enum Level {INFO, WARNING, ERROR}
//
// /**
// * Notification message.
// *
// * @return message.
// */
// public abstract String message();
//
// /**
// * Notification title.
// *
// * @return title.
// */
// public abstract String title();
//
// /**
// * Notification subtitle. <br>
// * Not available for all notifier implementation.
// *
// * @return subtitle.
// */
// @Nullable
// public abstract String subtitle();
//
// /**
// * Notification icon.
// *
// * @return icon.
// */
// public abstract Icon icon();
//
// /**
// * Indicate the notification priority type.
// *
// * @return type
// */
// public abstract Level level();
//
// Notification() {
// // prevent external subclasses
// }
//
// public static Builder builder(String title, String message, Icon icon) {
// return builder()
// .title(title)
// .message(message)
// .icon(icon);
// }
//
// public static Builder builder() {
// return new AutoValue_Notification.Builder().level(INFO);
// }
//
// @AutoValue.Builder
// public interface Builder {
// Builder title(String title);
// Builder message(String message);
// Builder icon(Icon icon);
// Builder subtitle(String subtitle);
// Builder level(Level level);
// Notification build();
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notifier.java
// public interface Notifier {
//
// /**
// * Send a notification.
// *
// * @param notification a notification.
// *
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// void send(Notification notification);
//
// /**
// * Close the notifier. <br>
// * This method must be called to release resources when the notifier is not needed anymore.
// */
// void close();
//
// /**
// * Indicate if the notifier is always displayed somewhere (menu/task bar, etc).
// * @return {@code true} if the notifier is persistent.
// */
// boolean isPersistent();
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/notifier/executor/Executor.java
// public interface Executor {
// void exec(String[] command);
// boolean tryExec(String[] command);
// void close();
// }
// Path: send-notification/src/main/java/fr/jcgay/notification/notifier/notificationcenter/SimpleNotificationCenterNotifier.java
import com.google.common.base.MoreObjects;
import com.google.common.base.Objects;
import fr.jcgay.notification.DiscoverableNotifier;
import fr.jcgay.notification.Notification;
import fr.jcgay.notification.Notifier;
import fr.jcgay.notification.notifier.executor.Executor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
package fr.jcgay.notification.notifier.notificationcenter;
public class SimpleNotificationCenterNotifier implements DiscoverableNotifier {
private static final Logger LOGGER = LoggerFactory.getLogger(SimpleNotificationCenterNotifier.class);
private static final String DOUBLE_QUOTE = "\"";
private final TerminalNotifierConfiguration configuration;
private final Executor executor;
public SimpleNotificationCenterNotifier(TerminalNotifierConfiguration configuration, Executor executor) {
LOGGER.debug("Configuring notification-center : {}.", configuration);
this.configuration = configuration;
this.executor = executor;
}
@Override | public Notifier init() { |
jcgay/send-notification | send-notification/src/main/java/fr/jcgay/notification/notifier/notificationcenter/SimpleNotificationCenterNotifier.java | // Path: send-notification/src/main/java/fr/jcgay/notification/DiscoverableNotifier.java
// public interface DiscoverableNotifier extends Notifier {
//
// /**
// * Initialize before usage. <br>
// * This method must be called before trying to send a notification. <br>
// * Calling {@code init()} multiple time should not fail. <br>
// *
// * For example a notifier can open a connection to register the application, or it can do nothing.
// *
// * @return a usable initiated {@link Notifier} to send notification(s)
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// Notifier init();
//
// boolean tryInit();
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notification.java
// @AutoValue
// public abstract class Notification {
//
// /**
// * Indicate notification priority.
// */
// public enum Level {INFO, WARNING, ERROR}
//
// /**
// * Notification message.
// *
// * @return message.
// */
// public abstract String message();
//
// /**
// * Notification title.
// *
// * @return title.
// */
// public abstract String title();
//
// /**
// * Notification subtitle. <br>
// * Not available for all notifier implementation.
// *
// * @return subtitle.
// */
// @Nullable
// public abstract String subtitle();
//
// /**
// * Notification icon.
// *
// * @return icon.
// */
// public abstract Icon icon();
//
// /**
// * Indicate the notification priority type.
// *
// * @return type
// */
// public abstract Level level();
//
// Notification() {
// // prevent external subclasses
// }
//
// public static Builder builder(String title, String message, Icon icon) {
// return builder()
// .title(title)
// .message(message)
// .icon(icon);
// }
//
// public static Builder builder() {
// return new AutoValue_Notification.Builder().level(INFO);
// }
//
// @AutoValue.Builder
// public interface Builder {
// Builder title(String title);
// Builder message(String message);
// Builder icon(Icon icon);
// Builder subtitle(String subtitle);
// Builder level(Level level);
// Notification build();
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notifier.java
// public interface Notifier {
//
// /**
// * Send a notification.
// *
// * @param notification a notification.
// *
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// void send(Notification notification);
//
// /**
// * Close the notifier. <br>
// * This method must be called to release resources when the notifier is not needed anymore.
// */
// void close();
//
// /**
// * Indicate if the notifier is always displayed somewhere (menu/task bar, etc).
// * @return {@code true} if the notifier is persistent.
// */
// boolean isPersistent();
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/notifier/executor/Executor.java
// public interface Executor {
// void exec(String[] command);
// boolean tryExec(String[] command);
// void close();
// }
| import com.google.common.base.MoreObjects;
import com.google.common.base.Objects;
import fr.jcgay.notification.DiscoverableNotifier;
import fr.jcgay.notification.Notification;
import fr.jcgay.notification.Notifier;
import fr.jcgay.notification.notifier.executor.Executor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List; | package fr.jcgay.notification.notifier.notificationcenter;
public class SimpleNotificationCenterNotifier implements DiscoverableNotifier {
private static final Logger LOGGER = LoggerFactory.getLogger(SimpleNotificationCenterNotifier.class);
private static final String DOUBLE_QUOTE = "\"";
private final TerminalNotifierConfiguration configuration;
private final Executor executor;
public SimpleNotificationCenterNotifier(TerminalNotifierConfiguration configuration, Executor executor) {
LOGGER.debug("Configuring notification-center : {}.", configuration);
this.configuration = configuration;
this.executor = executor;
}
@Override
public Notifier init() {
return this;
}
@Override | // Path: send-notification/src/main/java/fr/jcgay/notification/DiscoverableNotifier.java
// public interface DiscoverableNotifier extends Notifier {
//
// /**
// * Initialize before usage. <br>
// * This method must be called before trying to send a notification. <br>
// * Calling {@code init()} multiple time should not fail. <br>
// *
// * For example a notifier can open a connection to register the application, or it can do nothing.
// *
// * @return a usable initiated {@link Notifier} to send notification(s)
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// Notifier init();
//
// boolean tryInit();
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notification.java
// @AutoValue
// public abstract class Notification {
//
// /**
// * Indicate notification priority.
// */
// public enum Level {INFO, WARNING, ERROR}
//
// /**
// * Notification message.
// *
// * @return message.
// */
// public abstract String message();
//
// /**
// * Notification title.
// *
// * @return title.
// */
// public abstract String title();
//
// /**
// * Notification subtitle. <br>
// * Not available for all notifier implementation.
// *
// * @return subtitle.
// */
// @Nullable
// public abstract String subtitle();
//
// /**
// * Notification icon.
// *
// * @return icon.
// */
// public abstract Icon icon();
//
// /**
// * Indicate the notification priority type.
// *
// * @return type
// */
// public abstract Level level();
//
// Notification() {
// // prevent external subclasses
// }
//
// public static Builder builder(String title, String message, Icon icon) {
// return builder()
// .title(title)
// .message(message)
// .icon(icon);
// }
//
// public static Builder builder() {
// return new AutoValue_Notification.Builder().level(INFO);
// }
//
// @AutoValue.Builder
// public interface Builder {
// Builder title(String title);
// Builder message(String message);
// Builder icon(Icon icon);
// Builder subtitle(String subtitle);
// Builder level(Level level);
// Notification build();
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/Notifier.java
// public interface Notifier {
//
// /**
// * Send a notification.
// *
// * @param notification a notification.
// *
// * @throws fr.jcgay.notification.SendNotificationException when something fails.
// */
// void send(Notification notification);
//
// /**
// * Close the notifier. <br>
// * This method must be called to release resources when the notifier is not needed anymore.
// */
// void close();
//
// /**
// * Indicate if the notifier is always displayed somewhere (menu/task bar, etc).
// * @return {@code true} if the notifier is persistent.
// */
// boolean isPersistent();
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/notifier/executor/Executor.java
// public interface Executor {
// void exec(String[] command);
// boolean tryExec(String[] command);
// void close();
// }
// Path: send-notification/src/main/java/fr/jcgay/notification/notifier/notificationcenter/SimpleNotificationCenterNotifier.java
import com.google.common.base.MoreObjects;
import com.google.common.base.Objects;
import fr.jcgay.notification.DiscoverableNotifier;
import fr.jcgay.notification.Notification;
import fr.jcgay.notification.Notifier;
import fr.jcgay.notification.notifier.executor.Executor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
package fr.jcgay.notification.notifier.notificationcenter;
public class SimpleNotificationCenterNotifier implements DiscoverableNotifier {
private static final Logger LOGGER = LoggerFactory.getLogger(SimpleNotificationCenterNotifier.class);
private static final String DOUBLE_QUOTE = "\"";
private final TerminalNotifierConfiguration configuration;
private final Executor executor;
public SimpleNotificationCenterNotifier(TerminalNotifierConfiguration configuration, Executor executor) {
LOGGER.debug("Configuring notification-center : {}.", configuration);
this.configuration = configuration;
this.executor = executor;
}
@Override
public Notifier init() {
return this;
}
@Override | public void send(Notification notification) { |
jcgay/send-notification | send-notification/src/main/java/fr/jcgay/notification/notifier/anybar/AnyBarIconWriter.java | // Path: send-notification/src/main/java/fr/jcgay/notification/Icon.java
// @AutoValue
// public abstract class Icon {
//
// /**
// * A unique identifier. <br>
// * You should ensure that this id will be unique because it can be used to temporary write file on disk.
// *
// * @return unique identifier.
// */
// public abstract String id();
//
// /**
// * URL for this resource.
// *
// * @return URL to load icon.
// */
// public abstract URL content();
//
// public BufferedImage toImage() {
// try {
// return ImageIO.read(content());
// } catch (IOException e) {
// throw new SendNotificationException("Error while reading status icon.", e);
// }
// }
//
// public byte[] toByteArray() {
// try (InputStream is = content().openStream()) {
// return ByteStreams.toByteArray(is);
// } catch (IOException e) {
// throw new SendNotificationException("Error while reading status icon.", e);
// }
// }
//
// public String asPath() {
// String folder = System.getProperty("java.io.tmpdir") + "/send-notifications-icons/";
// String extension = extension();
// File icon = new File(folder + id() + "." + extension);
// if (!icon.exists()) {
// new File(folder).mkdirs();
// try {
// write(icon);
// } catch (IOException e) {
// throw new SendNotificationException("Can't write notification icon : " + icon.getPath(), e);
// }
// }
// return icon.getPath();
// }
//
// public String extension() {
// return content().getPath().substring(content().getPath().lastIndexOf(".") + 1);
// }
//
// public static Icon create(URL content, String id) {
// return new AutoValue_Icon(id, content);
// }
//
// private void write(File destination) throws IOException {
// try (InputStream input = content().openStream(); FileOutputStream output = new FileOutputStream(destination)) {
// byte[] buffer = new byte[1024 * 4];
// int n;
// while ((n = input.read(buffer)) != -1) {
// output.write(buffer, 0, n);
// }
// }
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/IconFileWriter.java
// public interface IconFileWriter {
//
// void write(Icon icon);
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/SendNotificationException.java
// public class SendNotificationException extends RuntimeException {
//
// public SendNotificationException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public SendNotificationException(String message) {
// super(message);
// }
// }
| import com.google.common.annotations.VisibleForTesting;
import fr.jcgay.notification.Icon;
import fr.jcgay.notification.IconFileWriter;
import fr.jcgay.notification.SendNotificationException;
import net.coobird.thumbnailator.Thumbnailator;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream; | package fr.jcgay.notification.notifier.anybar;
public class AnyBarIconWriter implements IconFileWriter {
private final String destination;
@VisibleForTesting
AnyBarIconWriter(String destination) {
this.destination = destination.endsWith("/") ? destination : destination + '/';
}
public AnyBarIconWriter() {
this(System.getProperty("user.home") + "/.AnyBar/");
}
@Override | // Path: send-notification/src/main/java/fr/jcgay/notification/Icon.java
// @AutoValue
// public abstract class Icon {
//
// /**
// * A unique identifier. <br>
// * You should ensure that this id will be unique because it can be used to temporary write file on disk.
// *
// * @return unique identifier.
// */
// public abstract String id();
//
// /**
// * URL for this resource.
// *
// * @return URL to load icon.
// */
// public abstract URL content();
//
// public BufferedImage toImage() {
// try {
// return ImageIO.read(content());
// } catch (IOException e) {
// throw new SendNotificationException("Error while reading status icon.", e);
// }
// }
//
// public byte[] toByteArray() {
// try (InputStream is = content().openStream()) {
// return ByteStreams.toByteArray(is);
// } catch (IOException e) {
// throw new SendNotificationException("Error while reading status icon.", e);
// }
// }
//
// public String asPath() {
// String folder = System.getProperty("java.io.tmpdir") + "/send-notifications-icons/";
// String extension = extension();
// File icon = new File(folder + id() + "." + extension);
// if (!icon.exists()) {
// new File(folder).mkdirs();
// try {
// write(icon);
// } catch (IOException e) {
// throw new SendNotificationException("Can't write notification icon : " + icon.getPath(), e);
// }
// }
// return icon.getPath();
// }
//
// public String extension() {
// return content().getPath().substring(content().getPath().lastIndexOf(".") + 1);
// }
//
// public static Icon create(URL content, String id) {
// return new AutoValue_Icon(id, content);
// }
//
// private void write(File destination) throws IOException {
// try (InputStream input = content().openStream(); FileOutputStream output = new FileOutputStream(destination)) {
// byte[] buffer = new byte[1024 * 4];
// int n;
// while ((n = input.read(buffer)) != -1) {
// output.write(buffer, 0, n);
// }
// }
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/IconFileWriter.java
// public interface IconFileWriter {
//
// void write(Icon icon);
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/SendNotificationException.java
// public class SendNotificationException extends RuntimeException {
//
// public SendNotificationException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public SendNotificationException(String message) {
// super(message);
// }
// }
// Path: send-notification/src/main/java/fr/jcgay/notification/notifier/anybar/AnyBarIconWriter.java
import com.google.common.annotations.VisibleForTesting;
import fr.jcgay.notification.Icon;
import fr.jcgay.notification.IconFileWriter;
import fr.jcgay.notification.SendNotificationException;
import net.coobird.thumbnailator.Thumbnailator;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
package fr.jcgay.notification.notifier.anybar;
public class AnyBarIconWriter implements IconFileWriter {
private final String destination;
@VisibleForTesting
AnyBarIconWriter(String destination) {
this.destination = destination.endsWith("/") ? destination : destination + '/';
}
public AnyBarIconWriter() {
this(System.getProperty("user.home") + "/.AnyBar/");
}
@Override | public void write(Icon icon) { |
jcgay/send-notification | send-notification/src/main/java/fr/jcgay/notification/notifier/anybar/AnyBarIconWriter.java | // Path: send-notification/src/main/java/fr/jcgay/notification/Icon.java
// @AutoValue
// public abstract class Icon {
//
// /**
// * A unique identifier. <br>
// * You should ensure that this id will be unique because it can be used to temporary write file on disk.
// *
// * @return unique identifier.
// */
// public abstract String id();
//
// /**
// * URL for this resource.
// *
// * @return URL to load icon.
// */
// public abstract URL content();
//
// public BufferedImage toImage() {
// try {
// return ImageIO.read(content());
// } catch (IOException e) {
// throw new SendNotificationException("Error while reading status icon.", e);
// }
// }
//
// public byte[] toByteArray() {
// try (InputStream is = content().openStream()) {
// return ByteStreams.toByteArray(is);
// } catch (IOException e) {
// throw new SendNotificationException("Error while reading status icon.", e);
// }
// }
//
// public String asPath() {
// String folder = System.getProperty("java.io.tmpdir") + "/send-notifications-icons/";
// String extension = extension();
// File icon = new File(folder + id() + "." + extension);
// if (!icon.exists()) {
// new File(folder).mkdirs();
// try {
// write(icon);
// } catch (IOException e) {
// throw new SendNotificationException("Can't write notification icon : " + icon.getPath(), e);
// }
// }
// return icon.getPath();
// }
//
// public String extension() {
// return content().getPath().substring(content().getPath().lastIndexOf(".") + 1);
// }
//
// public static Icon create(URL content, String id) {
// return new AutoValue_Icon(id, content);
// }
//
// private void write(File destination) throws IOException {
// try (InputStream input = content().openStream(); FileOutputStream output = new FileOutputStream(destination)) {
// byte[] buffer = new byte[1024 * 4];
// int n;
// while ((n = input.read(buffer)) != -1) {
// output.write(buffer, 0, n);
// }
// }
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/IconFileWriter.java
// public interface IconFileWriter {
//
// void write(Icon icon);
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/SendNotificationException.java
// public class SendNotificationException extends RuntimeException {
//
// public SendNotificationException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public SendNotificationException(String message) {
// super(message);
// }
// }
| import com.google.common.annotations.VisibleForTesting;
import fr.jcgay.notification.Icon;
import fr.jcgay.notification.IconFileWriter;
import fr.jcgay.notification.SendNotificationException;
import net.coobird.thumbnailator.Thumbnailator;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream; | package fr.jcgay.notification.notifier.anybar;
public class AnyBarIconWriter implements IconFileWriter {
private final String destination;
@VisibleForTesting
AnyBarIconWriter(String destination) {
this.destination = destination.endsWith("/") ? destination : destination + '/';
}
public AnyBarIconWriter() {
this(System.getProperty("user.home") + "/.AnyBar/");
}
@Override
public void write(Icon icon) {
for (Dimension dimension : Dimension.values()) {
File resizedIcon = new File(destination + icon.id() + dimension.fileNameSuffix + "." + icon.extension());
if (!resizedIcon.exists()) {
new File(destination).mkdirs();
try (InputStream input = icon.content().openStream(); FileOutputStream output = new FileOutputStream(resizedIcon)) {
Thumbnailator.createThumbnail(input, output, dimension.width, dimension.height);
} catch (IOException e) { | // Path: send-notification/src/main/java/fr/jcgay/notification/Icon.java
// @AutoValue
// public abstract class Icon {
//
// /**
// * A unique identifier. <br>
// * You should ensure that this id will be unique because it can be used to temporary write file on disk.
// *
// * @return unique identifier.
// */
// public abstract String id();
//
// /**
// * URL for this resource.
// *
// * @return URL to load icon.
// */
// public abstract URL content();
//
// public BufferedImage toImage() {
// try {
// return ImageIO.read(content());
// } catch (IOException e) {
// throw new SendNotificationException("Error while reading status icon.", e);
// }
// }
//
// public byte[] toByteArray() {
// try (InputStream is = content().openStream()) {
// return ByteStreams.toByteArray(is);
// } catch (IOException e) {
// throw new SendNotificationException("Error while reading status icon.", e);
// }
// }
//
// public String asPath() {
// String folder = System.getProperty("java.io.tmpdir") + "/send-notifications-icons/";
// String extension = extension();
// File icon = new File(folder + id() + "." + extension);
// if (!icon.exists()) {
// new File(folder).mkdirs();
// try {
// write(icon);
// } catch (IOException e) {
// throw new SendNotificationException("Can't write notification icon : " + icon.getPath(), e);
// }
// }
// return icon.getPath();
// }
//
// public String extension() {
// return content().getPath().substring(content().getPath().lastIndexOf(".") + 1);
// }
//
// public static Icon create(URL content, String id) {
// return new AutoValue_Icon(id, content);
// }
//
// private void write(File destination) throws IOException {
// try (InputStream input = content().openStream(); FileOutputStream output = new FileOutputStream(destination)) {
// byte[] buffer = new byte[1024 * 4];
// int n;
// while ((n = input.read(buffer)) != -1) {
// output.write(buffer, 0, n);
// }
// }
// }
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/IconFileWriter.java
// public interface IconFileWriter {
//
// void write(Icon icon);
// }
//
// Path: send-notification/src/main/java/fr/jcgay/notification/SendNotificationException.java
// public class SendNotificationException extends RuntimeException {
//
// public SendNotificationException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public SendNotificationException(String message) {
// super(message);
// }
// }
// Path: send-notification/src/main/java/fr/jcgay/notification/notifier/anybar/AnyBarIconWriter.java
import com.google.common.annotations.VisibleForTesting;
import fr.jcgay.notification.Icon;
import fr.jcgay.notification.IconFileWriter;
import fr.jcgay.notification.SendNotificationException;
import net.coobird.thumbnailator.Thumbnailator;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
package fr.jcgay.notification.notifier.anybar;
public class AnyBarIconWriter implements IconFileWriter {
private final String destination;
@VisibleForTesting
AnyBarIconWriter(String destination) {
this.destination = destination.endsWith("/") ? destination : destination + '/';
}
public AnyBarIconWriter() {
this(System.getProperty("user.home") + "/.AnyBar/");
}
@Override
public void write(Icon icon) {
for (Dimension dimension : Dimension.values()) {
File resizedIcon = new File(destination + icon.id() + dimension.fileNameSuffix + "." + icon.extension());
if (!resizedIcon.exists()) {
new File(destination).mkdirs();
try (InputStream input = icon.content().openStream(); FileOutputStream output = new FileOutputStream(resizedIcon)) {
Thumbnailator.createThumbnail(input, output, dimension.width, dimension.height);
} catch (IOException e) { | throw new SendNotificationException("Can't write notification icon: " + resizedIcon.getPath(), e); |
jcgay/send-notification | send-notification/src/main/java/fr/jcgay/notification/notifier/executor/RuntimeExecutor.java | // Path: send-notification/src/main/java/fr/jcgay/notification/SendNotificationException.java
// public class SendNotificationException extends RuntimeException {
//
// public SendNotificationException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public SendNotificationException(String message) {
// super(message);
// }
// }
| import com.google.common.base.Joiner;
import com.google.common.base.Throwables;
import fr.jcgay.notification.SendNotificationException;
import org.slf4j.Logger;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeoutException;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static org.slf4j.LoggerFactory.getLogger; | package fr.jcgay.notification.notifier.executor;
public class RuntimeExecutor implements Executor {
private static final Logger LOGGER = getLogger(RuntimeExecutor.class);
private static final int DEFAULT_WAIT_PROCESS_TIMEOUT = 500;
private final ExecutorService executor = Executors.newSingleThreadExecutor();
private final long timeout;
public RuntimeExecutor(long timeout) {
this.timeout = timeout == -1 ? DEFAULT_WAIT_PROCESS_TIMEOUT : timeout;
}
@Override
public void exec(final String[] command) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Will execute command line: {} (waiting at most: {} milliseconds)", logCommand(command), timeout);
}
Future<Integer> task = executor.submit(() -> {
try {
Process execution = new ProcessBuilder(command)
.redirectErrorStream(true)
.start();
int returnCode = execution.waitFor();
if (returnCode != 0) {
String message = "Command <[" + logCommand(command) + "]> returns code: " + returnCode + ".\n" + asString(execution.getInputStream());
LOGGER.debug(message); | // Path: send-notification/src/main/java/fr/jcgay/notification/SendNotificationException.java
// public class SendNotificationException extends RuntimeException {
//
// public SendNotificationException(String message, Throwable cause) {
// super(message, cause);
// }
//
// public SendNotificationException(String message) {
// super(message);
// }
// }
// Path: send-notification/src/main/java/fr/jcgay/notification/notifier/executor/RuntimeExecutor.java
import com.google.common.base.Joiner;
import com.google.common.base.Throwables;
import fr.jcgay.notification.SendNotificationException;
import org.slf4j.Logger;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeoutException;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static org.slf4j.LoggerFactory.getLogger;
package fr.jcgay.notification.notifier.executor;
public class RuntimeExecutor implements Executor {
private static final Logger LOGGER = getLogger(RuntimeExecutor.class);
private static final int DEFAULT_WAIT_PROCESS_TIMEOUT = 500;
private final ExecutorService executor = Executors.newSingleThreadExecutor();
private final long timeout;
public RuntimeExecutor(long timeout) {
this.timeout = timeout == -1 ? DEFAULT_WAIT_PROCESS_TIMEOUT : timeout;
}
@Override
public void exec(final String[] command) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Will execute command line: {} (waiting at most: {} milliseconds)", logCommand(command), timeout);
}
Future<Integer> task = executor.submit(() -> {
try {
Process execution = new ProcessBuilder(command)
.redirectErrorStream(true)
.start();
int returnCode = execution.waitFor();
if (returnCode != 0) {
String message = "Command <[" + logCommand(command) + "]> returns code: " + returnCode + ".\n" + asString(execution.getInputStream());
LOGGER.debug(message); | throw new SendNotificationException(message); |
j3kstrum/CodeCarnage | src/main/java/utilties/models/EntityTile.java | // Path: src/main/java/utilties/entities/Entity.java
// public abstract class Entity {
//
// protected EntityType entityType = null;
//
// protected Point location;
//
// /*
// Entity Type enum
// */
// public enum EntityType {
// EMPTY, PLAYER
// }
//
//
// public void setLocation(Point location) {
// this.location = location;
// }
//
// public Point getLocation() {
// return this.location;
// }
//
// public EntityType getEntityType() {
// return this.entityType;
// }
//
//
// }
| import org.mapeditor.core.Tile;
import utilties.entities.Entity;
import java.awt.*; | /*
* Copyright (c) 2017. Licensed under the Apache License 2.0.
* For full copyright, licensing, and sourcing information,
* please refer to the CodeCarnage GitHub repository's README.md file
* (found on https://github.com/j3kstrum/CodeCarnage).
*/
package utilties.models;
/**
* Model class for EntityTile. Holds location of tile and corresponding tile object
*/
public class EntityTile {
private Point _location;
| // Path: src/main/java/utilties/entities/Entity.java
// public abstract class Entity {
//
// protected EntityType entityType = null;
//
// protected Point location;
//
// /*
// Entity Type enum
// */
// public enum EntityType {
// EMPTY, PLAYER
// }
//
//
// public void setLocation(Point location) {
// this.location = location;
// }
//
// public Point getLocation() {
// return this.location;
// }
//
// public EntityType getEntityType() {
// return this.entityType;
// }
//
//
// }
// Path: src/main/java/utilties/models/EntityTile.java
import org.mapeditor.core.Tile;
import utilties.entities.Entity;
import java.awt.*;
/*
* Copyright (c) 2017. Licensed under the Apache License 2.0.
* For full copyright, licensing, and sourcing information,
* please refer to the CodeCarnage GitHub repository's README.md file
* (found on https://github.com/j3kstrum/CodeCarnage).
*/
package utilties.models;
/**
* Model class for EntityTile. Holds location of tile and corresponding tile object
*/
public class EntityTile {
private Point _location;
| private Entity _entity; |
j3kstrum/CodeCarnage | src/main/java/utilties/models/EntityMap.java | // Path: src/main/java/utilties/entities/Empty.java
// public class Empty extends Entity {
//
//
// /**
// * Empty Entity. Placed in a tile without any Objects
// */
// public Empty(Point location) {
// this.location = location;
// this.entityType = EntityType.EMPTY;
// }
//
// }
//
// Path: src/main/java/utilties/entities/Entity.java
// public abstract class Entity {
//
// protected EntityType entityType = null;
//
// protected Point location;
//
// /*
// Entity Type enum
// */
// public enum EntityType {
// EMPTY, PLAYER
// }
//
//
// public void setLocation(Point location) {
// this.location = location;
// }
//
// public Point getLocation() {
// return this.location;
// }
//
// public EntityType getEntityType() {
// return this.entityType;
// }
//
//
// }
//
// Path: src/main/java/utilties/entities/Player.java
// public class Player extends Entity {
//
// private int id;
// private int health;
// private int damage;
// private boolean isShielding;
// private int shieldStrength;
//
// /**
// * @param id Player ID
// * @param location Location of where Player will be added
// */
// public Player(int id, Point location) {
// this.id = id;
// this.health = 100;
// this.damage = 10;
// this.location = location;
// entityType = EntityType.PLAYER;
// this.isShielding = false;
// this.shieldStrength = 5;
// }
//
// /**
// * Get the ID of the player
// *
// * @return ID of player
// */
// public int getId() {
// return this.id;
// }
//
// /**
// * Get health of Player
// *
// * @return Health of Player
// */
// public int getHealth() {
// return this.health;
// }
//
//
// /**
// * Set health of player
// *
// * @param health Health to change to
// */
// public void setHealth(int health) {
// this.health = health;
// }
//
//
// public int getDamage() {
// return damage;
// }
//
// public void setDamage(int damage) {
// this.damage = damage;
// }
//
//
// public boolean isShielding() {
// return isShielding;
// }
//
// public void setShielding(boolean shielding) {
// isShielding = shielding;
// }
//
// public int getShieldStrength() {
// return shieldStrength;
// }
//
// public void setShieldStrength(int shieldStrength) {
// this.shieldStrength = shieldStrength;
// }
//
// }
| import org.mapeditor.core.Map;
import org.mapeditor.core.MapLayer;
import org.mapeditor.core.Tile;
import org.mapeditor.core.TileLayer;
import utilties.entities.Empty;
import utilties.entities.Entity;
import utilties.entities.Player;
import java.awt.*;
import java.util.ArrayList; | this._numberOfColumns = columns;
this._numberOfRows = rows;
initializeMap(columns, rows);
}
/**
* Initializes a 2D representation of the game map
*
* @param columns Number of columns
* @param rows Number of rows
*/
private void initializeMap(int columns, int rows) {
//Iterate through columns/rows and set tiles for every point for 2D array.
//Initializes all non player tiles to empty.
for (int x = 0; x < columns; x++) {
for (int y = 0; y < rows; y++) {
Point currentLocation = new Point(x, y);
//If the current coordinates are the player's location on map
if (_playerTile.getLocation().equals(currentLocation)) {
_entityTiles[x][y] = _playerTile;
//If the current coordinates are the opponent's location on map
} else if (_opponentTile.getLocation().equals(currentLocation)) {
_entityTiles[x][y] = _opponentTile;
// System.out.println(_entityTiles[x][y].getEntityType() == Entity.EntityType.PLAYER);
} else {
//Grab the empty tile reference at that location
TileLayer playerLayer = (TileLayer) this._gameMap.getLayer(PLAYER_LAYER);
//Create empty tile in location | // Path: src/main/java/utilties/entities/Empty.java
// public class Empty extends Entity {
//
//
// /**
// * Empty Entity. Placed in a tile without any Objects
// */
// public Empty(Point location) {
// this.location = location;
// this.entityType = EntityType.EMPTY;
// }
//
// }
//
// Path: src/main/java/utilties/entities/Entity.java
// public abstract class Entity {
//
// protected EntityType entityType = null;
//
// protected Point location;
//
// /*
// Entity Type enum
// */
// public enum EntityType {
// EMPTY, PLAYER
// }
//
//
// public void setLocation(Point location) {
// this.location = location;
// }
//
// public Point getLocation() {
// return this.location;
// }
//
// public EntityType getEntityType() {
// return this.entityType;
// }
//
//
// }
//
// Path: src/main/java/utilties/entities/Player.java
// public class Player extends Entity {
//
// private int id;
// private int health;
// private int damage;
// private boolean isShielding;
// private int shieldStrength;
//
// /**
// * @param id Player ID
// * @param location Location of where Player will be added
// */
// public Player(int id, Point location) {
// this.id = id;
// this.health = 100;
// this.damage = 10;
// this.location = location;
// entityType = EntityType.PLAYER;
// this.isShielding = false;
// this.shieldStrength = 5;
// }
//
// /**
// * Get the ID of the player
// *
// * @return ID of player
// */
// public int getId() {
// return this.id;
// }
//
// /**
// * Get health of Player
// *
// * @return Health of Player
// */
// public int getHealth() {
// return this.health;
// }
//
//
// /**
// * Set health of player
// *
// * @param health Health to change to
// */
// public void setHealth(int health) {
// this.health = health;
// }
//
//
// public int getDamage() {
// return damage;
// }
//
// public void setDamage(int damage) {
// this.damage = damage;
// }
//
//
// public boolean isShielding() {
// return isShielding;
// }
//
// public void setShielding(boolean shielding) {
// isShielding = shielding;
// }
//
// public int getShieldStrength() {
// return shieldStrength;
// }
//
// public void setShieldStrength(int shieldStrength) {
// this.shieldStrength = shieldStrength;
// }
//
// }
// Path: src/main/java/utilties/models/EntityMap.java
import org.mapeditor.core.Map;
import org.mapeditor.core.MapLayer;
import org.mapeditor.core.Tile;
import org.mapeditor.core.TileLayer;
import utilties.entities.Empty;
import utilties.entities.Entity;
import utilties.entities.Player;
import java.awt.*;
import java.util.ArrayList;
this._numberOfColumns = columns;
this._numberOfRows = rows;
initializeMap(columns, rows);
}
/**
* Initializes a 2D representation of the game map
*
* @param columns Number of columns
* @param rows Number of rows
*/
private void initializeMap(int columns, int rows) {
//Iterate through columns/rows and set tiles for every point for 2D array.
//Initializes all non player tiles to empty.
for (int x = 0; x < columns; x++) {
for (int y = 0; y < rows; y++) {
Point currentLocation = new Point(x, y);
//If the current coordinates are the player's location on map
if (_playerTile.getLocation().equals(currentLocation)) {
_entityTiles[x][y] = _playerTile;
//If the current coordinates are the opponent's location on map
} else if (_opponentTile.getLocation().equals(currentLocation)) {
_entityTiles[x][y] = _opponentTile;
// System.out.println(_entityTiles[x][y].getEntityType() == Entity.EntityType.PLAYER);
} else {
//Grab the empty tile reference at that location
TileLayer playerLayer = (TileLayer) this._gameMap.getLayer(PLAYER_LAYER);
//Create empty tile in location | _entityTiles[x][y] = new EntityTile(currentLocation, new Empty(currentLocation), playerLayer.getTileAt(currentLocation.x, currentLocation.y)); |
j3kstrum/CodeCarnage | src/main/java/utilties/models/EntityMap.java | // Path: src/main/java/utilties/entities/Empty.java
// public class Empty extends Entity {
//
//
// /**
// * Empty Entity. Placed in a tile without any Objects
// */
// public Empty(Point location) {
// this.location = location;
// this.entityType = EntityType.EMPTY;
// }
//
// }
//
// Path: src/main/java/utilties/entities/Entity.java
// public abstract class Entity {
//
// protected EntityType entityType = null;
//
// protected Point location;
//
// /*
// Entity Type enum
// */
// public enum EntityType {
// EMPTY, PLAYER
// }
//
//
// public void setLocation(Point location) {
// this.location = location;
// }
//
// public Point getLocation() {
// return this.location;
// }
//
// public EntityType getEntityType() {
// return this.entityType;
// }
//
//
// }
//
// Path: src/main/java/utilties/entities/Player.java
// public class Player extends Entity {
//
// private int id;
// private int health;
// private int damage;
// private boolean isShielding;
// private int shieldStrength;
//
// /**
// * @param id Player ID
// * @param location Location of where Player will be added
// */
// public Player(int id, Point location) {
// this.id = id;
// this.health = 100;
// this.damage = 10;
// this.location = location;
// entityType = EntityType.PLAYER;
// this.isShielding = false;
// this.shieldStrength = 5;
// }
//
// /**
// * Get the ID of the player
// *
// * @return ID of player
// */
// public int getId() {
// return this.id;
// }
//
// /**
// * Get health of Player
// *
// * @return Health of Player
// */
// public int getHealth() {
// return this.health;
// }
//
//
// /**
// * Set health of player
// *
// * @param health Health to change to
// */
// public void setHealth(int health) {
// this.health = health;
// }
//
//
// public int getDamage() {
// return damage;
// }
//
// public void setDamage(int damage) {
// this.damage = damage;
// }
//
//
// public boolean isShielding() {
// return isShielding;
// }
//
// public void setShielding(boolean shielding) {
// isShielding = shielding;
// }
//
// public int getShieldStrength() {
// return shieldStrength;
// }
//
// public void setShieldStrength(int shieldStrength) {
// this.shieldStrength = shieldStrength;
// }
//
// }
| import org.mapeditor.core.Map;
import org.mapeditor.core.MapLayer;
import org.mapeditor.core.Tile;
import org.mapeditor.core.TileLayer;
import utilties.entities.Empty;
import utilties.entities.Entity;
import utilties.entities.Player;
import java.awt.*;
import java.util.ArrayList; | }
ArrayList<Tile> playerTiles = new ArrayList<>();
Point playerLocation = null;
Point opponentLocation = null;
//Iterate through player layer to find player tiles
Tile tile;
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
tile = playerLayer.getTileAt(x, y);
if (tile == null) {
continue;
} else {
//If we haven't found a player yet, then tile found is player
if (playerTiles.size() == 0) {
playerLocation = new Point(x, y);
} else {
opponentLocation = new Point(x, y);
}
playerTiles.add(tile);
}
}
}
//Grab references
Tile playerTile = playerTiles.get(0);
Tile opponentTile = playerTiles.get(1);
//Add tiles to corresponding entity tile | // Path: src/main/java/utilties/entities/Empty.java
// public class Empty extends Entity {
//
//
// /**
// * Empty Entity. Placed in a tile without any Objects
// */
// public Empty(Point location) {
// this.location = location;
// this.entityType = EntityType.EMPTY;
// }
//
// }
//
// Path: src/main/java/utilties/entities/Entity.java
// public abstract class Entity {
//
// protected EntityType entityType = null;
//
// protected Point location;
//
// /*
// Entity Type enum
// */
// public enum EntityType {
// EMPTY, PLAYER
// }
//
//
// public void setLocation(Point location) {
// this.location = location;
// }
//
// public Point getLocation() {
// return this.location;
// }
//
// public EntityType getEntityType() {
// return this.entityType;
// }
//
//
// }
//
// Path: src/main/java/utilties/entities/Player.java
// public class Player extends Entity {
//
// private int id;
// private int health;
// private int damage;
// private boolean isShielding;
// private int shieldStrength;
//
// /**
// * @param id Player ID
// * @param location Location of where Player will be added
// */
// public Player(int id, Point location) {
// this.id = id;
// this.health = 100;
// this.damage = 10;
// this.location = location;
// entityType = EntityType.PLAYER;
// this.isShielding = false;
// this.shieldStrength = 5;
// }
//
// /**
// * Get the ID of the player
// *
// * @return ID of player
// */
// public int getId() {
// return this.id;
// }
//
// /**
// * Get health of Player
// *
// * @return Health of Player
// */
// public int getHealth() {
// return this.health;
// }
//
//
// /**
// * Set health of player
// *
// * @param health Health to change to
// */
// public void setHealth(int health) {
// this.health = health;
// }
//
//
// public int getDamage() {
// return damage;
// }
//
// public void setDamage(int damage) {
// this.damage = damage;
// }
//
//
// public boolean isShielding() {
// return isShielding;
// }
//
// public void setShielding(boolean shielding) {
// isShielding = shielding;
// }
//
// public int getShieldStrength() {
// return shieldStrength;
// }
//
// public void setShieldStrength(int shieldStrength) {
// this.shieldStrength = shieldStrength;
// }
//
// }
// Path: src/main/java/utilties/models/EntityMap.java
import org.mapeditor.core.Map;
import org.mapeditor.core.MapLayer;
import org.mapeditor.core.Tile;
import org.mapeditor.core.TileLayer;
import utilties.entities.Empty;
import utilties.entities.Entity;
import utilties.entities.Player;
import java.awt.*;
import java.util.ArrayList;
}
ArrayList<Tile> playerTiles = new ArrayList<>();
Point playerLocation = null;
Point opponentLocation = null;
//Iterate through player layer to find player tiles
Tile tile;
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
tile = playerLayer.getTileAt(x, y);
if (tile == null) {
continue;
} else {
//If we haven't found a player yet, then tile found is player
if (playerTiles.size() == 0) {
playerLocation = new Point(x, y);
} else {
opponentLocation = new Point(x, y);
}
playerTiles.add(tile);
}
}
}
//Grab references
Tile playerTile = playerTiles.get(0);
Tile opponentTile = playerTiles.get(1);
//Add tiles to corresponding entity tile | EntityTile playerEntityTile = new EntityTile(playerLocation, new Player(0, playerLocation), playerTile); |
j3kstrum/CodeCarnage | src/main/java/utilties/models/EntityMap.java | // Path: src/main/java/utilties/entities/Empty.java
// public class Empty extends Entity {
//
//
// /**
// * Empty Entity. Placed in a tile without any Objects
// */
// public Empty(Point location) {
// this.location = location;
// this.entityType = EntityType.EMPTY;
// }
//
// }
//
// Path: src/main/java/utilties/entities/Entity.java
// public abstract class Entity {
//
// protected EntityType entityType = null;
//
// protected Point location;
//
// /*
// Entity Type enum
// */
// public enum EntityType {
// EMPTY, PLAYER
// }
//
//
// public void setLocation(Point location) {
// this.location = location;
// }
//
// public Point getLocation() {
// return this.location;
// }
//
// public EntityType getEntityType() {
// return this.entityType;
// }
//
//
// }
//
// Path: src/main/java/utilties/entities/Player.java
// public class Player extends Entity {
//
// private int id;
// private int health;
// private int damage;
// private boolean isShielding;
// private int shieldStrength;
//
// /**
// * @param id Player ID
// * @param location Location of where Player will be added
// */
// public Player(int id, Point location) {
// this.id = id;
// this.health = 100;
// this.damage = 10;
// this.location = location;
// entityType = EntityType.PLAYER;
// this.isShielding = false;
// this.shieldStrength = 5;
// }
//
// /**
// * Get the ID of the player
// *
// * @return ID of player
// */
// public int getId() {
// return this.id;
// }
//
// /**
// * Get health of Player
// *
// * @return Health of Player
// */
// public int getHealth() {
// return this.health;
// }
//
//
// /**
// * Set health of player
// *
// * @param health Health to change to
// */
// public void setHealth(int health) {
// this.health = health;
// }
//
//
// public int getDamage() {
// return damage;
// }
//
// public void setDamage(int damage) {
// this.damage = damage;
// }
//
//
// public boolean isShielding() {
// return isShielding;
// }
//
// public void setShielding(boolean shielding) {
// isShielding = shielding;
// }
//
// public int getShieldStrength() {
// return shieldStrength;
// }
//
// public void setShieldStrength(int shieldStrength) {
// this.shieldStrength = shieldStrength;
// }
//
// }
| import org.mapeditor.core.Map;
import org.mapeditor.core.MapLayer;
import org.mapeditor.core.Tile;
import org.mapeditor.core.TileLayer;
import utilties.entities.Empty;
import utilties.entities.Entity;
import utilties.entities.Player;
import java.awt.*;
import java.util.ArrayList; | private TileLayer getPlayerLayer() {
ArrayList<MapLayer> layerList = new ArrayList<>(this._gameMap.getLayers());
return (TileLayer) layerList.get(2);
}
/**
* Moves location of EntityTile to new location. This updates both Tiled's TileMap and well as our custom game map.
* If the location to move to is occupied, the EntityTile stays in its current location, or if location is outside of player bounds
*
* @param entity Entity to move
* @param locationToMoveTo Location to move to
* @return If EntityTile can move to that location
*/
public boolean setLocation(EntityTile entity, Point locationToMoveTo) {
//If outside of player bounds return false
if (!isInsideMap(locationToMoveTo)) {
return false;
}
//All movement is done on the player layer. We need to grab a couple of references before we can move location.
TileLayer playerLayer = getPlayerLayer();
//Get the current location of the entity
Point entityCurrentLocation = new Point(entity.getLocation());
//Reference to the tile the player will be moving to
EntityTile tileToMoveTo = _entityTiles[locationToMoveTo.x][locationToMoveTo.y];
//If the tile to move to is empty, then it is a valid move | // Path: src/main/java/utilties/entities/Empty.java
// public class Empty extends Entity {
//
//
// /**
// * Empty Entity. Placed in a tile without any Objects
// */
// public Empty(Point location) {
// this.location = location;
// this.entityType = EntityType.EMPTY;
// }
//
// }
//
// Path: src/main/java/utilties/entities/Entity.java
// public abstract class Entity {
//
// protected EntityType entityType = null;
//
// protected Point location;
//
// /*
// Entity Type enum
// */
// public enum EntityType {
// EMPTY, PLAYER
// }
//
//
// public void setLocation(Point location) {
// this.location = location;
// }
//
// public Point getLocation() {
// return this.location;
// }
//
// public EntityType getEntityType() {
// return this.entityType;
// }
//
//
// }
//
// Path: src/main/java/utilties/entities/Player.java
// public class Player extends Entity {
//
// private int id;
// private int health;
// private int damage;
// private boolean isShielding;
// private int shieldStrength;
//
// /**
// * @param id Player ID
// * @param location Location of where Player will be added
// */
// public Player(int id, Point location) {
// this.id = id;
// this.health = 100;
// this.damage = 10;
// this.location = location;
// entityType = EntityType.PLAYER;
// this.isShielding = false;
// this.shieldStrength = 5;
// }
//
// /**
// * Get the ID of the player
// *
// * @return ID of player
// */
// public int getId() {
// return this.id;
// }
//
// /**
// * Get health of Player
// *
// * @return Health of Player
// */
// public int getHealth() {
// return this.health;
// }
//
//
// /**
// * Set health of player
// *
// * @param health Health to change to
// */
// public void setHealth(int health) {
// this.health = health;
// }
//
//
// public int getDamage() {
// return damage;
// }
//
// public void setDamage(int damage) {
// this.damage = damage;
// }
//
//
// public boolean isShielding() {
// return isShielding;
// }
//
// public void setShielding(boolean shielding) {
// isShielding = shielding;
// }
//
// public int getShieldStrength() {
// return shieldStrength;
// }
//
// public void setShieldStrength(int shieldStrength) {
// this.shieldStrength = shieldStrength;
// }
//
// }
// Path: src/main/java/utilties/models/EntityMap.java
import org.mapeditor.core.Map;
import org.mapeditor.core.MapLayer;
import org.mapeditor.core.Tile;
import org.mapeditor.core.TileLayer;
import utilties.entities.Empty;
import utilties.entities.Entity;
import utilties.entities.Player;
import java.awt.*;
import java.util.ArrayList;
private TileLayer getPlayerLayer() {
ArrayList<MapLayer> layerList = new ArrayList<>(this._gameMap.getLayers());
return (TileLayer) layerList.get(2);
}
/**
* Moves location of EntityTile to new location. This updates both Tiled's TileMap and well as our custom game map.
* If the location to move to is occupied, the EntityTile stays in its current location, or if location is outside of player bounds
*
* @param entity Entity to move
* @param locationToMoveTo Location to move to
* @return If EntityTile can move to that location
*/
public boolean setLocation(EntityTile entity, Point locationToMoveTo) {
//If outside of player bounds return false
if (!isInsideMap(locationToMoveTo)) {
return false;
}
//All movement is done on the player layer. We need to grab a couple of references before we can move location.
TileLayer playerLayer = getPlayerLayer();
//Get the current location of the entity
Point entityCurrentLocation = new Point(entity.getLocation());
//Reference to the tile the player will be moving to
EntityTile tileToMoveTo = _entityTiles[locationToMoveTo.x][locationToMoveTo.y];
//If the tile to move to is empty, then it is a valid move | if (tileToMoveTo.getEntityType() == Entity.EntityType.EMPTY) { |
j3kstrum/CodeCarnage | src/test/java/utilties/models/EntityMapTest.java | // Path: src/main/java/common/exceptions/LoadMapFailedException.java
// public class LoadMapFailedException extends ResourceNotFoundException {
//
// public LoadMapFailedException() {super();}
//
// public LoadMapFailedException(String message) {super(message);}
//
// }
//
// Path: src/main/java/utilties/entities/Entity.java
// public abstract class Entity {
//
// protected EntityType entityType = null;
//
// protected Point location;
//
// /*
// Entity Type enum
// */
// public enum EntityType {
// EMPTY, PLAYER
// }
//
//
// public void setLocation(Point location) {
// this.location = location;
// }
//
// public Point getLocation() {
// return this.location;
// }
//
// public EntityType getEntityType() {
// return this.entityType;
// }
//
//
// }
//
// Path: src/main/java/utilties/entities/Player.java
// public class Player extends Entity {
//
// private int id;
// private int health;
// private int damage;
// private boolean isShielding;
// private int shieldStrength;
//
// /**
// * @param id Player ID
// * @param location Location of where Player will be added
// */
// public Player(int id, Point location) {
// this.id = id;
// this.health = 100;
// this.damage = 10;
// this.location = location;
// entityType = EntityType.PLAYER;
// this.isShielding = false;
// this.shieldStrength = 5;
// }
//
// /**
// * Get the ID of the player
// *
// * @return ID of player
// */
// public int getId() {
// return this.id;
// }
//
// /**
// * Get health of Player
// *
// * @return Health of Player
// */
// public int getHealth() {
// return this.health;
// }
//
//
// /**
// * Set health of player
// *
// * @param health Health to change to
// */
// public void setHealth(int health) {
// this.health = health;
// }
//
//
// public int getDamage() {
// return damage;
// }
//
// public void setDamage(int damage) {
// this.damage = damage;
// }
//
//
// public boolean isShielding() {
// return isShielding;
// }
//
// public void setShielding(boolean shielding) {
// isShielding = shielding;
// }
//
// public int getShieldStrength() {
// return shieldStrength;
// }
//
// public void setShieldStrength(int shieldStrength) {
// this.shieldStrength = shieldStrength;
// }
//
// }
| import common.exceptions.LoadMapFailedException;
import org.junit.Before;
import org.junit.Test;
import org.mapeditor.io.MapReader;
import utilties.entities.Entity;
import utilties.entities.Player;
import java.awt.*;
import java.net.URL;
import static org.junit.Assert.assertTrue; | package utilties.models;
public class EntityMapTest{
private EntityMap entityMap;
@Before
public void setup() throws Exception {
try {
URL mapPath = new URL("https://www.cse.buffalo.edu/~jacobeks/codecarnage/me/r/game-map.tmx");
MapReader mr = new MapReader();
entityMap = new EntityMap(mr.readMap(mapPath), 25, 15);
} catch (Exception ex) { | // Path: src/main/java/common/exceptions/LoadMapFailedException.java
// public class LoadMapFailedException extends ResourceNotFoundException {
//
// public LoadMapFailedException() {super();}
//
// public LoadMapFailedException(String message) {super(message);}
//
// }
//
// Path: src/main/java/utilties/entities/Entity.java
// public abstract class Entity {
//
// protected EntityType entityType = null;
//
// protected Point location;
//
// /*
// Entity Type enum
// */
// public enum EntityType {
// EMPTY, PLAYER
// }
//
//
// public void setLocation(Point location) {
// this.location = location;
// }
//
// public Point getLocation() {
// return this.location;
// }
//
// public EntityType getEntityType() {
// return this.entityType;
// }
//
//
// }
//
// Path: src/main/java/utilties/entities/Player.java
// public class Player extends Entity {
//
// private int id;
// private int health;
// private int damage;
// private boolean isShielding;
// private int shieldStrength;
//
// /**
// * @param id Player ID
// * @param location Location of where Player will be added
// */
// public Player(int id, Point location) {
// this.id = id;
// this.health = 100;
// this.damage = 10;
// this.location = location;
// entityType = EntityType.PLAYER;
// this.isShielding = false;
// this.shieldStrength = 5;
// }
//
// /**
// * Get the ID of the player
// *
// * @return ID of player
// */
// public int getId() {
// return this.id;
// }
//
// /**
// * Get health of Player
// *
// * @return Health of Player
// */
// public int getHealth() {
// return this.health;
// }
//
//
// /**
// * Set health of player
// *
// * @param health Health to change to
// */
// public void setHealth(int health) {
// this.health = health;
// }
//
//
// public int getDamage() {
// return damage;
// }
//
// public void setDamage(int damage) {
// this.damage = damage;
// }
//
//
// public boolean isShielding() {
// return isShielding;
// }
//
// public void setShielding(boolean shielding) {
// isShielding = shielding;
// }
//
// public int getShieldStrength() {
// return shieldStrength;
// }
//
// public void setShieldStrength(int shieldStrength) {
// this.shieldStrength = shieldStrength;
// }
//
// }
// Path: src/test/java/utilties/models/EntityMapTest.java
import common.exceptions.LoadMapFailedException;
import org.junit.Before;
import org.junit.Test;
import org.mapeditor.io.MapReader;
import utilties.entities.Entity;
import utilties.entities.Player;
import java.awt.*;
import java.net.URL;
import static org.junit.Assert.assertTrue;
package utilties.models;
public class EntityMapTest{
private EntityMap entityMap;
@Before
public void setup() throws Exception {
try {
URL mapPath = new URL("https://www.cse.buffalo.edu/~jacobeks/codecarnage/me/r/game-map.tmx");
MapReader mr = new MapReader();
entityMap = new EntityMap(mr.readMap(mapPath), 25, 15);
} catch (Exception ex) { | throw new LoadMapFailedException(ex.getMessage()); |
j3kstrum/CodeCarnage | src/main/java/engine/data/EngineData.java | // Path: src/main/java/common/BaseLogger.java
// public class BaseLogger {
// private String _name;
// private String _format;
// private PrintStream _stream;
// private static final int level = 1;
//
// /**
// * Constructor for the logger. At its most basic, produces a logger with the given name
// * piped to standard error with the default format.
// *
// * @param name The name to be used for logging statements with this logger.
// */
// public BaseLogger(String name) {
// this(name, System.err);
// }
//
// /**
// * Constructor for the logger. Uses the basic format, but pipes output to the specified stream
// * with the specified name.
// *
// * @param name The name to be used when producing output.
// * @param stream The stream to which output should be sent.
// */
// public BaseLogger(String name, PrintStream stream) {
// this(name, stream, "%(level) [%(time)] %(name): %(message)");
// }
//
// /**
// * Constructor for the logger.
// *
// * @param name The name to be used when producing output.
// * @param stream The stream that output should be sent to.
// * @param format The format to be used for the logger's output.
// */
// public BaseLogger(String name, PrintStream stream, String format) {
// this._name = name;
// this._stream = stream;
// this._format = format;
// }
//
// /**
// * Outputs a message using the level string "DEBUG".
// *
// * @param message The message to be sent.
// */
// public void debug(String message) {
// this.print(message, "DEBUG");
// }
//
// /**
// * Outputs a message using the level string "INFO".
// *
// * @param message The message to be sent.
// */
// public void info(String message) {
// this.print(message, "INFO");
// }
//
// /**
// * Outputs a message using the level string "WARNING".
// *
// * @param message The message to be sent.
// */
// public void warning(String message) {
// this.print(message, "WARNING");
// }
//
// /**
// * Outputs a message using the level string "CRITICAL".
// *
// * @param message The message to be sent.
// */
// public void critical(String message) {
// this.print(message, "CRITICAL");
// }
//
// /**
// * Outputs a message using the level string "FATAL".
// *
// * @param message The message to be sent.
// */
// public void fatal(String message) {
// this.print(message, "FATAL");
// }
//
// /**
// * Generates and outputs the logging string containing the specified message.
// *
// * @param message The message to be attached to the logging string, or placed inside if formatting approves.
// * @param level The level to log at.
// */
// private void print(String message, String level) {
// if (message == null) {
// message = "<null message>";
// }
// String msg = this.format(this._format, level);
// if (msg.contains("%(message)")) {
// msg = msg.replace("%(message)", message);
// } else {
// msg = msg + " " + message;
// }
// this._stream.println(msg);
// }
//
// /**
// * Formats the provided malleable string with the specified level.
// *
// * @param formattable The string optionally containing formattable characters that must be formatted.
// * @param level The level to be placed in the formattable string, if appropriate.
// * @return The formatted string.
// */
// private String format(String formattable, String level) {
// formattable = this.formatName(formattable);
// formattable = this.formatTime(formattable);
// if (level != null) {
// formattable = this.formatLevel(formattable, level);
// }
// return formattable;
// }
//
// /**
// * Places the logger's name in the formattable string, if appropriate.
// *
// * @param formattable The string that may or may not have the name inserted.
// * @return The formattable string with all name tokens formatted.
// */
// private String formatName(String formattable) {
// if (formattable.contains("%(name)")) {
// return formattable.replace("%(name)", this._name);
// }
// return formattable;
// }
//
// /**
// * Places the logger's level in the formattable string, if appropriate.
// *
// * @param formattable The string that may or may not have the level inserted.
// * @return The formattable string with all level tokens formatted.
// */
// private String formatLevel(String formattable, String level) {
// if (formattable.contains("%(level)")) {
// return formattable.replace("%(level)", level);
// }
// return formattable;
// }
//
// /**
// * Places the time of the call in the formattable string, if appropriate.
// *
// * @param formattable The string that may or may not have the time inserted.
// * @return The formattable string with all time tokens formatted.
// */
// private String formatTime(String formattable) {
// if (formattable.contains("%(time)")) {
// return formattable.replace("%(time)", LocalDateTime.now().toString().replace('T', ' '));
// }
// return formattable;
// }
// }
//
// Path: src/main/java/common/data/GameMap.java
// public class GameMap {
// // TODO: Populate. I think Sean started some work on this.
//
// private org.mapeditor.core.Map _staticMap;
//
// public GameMap(org.mapeditor.core.Map tiledMap) {
// this._staticMap = tiledMap;
// }
// }
| import common.BaseLogger;
import common.data.GameMap;
import org.mapeditor.core.Map; | /*
* Copyright (c) 2017. Licensed under the Apache License 2.0.
* For full copyright, licensing, and sourcing information,
* please refer to the CodeCarnage GitHub repository's README.md file
* (found on https://github.com/j3kstrum/CodeCarnage).
*/
package engine.data;
/**
* The class containing the Engine's Data. It handles all lower-level data objects pertaining to the engine.
*
* @author jacob.ekstrum
*/
public class EngineData {
private Map _map; | // Path: src/main/java/common/BaseLogger.java
// public class BaseLogger {
// private String _name;
// private String _format;
// private PrintStream _stream;
// private static final int level = 1;
//
// /**
// * Constructor for the logger. At its most basic, produces a logger with the given name
// * piped to standard error with the default format.
// *
// * @param name The name to be used for logging statements with this logger.
// */
// public BaseLogger(String name) {
// this(name, System.err);
// }
//
// /**
// * Constructor for the logger. Uses the basic format, but pipes output to the specified stream
// * with the specified name.
// *
// * @param name The name to be used when producing output.
// * @param stream The stream to which output should be sent.
// */
// public BaseLogger(String name, PrintStream stream) {
// this(name, stream, "%(level) [%(time)] %(name): %(message)");
// }
//
// /**
// * Constructor for the logger.
// *
// * @param name The name to be used when producing output.
// * @param stream The stream that output should be sent to.
// * @param format The format to be used for the logger's output.
// */
// public BaseLogger(String name, PrintStream stream, String format) {
// this._name = name;
// this._stream = stream;
// this._format = format;
// }
//
// /**
// * Outputs a message using the level string "DEBUG".
// *
// * @param message The message to be sent.
// */
// public void debug(String message) {
// this.print(message, "DEBUG");
// }
//
// /**
// * Outputs a message using the level string "INFO".
// *
// * @param message The message to be sent.
// */
// public void info(String message) {
// this.print(message, "INFO");
// }
//
// /**
// * Outputs a message using the level string "WARNING".
// *
// * @param message The message to be sent.
// */
// public void warning(String message) {
// this.print(message, "WARNING");
// }
//
// /**
// * Outputs a message using the level string "CRITICAL".
// *
// * @param message The message to be sent.
// */
// public void critical(String message) {
// this.print(message, "CRITICAL");
// }
//
// /**
// * Outputs a message using the level string "FATAL".
// *
// * @param message The message to be sent.
// */
// public void fatal(String message) {
// this.print(message, "FATAL");
// }
//
// /**
// * Generates and outputs the logging string containing the specified message.
// *
// * @param message The message to be attached to the logging string, or placed inside if formatting approves.
// * @param level The level to log at.
// */
// private void print(String message, String level) {
// if (message == null) {
// message = "<null message>";
// }
// String msg = this.format(this._format, level);
// if (msg.contains("%(message)")) {
// msg = msg.replace("%(message)", message);
// } else {
// msg = msg + " " + message;
// }
// this._stream.println(msg);
// }
//
// /**
// * Formats the provided malleable string with the specified level.
// *
// * @param formattable The string optionally containing formattable characters that must be formatted.
// * @param level The level to be placed in the formattable string, if appropriate.
// * @return The formatted string.
// */
// private String format(String formattable, String level) {
// formattable = this.formatName(formattable);
// formattable = this.formatTime(formattable);
// if (level != null) {
// formattable = this.formatLevel(formattable, level);
// }
// return formattable;
// }
//
// /**
// * Places the logger's name in the formattable string, if appropriate.
// *
// * @param formattable The string that may or may not have the name inserted.
// * @return The formattable string with all name tokens formatted.
// */
// private String formatName(String formattable) {
// if (formattable.contains("%(name)")) {
// return formattable.replace("%(name)", this._name);
// }
// return formattable;
// }
//
// /**
// * Places the logger's level in the formattable string, if appropriate.
// *
// * @param formattable The string that may or may not have the level inserted.
// * @return The formattable string with all level tokens formatted.
// */
// private String formatLevel(String formattable, String level) {
// if (formattable.contains("%(level)")) {
// return formattable.replace("%(level)", level);
// }
// return formattable;
// }
//
// /**
// * Places the time of the call in the formattable string, if appropriate.
// *
// * @param formattable The string that may or may not have the time inserted.
// * @return The formattable string with all time tokens formatted.
// */
// private String formatTime(String formattable) {
// if (formattable.contains("%(time)")) {
// return formattable.replace("%(time)", LocalDateTime.now().toString().replace('T', ' '));
// }
// return formattable;
// }
// }
//
// Path: src/main/java/common/data/GameMap.java
// public class GameMap {
// // TODO: Populate. I think Sean started some work on this.
//
// private org.mapeditor.core.Map _staticMap;
//
// public GameMap(org.mapeditor.core.Map tiledMap) {
// this._staticMap = tiledMap;
// }
// }
// Path: src/main/java/engine/data/EngineData.java
import common.BaseLogger;
import common.data.GameMap;
import org.mapeditor.core.Map;
/*
* Copyright (c) 2017. Licensed under the Apache License 2.0.
* For full copyright, licensing, and sourcing information,
* please refer to the CodeCarnage GitHub repository's README.md file
* (found on https://github.com/j3kstrum/CodeCarnage).
*/
package engine.data;
/**
* The class containing the Engine's Data. It handles all lower-level data objects pertaining to the engine.
*
* @author jacob.ekstrum
*/
public class EngineData {
private Map _map; | private static final BaseLogger LOGGER = new BaseLogger("EngineData"); |
j3kstrum/CodeCarnage | src/main/java/gui/scripting/MouseEvents.java | // Path: src/main/java/interpreter/Check.java
// public class Check {
//
// private String data1;
// private String data2;
// private Operator operator;
//
// private static final BaseLogger LOGGER = new BaseLogger("Check");
//
// /**
// *
// * Default constructor when not dealing with user input.
// *
// * @param data1 First data element
// * @param data2 Second data element
// * @param operator Operator for comparison
// */
// public Check(String data1, String data2, Operator operator) {
// this.data1 = data1;
// this.data2 = data2;
// this.operator = operator;
// }
//
// public String getData1() {
// return data1;
// }
//
// public String getData2() {
// return data2;
// }
//
// public Operator getOperator() {
// return operator;
// }
//
//
// /**
// * Based on the current game state data, returns if condition is true.
// *
// * @param game takes in the model
// * @return if defined condition is true
// */
// boolean conditionIsTrue(Game game, int id) {
//
// int data1 = getData(this.data1, game, id);
// int data2 = getData(this.data2, game, id);
//
// switch (this.operator){
// case LESS_THAN:
// return data1 < data2;
// case GREATER_THAN:
// return data1 > data2;
// case LESS_THAN_OR_EQUAL_TO:
// return data1 <= data2;
// case GREATER_THAN_OR_EQUAL_TO:
// return data1 >= data2;
// case EQUALS:
// return data1 == data2;
// default:
// return false; // should never happen, but Java is Java
// }
// }
//
//
// /**
// * Based on the current game state data, returns if condition is true.
// *
// * @param data takes in the data to be returned
// * @param game is the pointer to the game model
// * @return the integer value of the game data that has been looked up
// */
// private int getData(String data, Game game, int id) {
//
// int otherId;
// if (id == 0){otherId = 1;}else{otherId = 0;}
//
// if (data.equals(Data.USER_HEALTH.text())) {
// return game.getPlayer(id).getHealth();
// } else if (data.equals(Data.OPPONENT_HEALTH.text())) {
// return game.getPlayer(otherId).getHealth();
// } else if (data.equals(Data.DISTANCE_FROM_OPPONENT.text())) {
// return game.pathDistanceToPlayer(id, otherId);
// } else {
// try {
// return Integer.parseInt(data);
// } catch (Exception ex) {
// LOGGER.critical("Unable to parse '" + data + "' as Data.");
// return -1;
// }
// }
// }
// }
//
// Path: src/main/java/interpreter/ScriptCommand.java
// public class ScriptCommand {
//
// private List<Check> checks;
// private Command command;
// private static final BaseLogger LOGGER = new BaseLogger("ScriptCommand");
//
// public ScriptCommand(List<Check> checks, Command command) {
// this.checks = checks;
// this.command = command;
// }
//
// /**
// * @return the command enum
// */
// public Command getCommand() {
// return command;
// }
//
// /**
// * @return the list of checks for this command
// */
// public List<Check> getChecks() {
// return checks;
// }
//
// /**
// * Method called to excecute a 'line' of the interpreter.
// *
// * @param game the instance of the game class passed in
// * @param id the id of the player excecuting this script
// * @return true if the command excecuted
// */
// public boolean doCommand(Game game, int id){
//
// for (Check c: this.checks){
// if (!c.conditionIsTrue(game, id)) {
// return false;
// }
// }
// executeFunction(game, id);
// return true;
// }
//
// /**
// * Called by doCommand to actually modify the game data with built-in functions
// *
// * @param game the instance of the game class passed in
// * @param id the id of the player executing this script
// */
// private void executeFunction(Game game, int id){
//
// int otherId;
//
// if (id == 0){otherId = 1;}else{otherId = 0;}
//
// if(id == 1){
// LOGGER.debug("Executing attack for player " + id + " "+ this.command);
// }
//
// switch(this.command){
// case APPROACH:
// game.approach(id, otherId);
// break;
// case ATTACK:
// game.attack(id);
// break;
// case HEAL:
// game.heal(id, 9);
// break;
// case EVADE:
// game.evade(id, otherId);
// case DO_NOTHING:
// game.doNothing(id);
// break;
// case DEFEND:
// game.defend(id);
// break;
// case SELF_DESTRUCT:
// game.selfDestruct(id);
// default:
// game.doNothing(id);
// break;
// }
// }
// }
| import interpreter.Check;
import interpreter.ScriptCommand;
import interpreter.enumerations.*;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Node;
import javafx.scene.control.Alert;
import javafx.scene.control.TextInputDialog;
import javax.management.InstanceNotFoundException;
import java.util.*;
import java.util.stream.Collectors; |
try {
op = getOperator(scriptingObjects.get(i + 1));
} catch (InstanceNotFoundException e) {
e.printStackTrace();
// Should never happen
return null;
}
Check check = new Check(scriptingObjects.get(i),
scriptingObjects.get(i + 2),
op);
checks.add(check);
// increment to end of the check that was located
i = i + 2;
}
}
return checks;
}
private static Operator getOperator(String text) throws InstanceNotFoundException {
for (Operator operator : Operator.values()) {
if (text.trim().equals(operator.text())) {
return operator;
}
}
throw new InstanceNotFoundException();
}
| // Path: src/main/java/interpreter/Check.java
// public class Check {
//
// private String data1;
// private String data2;
// private Operator operator;
//
// private static final BaseLogger LOGGER = new BaseLogger("Check");
//
// /**
// *
// * Default constructor when not dealing with user input.
// *
// * @param data1 First data element
// * @param data2 Second data element
// * @param operator Operator for comparison
// */
// public Check(String data1, String data2, Operator operator) {
// this.data1 = data1;
// this.data2 = data2;
// this.operator = operator;
// }
//
// public String getData1() {
// return data1;
// }
//
// public String getData2() {
// return data2;
// }
//
// public Operator getOperator() {
// return operator;
// }
//
//
// /**
// * Based on the current game state data, returns if condition is true.
// *
// * @param game takes in the model
// * @return if defined condition is true
// */
// boolean conditionIsTrue(Game game, int id) {
//
// int data1 = getData(this.data1, game, id);
// int data2 = getData(this.data2, game, id);
//
// switch (this.operator){
// case LESS_THAN:
// return data1 < data2;
// case GREATER_THAN:
// return data1 > data2;
// case LESS_THAN_OR_EQUAL_TO:
// return data1 <= data2;
// case GREATER_THAN_OR_EQUAL_TO:
// return data1 >= data2;
// case EQUALS:
// return data1 == data2;
// default:
// return false; // should never happen, but Java is Java
// }
// }
//
//
// /**
// * Based on the current game state data, returns if condition is true.
// *
// * @param data takes in the data to be returned
// * @param game is the pointer to the game model
// * @return the integer value of the game data that has been looked up
// */
// private int getData(String data, Game game, int id) {
//
// int otherId;
// if (id == 0){otherId = 1;}else{otherId = 0;}
//
// if (data.equals(Data.USER_HEALTH.text())) {
// return game.getPlayer(id).getHealth();
// } else if (data.equals(Data.OPPONENT_HEALTH.text())) {
// return game.getPlayer(otherId).getHealth();
// } else if (data.equals(Data.DISTANCE_FROM_OPPONENT.text())) {
// return game.pathDistanceToPlayer(id, otherId);
// } else {
// try {
// return Integer.parseInt(data);
// } catch (Exception ex) {
// LOGGER.critical("Unable to parse '" + data + "' as Data.");
// return -1;
// }
// }
// }
// }
//
// Path: src/main/java/interpreter/ScriptCommand.java
// public class ScriptCommand {
//
// private List<Check> checks;
// private Command command;
// private static final BaseLogger LOGGER = new BaseLogger("ScriptCommand");
//
// public ScriptCommand(List<Check> checks, Command command) {
// this.checks = checks;
// this.command = command;
// }
//
// /**
// * @return the command enum
// */
// public Command getCommand() {
// return command;
// }
//
// /**
// * @return the list of checks for this command
// */
// public List<Check> getChecks() {
// return checks;
// }
//
// /**
// * Method called to excecute a 'line' of the interpreter.
// *
// * @param game the instance of the game class passed in
// * @param id the id of the player excecuting this script
// * @return true if the command excecuted
// */
// public boolean doCommand(Game game, int id){
//
// for (Check c: this.checks){
// if (!c.conditionIsTrue(game, id)) {
// return false;
// }
// }
// executeFunction(game, id);
// return true;
// }
//
// /**
// * Called by doCommand to actually modify the game data with built-in functions
// *
// * @param game the instance of the game class passed in
// * @param id the id of the player executing this script
// */
// private void executeFunction(Game game, int id){
//
// int otherId;
//
// if (id == 0){otherId = 1;}else{otherId = 0;}
//
// if(id == 1){
// LOGGER.debug("Executing attack for player " + id + " "+ this.command);
// }
//
// switch(this.command){
// case APPROACH:
// game.approach(id, otherId);
// break;
// case ATTACK:
// game.attack(id);
// break;
// case HEAL:
// game.heal(id, 9);
// break;
// case EVADE:
// game.evade(id, otherId);
// case DO_NOTHING:
// game.doNothing(id);
// break;
// case DEFEND:
// game.defend(id);
// break;
// case SELF_DESTRUCT:
// game.selfDestruct(id);
// default:
// game.doNothing(id);
// break;
// }
// }
// }
// Path: src/main/java/gui/scripting/MouseEvents.java
import interpreter.Check;
import interpreter.ScriptCommand;
import interpreter.enumerations.*;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Node;
import javafx.scene.control.Alert;
import javafx.scene.control.TextInputDialog;
import javax.management.InstanceNotFoundException;
import java.util.*;
import java.util.stream.Collectors;
try {
op = getOperator(scriptingObjects.get(i + 1));
} catch (InstanceNotFoundException e) {
e.printStackTrace();
// Should never happen
return null;
}
Check check = new Check(scriptingObjects.get(i),
scriptingObjects.get(i + 2),
op);
checks.add(check);
// increment to end of the check that was located
i = i + 2;
}
}
return checks;
}
private static Operator getOperator(String text) throws InstanceNotFoundException {
for (Operator operator : Operator.values()) {
if (text.trim().equals(operator.text())) {
return operator;
}
}
throw new InstanceNotFoundException();
}
| List<ScriptCommand> getCommands() { |
Rowandjj/yitu | Yitu/src/cn/edu/chd/yitu/SplashActivity.java | // Path: Yitu/src/cn/edu/chd/utils/BitmapUtils.java
// public final class BitmapUtils
// {
// /**
// * ĬÈϲÉÑù±È
// */
// private static final int DEFAULT_SAMPLE_SIZE = 1;
// private static final String TAG = "BitmapUtils";
//
// /**
// * ¸ù¾Ý²ÉÑù±ÈѹËõͼƬ
// */
// public static Bitmap decodeSampledBitmapFromResource(Resources res,int resId,int reqWidth,int reqHeight)
// {
// BitmapFactory.Options opts = new BitmapFactory.Options();
// opts.inJustDecodeBounds = true;
// BitmapFactory.decodeResource(res, resId,opts);
// opts.inSampleSize = caclulateInSampleSize(opts, reqWidth, reqHeight);
// opts.inJustDecodeBounds = false;
// return BitmapFactory.decodeResource(res, resId, opts);
// }
// /**
// * ¸údecodeSampledBitmapFromResource¹¦ÄÜÏàͬ£¬»ñÈ¡bitmapµÄ·½Ê½²»Í¬
// */
// public static Bitmap decodeSampledBitmapFromFile(String pathName,int reqWidth,int reqHeight)
// {
// BitmapFactory.Options opts = new BitmapFactory.Options();
// opts.inJustDecodeBounds = true;
// BitmapFactory.decodeFile(pathName, opts);
// opts.inSampleSize = caclulateInSampleSize(opts, reqWidth, reqHeight);
// opts.inJustDecodeBounds = false;
// Log.i(TAG,"OPTS = "+opts.inSampleSize);
// return BitmapFactory.decodeFile(pathName, opts);
// }
// /**
// * ¸údecodeSampledBitmapFromResource¹¦ÄÜÏàͬ£¬»ñÈ¡bitmapµÄ·½Ê½²»Í¬
// */
// public static Bitmap decodeSampledBitmapFromByteArray(byte[] data,int reqWidth,int reqHeight)
// {
// BitmapFactory.Options opts = new BitmapFactory.Options();
// opts.inJustDecodeBounds = true;
// BitmapFactory.decodeByteArray(data, 0, data.length, opts);
// opts.inSampleSize = caclulateInSampleSize(opts, reqWidth, reqHeight);
// opts.inJustDecodeBounds = false;
// return BitmapFactory.decodeByteArray(data, 0, data.length, opts);
// }
// /**
// * ²»¿ÉÒÔÁ½´Îµ÷ÓÃdecodeStream,µÚ¶þ´Îµ÷ÓÃInptutStreamʱ£¬Ö¸ÕëÒѾָÏòĩβÁË.
// * @return
// */
// public static Bitmap decodeSampledBitmapFromStream(InputStream in,int reqWidth,int reqHeight)
// {
// ByteArrayOutputStream bout = new ByteArrayOutputStream();
// byte[] data = null;
// try
// {
// int len = 0;
// byte[] buf = new byte[1024];
// while((len = in.read(buf)) != -1)
// {
// bout.write(buf, 0, len);
// }
// data = bout.toByteArray();
// } catch (IOException e)
// {
// e.printStackTrace();
// }
// return decodeSampledBitmapFromByteArray(data, reqWidth, reqHeight);
// }
//
//
// /**
// * ¼ÆËã²ÉÑù±È
// */
// private static int caclulateInSampleSize(BitmapFactory.Options opts,int reqWidth,int reqHeight)
// {
// if(opts == null)
// return DEFAULT_SAMPLE_SIZE;
// int width = opts.outWidth;
// int height = opts.outHeight;
// int sampleSize = DEFAULT_SAMPLE_SIZE;
// if(width > reqWidth || height > reqHeight)
// {
// int widthRatio = (int) (width/(float)reqWidth);
// int heightRatio = (int) (height/(float)reqHeight);
//
// sampleSize = (widthRatio > heightRatio) ? heightRatio : widthRatio;
// }
// return sampleSize;
// }
// }
| import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.view.WindowManager;
import android.widget.ImageView;
import cn.edu.chd.utils.BitmapUtils;
| goGuide();
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_splash);
init();
if (isFirstIn())
{
//TODO load data here
handler.sendEmptyMessageDelayed(GO_GUIDE, DELAY_MILLIS);
} else
{
handler.sendEmptyMessageDelayed(GO_HOME, DELAY_MILLIS);
}
}
public void init()
{
WindowManager manager = (WindowManager) this
.getSystemService(Context.WINDOW_SERVICE);
int reqWidth = manager.getDefaultDisplay().getWidth();
int reqHeight = manager.getDefaultDisplay().getHeight();
splash_iv = (ImageView) findViewById(R.id.splash_iv);
| // Path: Yitu/src/cn/edu/chd/utils/BitmapUtils.java
// public final class BitmapUtils
// {
// /**
// * ĬÈϲÉÑù±È
// */
// private static final int DEFAULT_SAMPLE_SIZE = 1;
// private static final String TAG = "BitmapUtils";
//
// /**
// * ¸ù¾Ý²ÉÑù±ÈѹËõͼƬ
// */
// public static Bitmap decodeSampledBitmapFromResource(Resources res,int resId,int reqWidth,int reqHeight)
// {
// BitmapFactory.Options opts = new BitmapFactory.Options();
// opts.inJustDecodeBounds = true;
// BitmapFactory.decodeResource(res, resId,opts);
// opts.inSampleSize = caclulateInSampleSize(opts, reqWidth, reqHeight);
// opts.inJustDecodeBounds = false;
// return BitmapFactory.decodeResource(res, resId, opts);
// }
// /**
// * ¸údecodeSampledBitmapFromResource¹¦ÄÜÏàͬ£¬»ñÈ¡bitmapµÄ·½Ê½²»Í¬
// */
// public static Bitmap decodeSampledBitmapFromFile(String pathName,int reqWidth,int reqHeight)
// {
// BitmapFactory.Options opts = new BitmapFactory.Options();
// opts.inJustDecodeBounds = true;
// BitmapFactory.decodeFile(pathName, opts);
// opts.inSampleSize = caclulateInSampleSize(opts, reqWidth, reqHeight);
// opts.inJustDecodeBounds = false;
// Log.i(TAG,"OPTS = "+opts.inSampleSize);
// return BitmapFactory.decodeFile(pathName, opts);
// }
// /**
// * ¸údecodeSampledBitmapFromResource¹¦ÄÜÏàͬ£¬»ñÈ¡bitmapµÄ·½Ê½²»Í¬
// */
// public static Bitmap decodeSampledBitmapFromByteArray(byte[] data,int reqWidth,int reqHeight)
// {
// BitmapFactory.Options opts = new BitmapFactory.Options();
// opts.inJustDecodeBounds = true;
// BitmapFactory.decodeByteArray(data, 0, data.length, opts);
// opts.inSampleSize = caclulateInSampleSize(opts, reqWidth, reqHeight);
// opts.inJustDecodeBounds = false;
// return BitmapFactory.decodeByteArray(data, 0, data.length, opts);
// }
// /**
// * ²»¿ÉÒÔÁ½´Îµ÷ÓÃdecodeStream,µÚ¶þ´Îµ÷ÓÃInptutStreamʱ£¬Ö¸ÕëÒѾָÏòĩβÁË.
// * @return
// */
// public static Bitmap decodeSampledBitmapFromStream(InputStream in,int reqWidth,int reqHeight)
// {
// ByteArrayOutputStream bout = new ByteArrayOutputStream();
// byte[] data = null;
// try
// {
// int len = 0;
// byte[] buf = new byte[1024];
// while((len = in.read(buf)) != -1)
// {
// bout.write(buf, 0, len);
// }
// data = bout.toByteArray();
// } catch (IOException e)
// {
// e.printStackTrace();
// }
// return decodeSampledBitmapFromByteArray(data, reqWidth, reqHeight);
// }
//
//
// /**
// * ¼ÆËã²ÉÑù±È
// */
// private static int caclulateInSampleSize(BitmapFactory.Options opts,int reqWidth,int reqHeight)
// {
// if(opts == null)
// return DEFAULT_SAMPLE_SIZE;
// int width = opts.outWidth;
// int height = opts.outHeight;
// int sampleSize = DEFAULT_SAMPLE_SIZE;
// if(width > reqWidth || height > reqHeight)
// {
// int widthRatio = (int) (width/(float)reqWidth);
// int heightRatio = (int) (height/(float)reqHeight);
//
// sampleSize = (widthRatio > heightRatio) ? heightRatio : widthRatio;
// }
// return sampleSize;
// }
// }
// Path: Yitu/src/cn/edu/chd/yitu/SplashActivity.java
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.view.WindowManager;
import android.widget.ImageView;
import cn.edu.chd.utils.BitmapUtils;
goGuide();
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_splash);
init();
if (isFirstIn())
{
//TODO load data here
handler.sendEmptyMessageDelayed(GO_GUIDE, DELAY_MILLIS);
} else
{
handler.sendEmptyMessageDelayed(GO_HOME, DELAY_MILLIS);
}
}
public void init()
{
WindowManager manager = (WindowManager) this
.getSystemService(Context.WINDOW_SERVICE);
int reqWidth = manager.getDefaultDisplay().getWidth();
int reqHeight = manager.getDefaultDisplay().getHeight();
splash_iv = (ImageView) findViewById(R.id.splash_iv);
| splash_iv.setImageBitmap(BitmapUtils.decodeSampledBitmapFromResource(
|
NasaGeek/utexas-utilities | app/src/main/java/com/nasageek/utexasutilities/UtdAuthCookie.java | // Path: app/src/main/java/com/nasageek/utexasutilities/UTilitiesApplication.java
// public static final String UTD_AUTH_COOKIE_KEY = "utd_auth_cookie";
| import android.app.Application;
import static com.nasageek.utexasutilities.UTilitiesApplication.UTD_AUTH_COOKIE_KEY; | package com.nasageek.utexasutilities;
/**
* Created by chris on 9/16/14.
*/
public class UtdAuthCookie extends AuthCookie {
public UtdAuthCookie(Application mApp) { | // Path: app/src/main/java/com/nasageek/utexasutilities/UTilitiesApplication.java
// public static final String UTD_AUTH_COOKIE_KEY = "utd_auth_cookie";
// Path: app/src/main/java/com/nasageek/utexasutilities/UtdAuthCookie.java
import android.app.Application;
import static com.nasageek.utexasutilities.UTilitiesApplication.UTD_AUTH_COOKIE_KEY;
package com.nasageek.utexasutilities;
/**
* Created by chris on 9/16/14.
*/
public class UtdAuthCookie extends AuthCookie {
public UtdAuthCookie(Application mApp) { | super(UTD_AUTH_COOKIE_KEY, |
NasaGeek/utexas-utilities | app/src/main/java/com/nasageek/utexasutilities/UTLoginTask.java | // Path: app/src/main/java/com/nasageek/utexasutilities/model/LoadFailedEvent.java
// public class LoadFailedEvent {
// public String tag;
// public CharSequence errorMessage;
//
// public LoadFailedEvent(String tag, CharSequence msg) {
// this.tag = tag;
// errorMessage = msg;
// }
// }
| import com.nasageek.utexasutilities.model.LoadFailedEvent;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import java.io.IOException; | package com.nasageek.utexasutilities;
/**
* Created by chris on 2/7/16.
*/
public abstract class UTLoginTask<Params, Progress, Result> extends
TaggedAsyncTask<Params, Progress, Result> {
protected final OkHttpClient client = UTilitiesApplication.getInstance().getHttpClient();
protected String reqUrl;
protected String errorMsg;
public UTLoginTask(String tag, String reqUrl) {
super(tag);
this.reqUrl = reqUrl;
}
protected String fetchData(Request request) throws IOException, NotAuthenticatedException {
Response response = client.newCall(request).execute();
String pagedata = response.body().string();
// did we hit the login screen?
if (pagedata.contains("<title>UT EID Login</title>")) {
errorMsg = "You've been logged out of UTDirect, back out and log in again.";
UTilitiesApplication mApp = UTilitiesApplication.getInstance();
// if (!recursing) {
// try {
// mApp.getAuthCookie(UTD_AUTH_COOKIE_KEY).logout();
// mApp.getAuthCookie(UTD_AUTH_COOKIE_KEY).login();
// } catch (IOException e) {
// errorMsg = "UTilities could not fetch your class listing";
// cancel(true);
// e.printStackTrace();
// return null;
// } catch (TempLoginException tle) {
// /*
// ooooh boy is this lazy. I'd rather not init SharedPreferences here
// to check if persistent login is on, so we'll just catch the exception
// */
// Intent login = new Intent(mApp, LoginActivity.class);
// login.putExtra("activity", parentAct.getIntent().getComponent()
// .getClassName());
// login.putExtra("service", 'u');
// mApp.startActivity(login);
// parentAct.finish();
// errorMsg = "Session expired, please log in again";
// cancel(true);
// return null;
// }
// return doInBackground(true);
// } else {
mApp.logoutAll();
// }
throw new NotAuthenticatedException();
}
return pagedata;
}
@Override
protected void onCancelled(Result result) {
super.onCancelled(result); | // Path: app/src/main/java/com/nasageek/utexasutilities/model/LoadFailedEvent.java
// public class LoadFailedEvent {
// public String tag;
// public CharSequence errorMessage;
//
// public LoadFailedEvent(String tag, CharSequence msg) {
// this.tag = tag;
// errorMessage = msg;
// }
// }
// Path: app/src/main/java/com/nasageek/utexasutilities/UTLoginTask.java
import com.nasageek.utexasutilities.model.LoadFailedEvent;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import java.io.IOException;
package com.nasageek.utexasutilities;
/**
* Created by chris on 2/7/16.
*/
public abstract class UTLoginTask<Params, Progress, Result> extends
TaggedAsyncTask<Params, Progress, Result> {
protected final OkHttpClient client = UTilitiesApplication.getInstance().getHttpClient();
protected String reqUrl;
protected String errorMsg;
public UTLoginTask(String tag, String reqUrl) {
super(tag);
this.reqUrl = reqUrl;
}
protected String fetchData(Request request) throws IOException, NotAuthenticatedException {
Response response = client.newCall(request).execute();
String pagedata = response.body().string();
// did we hit the login screen?
if (pagedata.contains("<title>UT EID Login</title>")) {
errorMsg = "You've been logged out of UTDirect, back out and log in again.";
UTilitiesApplication mApp = UTilitiesApplication.getInstance();
// if (!recursing) {
// try {
// mApp.getAuthCookie(UTD_AUTH_COOKIE_KEY).logout();
// mApp.getAuthCookie(UTD_AUTH_COOKIE_KEY).login();
// } catch (IOException e) {
// errorMsg = "UTilities could not fetch your class listing";
// cancel(true);
// e.printStackTrace();
// return null;
// } catch (TempLoginException tle) {
// /*
// ooooh boy is this lazy. I'd rather not init SharedPreferences here
// to check if persistent login is on, so we'll just catch the exception
// */
// Intent login = new Intent(mApp, LoginActivity.class);
// login.putExtra("activity", parentAct.getIntent().getComponent()
// .getClassName());
// login.putExtra("service", 'u');
// mApp.startActivity(login);
// parentAct.finish();
// errorMsg = "Session expired, please log in again";
// cancel(true);
// return null;
// }
// return doInBackground(true);
// } else {
mApp.logoutAll();
// }
throw new NotAuthenticatedException();
}
return pagedata;
}
@Override
protected void onCancelled(Result result) {
super.onCancelled(result); | MyBus.getInstance().post(new LoadFailedEvent(getTag(), errorMsg)); |
NasaGeek/utexas-utilities | app/src/debug/java/com/nasageek/utexasutilities/fragments/DataSourceSelectionFragment.java | // Path: app/src/main/java/com/nasageek/utexasutilities/MyBus.java
// public class MyBus {
//
// private static final Bus BUS = new Bus();
//
// public static Bus getInstance() {
// return BUS;
// }
// }
| import android.app.Dialog;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog;
import com.nasageek.utexasutilities.MyBus;
import com.squareup.okhttp.mockwebserver.MockResponse;
import com.squareup.okhttp.mockwebserver.MockWebServer;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import okio.Buffer;
import okio.Okio; | Buffer htmlBuffer = new Buffer();
try {
String[] files = assets.list(filePath);
htmlBuffer.writeAll(Okio.source(assets
.open(filePath + "/" + files[which - 1])));
new Thread(() -> {
mockServer.enqueue(new MockResponse().setBody(htmlBuffer));
// Anything else the client tries to load from us should just fail.
// 20 chosen arbitrarily.
MockResponse badResponse = new MockResponse().setResponseCode(404);
for (int i = 0; i < 20; i++) {
mockServer.enqueue(badResponse);
}
try {
mockServer.start();
} catch (IOException e) {
e.printStackTrace();
}
cdl.countDown();
}).start();
} catch (IOException ioe) {
ioe.printStackTrace();
}
try {
cdl.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
reqUrl = mockServer.url("").toString();
} | // Path: app/src/main/java/com/nasageek/utexasutilities/MyBus.java
// public class MyBus {
//
// private static final Bus BUS = new Bus();
//
// public static Bus getInstance() {
// return BUS;
// }
// }
// Path: app/src/debug/java/com/nasageek/utexasutilities/fragments/DataSourceSelectionFragment.java
import android.app.Dialog;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog;
import com.nasageek.utexasutilities.MyBus;
import com.squareup.okhttp.mockwebserver.MockResponse;
import com.squareup.okhttp.mockwebserver.MockWebServer;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import okio.Buffer;
import okio.Okio;
Buffer htmlBuffer = new Buffer();
try {
String[] files = assets.list(filePath);
htmlBuffer.writeAll(Okio.source(assets
.open(filePath + "/" + files[which - 1])));
new Thread(() -> {
mockServer.enqueue(new MockResponse().setBody(htmlBuffer));
// Anything else the client tries to load from us should just fail.
// 20 chosen arbitrarily.
MockResponse badResponse = new MockResponse().setResponseCode(404);
for (int i = 0; i < 20; i++) {
mockServer.enqueue(badResponse);
}
try {
mockServer.start();
} catch (IOException e) {
e.printStackTrace();
}
cdl.countDown();
}).start();
} catch (IOException ioe) {
ioe.printStackTrace();
}
try {
cdl.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
reqUrl = mockServer.url("").toString();
} | MyBus.getInstance().post(new DataSourceSelectedEvent(reqUrl)); |
NasaGeek/utexas-utilities | app/src/main/java/com/nasageek/utexasutilities/fragments/PickCalendarDialogFragment.java | // Path: app/src/main/java/com/nasageek/utexasutilities/AnalyticsHandler.java
// public class AnalyticsHandler {
//
// private static FirebaseAnalytics analyticsTracker;
//
// private AnalyticsHandler() {
// // do nothing
// }
//
// public static void initTrackerIfNeeded(Context con, boolean enabled) {
// if (analyticsTracker == null) {
// analyticsTracker = FirebaseAnalytics.getInstance(con);
// analyticsTracker.setAnalyticsCollectionEnabled(enabled);
// }
// }
//
// public static void trackLogoutEvent() {
// analyticsTracker.logEvent("logout", null);
// }
//
// public static void trackCalendarExportEvent() {
// analyticsTracker.logEvent("export_calendar", null);
// }
//
// public static void trackMapAllClassesEvent() {
// analyticsTracker.logEvent("map_all_classes", null);
// }
//
// public static void trackGetDirectionsEvent() {
// analyticsTracker.logEvent("get_directions", null);
// }
//
// public static void trackBusRouteEvent() {
// analyticsTracker.logEvent("view_bus_route", null);
// }
// }
| import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.AsyncQueryHandler;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.provider.CalendarContract;
import android.support.annotation.NonNull;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import android.widget.Toast;
import com.nasageek.utexasutilities.AnalyticsHandler;
import com.nasageek.utexasutilities.R;
import java.util.ArrayList; | ArrayList<ContentValues> cvList = getArguments().getParcelableArrayList(
"valuesList");
ArrayList<Integer> indices = getArguments().getIntegerArrayList("indices");
int selection = indices.get(which);
for (int i = 0; i < cvList.size(); i++) {
cvList.get(i).put(CalendarContract.Events.CALENDAR_ID, selection);
cih.startInsert(i, null, CalendarContract.Events.CONTENT_URI, cvList.get(i));
}
})
.setTitle("Select calendar")
.create();
}
// Suppress because handler is very shortlived
@SuppressLint("HandlerLeak")
class CalendarInsertHandler extends AsyncQueryHandler {
public CalendarInsertHandler(ContentResolver cr) {
super(cr);
}
@Override
public void onInsertComplete(int token, Object cookie, Uri uri) {
if (token == getArguments().getParcelableArrayList("valuesList").size() - 1) {
Log.d("CalendarStuff", "insert finished");
Toast.makeText(
parentAct,
"This schedule has been exported successfully. It may take a minute or two "
+ "for it to show up on your calendar.", Toast.LENGTH_LONG).show(); | // Path: app/src/main/java/com/nasageek/utexasutilities/AnalyticsHandler.java
// public class AnalyticsHandler {
//
// private static FirebaseAnalytics analyticsTracker;
//
// private AnalyticsHandler() {
// // do nothing
// }
//
// public static void initTrackerIfNeeded(Context con, boolean enabled) {
// if (analyticsTracker == null) {
// analyticsTracker = FirebaseAnalytics.getInstance(con);
// analyticsTracker.setAnalyticsCollectionEnabled(enabled);
// }
// }
//
// public static void trackLogoutEvent() {
// analyticsTracker.logEvent("logout", null);
// }
//
// public static void trackCalendarExportEvent() {
// analyticsTracker.logEvent("export_calendar", null);
// }
//
// public static void trackMapAllClassesEvent() {
// analyticsTracker.logEvent("map_all_classes", null);
// }
//
// public static void trackGetDirectionsEvent() {
// analyticsTracker.logEvent("get_directions", null);
// }
//
// public static void trackBusRouteEvent() {
// analyticsTracker.logEvent("view_bus_route", null);
// }
// }
// Path: app/src/main/java/com/nasageek/utexasutilities/fragments/PickCalendarDialogFragment.java
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.AsyncQueryHandler;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.provider.CalendarContract;
import android.support.annotation.NonNull;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import android.widget.Toast;
import com.nasageek.utexasutilities.AnalyticsHandler;
import com.nasageek.utexasutilities.R;
import java.util.ArrayList;
ArrayList<ContentValues> cvList = getArguments().getParcelableArrayList(
"valuesList");
ArrayList<Integer> indices = getArguments().getIntegerArrayList("indices");
int selection = indices.get(which);
for (int i = 0; i < cvList.size(); i++) {
cvList.get(i).put(CalendarContract.Events.CALENDAR_ID, selection);
cih.startInsert(i, null, CalendarContract.Events.CONTENT_URI, cvList.get(i));
}
})
.setTitle("Select calendar")
.create();
}
// Suppress because handler is very shortlived
@SuppressLint("HandlerLeak")
class CalendarInsertHandler extends AsyncQueryHandler {
public CalendarInsertHandler(ContentResolver cr) {
super(cr);
}
@Override
public void onInsertComplete(int token, Object cookie, Uri uri) {
if (token == getArguments().getParcelableArrayList("valuesList").size() - 1) {
Log.d("CalendarStuff", "insert finished");
Toast.makeText(
parentAct,
"This schedule has been exported successfully. It may take a minute or two "
+ "for it to show up on your calendar.", Toast.LENGTH_LONG).show(); | AnalyticsHandler.trackCalendarExportEvent(); |
NasaGeek/utexas-utilities | app/src/main/java/com/nasageek/utexasutilities/adapters/ScheduleClassAdapter.java | // Path: app/src/main/java/com/nasageek/utexasutilities/model/UTClass.java
// public class UTClass implements Parcelable, Serializable {
//
// private static final long serialVersionUID = 1L;
//
// private String courseId, unique, name, color;
//
// private ArrayList<Classtime> classtimes;
//
// public static Parcelable.Creator<UTClass> CREATOR = new Parcelable.Creator<UTClass>() {
//
// @Override
// public UTClass createFromParcel(Parcel source) {
// return new UTClass(source);
// }
//
// @Override
// public UTClass[] newArray(int size) {
// return new UTClass[size];
// }
//
// };
//
// private UTClass(Parcel in) {
// unique = in.readString();
// courseId = in.readString();
// name = in.readString();
//
// classtimes = new ArrayList<>();
// in.readTypedList(classtimes, Classtime.CREATOR);
// color = in.readString();
// }
//
// public UTClass(String unique, String courseId, String name, String[] buildingIds,
// String[] buildingRooms, String[] days, String[] times, String color) {
// this.unique = unique;
// this.courseId = courseId;
// this.name = name.replace("&", "&");
// this.color = color;
//
// if (buildingIds.length != buildingRooms.length) {
// Log.e("UTClass creation", "building/room size inconsistency: b" + buildingIds.length
// + " r" + buildingRooms.length);
// }
//
// ArrayList<Building> buildings = new ArrayList<>();
// for (int i = 0; i < buildingIds.length; i++) {
// // If there are fewer rooms than buildings, just don't give rooms to later buildings.
// // I suspect a blank room indicates an error/oversight on the class listing, so
// // hopefully it's not an issue that will occur frequently
// if (i < buildingRooms.length) {
// buildings.add(new Building(buildingIds[i], buildingRooms[i]));
// } else {
// buildings.add(new Building(buildingIds[i], ""));
// }
// }
//
// /* Class Listing page leaves out building info if there are multiple sections in the same
// location at different times. See Chris Roberts Fall 2014 Class Listing. Here we check
// to see if location info was absent from a row.
// */
// if (buildings.size() < days.length) {
// buildings.add(new Building(buildings.get(0)));
// }
//
// classtimes = new ArrayList<>();
// if (!(days.length == times.length && days.length == buildings.size() && buildings.size() == times.length)) {
// Log.e("UTClass creation", "building/day/time size inconsistency: b" + buildings.size()
// + " d" + days.length + " t" + times.length);
// }
// for (int i = 0; i < days.length && i < times.length && i < buildings.size(); i++) {
// String[] dayArray = days[i].split("");
//
// for (int k = 1; k < dayArray.length; k++) {
// classtimes.add(new Classtime(dayArray[k], times[i], buildings.get(i), this.color,
// this.courseId, this.name, this.unique));
// }
// }
// }
//
// @Override
// public String toString() {
// String out = courseId + " in ";
// for (int i = 0; i < classtimes.size(); i++) {
// Classtime classtime = classtimes.get(i);
//
// out += classtime.getBuilding().getId() + " in room "
// + classtime.getBuilding().getRoom() + " at "
// + classtime.getStartTime() + "-" + classtime.getEndTime()
// + " on " + classtime.getDay();
// if (i != classtimes.size() - 1) {
// out += " and in ";
// }
// }
// return out;
// }
//
// public ArrayList<Classtime> getClassTimes() {
// return classtimes;
// }
//
// public String getName() {
// return name;
// }
//
// public String getId() {
// return courseId;
// }
//
// public String getUnique() {
// return unique;
// }
//
// public String getColor() {
// return color;
// }
//
// @Override
// public int describeContents() {
// return 0;
// }
//
// @Override
// public void writeToParcel(Parcel out, int flags) {
// out.writeString(unique);
// out.writeString(courseId);
// out.writeString(name);
// out.writeTypedList(classtimes);
// out.writeString(color);
// }
// }
| import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.BlurMaskFilter;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.Shape;
import android.preference.PreferenceManager;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.nasageek.utexasutilities.model.Classtime;
import com.nasageek.utexasutilities.model.UTClass;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map; |
package com.nasageek.utexasutilities.adapters;
public class ScheduleClassAdapter extends BaseAdapter {
// contains the Classtimes that have been ordered/grouped into a fake "grid"
private List<Classtime> orderedClasstimes = new ArrayList<>(180);
// element is true if it's the first cell of a class in the schedule (cells are a half hour)
private List<Boolean> firstlist = new ArrayList<>(180);
private Context mContext;
private int currentTimePos = -1;
private int currMinutes;
private String emptyCellBackgroundPref;
private static final int DARKGRAY = 0xFFCECECE;
private static final int LIGHTGRAY = 0xFFDCDCDC;
| // Path: app/src/main/java/com/nasageek/utexasutilities/model/UTClass.java
// public class UTClass implements Parcelable, Serializable {
//
// private static final long serialVersionUID = 1L;
//
// private String courseId, unique, name, color;
//
// private ArrayList<Classtime> classtimes;
//
// public static Parcelable.Creator<UTClass> CREATOR = new Parcelable.Creator<UTClass>() {
//
// @Override
// public UTClass createFromParcel(Parcel source) {
// return new UTClass(source);
// }
//
// @Override
// public UTClass[] newArray(int size) {
// return new UTClass[size];
// }
//
// };
//
// private UTClass(Parcel in) {
// unique = in.readString();
// courseId = in.readString();
// name = in.readString();
//
// classtimes = new ArrayList<>();
// in.readTypedList(classtimes, Classtime.CREATOR);
// color = in.readString();
// }
//
// public UTClass(String unique, String courseId, String name, String[] buildingIds,
// String[] buildingRooms, String[] days, String[] times, String color) {
// this.unique = unique;
// this.courseId = courseId;
// this.name = name.replace("&", "&");
// this.color = color;
//
// if (buildingIds.length != buildingRooms.length) {
// Log.e("UTClass creation", "building/room size inconsistency: b" + buildingIds.length
// + " r" + buildingRooms.length);
// }
//
// ArrayList<Building> buildings = new ArrayList<>();
// for (int i = 0; i < buildingIds.length; i++) {
// // If there are fewer rooms than buildings, just don't give rooms to later buildings.
// // I suspect a blank room indicates an error/oversight on the class listing, so
// // hopefully it's not an issue that will occur frequently
// if (i < buildingRooms.length) {
// buildings.add(new Building(buildingIds[i], buildingRooms[i]));
// } else {
// buildings.add(new Building(buildingIds[i], ""));
// }
// }
//
// /* Class Listing page leaves out building info if there are multiple sections in the same
// location at different times. See Chris Roberts Fall 2014 Class Listing. Here we check
// to see if location info was absent from a row.
// */
// if (buildings.size() < days.length) {
// buildings.add(new Building(buildings.get(0)));
// }
//
// classtimes = new ArrayList<>();
// if (!(days.length == times.length && days.length == buildings.size() && buildings.size() == times.length)) {
// Log.e("UTClass creation", "building/day/time size inconsistency: b" + buildings.size()
// + " d" + days.length + " t" + times.length);
// }
// for (int i = 0; i < days.length && i < times.length && i < buildings.size(); i++) {
// String[] dayArray = days[i].split("");
//
// for (int k = 1; k < dayArray.length; k++) {
// classtimes.add(new Classtime(dayArray[k], times[i], buildings.get(i), this.color,
// this.courseId, this.name, this.unique));
// }
// }
// }
//
// @Override
// public String toString() {
// String out = courseId + " in ";
// for (int i = 0; i < classtimes.size(); i++) {
// Classtime classtime = classtimes.get(i);
//
// out += classtime.getBuilding().getId() + " in room "
// + classtime.getBuilding().getRoom() + " at "
// + classtime.getStartTime() + "-" + classtime.getEndTime()
// + " on " + classtime.getDay();
// if (i != classtimes.size() - 1) {
// out += " and in ";
// }
// }
// return out;
// }
//
// public ArrayList<Classtime> getClassTimes() {
// return classtimes;
// }
//
// public String getName() {
// return name;
// }
//
// public String getId() {
// return courseId;
// }
//
// public String getUnique() {
// return unique;
// }
//
// public String getColor() {
// return color;
// }
//
// @Override
// public int describeContents() {
// return 0;
// }
//
// @Override
// public void writeToParcel(Parcel out, int flags) {
// out.writeString(unique);
// out.writeString(courseId);
// out.writeString(name);
// out.writeTypedList(classtimes);
// out.writeString(color);
// }
// }
// Path: app/src/main/java/com/nasageek/utexasutilities/adapters/ScheduleClassAdapter.java
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.BlurMaskFilter;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.Shape;
import android.preference.PreferenceManager;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.nasageek.utexasutilities.model.Classtime;
import com.nasageek.utexasutilities.model.UTClass;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
package com.nasageek.utexasutilities.adapters;
public class ScheduleClassAdapter extends BaseAdapter {
// contains the Classtimes that have been ordered/grouped into a fake "grid"
private List<Classtime> orderedClasstimes = new ArrayList<>(180);
// element is true if it's the first cell of a class in the schedule (cells are a half hour)
private List<Boolean> firstlist = new ArrayList<>(180);
private Context mContext;
private int currentTimePos = -1;
private int currMinutes;
private String emptyCellBackgroundPref;
private static final int DARKGRAY = 0xFFCECECE;
private static final int LIGHTGRAY = 0xFFDCDCDC;
| public ScheduleClassAdapter(Context c, List<UTClass> classList) { |
NasaGeek/utexas-utilities | app/src/main/java/com/nasageek/utexasutilities/activities/LoginActivity.java | // Path: app/src/main/java/com/nasageek/utexasutilities/LoginWebViewClient.java
// public class LoginWebViewClient extends WebViewClient {
//
// private Activity activity;
// private String nextActivity;
//
// public LoginWebViewClient(Activity activity, String nextActivity) {
// super();
// this.activity = activity;
// this.nextActivity = nextActivity;
// }
//
// @Override
// public boolean shouldOverrideUrlLoading(WebView view, String url) {
// return false;
// }
//
// @Override
// public void onPageFinished(WebView view, String url) {
// super.onPageFinished(view, url);
// String authCookie = "";
// if (url.contains("utexas.edu")) {
// String cookies = CookieManager.getInstance().getCookie("https://login.utexas.edu");
// if (cookies != null) {
// for (String s : cookies.split("; ")) {
// if (s.startsWith("utlogin-prod=")) {
// authCookie = s.substring(13);
// break;
// }
// }
// }
// if (!authCookie.equals("")
// && url.equals("https://www.utexas.edu/")) {
// UTilitiesApplication.getInstance().getAuthCookie(UTD_AUTH_COOKIE_KEY).setAuthCookieVal(authCookie);
// continueToActivity("UTLogin");
// }
// }
// }
//
// private void continueToActivity(String service) {
// Intent intent;
// try {
// intent = new Intent(activity, Class.forName(nextActivity));
// Toast.makeText(activity, "You're now logged in to " + service, Toast.LENGTH_SHORT)
// .show();
// } catch (ClassNotFoundException e) {
// e.printStackTrace();
// intent = new Intent(activity, UTilitiesActivity.class);
// intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Toast.makeText(activity, "Your attempt to log in went terribly wrong",
// Toast.LENGTH_SHORT).show();
// }
// activity.startActivity(intent);
// CookieManager.getInstance().removeAllCookie();
// activity.finish();
// }
// }
| import android.os.Bundle;
import android.webkit.CookieSyncManager;
import android.webkit.WebView;
import com.nasageek.utexasutilities.LoginWebViewClient; |
package com.nasageek.utexasutilities.activities;
public class LoginActivity extends BaseActivity {
private WebView webView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setupActionBar();
webView = new WebView(this);
| // Path: app/src/main/java/com/nasageek/utexasutilities/LoginWebViewClient.java
// public class LoginWebViewClient extends WebViewClient {
//
// private Activity activity;
// private String nextActivity;
//
// public LoginWebViewClient(Activity activity, String nextActivity) {
// super();
// this.activity = activity;
// this.nextActivity = nextActivity;
// }
//
// @Override
// public boolean shouldOverrideUrlLoading(WebView view, String url) {
// return false;
// }
//
// @Override
// public void onPageFinished(WebView view, String url) {
// super.onPageFinished(view, url);
// String authCookie = "";
// if (url.contains("utexas.edu")) {
// String cookies = CookieManager.getInstance().getCookie("https://login.utexas.edu");
// if (cookies != null) {
// for (String s : cookies.split("; ")) {
// if (s.startsWith("utlogin-prod=")) {
// authCookie = s.substring(13);
// break;
// }
// }
// }
// if (!authCookie.equals("")
// && url.equals("https://www.utexas.edu/")) {
// UTilitiesApplication.getInstance().getAuthCookie(UTD_AUTH_COOKIE_KEY).setAuthCookieVal(authCookie);
// continueToActivity("UTLogin");
// }
// }
// }
//
// private void continueToActivity(String service) {
// Intent intent;
// try {
// intent = new Intent(activity, Class.forName(nextActivity));
// Toast.makeText(activity, "You're now logged in to " + service, Toast.LENGTH_SHORT)
// .show();
// } catch (ClassNotFoundException e) {
// e.printStackTrace();
// intent = new Intent(activity, UTilitiesActivity.class);
// intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Toast.makeText(activity, "Your attempt to log in went terribly wrong",
// Toast.LENGTH_SHORT).show();
// }
// activity.startActivity(intent);
// CookieManager.getInstance().removeAllCookie();
// activity.finish();
// }
// }
// Path: app/src/main/java/com/nasageek/utexasutilities/activities/LoginActivity.java
import android.os.Bundle;
import android.webkit.CookieSyncManager;
import android.webkit.WebView;
import com.nasageek.utexasutilities.LoginWebViewClient;
package com.nasageek.utexasutilities.activities;
public class LoginActivity extends BaseActivity {
private WebView webView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setupActionBar();
webView = new WebView(this);
| LoginWebViewClient wvlc = new LoginWebViewClient(this, getIntent().getStringExtra( |
mlaccetti/JavaPNS | src/main/java/javapns/notification/PayloadPerDevice.java | // Path: src/main/java/javapns/devices/Device.java
// public interface Device {
// /**
// * An id representing a particular device.
// * <p>
// * Note that this is a local reference to the device,
// * which is not related to the actual device UUID or
// * other device-specific identification. Most of the
// * time, this deviceId should be the same as the token.
// *
// * @return the device id
// */
// String getDeviceId();
//
// /**
// * An id representing a particular device.
// * <p>
// * Note that this is a local reference to the device,
// * which is not related to the actual device UUID or
// * other device-specific identification. Most of the
// * time, this deviceId should be the same as the token.
// *
// * @param id the device id
// */
// void setDeviceId(String id);
//
// /**
// * A device token.
// *
// * @return the device token
// */
// String getToken();
//
// /**
// * Set the device token
// *
// * @param token
// */
// void setToken(String token);
//
// /**
// * @return the last register
// */
// Timestamp getLastRegister();
//
// /**
// * @param lastRegister the last register
// */
// void setLastRegister(Timestamp lastRegister);
// }
//
// Path: src/main/java/javapns/devices/exceptions/InvalidDeviceTokenFormatException.java
// public class InvalidDeviceTokenFormatException extends Exception {
//
// private static final long serialVersionUID = -8571997399252125457L;
//
// public InvalidDeviceTokenFormatException(final String message) {
// super(message);
// }
//
// public InvalidDeviceTokenFormatException(final String token, final String problem) {
// super(String.format("Device token cannot be parsed, most likely because it contains invalid hexadecimal characters: %s in %s", problem, token));
// }
//
// }
//
// Path: src/main/java/javapns/devices/implementations/basic/BasicDevice.java
// public class BasicDevice implements Device {
//
// /*
// * An id representing a particular device.
// *
// * Note that this is a local reference to the device,
// * which is not related to the actual device UUID or
// * other device-specific identification. Most of the
// * time, this deviceId should be the same as the token.
// */
// private String deviceId;
//
// /* The device token given by Apple Server, hexadecimal form, 64bits length */
// private String token;
//
// /* The last time a device registered */
// private Timestamp lastRegister;
//
// public BasicDevice() {
// // empty
// }
//
// /**
// * Default constructor.
// *
// * @param token The device token
// */
// public BasicDevice(final String token) throws InvalidDeviceTokenFormatException {
// this(token, true);
// }
//
// private BasicDevice(final String token, final boolean validate) throws InvalidDeviceTokenFormatException {
// super();
// this.deviceId = token;
// this.token = token;
// try {
// this.lastRegister = new Timestamp(System.currentTimeMillis());
// } catch (final Exception e) {
// // empty
// }
//
// if (validate) {
// validateTokenFormat(token);
// }
// }
//
// /**
// * Constructor
// *
// * @param id The device id
// * @param token The device token
// */
// BasicDevice(final String id, final String token, final Timestamp register) throws InvalidDeviceTokenFormatException {
// super();
// this.deviceId = id;
// this.token = token;
// this.lastRegister = register;
//
// validateTokenFormat(token);
//
// }
//
// public static void validateTokenFormat(final String token) throws InvalidDeviceTokenFormatException {
// if (token == null) {
// throw new InvalidDeviceTokenFormatException("Device Token is null, and not the required 64 bytes...");
// }
//
// if (token.getBytes().length != 64) {
// throw new InvalidDeviceTokenFormatException("Device Token has a length of [" + token.getBytes().length + "] and not the required 64 bytes!");
// }
// }
//
// public void validateTokenFormat() throws InvalidDeviceTokenFormatException {
// validateTokenFormat(token);
// }
//
// /**
// * Getter
// *
// * @return the device id
// */
// public String getDeviceId() {
// return deviceId;
// }
//
// /**
// * Setter
// *
// * @param id the device id
// */
// public void setDeviceId(final String id) {
// this.deviceId = id;
// }
//
// /**
// * Getter
// *
// * @return the device token
// */
// public String getToken() {
// return token;
// }
//
// /**
// * Setter the device token
// *
// * @param token
// */
// public void setToken(final String token) {
// this.token = token;
// }
//
// /**
// * Getter
// *
// * @return the last register
// */
// public Timestamp getLastRegister() {
// return lastRegister;
// }
//
// public void setLastRegister(final Timestamp lastRegister) {
// this.lastRegister = lastRegister;
// }
// }
| import javapns.devices.Device;
import javapns.devices.exceptions.InvalidDeviceTokenFormatException;
import javapns.devices.implementations.basic.BasicDevice; | package javapns.notification;
/**
* A one-to-one link between a payload and device.
* Provides support for a typical payload-per-device scenario.
*
* @author Sylvain Pedneault
*/
public class PayloadPerDevice {
private final Payload payload; | // Path: src/main/java/javapns/devices/Device.java
// public interface Device {
// /**
// * An id representing a particular device.
// * <p>
// * Note that this is a local reference to the device,
// * which is not related to the actual device UUID or
// * other device-specific identification. Most of the
// * time, this deviceId should be the same as the token.
// *
// * @return the device id
// */
// String getDeviceId();
//
// /**
// * An id representing a particular device.
// * <p>
// * Note that this is a local reference to the device,
// * which is not related to the actual device UUID or
// * other device-specific identification. Most of the
// * time, this deviceId should be the same as the token.
// *
// * @param id the device id
// */
// void setDeviceId(String id);
//
// /**
// * A device token.
// *
// * @return the device token
// */
// String getToken();
//
// /**
// * Set the device token
// *
// * @param token
// */
// void setToken(String token);
//
// /**
// * @return the last register
// */
// Timestamp getLastRegister();
//
// /**
// * @param lastRegister the last register
// */
// void setLastRegister(Timestamp lastRegister);
// }
//
// Path: src/main/java/javapns/devices/exceptions/InvalidDeviceTokenFormatException.java
// public class InvalidDeviceTokenFormatException extends Exception {
//
// private static final long serialVersionUID = -8571997399252125457L;
//
// public InvalidDeviceTokenFormatException(final String message) {
// super(message);
// }
//
// public InvalidDeviceTokenFormatException(final String token, final String problem) {
// super(String.format("Device token cannot be parsed, most likely because it contains invalid hexadecimal characters: %s in %s", problem, token));
// }
//
// }
//
// Path: src/main/java/javapns/devices/implementations/basic/BasicDevice.java
// public class BasicDevice implements Device {
//
// /*
// * An id representing a particular device.
// *
// * Note that this is a local reference to the device,
// * which is not related to the actual device UUID or
// * other device-specific identification. Most of the
// * time, this deviceId should be the same as the token.
// */
// private String deviceId;
//
// /* The device token given by Apple Server, hexadecimal form, 64bits length */
// private String token;
//
// /* The last time a device registered */
// private Timestamp lastRegister;
//
// public BasicDevice() {
// // empty
// }
//
// /**
// * Default constructor.
// *
// * @param token The device token
// */
// public BasicDevice(final String token) throws InvalidDeviceTokenFormatException {
// this(token, true);
// }
//
// private BasicDevice(final String token, final boolean validate) throws InvalidDeviceTokenFormatException {
// super();
// this.deviceId = token;
// this.token = token;
// try {
// this.lastRegister = new Timestamp(System.currentTimeMillis());
// } catch (final Exception e) {
// // empty
// }
//
// if (validate) {
// validateTokenFormat(token);
// }
// }
//
// /**
// * Constructor
// *
// * @param id The device id
// * @param token The device token
// */
// BasicDevice(final String id, final String token, final Timestamp register) throws InvalidDeviceTokenFormatException {
// super();
// this.deviceId = id;
// this.token = token;
// this.lastRegister = register;
//
// validateTokenFormat(token);
//
// }
//
// public static void validateTokenFormat(final String token) throws InvalidDeviceTokenFormatException {
// if (token == null) {
// throw new InvalidDeviceTokenFormatException("Device Token is null, and not the required 64 bytes...");
// }
//
// if (token.getBytes().length != 64) {
// throw new InvalidDeviceTokenFormatException("Device Token has a length of [" + token.getBytes().length + "] and not the required 64 bytes!");
// }
// }
//
// public void validateTokenFormat() throws InvalidDeviceTokenFormatException {
// validateTokenFormat(token);
// }
//
// /**
// * Getter
// *
// * @return the device id
// */
// public String getDeviceId() {
// return deviceId;
// }
//
// /**
// * Setter
// *
// * @param id the device id
// */
// public void setDeviceId(final String id) {
// this.deviceId = id;
// }
//
// /**
// * Getter
// *
// * @return the device token
// */
// public String getToken() {
// return token;
// }
//
// /**
// * Setter the device token
// *
// * @param token
// */
// public void setToken(final String token) {
// this.token = token;
// }
//
// /**
// * Getter
// *
// * @return the last register
// */
// public Timestamp getLastRegister() {
// return lastRegister;
// }
//
// public void setLastRegister(final Timestamp lastRegister) {
// this.lastRegister = lastRegister;
// }
// }
// Path: src/main/java/javapns/notification/PayloadPerDevice.java
import javapns.devices.Device;
import javapns.devices.exceptions.InvalidDeviceTokenFormatException;
import javapns.devices.implementations.basic.BasicDevice;
package javapns.notification;
/**
* A one-to-one link between a payload and device.
* Provides support for a typical payload-per-device scenario.
*
* @author Sylvain Pedneault
*/
public class PayloadPerDevice {
private final Payload payload; | private final Device device; |
mlaccetti/JavaPNS | src/main/java/javapns/notification/PayloadPerDevice.java | // Path: src/main/java/javapns/devices/Device.java
// public interface Device {
// /**
// * An id representing a particular device.
// * <p>
// * Note that this is a local reference to the device,
// * which is not related to the actual device UUID or
// * other device-specific identification. Most of the
// * time, this deviceId should be the same as the token.
// *
// * @return the device id
// */
// String getDeviceId();
//
// /**
// * An id representing a particular device.
// * <p>
// * Note that this is a local reference to the device,
// * which is not related to the actual device UUID or
// * other device-specific identification. Most of the
// * time, this deviceId should be the same as the token.
// *
// * @param id the device id
// */
// void setDeviceId(String id);
//
// /**
// * A device token.
// *
// * @return the device token
// */
// String getToken();
//
// /**
// * Set the device token
// *
// * @param token
// */
// void setToken(String token);
//
// /**
// * @return the last register
// */
// Timestamp getLastRegister();
//
// /**
// * @param lastRegister the last register
// */
// void setLastRegister(Timestamp lastRegister);
// }
//
// Path: src/main/java/javapns/devices/exceptions/InvalidDeviceTokenFormatException.java
// public class InvalidDeviceTokenFormatException extends Exception {
//
// private static final long serialVersionUID = -8571997399252125457L;
//
// public InvalidDeviceTokenFormatException(final String message) {
// super(message);
// }
//
// public InvalidDeviceTokenFormatException(final String token, final String problem) {
// super(String.format("Device token cannot be parsed, most likely because it contains invalid hexadecimal characters: %s in %s", problem, token));
// }
//
// }
//
// Path: src/main/java/javapns/devices/implementations/basic/BasicDevice.java
// public class BasicDevice implements Device {
//
// /*
// * An id representing a particular device.
// *
// * Note that this is a local reference to the device,
// * which is not related to the actual device UUID or
// * other device-specific identification. Most of the
// * time, this deviceId should be the same as the token.
// */
// private String deviceId;
//
// /* The device token given by Apple Server, hexadecimal form, 64bits length */
// private String token;
//
// /* The last time a device registered */
// private Timestamp lastRegister;
//
// public BasicDevice() {
// // empty
// }
//
// /**
// * Default constructor.
// *
// * @param token The device token
// */
// public BasicDevice(final String token) throws InvalidDeviceTokenFormatException {
// this(token, true);
// }
//
// private BasicDevice(final String token, final boolean validate) throws InvalidDeviceTokenFormatException {
// super();
// this.deviceId = token;
// this.token = token;
// try {
// this.lastRegister = new Timestamp(System.currentTimeMillis());
// } catch (final Exception e) {
// // empty
// }
//
// if (validate) {
// validateTokenFormat(token);
// }
// }
//
// /**
// * Constructor
// *
// * @param id The device id
// * @param token The device token
// */
// BasicDevice(final String id, final String token, final Timestamp register) throws InvalidDeviceTokenFormatException {
// super();
// this.deviceId = id;
// this.token = token;
// this.lastRegister = register;
//
// validateTokenFormat(token);
//
// }
//
// public static void validateTokenFormat(final String token) throws InvalidDeviceTokenFormatException {
// if (token == null) {
// throw new InvalidDeviceTokenFormatException("Device Token is null, and not the required 64 bytes...");
// }
//
// if (token.getBytes().length != 64) {
// throw new InvalidDeviceTokenFormatException("Device Token has a length of [" + token.getBytes().length + "] and not the required 64 bytes!");
// }
// }
//
// public void validateTokenFormat() throws InvalidDeviceTokenFormatException {
// validateTokenFormat(token);
// }
//
// /**
// * Getter
// *
// * @return the device id
// */
// public String getDeviceId() {
// return deviceId;
// }
//
// /**
// * Setter
// *
// * @param id the device id
// */
// public void setDeviceId(final String id) {
// this.deviceId = id;
// }
//
// /**
// * Getter
// *
// * @return the device token
// */
// public String getToken() {
// return token;
// }
//
// /**
// * Setter the device token
// *
// * @param token
// */
// public void setToken(final String token) {
// this.token = token;
// }
//
// /**
// * Getter
// *
// * @return the last register
// */
// public Timestamp getLastRegister() {
// return lastRegister;
// }
//
// public void setLastRegister(final Timestamp lastRegister) {
// this.lastRegister = lastRegister;
// }
// }
| import javapns.devices.Device;
import javapns.devices.exceptions.InvalidDeviceTokenFormatException;
import javapns.devices.implementations.basic.BasicDevice; | package javapns.notification;
/**
* A one-to-one link between a payload and device.
* Provides support for a typical payload-per-device scenario.
*
* @author Sylvain Pedneault
*/
public class PayloadPerDevice {
private final Payload payload;
private final Device device;
| // Path: src/main/java/javapns/devices/Device.java
// public interface Device {
// /**
// * An id representing a particular device.
// * <p>
// * Note that this is a local reference to the device,
// * which is not related to the actual device UUID or
// * other device-specific identification. Most of the
// * time, this deviceId should be the same as the token.
// *
// * @return the device id
// */
// String getDeviceId();
//
// /**
// * An id representing a particular device.
// * <p>
// * Note that this is a local reference to the device,
// * which is not related to the actual device UUID or
// * other device-specific identification. Most of the
// * time, this deviceId should be the same as the token.
// *
// * @param id the device id
// */
// void setDeviceId(String id);
//
// /**
// * A device token.
// *
// * @return the device token
// */
// String getToken();
//
// /**
// * Set the device token
// *
// * @param token
// */
// void setToken(String token);
//
// /**
// * @return the last register
// */
// Timestamp getLastRegister();
//
// /**
// * @param lastRegister the last register
// */
// void setLastRegister(Timestamp lastRegister);
// }
//
// Path: src/main/java/javapns/devices/exceptions/InvalidDeviceTokenFormatException.java
// public class InvalidDeviceTokenFormatException extends Exception {
//
// private static final long serialVersionUID = -8571997399252125457L;
//
// public InvalidDeviceTokenFormatException(final String message) {
// super(message);
// }
//
// public InvalidDeviceTokenFormatException(final String token, final String problem) {
// super(String.format("Device token cannot be parsed, most likely because it contains invalid hexadecimal characters: %s in %s", problem, token));
// }
//
// }
//
// Path: src/main/java/javapns/devices/implementations/basic/BasicDevice.java
// public class BasicDevice implements Device {
//
// /*
// * An id representing a particular device.
// *
// * Note that this is a local reference to the device,
// * which is not related to the actual device UUID or
// * other device-specific identification. Most of the
// * time, this deviceId should be the same as the token.
// */
// private String deviceId;
//
// /* The device token given by Apple Server, hexadecimal form, 64bits length */
// private String token;
//
// /* The last time a device registered */
// private Timestamp lastRegister;
//
// public BasicDevice() {
// // empty
// }
//
// /**
// * Default constructor.
// *
// * @param token The device token
// */
// public BasicDevice(final String token) throws InvalidDeviceTokenFormatException {
// this(token, true);
// }
//
// private BasicDevice(final String token, final boolean validate) throws InvalidDeviceTokenFormatException {
// super();
// this.deviceId = token;
// this.token = token;
// try {
// this.lastRegister = new Timestamp(System.currentTimeMillis());
// } catch (final Exception e) {
// // empty
// }
//
// if (validate) {
// validateTokenFormat(token);
// }
// }
//
// /**
// * Constructor
// *
// * @param id The device id
// * @param token The device token
// */
// BasicDevice(final String id, final String token, final Timestamp register) throws InvalidDeviceTokenFormatException {
// super();
// this.deviceId = id;
// this.token = token;
// this.lastRegister = register;
//
// validateTokenFormat(token);
//
// }
//
// public static void validateTokenFormat(final String token) throws InvalidDeviceTokenFormatException {
// if (token == null) {
// throw new InvalidDeviceTokenFormatException("Device Token is null, and not the required 64 bytes...");
// }
//
// if (token.getBytes().length != 64) {
// throw new InvalidDeviceTokenFormatException("Device Token has a length of [" + token.getBytes().length + "] and not the required 64 bytes!");
// }
// }
//
// public void validateTokenFormat() throws InvalidDeviceTokenFormatException {
// validateTokenFormat(token);
// }
//
// /**
// * Getter
// *
// * @return the device id
// */
// public String getDeviceId() {
// return deviceId;
// }
//
// /**
// * Setter
// *
// * @param id the device id
// */
// public void setDeviceId(final String id) {
// this.deviceId = id;
// }
//
// /**
// * Getter
// *
// * @return the device token
// */
// public String getToken() {
// return token;
// }
//
// /**
// * Setter the device token
// *
// * @param token
// */
// public void setToken(final String token) {
// this.token = token;
// }
//
// /**
// * Getter
// *
// * @return the last register
// */
// public Timestamp getLastRegister() {
// return lastRegister;
// }
//
// public void setLastRegister(final Timestamp lastRegister) {
// this.lastRegister = lastRegister;
// }
// }
// Path: src/main/java/javapns/notification/PayloadPerDevice.java
import javapns.devices.Device;
import javapns.devices.exceptions.InvalidDeviceTokenFormatException;
import javapns.devices.implementations.basic.BasicDevice;
package javapns.notification;
/**
* A one-to-one link between a payload and device.
* Provides support for a typical payload-per-device scenario.
*
* @author Sylvain Pedneault
*/
public class PayloadPerDevice {
private final Payload payload;
private final Device device;
| public PayloadPerDevice(final Payload payload, final String token) throws InvalidDeviceTokenFormatException { |
mlaccetti/JavaPNS | src/main/java/javapns/notification/PayloadPerDevice.java | // Path: src/main/java/javapns/devices/Device.java
// public interface Device {
// /**
// * An id representing a particular device.
// * <p>
// * Note that this is a local reference to the device,
// * which is not related to the actual device UUID or
// * other device-specific identification. Most of the
// * time, this deviceId should be the same as the token.
// *
// * @return the device id
// */
// String getDeviceId();
//
// /**
// * An id representing a particular device.
// * <p>
// * Note that this is a local reference to the device,
// * which is not related to the actual device UUID or
// * other device-specific identification. Most of the
// * time, this deviceId should be the same as the token.
// *
// * @param id the device id
// */
// void setDeviceId(String id);
//
// /**
// * A device token.
// *
// * @return the device token
// */
// String getToken();
//
// /**
// * Set the device token
// *
// * @param token
// */
// void setToken(String token);
//
// /**
// * @return the last register
// */
// Timestamp getLastRegister();
//
// /**
// * @param lastRegister the last register
// */
// void setLastRegister(Timestamp lastRegister);
// }
//
// Path: src/main/java/javapns/devices/exceptions/InvalidDeviceTokenFormatException.java
// public class InvalidDeviceTokenFormatException extends Exception {
//
// private static final long serialVersionUID = -8571997399252125457L;
//
// public InvalidDeviceTokenFormatException(final String message) {
// super(message);
// }
//
// public InvalidDeviceTokenFormatException(final String token, final String problem) {
// super(String.format("Device token cannot be parsed, most likely because it contains invalid hexadecimal characters: %s in %s", problem, token));
// }
//
// }
//
// Path: src/main/java/javapns/devices/implementations/basic/BasicDevice.java
// public class BasicDevice implements Device {
//
// /*
// * An id representing a particular device.
// *
// * Note that this is a local reference to the device,
// * which is not related to the actual device UUID or
// * other device-specific identification. Most of the
// * time, this deviceId should be the same as the token.
// */
// private String deviceId;
//
// /* The device token given by Apple Server, hexadecimal form, 64bits length */
// private String token;
//
// /* The last time a device registered */
// private Timestamp lastRegister;
//
// public BasicDevice() {
// // empty
// }
//
// /**
// * Default constructor.
// *
// * @param token The device token
// */
// public BasicDevice(final String token) throws InvalidDeviceTokenFormatException {
// this(token, true);
// }
//
// private BasicDevice(final String token, final boolean validate) throws InvalidDeviceTokenFormatException {
// super();
// this.deviceId = token;
// this.token = token;
// try {
// this.lastRegister = new Timestamp(System.currentTimeMillis());
// } catch (final Exception e) {
// // empty
// }
//
// if (validate) {
// validateTokenFormat(token);
// }
// }
//
// /**
// * Constructor
// *
// * @param id The device id
// * @param token The device token
// */
// BasicDevice(final String id, final String token, final Timestamp register) throws InvalidDeviceTokenFormatException {
// super();
// this.deviceId = id;
// this.token = token;
// this.lastRegister = register;
//
// validateTokenFormat(token);
//
// }
//
// public static void validateTokenFormat(final String token) throws InvalidDeviceTokenFormatException {
// if (token == null) {
// throw new InvalidDeviceTokenFormatException("Device Token is null, and not the required 64 bytes...");
// }
//
// if (token.getBytes().length != 64) {
// throw new InvalidDeviceTokenFormatException("Device Token has a length of [" + token.getBytes().length + "] and not the required 64 bytes!");
// }
// }
//
// public void validateTokenFormat() throws InvalidDeviceTokenFormatException {
// validateTokenFormat(token);
// }
//
// /**
// * Getter
// *
// * @return the device id
// */
// public String getDeviceId() {
// return deviceId;
// }
//
// /**
// * Setter
// *
// * @param id the device id
// */
// public void setDeviceId(final String id) {
// this.deviceId = id;
// }
//
// /**
// * Getter
// *
// * @return the device token
// */
// public String getToken() {
// return token;
// }
//
// /**
// * Setter the device token
// *
// * @param token
// */
// public void setToken(final String token) {
// this.token = token;
// }
//
// /**
// * Getter
// *
// * @return the last register
// */
// public Timestamp getLastRegister() {
// return lastRegister;
// }
//
// public void setLastRegister(final Timestamp lastRegister) {
// this.lastRegister = lastRegister;
// }
// }
| import javapns.devices.Device;
import javapns.devices.exceptions.InvalidDeviceTokenFormatException;
import javapns.devices.implementations.basic.BasicDevice; | package javapns.notification;
/**
* A one-to-one link between a payload and device.
* Provides support for a typical payload-per-device scenario.
*
* @author Sylvain Pedneault
*/
public class PayloadPerDevice {
private final Payload payload;
private final Device device;
public PayloadPerDevice(final Payload payload, final String token) throws InvalidDeviceTokenFormatException {
super();
this.payload = payload; | // Path: src/main/java/javapns/devices/Device.java
// public interface Device {
// /**
// * An id representing a particular device.
// * <p>
// * Note that this is a local reference to the device,
// * which is not related to the actual device UUID or
// * other device-specific identification. Most of the
// * time, this deviceId should be the same as the token.
// *
// * @return the device id
// */
// String getDeviceId();
//
// /**
// * An id representing a particular device.
// * <p>
// * Note that this is a local reference to the device,
// * which is not related to the actual device UUID or
// * other device-specific identification. Most of the
// * time, this deviceId should be the same as the token.
// *
// * @param id the device id
// */
// void setDeviceId(String id);
//
// /**
// * A device token.
// *
// * @return the device token
// */
// String getToken();
//
// /**
// * Set the device token
// *
// * @param token
// */
// void setToken(String token);
//
// /**
// * @return the last register
// */
// Timestamp getLastRegister();
//
// /**
// * @param lastRegister the last register
// */
// void setLastRegister(Timestamp lastRegister);
// }
//
// Path: src/main/java/javapns/devices/exceptions/InvalidDeviceTokenFormatException.java
// public class InvalidDeviceTokenFormatException extends Exception {
//
// private static final long serialVersionUID = -8571997399252125457L;
//
// public InvalidDeviceTokenFormatException(final String message) {
// super(message);
// }
//
// public InvalidDeviceTokenFormatException(final String token, final String problem) {
// super(String.format("Device token cannot be parsed, most likely because it contains invalid hexadecimal characters: %s in %s", problem, token));
// }
//
// }
//
// Path: src/main/java/javapns/devices/implementations/basic/BasicDevice.java
// public class BasicDevice implements Device {
//
// /*
// * An id representing a particular device.
// *
// * Note that this is a local reference to the device,
// * which is not related to the actual device UUID or
// * other device-specific identification. Most of the
// * time, this deviceId should be the same as the token.
// */
// private String deviceId;
//
// /* The device token given by Apple Server, hexadecimal form, 64bits length */
// private String token;
//
// /* The last time a device registered */
// private Timestamp lastRegister;
//
// public BasicDevice() {
// // empty
// }
//
// /**
// * Default constructor.
// *
// * @param token The device token
// */
// public BasicDevice(final String token) throws InvalidDeviceTokenFormatException {
// this(token, true);
// }
//
// private BasicDevice(final String token, final boolean validate) throws InvalidDeviceTokenFormatException {
// super();
// this.deviceId = token;
// this.token = token;
// try {
// this.lastRegister = new Timestamp(System.currentTimeMillis());
// } catch (final Exception e) {
// // empty
// }
//
// if (validate) {
// validateTokenFormat(token);
// }
// }
//
// /**
// * Constructor
// *
// * @param id The device id
// * @param token The device token
// */
// BasicDevice(final String id, final String token, final Timestamp register) throws InvalidDeviceTokenFormatException {
// super();
// this.deviceId = id;
// this.token = token;
// this.lastRegister = register;
//
// validateTokenFormat(token);
//
// }
//
// public static void validateTokenFormat(final String token) throws InvalidDeviceTokenFormatException {
// if (token == null) {
// throw new InvalidDeviceTokenFormatException("Device Token is null, and not the required 64 bytes...");
// }
//
// if (token.getBytes().length != 64) {
// throw new InvalidDeviceTokenFormatException("Device Token has a length of [" + token.getBytes().length + "] and not the required 64 bytes!");
// }
// }
//
// public void validateTokenFormat() throws InvalidDeviceTokenFormatException {
// validateTokenFormat(token);
// }
//
// /**
// * Getter
// *
// * @return the device id
// */
// public String getDeviceId() {
// return deviceId;
// }
//
// /**
// * Setter
// *
// * @param id the device id
// */
// public void setDeviceId(final String id) {
// this.deviceId = id;
// }
//
// /**
// * Getter
// *
// * @return the device token
// */
// public String getToken() {
// return token;
// }
//
// /**
// * Setter the device token
// *
// * @param token
// */
// public void setToken(final String token) {
// this.token = token;
// }
//
// /**
// * Getter
// *
// * @return the last register
// */
// public Timestamp getLastRegister() {
// return lastRegister;
// }
//
// public void setLastRegister(final Timestamp lastRegister) {
// this.lastRegister = lastRegister;
// }
// }
// Path: src/main/java/javapns/notification/PayloadPerDevice.java
import javapns.devices.Device;
import javapns.devices.exceptions.InvalidDeviceTokenFormatException;
import javapns.devices.implementations.basic.BasicDevice;
package javapns.notification;
/**
* A one-to-one link between a payload and device.
* Provides support for a typical payload-per-device scenario.
*
* @author Sylvain Pedneault
*/
public class PayloadPerDevice {
private final Payload payload;
private final Device device;
public PayloadPerDevice(final Payload payload, final String token) throws InvalidDeviceTokenFormatException {
super();
this.payload = payload; | this.device = new BasicDevice(token); |
mlaccetti/JavaPNS | src/main/java/javapns/notification/exceptions/ErrorResponsePacketReceivedException.java | // Path: src/main/java/javapns/notification/ResponsePacket.java
// public class ResponsePacket {
// private int command;
// private int status;
// private int identifier;
//
// protected ResponsePacket() {
// // empty
// }
//
// ResponsePacket(final int command, final int status, final int identifier) {
// this.command = command;
// this.status = status;
// this.identifier = identifier;
// }
//
// void linkToPushedNotification(final PushNotificationManager notificationManager) {
// final PushedNotification notification;
// try {
// notification = notificationManager.getPushedNotifications().get(identifier);
// if (notification != null) {
// notification.setResponse(this);
// }
// } catch (final Exception e) {
// // empty
// }
// }
//
// /**
// * Returns the response's command number. It should be 8 for all error responses.
// *
// * @return the response's command number (which should be 8)
// */
// public int getCommand() {
// return command;
// }
//
// protected void setCommand(final int command) {
// this.command = command;
// }
//
// /**
// * Determine if this packet is an error-response packet.
// *
// * @return true if command number is 8, false otherwise
// */
// private boolean isErrorResponsePacket() {
// return command == 8;
// }
//
// /**
// * Returns the response's status code <i>(see getMessage() for a human-friendly status message instead)</i>.
// *
// * @return the response's status code
// */
// public int getStatus() {
// return status;
// }
//
// protected void setStatus(final int status) {
// this.status = status;
// }
//
// /**
// * Determine if this packet is a valid error-response packet.
// * To be valid, it must be an error-response packet (command number 8) and it must have a non-zero status code.
// *
// * @return true if command number is 8 and status code is not 0, false otherwise
// */
// public boolean isValidErrorMessage() {
// return isErrorResponsePacket() && status != 0;
// }
//
// /**
// * Returns the response's identifier, which matches the pushed notification's.
// *
// * @return the response's identifier
// */
// public int getIdentifier() {
// return identifier;
// }
//
// protected void setIdentifier(final int identifier) {
// this.identifier = identifier;
// }
//
// /**
// * Returns a humand-friendly error message, as documented by Apple.
// *
// * @return a humand-friendly error message
// */
// public String getMessage() {
// if (command == 8) {
// final String prefix = "APNS: [" + identifier + "] "; //APNS ERROR FOR MESSAGE ID #" + identifier + ": ";
// if (status == 0) {
// return prefix + "No errors encountered";
// }
// if (status == 1) {
// return prefix + "Processing error";
// }
// if (status == 2) {
// return prefix + "Missing device token";
// }
// if (status == 3) {
// return prefix + "Missing topic";
// }
// if (status == 4) {
// return prefix + "Missing payload";
// }
// if (status == 5) {
// return prefix + "Invalid token size";
// }
// if (status == 6) {
// return prefix + "Invalid topic size";
// }
// if (status == 7) {
// return prefix + "Invalid payload size";
// }
// if (status == 8) {
// return prefix + "Invalid token";
// }
// if (status == 255) {
// return prefix + "None (unknown)";
// }
// return prefix + "Undocumented status code: " + status;
// }
// return "APNS: Undocumented response command: " + command;
// }
// }
| import javapns.notification.ResponsePacket; | package javapns.notification.exceptions;
/**
* Thrown when an error response packet was received from an APNS server.
*
* @author Sylvain Pedneault
*/
public class ErrorResponsePacketReceivedException extends Exception {
private static final long serialVersionUID = 5798868422603574079L; | // Path: src/main/java/javapns/notification/ResponsePacket.java
// public class ResponsePacket {
// private int command;
// private int status;
// private int identifier;
//
// protected ResponsePacket() {
// // empty
// }
//
// ResponsePacket(final int command, final int status, final int identifier) {
// this.command = command;
// this.status = status;
// this.identifier = identifier;
// }
//
// void linkToPushedNotification(final PushNotificationManager notificationManager) {
// final PushedNotification notification;
// try {
// notification = notificationManager.getPushedNotifications().get(identifier);
// if (notification != null) {
// notification.setResponse(this);
// }
// } catch (final Exception e) {
// // empty
// }
// }
//
// /**
// * Returns the response's command number. It should be 8 for all error responses.
// *
// * @return the response's command number (which should be 8)
// */
// public int getCommand() {
// return command;
// }
//
// protected void setCommand(final int command) {
// this.command = command;
// }
//
// /**
// * Determine if this packet is an error-response packet.
// *
// * @return true if command number is 8, false otherwise
// */
// private boolean isErrorResponsePacket() {
// return command == 8;
// }
//
// /**
// * Returns the response's status code <i>(see getMessage() for a human-friendly status message instead)</i>.
// *
// * @return the response's status code
// */
// public int getStatus() {
// return status;
// }
//
// protected void setStatus(final int status) {
// this.status = status;
// }
//
// /**
// * Determine if this packet is a valid error-response packet.
// * To be valid, it must be an error-response packet (command number 8) and it must have a non-zero status code.
// *
// * @return true if command number is 8 and status code is not 0, false otherwise
// */
// public boolean isValidErrorMessage() {
// return isErrorResponsePacket() && status != 0;
// }
//
// /**
// * Returns the response's identifier, which matches the pushed notification's.
// *
// * @return the response's identifier
// */
// public int getIdentifier() {
// return identifier;
// }
//
// protected void setIdentifier(final int identifier) {
// this.identifier = identifier;
// }
//
// /**
// * Returns a humand-friendly error message, as documented by Apple.
// *
// * @return a humand-friendly error message
// */
// public String getMessage() {
// if (command == 8) {
// final String prefix = "APNS: [" + identifier + "] "; //APNS ERROR FOR MESSAGE ID #" + identifier + ": ";
// if (status == 0) {
// return prefix + "No errors encountered";
// }
// if (status == 1) {
// return prefix + "Processing error";
// }
// if (status == 2) {
// return prefix + "Missing device token";
// }
// if (status == 3) {
// return prefix + "Missing topic";
// }
// if (status == 4) {
// return prefix + "Missing payload";
// }
// if (status == 5) {
// return prefix + "Invalid token size";
// }
// if (status == 6) {
// return prefix + "Invalid topic size";
// }
// if (status == 7) {
// return prefix + "Invalid payload size";
// }
// if (status == 8) {
// return prefix + "Invalid token";
// }
// if (status == 255) {
// return prefix + "None (unknown)";
// }
// return prefix + "Undocumented status code: " + status;
// }
// return "APNS: Undocumented response command: " + command;
// }
// }
// Path: src/main/java/javapns/notification/exceptions/ErrorResponsePacketReceivedException.java
import javapns.notification.ResponsePacket;
package javapns.notification.exceptions;
/**
* Thrown when an error response packet was received from an APNS server.
*
* @author Sylvain Pedneault
*/
public class ErrorResponsePacketReceivedException extends Exception {
private static final long serialVersionUID = 5798868422603574079L; | private final ResponsePacket packet; |
mlaccetti/JavaPNS | src/main/java/javapns/communication/AppleServerBasicImpl.java | // Path: src/main/java/javapns/communication/exceptions/InvalidKeystoreReferenceException.java
// public class InvalidKeystoreReferenceException extends KeystoreException {
//
// private static final long serialVersionUID = 3144387163593035745L;
//
// /**
// * Constructor
// */
// public InvalidKeystoreReferenceException() {
// super("Invalid keystore parameter. Must be InputStream, File, String (as a file path), or byte[].");
// }
//
// /**
// * Constructor with custom message
// *
// * @param keystore
// */
// public InvalidKeystoreReferenceException(final Object keystore) {
// super("Invalid keystore parameter (" + keystore + "). Must be InputStream, File, String (as a file path), or byte[].");
// }
//
// /**
// * Constructor with custom message
// *
// * @param message
// */
// public InvalidKeystoreReferenceException(final String message) {
// super(message);
// }
// }
//
// Path: src/main/java/javapns/communication/exceptions/KeystoreException.java
// public class KeystoreException extends Exception {
//
// private static final long serialVersionUID = 2549063865160633139L;
//
// /**
// * Constructor with custom message
// *
// * @param message
// */
// public KeystoreException(final String message) {
// super(message);
// }
//
// /**
// * Constructor with custom message
// *
// * @param message
// */
// public KeystoreException(final String message, final Exception cause) {
// super(message, cause);
// }
//
// }
| import javapns.communication.exceptions.InvalidKeystoreReferenceException;
import javapns.communication.exceptions.KeystoreException;
import java.io.InputStream; | package javapns.communication;
/**
* A basic and abstract implementation of the AppleServer interface
* intended to facilitate rapid deployment.
*
* @author Sylvain Pedneault
*/
public abstract class AppleServerBasicImpl implements AppleServer {
private final String password;
private final String type;
private Object keystore;
private String proxyHost;
private int proxyPort;
/**
* Constructs a AppleServerBasicImpl object.
*
* @param keystore The keystore to use (can be a File, an InputStream, a String for a file path, or a byte[] array)
* @param password The keystore's password
* @param type The keystore type (typically PKCS12)
* @throws KeystoreException thrown if an error occurs when loading the keystore
*/ | // Path: src/main/java/javapns/communication/exceptions/InvalidKeystoreReferenceException.java
// public class InvalidKeystoreReferenceException extends KeystoreException {
//
// private static final long serialVersionUID = 3144387163593035745L;
//
// /**
// * Constructor
// */
// public InvalidKeystoreReferenceException() {
// super("Invalid keystore parameter. Must be InputStream, File, String (as a file path), or byte[].");
// }
//
// /**
// * Constructor with custom message
// *
// * @param keystore
// */
// public InvalidKeystoreReferenceException(final Object keystore) {
// super("Invalid keystore parameter (" + keystore + "). Must be InputStream, File, String (as a file path), or byte[].");
// }
//
// /**
// * Constructor with custom message
// *
// * @param message
// */
// public InvalidKeystoreReferenceException(final String message) {
// super(message);
// }
// }
//
// Path: src/main/java/javapns/communication/exceptions/KeystoreException.java
// public class KeystoreException extends Exception {
//
// private static final long serialVersionUID = 2549063865160633139L;
//
// /**
// * Constructor with custom message
// *
// * @param message
// */
// public KeystoreException(final String message) {
// super(message);
// }
//
// /**
// * Constructor with custom message
// *
// * @param message
// */
// public KeystoreException(final String message, final Exception cause) {
// super(message, cause);
// }
//
// }
// Path: src/main/java/javapns/communication/AppleServerBasicImpl.java
import javapns.communication.exceptions.InvalidKeystoreReferenceException;
import javapns.communication.exceptions.KeystoreException;
import java.io.InputStream;
package javapns.communication;
/**
* A basic and abstract implementation of the AppleServer interface
* intended to facilitate rapid deployment.
*
* @author Sylvain Pedneault
*/
public abstract class AppleServerBasicImpl implements AppleServer {
private final String password;
private final String type;
private Object keystore;
private String proxyHost;
private int proxyPort;
/**
* Constructs a AppleServerBasicImpl object.
*
* @param keystore The keystore to use (can be a File, an InputStream, a String for a file path, or a byte[] array)
* @param password The keystore's password
* @param type The keystore type (typically PKCS12)
* @throws KeystoreException thrown if an error occurs when loading the keystore
*/ | protected AppleServerBasicImpl(final Object keystore, final String password, final String type) throws KeystoreException { |
mlaccetti/JavaPNS | src/main/java/javapns/communication/AppleServerBasicImpl.java | // Path: src/main/java/javapns/communication/exceptions/InvalidKeystoreReferenceException.java
// public class InvalidKeystoreReferenceException extends KeystoreException {
//
// private static final long serialVersionUID = 3144387163593035745L;
//
// /**
// * Constructor
// */
// public InvalidKeystoreReferenceException() {
// super("Invalid keystore parameter. Must be InputStream, File, String (as a file path), or byte[].");
// }
//
// /**
// * Constructor with custom message
// *
// * @param keystore
// */
// public InvalidKeystoreReferenceException(final Object keystore) {
// super("Invalid keystore parameter (" + keystore + "). Must be InputStream, File, String (as a file path), or byte[].");
// }
//
// /**
// * Constructor with custom message
// *
// * @param message
// */
// public InvalidKeystoreReferenceException(final String message) {
// super(message);
// }
// }
//
// Path: src/main/java/javapns/communication/exceptions/KeystoreException.java
// public class KeystoreException extends Exception {
//
// private static final long serialVersionUID = 2549063865160633139L;
//
// /**
// * Constructor with custom message
// *
// * @param message
// */
// public KeystoreException(final String message) {
// super(message);
// }
//
// /**
// * Constructor with custom message
// *
// * @param message
// */
// public KeystoreException(final String message, final Exception cause) {
// super(message, cause);
// }
//
// }
| import javapns.communication.exceptions.InvalidKeystoreReferenceException;
import javapns.communication.exceptions.KeystoreException;
import java.io.InputStream; | package javapns.communication;
/**
* A basic and abstract implementation of the AppleServer interface
* intended to facilitate rapid deployment.
*
* @author Sylvain Pedneault
*/
public abstract class AppleServerBasicImpl implements AppleServer {
private final String password;
private final String type;
private Object keystore;
private String proxyHost;
private int proxyPort;
/**
* Constructs a AppleServerBasicImpl object.
*
* @param keystore The keystore to use (can be a File, an InputStream, a String for a file path, or a byte[] array)
* @param password The keystore's password
* @param type The keystore type (typically PKCS12)
* @throws KeystoreException thrown if an error occurs when loading the keystore
*/
protected AppleServerBasicImpl(final Object keystore, final String password, final String type) throws KeystoreException {
KeystoreManager.validateKeystoreParameter(keystore);
this.keystore = keystore;
this.password = password;
this.type = type;
/* Make sure that the keystore reference is reusable. */
this.keystore = KeystoreManager.ensureReusableKeystore(this, this.keystore);
}
| // Path: src/main/java/javapns/communication/exceptions/InvalidKeystoreReferenceException.java
// public class InvalidKeystoreReferenceException extends KeystoreException {
//
// private static final long serialVersionUID = 3144387163593035745L;
//
// /**
// * Constructor
// */
// public InvalidKeystoreReferenceException() {
// super("Invalid keystore parameter. Must be InputStream, File, String (as a file path), or byte[].");
// }
//
// /**
// * Constructor with custom message
// *
// * @param keystore
// */
// public InvalidKeystoreReferenceException(final Object keystore) {
// super("Invalid keystore parameter (" + keystore + "). Must be InputStream, File, String (as a file path), or byte[].");
// }
//
// /**
// * Constructor with custom message
// *
// * @param message
// */
// public InvalidKeystoreReferenceException(final String message) {
// super(message);
// }
// }
//
// Path: src/main/java/javapns/communication/exceptions/KeystoreException.java
// public class KeystoreException extends Exception {
//
// private static final long serialVersionUID = 2549063865160633139L;
//
// /**
// * Constructor with custom message
// *
// * @param message
// */
// public KeystoreException(final String message) {
// super(message);
// }
//
// /**
// * Constructor with custom message
// *
// * @param message
// */
// public KeystoreException(final String message, final Exception cause) {
// super(message, cause);
// }
//
// }
// Path: src/main/java/javapns/communication/AppleServerBasicImpl.java
import javapns.communication.exceptions.InvalidKeystoreReferenceException;
import javapns.communication.exceptions.KeystoreException;
import java.io.InputStream;
package javapns.communication;
/**
* A basic and abstract implementation of the AppleServer interface
* intended to facilitate rapid deployment.
*
* @author Sylvain Pedneault
*/
public abstract class AppleServerBasicImpl implements AppleServer {
private final String password;
private final String type;
private Object keystore;
private String proxyHost;
private int proxyPort;
/**
* Constructs a AppleServerBasicImpl object.
*
* @param keystore The keystore to use (can be a File, an InputStream, a String for a file path, or a byte[] array)
* @param password The keystore's password
* @param type The keystore type (typically PKCS12)
* @throws KeystoreException thrown if an error occurs when loading the keystore
*/
protected AppleServerBasicImpl(final Object keystore, final String password, final String type) throws KeystoreException {
KeystoreManager.validateKeystoreParameter(keystore);
this.keystore = keystore;
this.password = password;
this.type = type;
/* Make sure that the keystore reference is reusable. */
this.keystore = KeystoreManager.ensureReusableKeystore(this, this.keystore);
}
| public InputStream getKeystoreStream() throws InvalidKeystoreReferenceException { |
mlaccetti/JavaPNS | src/main/java/javapns/communication/ConnectionToAppleServer.java | // Path: src/main/java/javapns/communication/exceptions/CommunicationException.java
// public class CommunicationException extends Exception {
// private static final long serialVersionUID = 1286560293829685555L;
//
// public CommunicationException(final String message, final Exception cause) {
// super(message, cause);
// }
// }
//
// Path: src/main/java/javapns/communication/exceptions/KeystoreException.java
// public class KeystoreException extends Exception {
//
// private static final long serialVersionUID = 2549063865160633139L;
//
// /**
// * Constructor with custom message
// *
// * @param message
// */
// public KeystoreException(final String message) {
// super(message);
// }
//
// /**
// * Constructor with custom message
// *
// * @param message
// */
// public KeystoreException(final String message, final Exception cause) {
// super(message, cause);
// }
//
// }
| import javapns.communication.exceptions.CommunicationException;
import javapns.communication.exceptions.KeystoreException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.net.ssl.*;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
import java.security.KeyStore; | }
public abstract String getServerHost();
protected abstract int getServerPort();
/**
* Return a SSLSocketFactory for creating sockets to communicate with Apple.
*
* @return SSLSocketFactory
* @throws KeystoreException
*/
private SSLSocketFactory createSSLSocketFactory() throws KeystoreException {
return createSSLSocketFactoryWithTrustManagers(new TrustManager[]{new ServerTrustingTrustManager()});
}
private SSLSocketFactory getSSLSocketFactory() throws KeystoreException {
if (socketFactory == null) {
socketFactory = createSSLSocketFactory();
}
return socketFactory;
}
/**
* Create a SSLSocket which will be used to send data to Apple
*
* @return the SSLSocket
* @throws KeystoreException
* @throws CommunicationException
*/ | // Path: src/main/java/javapns/communication/exceptions/CommunicationException.java
// public class CommunicationException extends Exception {
// private static final long serialVersionUID = 1286560293829685555L;
//
// public CommunicationException(final String message, final Exception cause) {
// super(message, cause);
// }
// }
//
// Path: src/main/java/javapns/communication/exceptions/KeystoreException.java
// public class KeystoreException extends Exception {
//
// private static final long serialVersionUID = 2549063865160633139L;
//
// /**
// * Constructor with custom message
// *
// * @param message
// */
// public KeystoreException(final String message) {
// super(message);
// }
//
// /**
// * Constructor with custom message
// *
// * @param message
// */
// public KeystoreException(final String message, final Exception cause) {
// super(message, cause);
// }
//
// }
// Path: src/main/java/javapns/communication/ConnectionToAppleServer.java
import javapns.communication.exceptions.CommunicationException;
import javapns.communication.exceptions.KeystoreException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.net.ssl.*;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
import java.security.KeyStore;
}
public abstract String getServerHost();
protected abstract int getServerPort();
/**
* Return a SSLSocketFactory for creating sockets to communicate with Apple.
*
* @return SSLSocketFactory
* @throws KeystoreException
*/
private SSLSocketFactory createSSLSocketFactory() throws KeystoreException {
return createSSLSocketFactoryWithTrustManagers(new TrustManager[]{new ServerTrustingTrustManager()});
}
private SSLSocketFactory getSSLSocketFactory() throws KeystoreException {
if (socketFactory == null) {
socketFactory = createSSLSocketFactory();
}
return socketFactory;
}
/**
* Create a SSLSocket which will be used to send data to Apple
*
* @return the SSLSocket
* @throws KeystoreException
* @throws CommunicationException
*/ | public SSLSocket getSSLSocket() throws KeystoreException, CommunicationException { |
mlaccetti/JavaPNS | src/main/java/javapns/notification/PushedNotification.java | // Path: src/main/java/javapns/devices/Device.java
// public interface Device {
// /**
// * An id representing a particular device.
// * <p>
// * Note that this is a local reference to the device,
// * which is not related to the actual device UUID or
// * other device-specific identification. Most of the
// * time, this deviceId should be the same as the token.
// *
// * @return the device id
// */
// String getDeviceId();
//
// /**
// * An id representing a particular device.
// * <p>
// * Note that this is a local reference to the device,
// * which is not related to the actual device UUID or
// * other device-specific identification. Most of the
// * time, this deviceId should be the same as the token.
// *
// * @param id the device id
// */
// void setDeviceId(String id);
//
// /**
// * A device token.
// *
// * @return the device token
// */
// String getToken();
//
// /**
// * Set the device token
// *
// * @param token
// */
// void setToken(String token);
//
// /**
// * @return the last register
// */
// Timestamp getLastRegister();
//
// /**
// * @param lastRegister the last register
// */
// void setLastRegister(Timestamp lastRegister);
// }
//
// Path: src/main/java/javapns/notification/exceptions/ErrorResponsePacketReceivedException.java
// public class ErrorResponsePacketReceivedException extends Exception {
//
// private static final long serialVersionUID = 5798868422603574079L;
// private final ResponsePacket packet;
//
// public ErrorResponsePacketReceivedException(final ResponsePacket packet) {
// super(String.format("An error response packet was received from the APNS server: %s", packet.getMessage()));
// this.packet = packet;
// }
//
// public ResponsePacket getPacket() {
// return packet;
// }
//
// }
| import javapns.devices.Device;
import javapns.notification.exceptions.ErrorResponsePacketReceivedException;
import java.util.ArrayList;
import java.util.List; | package javapns.notification;
/**
* <p>An object representing the result of a push notification to a specific payload to a single device.</p>
* <p>
* <p>If any error occurred while trying to push the notification, an exception is attached.</p>
* <p>
* <p>If Apple's Push Notification Service returned an error-response packet, it is linked to the related PushedNotification
* so you can find out what the actual error was.</p>
*
* @author Sylvain Pedneault
*/
public class PushedNotification {
private Payload payload; | // Path: src/main/java/javapns/devices/Device.java
// public interface Device {
// /**
// * An id representing a particular device.
// * <p>
// * Note that this is a local reference to the device,
// * which is not related to the actual device UUID or
// * other device-specific identification. Most of the
// * time, this deviceId should be the same as the token.
// *
// * @return the device id
// */
// String getDeviceId();
//
// /**
// * An id representing a particular device.
// * <p>
// * Note that this is a local reference to the device,
// * which is not related to the actual device UUID or
// * other device-specific identification. Most of the
// * time, this deviceId should be the same as the token.
// *
// * @param id the device id
// */
// void setDeviceId(String id);
//
// /**
// * A device token.
// *
// * @return the device token
// */
// String getToken();
//
// /**
// * Set the device token
// *
// * @param token
// */
// void setToken(String token);
//
// /**
// * @return the last register
// */
// Timestamp getLastRegister();
//
// /**
// * @param lastRegister the last register
// */
// void setLastRegister(Timestamp lastRegister);
// }
//
// Path: src/main/java/javapns/notification/exceptions/ErrorResponsePacketReceivedException.java
// public class ErrorResponsePacketReceivedException extends Exception {
//
// private static final long serialVersionUID = 5798868422603574079L;
// private final ResponsePacket packet;
//
// public ErrorResponsePacketReceivedException(final ResponsePacket packet) {
// super(String.format("An error response packet was received from the APNS server: %s", packet.getMessage()));
// this.packet = packet;
// }
//
// public ResponsePacket getPacket() {
// return packet;
// }
//
// }
// Path: src/main/java/javapns/notification/PushedNotification.java
import javapns.devices.Device;
import javapns.notification.exceptions.ErrorResponsePacketReceivedException;
import java.util.ArrayList;
import java.util.List;
package javapns.notification;
/**
* <p>An object representing the result of a push notification to a specific payload to a single device.</p>
* <p>
* <p>If any error occurred while trying to push the notification, an exception is attached.</p>
* <p>
* <p>If Apple's Push Notification Service returned an error-response packet, it is linked to the related PushedNotification
* so you can find out what the actual error was.</p>
*
* @author Sylvain Pedneault
*/
public class PushedNotification {
private Payload payload; | private Device device; |
mlaccetti/JavaPNS | src/main/java/javapns/notification/PushedNotification.java | // Path: src/main/java/javapns/devices/Device.java
// public interface Device {
// /**
// * An id representing a particular device.
// * <p>
// * Note that this is a local reference to the device,
// * which is not related to the actual device UUID or
// * other device-specific identification. Most of the
// * time, this deviceId should be the same as the token.
// *
// * @return the device id
// */
// String getDeviceId();
//
// /**
// * An id representing a particular device.
// * <p>
// * Note that this is a local reference to the device,
// * which is not related to the actual device UUID or
// * other device-specific identification. Most of the
// * time, this deviceId should be the same as the token.
// *
// * @param id the device id
// */
// void setDeviceId(String id);
//
// /**
// * A device token.
// *
// * @return the device token
// */
// String getToken();
//
// /**
// * Set the device token
// *
// * @param token
// */
// void setToken(String token);
//
// /**
// * @return the last register
// */
// Timestamp getLastRegister();
//
// /**
// * @param lastRegister the last register
// */
// void setLastRegister(Timestamp lastRegister);
// }
//
// Path: src/main/java/javapns/notification/exceptions/ErrorResponsePacketReceivedException.java
// public class ErrorResponsePacketReceivedException extends Exception {
//
// private static final long serialVersionUID = 5798868422603574079L;
// private final ResponsePacket packet;
//
// public ErrorResponsePacketReceivedException(final ResponsePacket packet) {
// super(String.format("An error response packet was received from the APNS server: %s", packet.getMessage()));
// this.packet = packet;
// }
//
// public ResponsePacket getPacket() {
// return packet;
// }
//
// }
| import javapns.devices.Device;
import javapns.notification.exceptions.ErrorResponsePacketReceivedException;
import java.util.ArrayList;
import java.util.List; |
/**
* Indicates if the notification has been streamed successfully to Apple's server.
* This does <b>not</b> indicate if an error-response was received or not, but simply
* that the library successfully completed the transmission of the notification to
* Apple's server.
*
* @return true if the notification was successfully streamed to Apple, false otherwise
*/
public boolean isTransmissionCompleted() {
return transmissionCompleted;
}
void setTransmissionCompleted(final boolean completed) {
this.transmissionCompleted = completed;
}
/**
* If a response packet regarding this notification was received,
* this method returns it. Otherwise it returns null.
*
* @return a response packet, if one was received for this notification
*/
public ResponsePacket getResponse() {
return response;
}
void setResponse(final ResponsePacket response) {
this.response = response;
if (response != null && exception == null) { | // Path: src/main/java/javapns/devices/Device.java
// public interface Device {
// /**
// * An id representing a particular device.
// * <p>
// * Note that this is a local reference to the device,
// * which is not related to the actual device UUID or
// * other device-specific identification. Most of the
// * time, this deviceId should be the same as the token.
// *
// * @return the device id
// */
// String getDeviceId();
//
// /**
// * An id representing a particular device.
// * <p>
// * Note that this is a local reference to the device,
// * which is not related to the actual device UUID or
// * other device-specific identification. Most of the
// * time, this deviceId should be the same as the token.
// *
// * @param id the device id
// */
// void setDeviceId(String id);
//
// /**
// * A device token.
// *
// * @return the device token
// */
// String getToken();
//
// /**
// * Set the device token
// *
// * @param token
// */
// void setToken(String token);
//
// /**
// * @return the last register
// */
// Timestamp getLastRegister();
//
// /**
// * @param lastRegister the last register
// */
// void setLastRegister(Timestamp lastRegister);
// }
//
// Path: src/main/java/javapns/notification/exceptions/ErrorResponsePacketReceivedException.java
// public class ErrorResponsePacketReceivedException extends Exception {
//
// private static final long serialVersionUID = 5798868422603574079L;
// private final ResponsePacket packet;
//
// public ErrorResponsePacketReceivedException(final ResponsePacket packet) {
// super(String.format("An error response packet was received from the APNS server: %s", packet.getMessage()));
// this.packet = packet;
// }
//
// public ResponsePacket getPacket() {
// return packet;
// }
//
// }
// Path: src/main/java/javapns/notification/PushedNotification.java
import javapns.devices.Device;
import javapns.notification.exceptions.ErrorResponsePacketReceivedException;
import java.util.ArrayList;
import java.util.List;
/**
* Indicates if the notification has been streamed successfully to Apple's server.
* This does <b>not</b> indicate if an error-response was received or not, but simply
* that the library successfully completed the transmission of the notification to
* Apple's server.
*
* @return true if the notification was successfully streamed to Apple, false otherwise
*/
public boolean isTransmissionCompleted() {
return transmissionCompleted;
}
void setTransmissionCompleted(final boolean completed) {
this.transmissionCompleted = completed;
}
/**
* If a response packet regarding this notification was received,
* this method returns it. Otherwise it returns null.
*
* @return a response packet, if one was received for this notification
*/
public ResponsePacket getResponse() {
return response;
}
void setResponse(final ResponsePacket response) {
this.response = response;
if (response != null && exception == null) { | exception = new ErrorResponsePacketReceivedException(response); |
mlaccetti/JavaPNS | src/main/java/javapns/notification/Payload.java | // Path: src/main/java/javapns/notification/exceptions/PayloadMaxSizeExceededException.java
// public class PayloadMaxSizeExceededException extends Exception {
//
// private static final long serialVersionUID = 2896151447959250527L;
//
// /**
// * Default constructor
// */
// public PayloadMaxSizeExceededException() {
// super("Total payload size exceeds allowed limit");
// }
//
// public PayloadMaxSizeExceededException(final int maxSize) {
// super(String.format("Total payload size exceeds allowed limit (%s bytes max)", maxSize));
// }
//
// public PayloadMaxSizeExceededException(final int maxSize, final int currentSize) {
// super(String.format("Total payload size exceeds allowed limit (payload is %s bytes, limit is %s)", currentSize, maxSize));
// }
//
// /**
// * Constructor with custom message
// *
// * @param message
// */
// public PayloadMaxSizeExceededException(final String message) {
// super(message);
// }
//
// }
//
// Path: src/main/java/javapns/notification/exceptions/PayloadMaxSizeProbablyExceededException.java
// public class PayloadMaxSizeProbablyExceededException extends JSONException {
//
// private static final long serialVersionUID = 580227446786047134L;
//
// /**
// * Default constructor
// */
// public PayloadMaxSizeProbablyExceededException() {
// super("Total payload size will most likely exceed allowed limit");
// }
//
// public PayloadMaxSizeProbablyExceededException(final int maxSize) {
// super(String.format("Total payload size will most likely exceed allowed limit (%s bytes max)", maxSize));
// }
//
// public PayloadMaxSizeProbablyExceededException(final int maxSize, final int estimatedSize) {
// super(String.format("Total payload size will most likely exceed allowed limit (estimated to become %s bytes, limit is %s)", estimatedSize, maxSize));
// }
//
// /**
// * Constructor with custom message
// *
// * @param message
// */
// public PayloadMaxSizeProbablyExceededException(final String message) {
// super(message);
// }
//
// }
| import javapns.notification.exceptions.PayloadMaxSizeExceededException;
import javapns.notification.exceptions.PayloadMaxSizeProbablyExceededException;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List; | try {
return getPayloadSize();
} catch (final Exception e1) {
return 0;
}
}
}
/**
* Validate if the estimated payload size after adding a given property will be allowed.
* For performance reasons, this estimate is not as reliable as actually adding
* the property and checking the payload size afterwards.
*
* @param propertyName the name of the property to use for calculating the estimation
* @param propertyValue the value of the property to use for calculating the estimation
* @return true if the payload size is not expected to exceed the maximum allowed, false if it might be too big
*/
public boolean isEstimatedPayloadSizeAllowedAfterAdding(final String propertyName, final Object propertyValue) {
final int maximumPayloadSize = getMaximumPayloadSize();
final int estimatedPayloadSize = estimatePayloadSizeAfterAdding(propertyName, propertyValue);
return estimatedPayloadSize <= maximumPayloadSize;
}
/**
* Validate that the payload does not exceed the maximum size allowed.
* If the limit is exceeded, a PayloadMaxSizeExceededException is thrown.
*
* @param currentPayloadSize the total size of the payload in bytes
* @throws PayloadMaxSizeExceededException if the payload exceeds the maximum size allowed
*/ | // Path: src/main/java/javapns/notification/exceptions/PayloadMaxSizeExceededException.java
// public class PayloadMaxSizeExceededException extends Exception {
//
// private static final long serialVersionUID = 2896151447959250527L;
//
// /**
// * Default constructor
// */
// public PayloadMaxSizeExceededException() {
// super("Total payload size exceeds allowed limit");
// }
//
// public PayloadMaxSizeExceededException(final int maxSize) {
// super(String.format("Total payload size exceeds allowed limit (%s bytes max)", maxSize));
// }
//
// public PayloadMaxSizeExceededException(final int maxSize, final int currentSize) {
// super(String.format("Total payload size exceeds allowed limit (payload is %s bytes, limit is %s)", currentSize, maxSize));
// }
//
// /**
// * Constructor with custom message
// *
// * @param message
// */
// public PayloadMaxSizeExceededException(final String message) {
// super(message);
// }
//
// }
//
// Path: src/main/java/javapns/notification/exceptions/PayloadMaxSizeProbablyExceededException.java
// public class PayloadMaxSizeProbablyExceededException extends JSONException {
//
// private static final long serialVersionUID = 580227446786047134L;
//
// /**
// * Default constructor
// */
// public PayloadMaxSizeProbablyExceededException() {
// super("Total payload size will most likely exceed allowed limit");
// }
//
// public PayloadMaxSizeProbablyExceededException(final int maxSize) {
// super(String.format("Total payload size will most likely exceed allowed limit (%s bytes max)", maxSize));
// }
//
// public PayloadMaxSizeProbablyExceededException(final int maxSize, final int estimatedSize) {
// super(String.format("Total payload size will most likely exceed allowed limit (estimated to become %s bytes, limit is %s)", estimatedSize, maxSize));
// }
//
// /**
// * Constructor with custom message
// *
// * @param message
// */
// public PayloadMaxSizeProbablyExceededException(final String message) {
// super(message);
// }
//
// }
// Path: src/main/java/javapns/notification/Payload.java
import javapns.notification.exceptions.PayloadMaxSizeExceededException;
import javapns.notification.exceptions.PayloadMaxSizeProbablyExceededException;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
try {
return getPayloadSize();
} catch (final Exception e1) {
return 0;
}
}
}
/**
* Validate if the estimated payload size after adding a given property will be allowed.
* For performance reasons, this estimate is not as reliable as actually adding
* the property and checking the payload size afterwards.
*
* @param propertyName the name of the property to use for calculating the estimation
* @param propertyValue the value of the property to use for calculating the estimation
* @return true if the payload size is not expected to exceed the maximum allowed, false if it might be too big
*/
public boolean isEstimatedPayloadSizeAllowedAfterAdding(final String propertyName, final Object propertyValue) {
final int maximumPayloadSize = getMaximumPayloadSize();
final int estimatedPayloadSize = estimatePayloadSizeAfterAdding(propertyName, propertyValue);
return estimatedPayloadSize <= maximumPayloadSize;
}
/**
* Validate that the payload does not exceed the maximum size allowed.
* If the limit is exceeded, a PayloadMaxSizeExceededException is thrown.
*
* @param currentPayloadSize the total size of the payload in bytes
* @throws PayloadMaxSizeExceededException if the payload exceeds the maximum size allowed
*/ | private void validateMaximumPayloadSize(final int currentPayloadSize) throws PayloadMaxSizeExceededException { |
mlaccetti/JavaPNS | src/main/java/javapns/notification/Payload.java | // Path: src/main/java/javapns/notification/exceptions/PayloadMaxSizeExceededException.java
// public class PayloadMaxSizeExceededException extends Exception {
//
// private static final long serialVersionUID = 2896151447959250527L;
//
// /**
// * Default constructor
// */
// public PayloadMaxSizeExceededException() {
// super("Total payload size exceeds allowed limit");
// }
//
// public PayloadMaxSizeExceededException(final int maxSize) {
// super(String.format("Total payload size exceeds allowed limit (%s bytes max)", maxSize));
// }
//
// public PayloadMaxSizeExceededException(final int maxSize, final int currentSize) {
// super(String.format("Total payload size exceeds allowed limit (payload is %s bytes, limit is %s)", currentSize, maxSize));
// }
//
// /**
// * Constructor with custom message
// *
// * @param message
// */
// public PayloadMaxSizeExceededException(final String message) {
// super(message);
// }
//
// }
//
// Path: src/main/java/javapns/notification/exceptions/PayloadMaxSizeProbablyExceededException.java
// public class PayloadMaxSizeProbablyExceededException extends JSONException {
//
// private static final long serialVersionUID = 580227446786047134L;
//
// /**
// * Default constructor
// */
// public PayloadMaxSizeProbablyExceededException() {
// super("Total payload size will most likely exceed allowed limit");
// }
//
// public PayloadMaxSizeProbablyExceededException(final int maxSize) {
// super(String.format("Total payload size will most likely exceed allowed limit (%s bytes max)", maxSize));
// }
//
// public PayloadMaxSizeProbablyExceededException(final int maxSize, final int estimatedSize) {
// super(String.format("Total payload size will most likely exceed allowed limit (estimated to become %s bytes, limit is %s)", estimatedSize, maxSize));
// }
//
// /**
// * Constructor with custom message
// *
// * @param message
// */
// public PayloadMaxSizeProbablyExceededException(final String message) {
// super(message);
// }
//
// }
| import javapns.notification.exceptions.PayloadMaxSizeExceededException;
import javapns.notification.exceptions.PayloadMaxSizeProbablyExceededException;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List; | /**
* Validate that the payload does not exceed the maximum size allowed.
* If the limit is exceeded, a PayloadMaxSizeExceededException is thrown.
*
* @param currentPayloadSize the total size of the payload in bytes
* @throws PayloadMaxSizeExceededException if the payload exceeds the maximum size allowed
*/
private void validateMaximumPayloadSize(final int currentPayloadSize) throws PayloadMaxSizeExceededException {
final int maximumPayloadSize = getMaximumPayloadSize();
if (currentPayloadSize > maximumPayloadSize) {
throw new PayloadMaxSizeExceededException(maximumPayloadSize, currentPayloadSize);
}
}
/**
* Puts a property in a JSONObject, while possibly checking for estimated payload size violation.
*
* @param propertyName the name of the property to use for calculating the estimation
* @param propertyValue the value of the property to use for calculating the estimation
* @param object the JSONObject to put the property in
* @param opt true to use putOpt, false to use put
* @throws JSONException
*/
void put(final String propertyName, final Object propertyValue, final JSONObject object, final boolean opt) throws JSONException {
try {
if (isPayloadSizeEstimatedWhenAdding()) {
final int maximumPayloadSize = getMaximumPayloadSize();
final int estimatedPayloadSize = estimatePayloadSizeAfterAdding(propertyName, propertyValue);
final boolean estimatedToExceed = estimatedPayloadSize > maximumPayloadSize;
if (estimatedToExceed) { | // Path: src/main/java/javapns/notification/exceptions/PayloadMaxSizeExceededException.java
// public class PayloadMaxSizeExceededException extends Exception {
//
// private static final long serialVersionUID = 2896151447959250527L;
//
// /**
// * Default constructor
// */
// public PayloadMaxSizeExceededException() {
// super("Total payload size exceeds allowed limit");
// }
//
// public PayloadMaxSizeExceededException(final int maxSize) {
// super(String.format("Total payload size exceeds allowed limit (%s bytes max)", maxSize));
// }
//
// public PayloadMaxSizeExceededException(final int maxSize, final int currentSize) {
// super(String.format("Total payload size exceeds allowed limit (payload is %s bytes, limit is %s)", currentSize, maxSize));
// }
//
// /**
// * Constructor with custom message
// *
// * @param message
// */
// public PayloadMaxSizeExceededException(final String message) {
// super(message);
// }
//
// }
//
// Path: src/main/java/javapns/notification/exceptions/PayloadMaxSizeProbablyExceededException.java
// public class PayloadMaxSizeProbablyExceededException extends JSONException {
//
// private static final long serialVersionUID = 580227446786047134L;
//
// /**
// * Default constructor
// */
// public PayloadMaxSizeProbablyExceededException() {
// super("Total payload size will most likely exceed allowed limit");
// }
//
// public PayloadMaxSizeProbablyExceededException(final int maxSize) {
// super(String.format("Total payload size will most likely exceed allowed limit (%s bytes max)", maxSize));
// }
//
// public PayloadMaxSizeProbablyExceededException(final int maxSize, final int estimatedSize) {
// super(String.format("Total payload size will most likely exceed allowed limit (estimated to become %s bytes, limit is %s)", estimatedSize, maxSize));
// }
//
// /**
// * Constructor with custom message
// *
// * @param message
// */
// public PayloadMaxSizeProbablyExceededException(final String message) {
// super(message);
// }
//
// }
// Path: src/main/java/javapns/notification/Payload.java
import javapns.notification.exceptions.PayloadMaxSizeExceededException;
import javapns.notification.exceptions.PayloadMaxSizeProbablyExceededException;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
/**
* Validate that the payload does not exceed the maximum size allowed.
* If the limit is exceeded, a PayloadMaxSizeExceededException is thrown.
*
* @param currentPayloadSize the total size of the payload in bytes
* @throws PayloadMaxSizeExceededException if the payload exceeds the maximum size allowed
*/
private void validateMaximumPayloadSize(final int currentPayloadSize) throws PayloadMaxSizeExceededException {
final int maximumPayloadSize = getMaximumPayloadSize();
if (currentPayloadSize > maximumPayloadSize) {
throw new PayloadMaxSizeExceededException(maximumPayloadSize, currentPayloadSize);
}
}
/**
* Puts a property in a JSONObject, while possibly checking for estimated payload size violation.
*
* @param propertyName the name of the property to use for calculating the estimation
* @param propertyValue the value of the property to use for calculating the estimation
* @param object the JSONObject to put the property in
* @param opt true to use putOpt, false to use put
* @throws JSONException
*/
void put(final String propertyName, final Object propertyValue, final JSONObject object, final boolean opt) throws JSONException {
try {
if (isPayloadSizeEstimatedWhenAdding()) {
final int maximumPayloadSize = getMaximumPayloadSize();
final int estimatedPayloadSize = estimatePayloadSizeAfterAdding(propertyName, propertyValue);
final boolean estimatedToExceed = estimatedPayloadSize > maximumPayloadSize;
if (estimatedToExceed) { | throw new PayloadMaxSizeProbablyExceededException(maximumPayloadSize, estimatedPayloadSize); |
mlaccetti/JavaPNS | src/main/java/javapns/devices/Devices.java | // Path: src/main/java/javapns/devices/implementations/basic/BasicDevice.java
// public class BasicDevice implements Device {
//
// /*
// * An id representing a particular device.
// *
// * Note that this is a local reference to the device,
// * which is not related to the actual device UUID or
// * other device-specific identification. Most of the
// * time, this deviceId should be the same as the token.
// */
// private String deviceId;
//
// /* The device token given by Apple Server, hexadecimal form, 64bits length */
// private String token;
//
// /* The last time a device registered */
// private Timestamp lastRegister;
//
// public BasicDevice() {
// // empty
// }
//
// /**
// * Default constructor.
// *
// * @param token The device token
// */
// public BasicDevice(final String token) throws InvalidDeviceTokenFormatException {
// this(token, true);
// }
//
// private BasicDevice(final String token, final boolean validate) throws InvalidDeviceTokenFormatException {
// super();
// this.deviceId = token;
// this.token = token;
// try {
// this.lastRegister = new Timestamp(System.currentTimeMillis());
// } catch (final Exception e) {
// // empty
// }
//
// if (validate) {
// validateTokenFormat(token);
// }
// }
//
// /**
// * Constructor
// *
// * @param id The device id
// * @param token The device token
// */
// BasicDevice(final String id, final String token, final Timestamp register) throws InvalidDeviceTokenFormatException {
// super();
// this.deviceId = id;
// this.token = token;
// this.lastRegister = register;
//
// validateTokenFormat(token);
//
// }
//
// public static void validateTokenFormat(final String token) throws InvalidDeviceTokenFormatException {
// if (token == null) {
// throw new InvalidDeviceTokenFormatException("Device Token is null, and not the required 64 bytes...");
// }
//
// if (token.getBytes().length != 64) {
// throw new InvalidDeviceTokenFormatException("Device Token has a length of [" + token.getBytes().length + "] and not the required 64 bytes!");
// }
// }
//
// public void validateTokenFormat() throws InvalidDeviceTokenFormatException {
// validateTokenFormat(token);
// }
//
// /**
// * Getter
// *
// * @return the device id
// */
// public String getDeviceId() {
// return deviceId;
// }
//
// /**
// * Setter
// *
// * @param id the device id
// */
// public void setDeviceId(final String id) {
// this.deviceId = id;
// }
//
// /**
// * Getter
// *
// * @return the device token
// */
// public String getToken() {
// return token;
// }
//
// /**
// * Setter the device token
// *
// * @param token
// */
// public void setToken(final String token) {
// this.token = token;
// }
//
// /**
// * Getter
// *
// * @return the last register
// */
// public Timestamp getLastRegister() {
// return lastRegister;
// }
//
// public void setLastRegister(final Timestamp lastRegister) {
// this.lastRegister = lastRegister;
// }
// }
//
// Path: src/main/java/javapns/notification/PayloadPerDevice.java
// public class PayloadPerDevice {
// private final Payload payload;
// private final Device device;
//
// public PayloadPerDevice(final Payload payload, final String token) throws InvalidDeviceTokenFormatException {
// super();
// this.payload = payload;
// this.device = new BasicDevice(token);
// }
//
// public PayloadPerDevice(final Payload payload, final Device device) {
// super();
// this.payload = payload;
// this.device = device;
// }
//
// public Payload getPayload() {
// return payload;
// }
//
// public Device getDevice() {
// return device;
// }
//
// }
| import javapns.devices.implementations.basic.BasicDevice;
import javapns.notification.PayloadPerDevice;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List; | package javapns.devices;
public class Devices {
private Devices() {}
public static List<Device> asDevices(final Object rawList) {
final List<Device> list = new ArrayList<>();
if (rawList == null) {
return list;
}
if (rawList instanceof List) {
final List devices = (List) rawList;
if (devices.isEmpty()) {
return list;
}
final Object firstDevice = devices.get(0);
if (firstDevice instanceof Device) {
//noinspection unchecked
return devices;
} else if (firstDevice instanceof String) {
for (final Object token : devices) { | // Path: src/main/java/javapns/devices/implementations/basic/BasicDevice.java
// public class BasicDevice implements Device {
//
// /*
// * An id representing a particular device.
// *
// * Note that this is a local reference to the device,
// * which is not related to the actual device UUID or
// * other device-specific identification. Most of the
// * time, this deviceId should be the same as the token.
// */
// private String deviceId;
//
// /* The device token given by Apple Server, hexadecimal form, 64bits length */
// private String token;
//
// /* The last time a device registered */
// private Timestamp lastRegister;
//
// public BasicDevice() {
// // empty
// }
//
// /**
// * Default constructor.
// *
// * @param token The device token
// */
// public BasicDevice(final String token) throws InvalidDeviceTokenFormatException {
// this(token, true);
// }
//
// private BasicDevice(final String token, final boolean validate) throws InvalidDeviceTokenFormatException {
// super();
// this.deviceId = token;
// this.token = token;
// try {
// this.lastRegister = new Timestamp(System.currentTimeMillis());
// } catch (final Exception e) {
// // empty
// }
//
// if (validate) {
// validateTokenFormat(token);
// }
// }
//
// /**
// * Constructor
// *
// * @param id The device id
// * @param token The device token
// */
// BasicDevice(final String id, final String token, final Timestamp register) throws InvalidDeviceTokenFormatException {
// super();
// this.deviceId = id;
// this.token = token;
// this.lastRegister = register;
//
// validateTokenFormat(token);
//
// }
//
// public static void validateTokenFormat(final String token) throws InvalidDeviceTokenFormatException {
// if (token == null) {
// throw new InvalidDeviceTokenFormatException("Device Token is null, and not the required 64 bytes...");
// }
//
// if (token.getBytes().length != 64) {
// throw new InvalidDeviceTokenFormatException("Device Token has a length of [" + token.getBytes().length + "] and not the required 64 bytes!");
// }
// }
//
// public void validateTokenFormat() throws InvalidDeviceTokenFormatException {
// validateTokenFormat(token);
// }
//
// /**
// * Getter
// *
// * @return the device id
// */
// public String getDeviceId() {
// return deviceId;
// }
//
// /**
// * Setter
// *
// * @param id the device id
// */
// public void setDeviceId(final String id) {
// this.deviceId = id;
// }
//
// /**
// * Getter
// *
// * @return the device token
// */
// public String getToken() {
// return token;
// }
//
// /**
// * Setter the device token
// *
// * @param token
// */
// public void setToken(final String token) {
// this.token = token;
// }
//
// /**
// * Getter
// *
// * @return the last register
// */
// public Timestamp getLastRegister() {
// return lastRegister;
// }
//
// public void setLastRegister(final Timestamp lastRegister) {
// this.lastRegister = lastRegister;
// }
// }
//
// Path: src/main/java/javapns/notification/PayloadPerDevice.java
// public class PayloadPerDevice {
// private final Payload payload;
// private final Device device;
//
// public PayloadPerDevice(final Payload payload, final String token) throws InvalidDeviceTokenFormatException {
// super();
// this.payload = payload;
// this.device = new BasicDevice(token);
// }
//
// public PayloadPerDevice(final Payload payload, final Device device) {
// super();
// this.payload = payload;
// this.device = device;
// }
//
// public Payload getPayload() {
// return payload;
// }
//
// public Device getDevice() {
// return device;
// }
//
// }
// Path: src/main/java/javapns/devices/Devices.java
import javapns.devices.implementations.basic.BasicDevice;
import javapns.notification.PayloadPerDevice;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
package javapns.devices;
public class Devices {
private Devices() {}
public static List<Device> asDevices(final Object rawList) {
final List<Device> list = new ArrayList<>();
if (rawList == null) {
return list;
}
if (rawList instanceof List) {
final List devices = (List) rawList;
if (devices.isEmpty()) {
return list;
}
final Object firstDevice = devices.get(0);
if (firstDevice instanceof Device) {
//noinspection unchecked
return devices;
} else if (firstDevice instanceof String) {
for (final Object token : devices) { | final BasicDevice device = new BasicDevice(); |
mlaccetti/JavaPNS | src/main/java/javapns/devices/Devices.java | // Path: src/main/java/javapns/devices/implementations/basic/BasicDevice.java
// public class BasicDevice implements Device {
//
// /*
// * An id representing a particular device.
// *
// * Note that this is a local reference to the device,
// * which is not related to the actual device UUID or
// * other device-specific identification. Most of the
// * time, this deviceId should be the same as the token.
// */
// private String deviceId;
//
// /* The device token given by Apple Server, hexadecimal form, 64bits length */
// private String token;
//
// /* The last time a device registered */
// private Timestamp lastRegister;
//
// public BasicDevice() {
// // empty
// }
//
// /**
// * Default constructor.
// *
// * @param token The device token
// */
// public BasicDevice(final String token) throws InvalidDeviceTokenFormatException {
// this(token, true);
// }
//
// private BasicDevice(final String token, final boolean validate) throws InvalidDeviceTokenFormatException {
// super();
// this.deviceId = token;
// this.token = token;
// try {
// this.lastRegister = new Timestamp(System.currentTimeMillis());
// } catch (final Exception e) {
// // empty
// }
//
// if (validate) {
// validateTokenFormat(token);
// }
// }
//
// /**
// * Constructor
// *
// * @param id The device id
// * @param token The device token
// */
// BasicDevice(final String id, final String token, final Timestamp register) throws InvalidDeviceTokenFormatException {
// super();
// this.deviceId = id;
// this.token = token;
// this.lastRegister = register;
//
// validateTokenFormat(token);
//
// }
//
// public static void validateTokenFormat(final String token) throws InvalidDeviceTokenFormatException {
// if (token == null) {
// throw new InvalidDeviceTokenFormatException("Device Token is null, and not the required 64 bytes...");
// }
//
// if (token.getBytes().length != 64) {
// throw new InvalidDeviceTokenFormatException("Device Token has a length of [" + token.getBytes().length + "] and not the required 64 bytes!");
// }
// }
//
// public void validateTokenFormat() throws InvalidDeviceTokenFormatException {
// validateTokenFormat(token);
// }
//
// /**
// * Getter
// *
// * @return the device id
// */
// public String getDeviceId() {
// return deviceId;
// }
//
// /**
// * Setter
// *
// * @param id the device id
// */
// public void setDeviceId(final String id) {
// this.deviceId = id;
// }
//
// /**
// * Getter
// *
// * @return the device token
// */
// public String getToken() {
// return token;
// }
//
// /**
// * Setter the device token
// *
// * @param token
// */
// public void setToken(final String token) {
// this.token = token;
// }
//
// /**
// * Getter
// *
// * @return the last register
// */
// public Timestamp getLastRegister() {
// return lastRegister;
// }
//
// public void setLastRegister(final Timestamp lastRegister) {
// this.lastRegister = lastRegister;
// }
// }
//
// Path: src/main/java/javapns/notification/PayloadPerDevice.java
// public class PayloadPerDevice {
// private final Payload payload;
// private final Device device;
//
// public PayloadPerDevice(final Payload payload, final String token) throws InvalidDeviceTokenFormatException {
// super();
// this.payload = payload;
// this.device = new BasicDevice(token);
// }
//
// public PayloadPerDevice(final Payload payload, final Device device) {
// super();
// this.payload = payload;
// this.device = device;
// }
//
// public Payload getPayload() {
// return payload;
// }
//
// public Device getDevice() {
// return device;
// }
//
// }
| import javapns.devices.implementations.basic.BasicDevice;
import javapns.notification.PayloadPerDevice;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List; | return devices;
} else if (firstDevice instanceof String) {
for (final Object token : devices) {
final BasicDevice device = new BasicDevice();
device.setToken((String) token);
list.add(device);
}
}
} else if (rawList instanceof String[]) {
final String[] tokens = (String[]) rawList;
for (final String token : tokens) {
final BasicDevice device = new BasicDevice();
device.setToken(token);
list.add(device);
}
} else if (rawList instanceof Device[]) {
final Device[] dvs = (Device[]) rawList;
return Arrays.asList(dvs);
} else if (rawList instanceof String) {
final BasicDevice device = new BasicDevice();
device.setToken((String) rawList);
list.add(device);
} else if (rawList instanceof Device) {
list.add((Device) rawList);
} else {
throw new IllegalArgumentException("Device list type not supported. Supported types are: String[], List<String>, Device[], List<Device>, String and Device");
}
return list;
}
| // Path: src/main/java/javapns/devices/implementations/basic/BasicDevice.java
// public class BasicDevice implements Device {
//
// /*
// * An id representing a particular device.
// *
// * Note that this is a local reference to the device,
// * which is not related to the actual device UUID or
// * other device-specific identification. Most of the
// * time, this deviceId should be the same as the token.
// */
// private String deviceId;
//
// /* The device token given by Apple Server, hexadecimal form, 64bits length */
// private String token;
//
// /* The last time a device registered */
// private Timestamp lastRegister;
//
// public BasicDevice() {
// // empty
// }
//
// /**
// * Default constructor.
// *
// * @param token The device token
// */
// public BasicDevice(final String token) throws InvalidDeviceTokenFormatException {
// this(token, true);
// }
//
// private BasicDevice(final String token, final boolean validate) throws InvalidDeviceTokenFormatException {
// super();
// this.deviceId = token;
// this.token = token;
// try {
// this.lastRegister = new Timestamp(System.currentTimeMillis());
// } catch (final Exception e) {
// // empty
// }
//
// if (validate) {
// validateTokenFormat(token);
// }
// }
//
// /**
// * Constructor
// *
// * @param id The device id
// * @param token The device token
// */
// BasicDevice(final String id, final String token, final Timestamp register) throws InvalidDeviceTokenFormatException {
// super();
// this.deviceId = id;
// this.token = token;
// this.lastRegister = register;
//
// validateTokenFormat(token);
//
// }
//
// public static void validateTokenFormat(final String token) throws InvalidDeviceTokenFormatException {
// if (token == null) {
// throw new InvalidDeviceTokenFormatException("Device Token is null, and not the required 64 bytes...");
// }
//
// if (token.getBytes().length != 64) {
// throw new InvalidDeviceTokenFormatException("Device Token has a length of [" + token.getBytes().length + "] and not the required 64 bytes!");
// }
// }
//
// public void validateTokenFormat() throws InvalidDeviceTokenFormatException {
// validateTokenFormat(token);
// }
//
// /**
// * Getter
// *
// * @return the device id
// */
// public String getDeviceId() {
// return deviceId;
// }
//
// /**
// * Setter
// *
// * @param id the device id
// */
// public void setDeviceId(final String id) {
// this.deviceId = id;
// }
//
// /**
// * Getter
// *
// * @return the device token
// */
// public String getToken() {
// return token;
// }
//
// /**
// * Setter the device token
// *
// * @param token
// */
// public void setToken(final String token) {
// this.token = token;
// }
//
// /**
// * Getter
// *
// * @return the last register
// */
// public Timestamp getLastRegister() {
// return lastRegister;
// }
//
// public void setLastRegister(final Timestamp lastRegister) {
// this.lastRegister = lastRegister;
// }
// }
//
// Path: src/main/java/javapns/notification/PayloadPerDevice.java
// public class PayloadPerDevice {
// private final Payload payload;
// private final Device device;
//
// public PayloadPerDevice(final Payload payload, final String token) throws InvalidDeviceTokenFormatException {
// super();
// this.payload = payload;
// this.device = new BasicDevice(token);
// }
//
// public PayloadPerDevice(final Payload payload, final Device device) {
// super();
// this.payload = payload;
// this.device = device;
// }
//
// public Payload getPayload() {
// return payload;
// }
//
// public Device getDevice() {
// return device;
// }
//
// }
// Path: src/main/java/javapns/devices/Devices.java
import javapns.devices.implementations.basic.BasicDevice;
import javapns.notification.PayloadPerDevice;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
return devices;
} else if (firstDevice instanceof String) {
for (final Object token : devices) {
final BasicDevice device = new BasicDevice();
device.setToken((String) token);
list.add(device);
}
}
} else if (rawList instanceof String[]) {
final String[] tokens = (String[]) rawList;
for (final String token : tokens) {
final BasicDevice device = new BasicDevice();
device.setToken(token);
list.add(device);
}
} else if (rawList instanceof Device[]) {
final Device[] dvs = (Device[]) rawList;
return Arrays.asList(dvs);
} else if (rawList instanceof String) {
final BasicDevice device = new BasicDevice();
device.setToken((String) rawList);
list.add(device);
} else if (rawList instanceof Device) {
list.add((Device) rawList);
} else {
throw new IllegalArgumentException("Device list type not supported. Supported types are: String[], List<String>, Device[], List<Device>, String and Device");
}
return list;
}
| public static List<PayloadPerDevice> asPayloadsPerDevices(final Object rawList) { |
mlaccetti/JavaPNS | src/main/java/javapns/devices/implementations/basic/BasicDevice.java | // Path: src/main/java/javapns/devices/Device.java
// public interface Device {
// /**
// * An id representing a particular device.
// * <p>
// * Note that this is a local reference to the device,
// * which is not related to the actual device UUID or
// * other device-specific identification. Most of the
// * time, this deviceId should be the same as the token.
// *
// * @return the device id
// */
// String getDeviceId();
//
// /**
// * An id representing a particular device.
// * <p>
// * Note that this is a local reference to the device,
// * which is not related to the actual device UUID or
// * other device-specific identification. Most of the
// * time, this deviceId should be the same as the token.
// *
// * @param id the device id
// */
// void setDeviceId(String id);
//
// /**
// * A device token.
// *
// * @return the device token
// */
// String getToken();
//
// /**
// * Set the device token
// *
// * @param token
// */
// void setToken(String token);
//
// /**
// * @return the last register
// */
// Timestamp getLastRegister();
//
// /**
// * @param lastRegister the last register
// */
// void setLastRegister(Timestamp lastRegister);
// }
//
// Path: src/main/java/javapns/devices/exceptions/InvalidDeviceTokenFormatException.java
// public class InvalidDeviceTokenFormatException extends Exception {
//
// private static final long serialVersionUID = -8571997399252125457L;
//
// public InvalidDeviceTokenFormatException(final String message) {
// super(message);
// }
//
// public InvalidDeviceTokenFormatException(final String token, final String problem) {
// super(String.format("Device token cannot be parsed, most likely because it contains invalid hexadecimal characters: %s in %s", problem, token));
// }
//
// }
| import javapns.devices.Device;
import javapns.devices.exceptions.InvalidDeviceTokenFormatException;
import java.sql.Timestamp; | package javapns.devices.implementations.basic;
/**
* This class is used to represent a Device (iPhone)
*
* @author Maxime Peron
*/
public class BasicDevice implements Device {
/*
* An id representing a particular device.
*
* Note that this is a local reference to the device,
* which is not related to the actual device UUID or
* other device-specific identification. Most of the
* time, this deviceId should be the same as the token.
*/
private String deviceId;
/* The device token given by Apple Server, hexadecimal form, 64bits length */
private String token;
/* The last time a device registered */
private Timestamp lastRegister;
public BasicDevice() {
// empty
}
/**
* Default constructor.
*
* @param token The device token
*/ | // Path: src/main/java/javapns/devices/Device.java
// public interface Device {
// /**
// * An id representing a particular device.
// * <p>
// * Note that this is a local reference to the device,
// * which is not related to the actual device UUID or
// * other device-specific identification. Most of the
// * time, this deviceId should be the same as the token.
// *
// * @return the device id
// */
// String getDeviceId();
//
// /**
// * An id representing a particular device.
// * <p>
// * Note that this is a local reference to the device,
// * which is not related to the actual device UUID or
// * other device-specific identification. Most of the
// * time, this deviceId should be the same as the token.
// *
// * @param id the device id
// */
// void setDeviceId(String id);
//
// /**
// * A device token.
// *
// * @return the device token
// */
// String getToken();
//
// /**
// * Set the device token
// *
// * @param token
// */
// void setToken(String token);
//
// /**
// * @return the last register
// */
// Timestamp getLastRegister();
//
// /**
// * @param lastRegister the last register
// */
// void setLastRegister(Timestamp lastRegister);
// }
//
// Path: src/main/java/javapns/devices/exceptions/InvalidDeviceTokenFormatException.java
// public class InvalidDeviceTokenFormatException extends Exception {
//
// private static final long serialVersionUID = -8571997399252125457L;
//
// public InvalidDeviceTokenFormatException(final String message) {
// super(message);
// }
//
// public InvalidDeviceTokenFormatException(final String token, final String problem) {
// super(String.format("Device token cannot be parsed, most likely because it contains invalid hexadecimal characters: %s in %s", problem, token));
// }
//
// }
// Path: src/main/java/javapns/devices/implementations/basic/BasicDevice.java
import javapns.devices.Device;
import javapns.devices.exceptions.InvalidDeviceTokenFormatException;
import java.sql.Timestamp;
package javapns.devices.implementations.basic;
/**
* This class is used to represent a Device (iPhone)
*
* @author Maxime Peron
*/
public class BasicDevice implements Device {
/*
* An id representing a particular device.
*
* Note that this is a local reference to the device,
* which is not related to the actual device UUID or
* other device-specific identification. Most of the
* time, this deviceId should be the same as the token.
*/
private String deviceId;
/* The device token given by Apple Server, hexadecimal form, 64bits length */
private String token;
/* The last time a device registered */
private Timestamp lastRegister;
public BasicDevice() {
// empty
}
/**
* Default constructor.
*
* @param token The device token
*/ | public BasicDevice(final String token) throws InvalidDeviceTokenFormatException { |
mlaccetti/JavaPNS | src/main/java/javapns/communication/KeystoreManager.java | // Path: src/main/java/javapns/communication/exceptions/InvalidKeystoreFormatException.java
// public class InvalidKeystoreFormatException extends KeystoreException {
//
// private static final long serialVersionUID = 8822634206752412121L;
//
// /**
// * Constructor
// */
// public InvalidKeystoreFormatException() {
// super("Invalid keystore format! Make sure it is PKCS12...");
// }
//
// /**
// * Constructor with custom message
// *
// * @param message
// */
// public InvalidKeystoreFormatException(final String message) {
// super(message);
// }
//
// }
//
// Path: src/main/java/javapns/communication/exceptions/InvalidKeystorePasswordException.java
// public class InvalidKeystorePasswordException extends KeystoreException {
//
// private static final long serialVersionUID = 5973743951334025887L;
//
// /**
// * Constructor
// */
// public InvalidKeystorePasswordException() {
// super("Invalid keystore password! Verify settings for connecting to Apple...");
// }
//
// /**
// * Constructor with custom message
// *
// * @param message
// */
// public InvalidKeystorePasswordException(final String message) {
// super(message);
// }
//
// }
//
// Path: src/main/java/javapns/communication/exceptions/InvalidKeystoreReferenceException.java
// public class InvalidKeystoreReferenceException extends KeystoreException {
//
// private static final long serialVersionUID = 3144387163593035745L;
//
// /**
// * Constructor
// */
// public InvalidKeystoreReferenceException() {
// super("Invalid keystore parameter. Must be InputStream, File, String (as a file path), or byte[].");
// }
//
// /**
// * Constructor with custom message
// *
// * @param keystore
// */
// public InvalidKeystoreReferenceException(final Object keystore) {
// super("Invalid keystore parameter (" + keystore + "). Must be InputStream, File, String (as a file path), or byte[].");
// }
//
// /**
// * Constructor with custom message
// *
// * @param message
// */
// public InvalidKeystoreReferenceException(final String message) {
// super(message);
// }
// }
//
// Path: src/main/java/javapns/communication/exceptions/KeystoreException.java
// public class KeystoreException extends Exception {
//
// private static final long serialVersionUID = 2549063865160633139L;
//
// /**
// * Constructor with custom message
// *
// * @param message
// */
// public KeystoreException(final String message) {
// super(message);
// }
//
// /**
// * Constructor with custom message
// *
// * @param message
// */
// public KeystoreException(final String message, final Exception cause) {
// super(message, cause);
// }
//
// }
| import javapns.communication.exceptions.InvalidKeystoreFormatException;
import javapns.communication.exceptions.InvalidKeystorePasswordException;
import javapns.communication.exceptions.InvalidKeystoreReferenceException;
import javapns.communication.exceptions.KeystoreException;
import java.io.*;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.security.cert.CertificateExpiredException;
import java.security.cert.CertificateNotYetValidException;
import java.security.cert.X509Certificate;
import java.util.Enumeration; | package javapns.communication;
/**
* Class responsible for dealing with keystores.
*
* @author Sylvain Pedneault
*/
public class KeystoreManager {
private static final String REVIEW_MESSAGE = " Please review the procedure for generating a keystore for JavaPNS.";
private KeystoreManager() {}
/**
* Loads a keystore.
*
* @param server The server the keystore is intended for
* @return A loaded keystore
* @throws KeystoreException
*/ | // Path: src/main/java/javapns/communication/exceptions/InvalidKeystoreFormatException.java
// public class InvalidKeystoreFormatException extends KeystoreException {
//
// private static final long serialVersionUID = 8822634206752412121L;
//
// /**
// * Constructor
// */
// public InvalidKeystoreFormatException() {
// super("Invalid keystore format! Make sure it is PKCS12...");
// }
//
// /**
// * Constructor with custom message
// *
// * @param message
// */
// public InvalidKeystoreFormatException(final String message) {
// super(message);
// }
//
// }
//
// Path: src/main/java/javapns/communication/exceptions/InvalidKeystorePasswordException.java
// public class InvalidKeystorePasswordException extends KeystoreException {
//
// private static final long serialVersionUID = 5973743951334025887L;
//
// /**
// * Constructor
// */
// public InvalidKeystorePasswordException() {
// super("Invalid keystore password! Verify settings for connecting to Apple...");
// }
//
// /**
// * Constructor with custom message
// *
// * @param message
// */
// public InvalidKeystorePasswordException(final String message) {
// super(message);
// }
//
// }
//
// Path: src/main/java/javapns/communication/exceptions/InvalidKeystoreReferenceException.java
// public class InvalidKeystoreReferenceException extends KeystoreException {
//
// private static final long serialVersionUID = 3144387163593035745L;
//
// /**
// * Constructor
// */
// public InvalidKeystoreReferenceException() {
// super("Invalid keystore parameter. Must be InputStream, File, String (as a file path), or byte[].");
// }
//
// /**
// * Constructor with custom message
// *
// * @param keystore
// */
// public InvalidKeystoreReferenceException(final Object keystore) {
// super("Invalid keystore parameter (" + keystore + "). Must be InputStream, File, String (as a file path), or byte[].");
// }
//
// /**
// * Constructor with custom message
// *
// * @param message
// */
// public InvalidKeystoreReferenceException(final String message) {
// super(message);
// }
// }
//
// Path: src/main/java/javapns/communication/exceptions/KeystoreException.java
// public class KeystoreException extends Exception {
//
// private static final long serialVersionUID = 2549063865160633139L;
//
// /**
// * Constructor with custom message
// *
// * @param message
// */
// public KeystoreException(final String message) {
// super(message);
// }
//
// /**
// * Constructor with custom message
// *
// * @param message
// */
// public KeystoreException(final String message, final Exception cause) {
// super(message, cause);
// }
//
// }
// Path: src/main/java/javapns/communication/KeystoreManager.java
import javapns.communication.exceptions.InvalidKeystoreFormatException;
import javapns.communication.exceptions.InvalidKeystorePasswordException;
import javapns.communication.exceptions.InvalidKeystoreReferenceException;
import javapns.communication.exceptions.KeystoreException;
import java.io.*;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.security.cert.CertificateExpiredException;
import java.security.cert.CertificateNotYetValidException;
import java.security.cert.X509Certificate;
import java.util.Enumeration;
package javapns.communication;
/**
* Class responsible for dealing with keystores.
*
* @author Sylvain Pedneault
*/
public class KeystoreManager {
private static final String REVIEW_MESSAGE = " Please review the procedure for generating a keystore for JavaPNS.";
private KeystoreManager() {}
/**
* Loads a keystore.
*
* @param server The server the keystore is intended for
* @return A loaded keystore
* @throws KeystoreException
*/ | static KeyStore loadKeystore(final AppleServer server) throws KeystoreException { |
mlaccetti/JavaPNS | src/main/java/javapns/communication/KeystoreManager.java | // Path: src/main/java/javapns/communication/exceptions/InvalidKeystoreFormatException.java
// public class InvalidKeystoreFormatException extends KeystoreException {
//
// private static final long serialVersionUID = 8822634206752412121L;
//
// /**
// * Constructor
// */
// public InvalidKeystoreFormatException() {
// super("Invalid keystore format! Make sure it is PKCS12...");
// }
//
// /**
// * Constructor with custom message
// *
// * @param message
// */
// public InvalidKeystoreFormatException(final String message) {
// super(message);
// }
//
// }
//
// Path: src/main/java/javapns/communication/exceptions/InvalidKeystorePasswordException.java
// public class InvalidKeystorePasswordException extends KeystoreException {
//
// private static final long serialVersionUID = 5973743951334025887L;
//
// /**
// * Constructor
// */
// public InvalidKeystorePasswordException() {
// super("Invalid keystore password! Verify settings for connecting to Apple...");
// }
//
// /**
// * Constructor with custom message
// *
// * @param message
// */
// public InvalidKeystorePasswordException(final String message) {
// super(message);
// }
//
// }
//
// Path: src/main/java/javapns/communication/exceptions/InvalidKeystoreReferenceException.java
// public class InvalidKeystoreReferenceException extends KeystoreException {
//
// private static final long serialVersionUID = 3144387163593035745L;
//
// /**
// * Constructor
// */
// public InvalidKeystoreReferenceException() {
// super("Invalid keystore parameter. Must be InputStream, File, String (as a file path), or byte[].");
// }
//
// /**
// * Constructor with custom message
// *
// * @param keystore
// */
// public InvalidKeystoreReferenceException(final Object keystore) {
// super("Invalid keystore parameter (" + keystore + "). Must be InputStream, File, String (as a file path), or byte[].");
// }
//
// /**
// * Constructor with custom message
// *
// * @param message
// */
// public InvalidKeystoreReferenceException(final String message) {
// super(message);
// }
// }
//
// Path: src/main/java/javapns/communication/exceptions/KeystoreException.java
// public class KeystoreException extends Exception {
//
// private static final long serialVersionUID = 2549063865160633139L;
//
// /**
// * Constructor with custom message
// *
// * @param message
// */
// public KeystoreException(final String message) {
// super(message);
// }
//
// /**
// * Constructor with custom message
// *
// * @param message
// */
// public KeystoreException(final String message, final Exception cause) {
// super(message, cause);
// }
//
// }
| import javapns.communication.exceptions.InvalidKeystoreFormatException;
import javapns.communication.exceptions.InvalidKeystorePasswordException;
import javapns.communication.exceptions.InvalidKeystoreReferenceException;
import javapns.communication.exceptions.KeystoreException;
import java.io.*;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.security.cert.CertificateExpiredException;
import java.security.cert.CertificateNotYetValidException;
import java.security.cert.X509Certificate;
import java.util.Enumeration; | throw new KeystoreException("Keystore does not contain any valid certificate." + REVIEW_MESSAGE);
}
if (numberOfCertificates > 1) {
throw new KeystoreException("Keystore contains too many certificates." + REVIEW_MESSAGE);
}
} catch (final KeystoreException e) {
throw e;
} catch (final CertificateExpiredException e) {
throw new KeystoreException("Certificate is expired. A new one must be issued.", e);
} catch (final CertificateNotYetValidException e) {
throw new KeystoreException("Certificate is not yet valid. Wait until the validity period is reached or issue a new certificate.", e);
} catch (final Exception e) {
/* We ignore any other exception, as we do not want to interrupt the process because of an error we did not expect. */
}
}
static char[] getKeystorePasswordForSSL(final AppleServer server) {
String password = server.getKeystorePassword();
if (password == null) {
password = "";
}
return password.toCharArray();
}
static KeystoreException wrapKeystoreException(final Exception e) {
if (e != null) {
final String msg = e.toString();
if (msg.contains("javax.crypto.BadPaddingException")) { | // Path: src/main/java/javapns/communication/exceptions/InvalidKeystoreFormatException.java
// public class InvalidKeystoreFormatException extends KeystoreException {
//
// private static final long serialVersionUID = 8822634206752412121L;
//
// /**
// * Constructor
// */
// public InvalidKeystoreFormatException() {
// super("Invalid keystore format! Make sure it is PKCS12...");
// }
//
// /**
// * Constructor with custom message
// *
// * @param message
// */
// public InvalidKeystoreFormatException(final String message) {
// super(message);
// }
//
// }
//
// Path: src/main/java/javapns/communication/exceptions/InvalidKeystorePasswordException.java
// public class InvalidKeystorePasswordException extends KeystoreException {
//
// private static final long serialVersionUID = 5973743951334025887L;
//
// /**
// * Constructor
// */
// public InvalidKeystorePasswordException() {
// super("Invalid keystore password! Verify settings for connecting to Apple...");
// }
//
// /**
// * Constructor with custom message
// *
// * @param message
// */
// public InvalidKeystorePasswordException(final String message) {
// super(message);
// }
//
// }
//
// Path: src/main/java/javapns/communication/exceptions/InvalidKeystoreReferenceException.java
// public class InvalidKeystoreReferenceException extends KeystoreException {
//
// private static final long serialVersionUID = 3144387163593035745L;
//
// /**
// * Constructor
// */
// public InvalidKeystoreReferenceException() {
// super("Invalid keystore parameter. Must be InputStream, File, String (as a file path), or byte[].");
// }
//
// /**
// * Constructor with custom message
// *
// * @param keystore
// */
// public InvalidKeystoreReferenceException(final Object keystore) {
// super("Invalid keystore parameter (" + keystore + "). Must be InputStream, File, String (as a file path), or byte[].");
// }
//
// /**
// * Constructor with custom message
// *
// * @param message
// */
// public InvalidKeystoreReferenceException(final String message) {
// super(message);
// }
// }
//
// Path: src/main/java/javapns/communication/exceptions/KeystoreException.java
// public class KeystoreException extends Exception {
//
// private static final long serialVersionUID = 2549063865160633139L;
//
// /**
// * Constructor with custom message
// *
// * @param message
// */
// public KeystoreException(final String message) {
// super(message);
// }
//
// /**
// * Constructor with custom message
// *
// * @param message
// */
// public KeystoreException(final String message, final Exception cause) {
// super(message, cause);
// }
//
// }
// Path: src/main/java/javapns/communication/KeystoreManager.java
import javapns.communication.exceptions.InvalidKeystoreFormatException;
import javapns.communication.exceptions.InvalidKeystorePasswordException;
import javapns.communication.exceptions.InvalidKeystoreReferenceException;
import javapns.communication.exceptions.KeystoreException;
import java.io.*;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.security.cert.CertificateExpiredException;
import java.security.cert.CertificateNotYetValidException;
import java.security.cert.X509Certificate;
import java.util.Enumeration;
throw new KeystoreException("Keystore does not contain any valid certificate." + REVIEW_MESSAGE);
}
if (numberOfCertificates > 1) {
throw new KeystoreException("Keystore contains too many certificates." + REVIEW_MESSAGE);
}
} catch (final KeystoreException e) {
throw e;
} catch (final CertificateExpiredException e) {
throw new KeystoreException("Certificate is expired. A new one must be issued.", e);
} catch (final CertificateNotYetValidException e) {
throw new KeystoreException("Certificate is not yet valid. Wait until the validity period is reached or issue a new certificate.", e);
} catch (final Exception e) {
/* We ignore any other exception, as we do not want to interrupt the process because of an error we did not expect. */
}
}
static char[] getKeystorePasswordForSSL(final AppleServer server) {
String password = server.getKeystorePassword();
if (password == null) {
password = "";
}
return password.toCharArray();
}
static KeystoreException wrapKeystoreException(final Exception e) {
if (e != null) {
final String msg = e.toString();
if (msg.contains("javax.crypto.BadPaddingException")) { | return new InvalidKeystorePasswordException(); |
mlaccetti/JavaPNS | src/main/java/javapns/communication/KeystoreManager.java | // Path: src/main/java/javapns/communication/exceptions/InvalidKeystoreFormatException.java
// public class InvalidKeystoreFormatException extends KeystoreException {
//
// private static final long serialVersionUID = 8822634206752412121L;
//
// /**
// * Constructor
// */
// public InvalidKeystoreFormatException() {
// super("Invalid keystore format! Make sure it is PKCS12...");
// }
//
// /**
// * Constructor with custom message
// *
// * @param message
// */
// public InvalidKeystoreFormatException(final String message) {
// super(message);
// }
//
// }
//
// Path: src/main/java/javapns/communication/exceptions/InvalidKeystorePasswordException.java
// public class InvalidKeystorePasswordException extends KeystoreException {
//
// private static final long serialVersionUID = 5973743951334025887L;
//
// /**
// * Constructor
// */
// public InvalidKeystorePasswordException() {
// super("Invalid keystore password! Verify settings for connecting to Apple...");
// }
//
// /**
// * Constructor with custom message
// *
// * @param message
// */
// public InvalidKeystorePasswordException(final String message) {
// super(message);
// }
//
// }
//
// Path: src/main/java/javapns/communication/exceptions/InvalidKeystoreReferenceException.java
// public class InvalidKeystoreReferenceException extends KeystoreException {
//
// private static final long serialVersionUID = 3144387163593035745L;
//
// /**
// * Constructor
// */
// public InvalidKeystoreReferenceException() {
// super("Invalid keystore parameter. Must be InputStream, File, String (as a file path), or byte[].");
// }
//
// /**
// * Constructor with custom message
// *
// * @param keystore
// */
// public InvalidKeystoreReferenceException(final Object keystore) {
// super("Invalid keystore parameter (" + keystore + "). Must be InputStream, File, String (as a file path), or byte[].");
// }
//
// /**
// * Constructor with custom message
// *
// * @param message
// */
// public InvalidKeystoreReferenceException(final String message) {
// super(message);
// }
// }
//
// Path: src/main/java/javapns/communication/exceptions/KeystoreException.java
// public class KeystoreException extends Exception {
//
// private static final long serialVersionUID = 2549063865160633139L;
//
// /**
// * Constructor with custom message
// *
// * @param message
// */
// public KeystoreException(final String message) {
// super(message);
// }
//
// /**
// * Constructor with custom message
// *
// * @param message
// */
// public KeystoreException(final String message, final Exception cause) {
// super(message, cause);
// }
//
// }
| import javapns.communication.exceptions.InvalidKeystoreFormatException;
import javapns.communication.exceptions.InvalidKeystorePasswordException;
import javapns.communication.exceptions.InvalidKeystoreReferenceException;
import javapns.communication.exceptions.KeystoreException;
import java.io.*;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.security.cert.CertificateExpiredException;
import java.security.cert.CertificateNotYetValidException;
import java.security.cert.X509Certificate;
import java.util.Enumeration; | throw new KeystoreException("Keystore contains too many certificates." + REVIEW_MESSAGE);
}
} catch (final KeystoreException e) {
throw e;
} catch (final CertificateExpiredException e) {
throw new KeystoreException("Certificate is expired. A new one must be issued.", e);
} catch (final CertificateNotYetValidException e) {
throw new KeystoreException("Certificate is not yet valid. Wait until the validity period is reached or issue a new certificate.", e);
} catch (final Exception e) {
/* We ignore any other exception, as we do not want to interrupt the process because of an error we did not expect. */
}
}
static char[] getKeystorePasswordForSSL(final AppleServer server) {
String password = server.getKeystorePassword();
if (password == null) {
password = "";
}
return password.toCharArray();
}
static KeystoreException wrapKeystoreException(final Exception e) {
if (e != null) {
final String msg = e.toString();
if (msg.contains("javax.crypto.BadPaddingException")) {
return new InvalidKeystorePasswordException();
}
if (msg.contains("DerInputStream.getLength(): lengthTag=127, too big")) { | // Path: src/main/java/javapns/communication/exceptions/InvalidKeystoreFormatException.java
// public class InvalidKeystoreFormatException extends KeystoreException {
//
// private static final long serialVersionUID = 8822634206752412121L;
//
// /**
// * Constructor
// */
// public InvalidKeystoreFormatException() {
// super("Invalid keystore format! Make sure it is PKCS12...");
// }
//
// /**
// * Constructor with custom message
// *
// * @param message
// */
// public InvalidKeystoreFormatException(final String message) {
// super(message);
// }
//
// }
//
// Path: src/main/java/javapns/communication/exceptions/InvalidKeystorePasswordException.java
// public class InvalidKeystorePasswordException extends KeystoreException {
//
// private static final long serialVersionUID = 5973743951334025887L;
//
// /**
// * Constructor
// */
// public InvalidKeystorePasswordException() {
// super("Invalid keystore password! Verify settings for connecting to Apple...");
// }
//
// /**
// * Constructor with custom message
// *
// * @param message
// */
// public InvalidKeystorePasswordException(final String message) {
// super(message);
// }
//
// }
//
// Path: src/main/java/javapns/communication/exceptions/InvalidKeystoreReferenceException.java
// public class InvalidKeystoreReferenceException extends KeystoreException {
//
// private static final long serialVersionUID = 3144387163593035745L;
//
// /**
// * Constructor
// */
// public InvalidKeystoreReferenceException() {
// super("Invalid keystore parameter. Must be InputStream, File, String (as a file path), or byte[].");
// }
//
// /**
// * Constructor with custom message
// *
// * @param keystore
// */
// public InvalidKeystoreReferenceException(final Object keystore) {
// super("Invalid keystore parameter (" + keystore + "). Must be InputStream, File, String (as a file path), or byte[].");
// }
//
// /**
// * Constructor with custom message
// *
// * @param message
// */
// public InvalidKeystoreReferenceException(final String message) {
// super(message);
// }
// }
//
// Path: src/main/java/javapns/communication/exceptions/KeystoreException.java
// public class KeystoreException extends Exception {
//
// private static final long serialVersionUID = 2549063865160633139L;
//
// /**
// * Constructor with custom message
// *
// * @param message
// */
// public KeystoreException(final String message) {
// super(message);
// }
//
// /**
// * Constructor with custom message
// *
// * @param message
// */
// public KeystoreException(final String message, final Exception cause) {
// super(message, cause);
// }
//
// }
// Path: src/main/java/javapns/communication/KeystoreManager.java
import javapns.communication.exceptions.InvalidKeystoreFormatException;
import javapns.communication.exceptions.InvalidKeystorePasswordException;
import javapns.communication.exceptions.InvalidKeystoreReferenceException;
import javapns.communication.exceptions.KeystoreException;
import java.io.*;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.security.cert.CertificateExpiredException;
import java.security.cert.CertificateNotYetValidException;
import java.security.cert.X509Certificate;
import java.util.Enumeration;
throw new KeystoreException("Keystore contains too many certificates." + REVIEW_MESSAGE);
}
} catch (final KeystoreException e) {
throw e;
} catch (final CertificateExpiredException e) {
throw new KeystoreException("Certificate is expired. A new one must be issued.", e);
} catch (final CertificateNotYetValidException e) {
throw new KeystoreException("Certificate is not yet valid. Wait until the validity period is reached or issue a new certificate.", e);
} catch (final Exception e) {
/* We ignore any other exception, as we do not want to interrupt the process because of an error we did not expect. */
}
}
static char[] getKeystorePasswordForSSL(final AppleServer server) {
String password = server.getKeystorePassword();
if (password == null) {
password = "";
}
return password.toCharArray();
}
static KeystoreException wrapKeystoreException(final Exception e) {
if (e != null) {
final String msg = e.toString();
if (msg.contains("javax.crypto.BadPaddingException")) {
return new InvalidKeystorePasswordException();
}
if (msg.contains("DerInputStream.getLength(): lengthTag=127, too big")) { | return new InvalidKeystoreFormatException(); |
mlaccetti/JavaPNS | src/main/java/javapns/communication/KeystoreManager.java | // Path: src/main/java/javapns/communication/exceptions/InvalidKeystoreFormatException.java
// public class InvalidKeystoreFormatException extends KeystoreException {
//
// private static final long serialVersionUID = 8822634206752412121L;
//
// /**
// * Constructor
// */
// public InvalidKeystoreFormatException() {
// super("Invalid keystore format! Make sure it is PKCS12...");
// }
//
// /**
// * Constructor with custom message
// *
// * @param message
// */
// public InvalidKeystoreFormatException(final String message) {
// super(message);
// }
//
// }
//
// Path: src/main/java/javapns/communication/exceptions/InvalidKeystorePasswordException.java
// public class InvalidKeystorePasswordException extends KeystoreException {
//
// private static final long serialVersionUID = 5973743951334025887L;
//
// /**
// * Constructor
// */
// public InvalidKeystorePasswordException() {
// super("Invalid keystore password! Verify settings for connecting to Apple...");
// }
//
// /**
// * Constructor with custom message
// *
// * @param message
// */
// public InvalidKeystorePasswordException(final String message) {
// super(message);
// }
//
// }
//
// Path: src/main/java/javapns/communication/exceptions/InvalidKeystoreReferenceException.java
// public class InvalidKeystoreReferenceException extends KeystoreException {
//
// private static final long serialVersionUID = 3144387163593035745L;
//
// /**
// * Constructor
// */
// public InvalidKeystoreReferenceException() {
// super("Invalid keystore parameter. Must be InputStream, File, String (as a file path), or byte[].");
// }
//
// /**
// * Constructor with custom message
// *
// * @param keystore
// */
// public InvalidKeystoreReferenceException(final Object keystore) {
// super("Invalid keystore parameter (" + keystore + "). Must be InputStream, File, String (as a file path), or byte[].");
// }
//
// /**
// * Constructor with custom message
// *
// * @param message
// */
// public InvalidKeystoreReferenceException(final String message) {
// super(message);
// }
// }
//
// Path: src/main/java/javapns/communication/exceptions/KeystoreException.java
// public class KeystoreException extends Exception {
//
// private static final long serialVersionUID = 2549063865160633139L;
//
// /**
// * Constructor with custom message
// *
// * @param message
// */
// public KeystoreException(final String message) {
// super(message);
// }
//
// /**
// * Constructor with custom message
// *
// * @param message
// */
// public KeystoreException(final String message, final Exception cause) {
// super(message, cause);
// }
//
// }
| import javapns.communication.exceptions.InvalidKeystoreFormatException;
import javapns.communication.exceptions.InvalidKeystorePasswordException;
import javapns.communication.exceptions.InvalidKeystoreReferenceException;
import javapns.communication.exceptions.KeystoreException;
import java.io.*;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.security.cert.CertificateExpiredException;
import java.security.cert.CertificateNotYetValidException;
import java.security.cert.X509Certificate;
import java.util.Enumeration; |
return password.toCharArray();
}
static KeystoreException wrapKeystoreException(final Exception e) {
if (e != null) {
final String msg = e.toString();
if (msg.contains("javax.crypto.BadPaddingException")) {
return new InvalidKeystorePasswordException();
}
if (msg.contains("DerInputStream.getLength(): lengthTag=127, too big")) {
return new InvalidKeystoreFormatException();
}
if (msg.contains("java.lang.ArithmeticException: / by zero") || msg.contains("java.security.UnrecoverableKeyException: Get Key failed: / by zero")) {
return new InvalidKeystorePasswordException("Blank passwords not supported (#38). You must create your keystore with a non-empty password.");
}
}
return new KeystoreException("Keystore exception: " + (e != null ? e.getMessage() : null), e);
}
/**
* Given an object representing a keystore, returns an actual stream for that keystore.
* Allows you to provide an actual keystore as an InputStream or a byte[] array,
* or a reference to a keystore file as a File object or a String path.
*
* @param keystore a keystore containing your private key and the certificate signed by Apple (File, InputStream, byte[], KeyStore or String for a file path)
* @return A stream to the keystore.
* @throws InvalidKeystoreReferenceException
*/ | // Path: src/main/java/javapns/communication/exceptions/InvalidKeystoreFormatException.java
// public class InvalidKeystoreFormatException extends KeystoreException {
//
// private static final long serialVersionUID = 8822634206752412121L;
//
// /**
// * Constructor
// */
// public InvalidKeystoreFormatException() {
// super("Invalid keystore format! Make sure it is PKCS12...");
// }
//
// /**
// * Constructor with custom message
// *
// * @param message
// */
// public InvalidKeystoreFormatException(final String message) {
// super(message);
// }
//
// }
//
// Path: src/main/java/javapns/communication/exceptions/InvalidKeystorePasswordException.java
// public class InvalidKeystorePasswordException extends KeystoreException {
//
// private static final long serialVersionUID = 5973743951334025887L;
//
// /**
// * Constructor
// */
// public InvalidKeystorePasswordException() {
// super("Invalid keystore password! Verify settings for connecting to Apple...");
// }
//
// /**
// * Constructor with custom message
// *
// * @param message
// */
// public InvalidKeystorePasswordException(final String message) {
// super(message);
// }
//
// }
//
// Path: src/main/java/javapns/communication/exceptions/InvalidKeystoreReferenceException.java
// public class InvalidKeystoreReferenceException extends KeystoreException {
//
// private static final long serialVersionUID = 3144387163593035745L;
//
// /**
// * Constructor
// */
// public InvalidKeystoreReferenceException() {
// super("Invalid keystore parameter. Must be InputStream, File, String (as a file path), or byte[].");
// }
//
// /**
// * Constructor with custom message
// *
// * @param keystore
// */
// public InvalidKeystoreReferenceException(final Object keystore) {
// super("Invalid keystore parameter (" + keystore + "). Must be InputStream, File, String (as a file path), or byte[].");
// }
//
// /**
// * Constructor with custom message
// *
// * @param message
// */
// public InvalidKeystoreReferenceException(final String message) {
// super(message);
// }
// }
//
// Path: src/main/java/javapns/communication/exceptions/KeystoreException.java
// public class KeystoreException extends Exception {
//
// private static final long serialVersionUID = 2549063865160633139L;
//
// /**
// * Constructor with custom message
// *
// * @param message
// */
// public KeystoreException(final String message) {
// super(message);
// }
//
// /**
// * Constructor with custom message
// *
// * @param message
// */
// public KeystoreException(final String message, final Exception cause) {
// super(message, cause);
// }
//
// }
// Path: src/main/java/javapns/communication/KeystoreManager.java
import javapns.communication.exceptions.InvalidKeystoreFormatException;
import javapns.communication.exceptions.InvalidKeystorePasswordException;
import javapns.communication.exceptions.InvalidKeystoreReferenceException;
import javapns.communication.exceptions.KeystoreException;
import java.io.*;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.security.cert.CertificateExpiredException;
import java.security.cert.CertificateNotYetValidException;
import java.security.cert.X509Certificate;
import java.util.Enumeration;
return password.toCharArray();
}
static KeystoreException wrapKeystoreException(final Exception e) {
if (e != null) {
final String msg = e.toString();
if (msg.contains("javax.crypto.BadPaddingException")) {
return new InvalidKeystorePasswordException();
}
if (msg.contains("DerInputStream.getLength(): lengthTag=127, too big")) {
return new InvalidKeystoreFormatException();
}
if (msg.contains("java.lang.ArithmeticException: / by zero") || msg.contains("java.security.UnrecoverableKeyException: Get Key failed: / by zero")) {
return new InvalidKeystorePasswordException("Blank passwords not supported (#38). You must create your keystore with a non-empty password.");
}
}
return new KeystoreException("Keystore exception: " + (e != null ? e.getMessage() : null), e);
}
/**
* Given an object representing a keystore, returns an actual stream for that keystore.
* Allows you to provide an actual keystore as an InputStream or a byte[] array,
* or a reference to a keystore file as a File object or a String path.
*
* @param keystore a keystore containing your private key and the certificate signed by Apple (File, InputStream, byte[], KeyStore or String for a file path)
* @return A stream to the keystore.
* @throws InvalidKeystoreReferenceException
*/ | static InputStream streamKeystore(final Object keystore) throws InvalidKeystoreReferenceException { |
mlaccetti/JavaPNS | src/main/java/javapns/notification/transmission/NotificationThreads.java | // Path: src/main/java/javapns/devices/Device.java
// public interface Device {
// /**
// * An id representing a particular device.
// * <p>
// * Note that this is a local reference to the device,
// * which is not related to the actual device UUID or
// * other device-specific identification. Most of the
// * time, this deviceId should be the same as the token.
// *
// * @return the device id
// */
// String getDeviceId();
//
// /**
// * An id representing a particular device.
// * <p>
// * Note that this is a local reference to the device,
// * which is not related to the actual device UUID or
// * other device-specific identification. Most of the
// * time, this deviceId should be the same as the token.
// *
// * @param id the device id
// */
// void setDeviceId(String id);
//
// /**
// * A device token.
// *
// * @return the device token
// */
// String getToken();
//
// /**
// * Set the device token
// *
// * @param token
// */
// void setToken(String token);
//
// /**
// * @return the last register
// */
// Timestamp getLastRegister();
//
// /**
// * @param lastRegister the last register
// */
// void setLastRegister(Timestamp lastRegister);
// }
//
// Path: src/main/java/javapns/devices/Devices.java
// public class Devices {
//
// private Devices() {}
//
// public static List<Device> asDevices(final Object rawList) {
// final List<Device> list = new ArrayList<>();
// if (rawList == null) {
// return list;
// }
//
// if (rawList instanceof List) {
// final List devices = (List) rawList;
// if (devices.isEmpty()) {
// return list;
// }
//
// final Object firstDevice = devices.get(0);
// if (firstDevice instanceof Device) {
// //noinspection unchecked
// return devices;
// } else if (firstDevice instanceof String) {
// for (final Object token : devices) {
// final BasicDevice device = new BasicDevice();
// device.setToken((String) token);
// list.add(device);
// }
// }
// } else if (rawList instanceof String[]) {
// final String[] tokens = (String[]) rawList;
// for (final String token : tokens) {
// final BasicDevice device = new BasicDevice();
// device.setToken(token);
// list.add(device);
// }
// } else if (rawList instanceof Device[]) {
// final Device[] dvs = (Device[]) rawList;
// return Arrays.asList(dvs);
// } else if (rawList instanceof String) {
// final BasicDevice device = new BasicDevice();
// device.setToken((String) rawList);
// list.add(device);
// } else if (rawList instanceof Device) {
// list.add((Device) rawList);
// } else {
// throw new IllegalArgumentException("Device list type not supported. Supported types are: String[], List<String>, Device[], List<Device>, String and Device");
// }
// return list;
// }
//
// public static List<PayloadPerDevice> asPayloadsPerDevices(final Object rawList) {
// final List<PayloadPerDevice> list = new ArrayList<>();
// if (rawList == null) {
// return list;
// }
// if (rawList instanceof List) {
// final List devices = (List) rawList;
// if (devices.isEmpty()) {
// return list;
// }
// //noinspection unchecked
// return devices;
// } else if (rawList instanceof PayloadPerDevice[]) {
// final PayloadPerDevice[] dvs = (PayloadPerDevice[]) rawList;
// return Arrays.asList(dvs);
// } else if (rawList instanceof PayloadPerDevice) {
// list.add((PayloadPerDevice) rawList);
// } else {
// throw new IllegalArgumentException("PayloadPerDevice list type not supported. Supported types are: PayloadPerDevice[], List<PayloadPerDevice> and PayloadPerDevice");
// }
// return list;
// }
// }
//
// Path: src/main/java/javapns/devices/exceptions/InvalidDeviceTokenFormatException.java
// public class InvalidDeviceTokenFormatException extends Exception {
//
// private static final long serialVersionUID = -8571997399252125457L;
//
// public InvalidDeviceTokenFormatException(final String message) {
// super(message);
// }
//
// public InvalidDeviceTokenFormatException(final String token, final String problem) {
// super(String.format("Device token cannot be parsed, most likely because it contains invalid hexadecimal characters: %s in %s", problem, token));
// }
//
// }
| import javapns.devices.Device;
import javapns.devices.Devices;
import javapns.devices.exceptions.InvalidDeviceTokenFormatException;
import javapns.notification.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import java.util.stream.Collectors; | package javapns.notification.transmission;
/**
* <h1>Pushes a payload to a large number of devices using multiple threads</h1>
* <p>
* <p>The list of devices is spread evenly into multiple {@link javapns.notification.transmission.NotificationThread}s.</p>
* <p>
* <p>Usage: once a NotificationThreads is created, invoke {@code start()} to start all {@link javapns.notification.transmission.NotificationThread} threads.</p>
* <p>You can provide a {@link javapns.notification.transmission.NotificationProgressListener} to receive events about the work being done.</p>
*
* @author Sylvain Pedneault
* @see NotificationThread.MODE
* @see NotificationThread
*/
public class NotificationThreads extends ThreadGroup implements PushQueue {
private static final long DEFAULT_DELAY_BETWEEN_THREADS = 500; // the number of milliseconds to wait between each thread startup
private static final String JAVAPNS_NOTIFICATION_THREADS = "javapns notification threads (";
private static final String THREADS = " threads)";
private final Object finishPoint = new Object();
private List<NotificationThread> threads = new ArrayList<>();
private NotificationProgressListener listener;
private boolean started = false;
private int threadsRunning = 0;
private int nextThread = 0;
private long delayBetweenThreads = DEFAULT_DELAY_BETWEEN_THREADS;
/**
* Create the specified number of notification threads and spread the devices evenly between the threads.
*
* @param server the server to push to
* @param payload the payload to push
* @param devices a very large list of devices
* @param numberOfThreads the number of threads to create to share the work
*/ | // Path: src/main/java/javapns/devices/Device.java
// public interface Device {
// /**
// * An id representing a particular device.
// * <p>
// * Note that this is a local reference to the device,
// * which is not related to the actual device UUID or
// * other device-specific identification. Most of the
// * time, this deviceId should be the same as the token.
// *
// * @return the device id
// */
// String getDeviceId();
//
// /**
// * An id representing a particular device.
// * <p>
// * Note that this is a local reference to the device,
// * which is not related to the actual device UUID or
// * other device-specific identification. Most of the
// * time, this deviceId should be the same as the token.
// *
// * @param id the device id
// */
// void setDeviceId(String id);
//
// /**
// * A device token.
// *
// * @return the device token
// */
// String getToken();
//
// /**
// * Set the device token
// *
// * @param token
// */
// void setToken(String token);
//
// /**
// * @return the last register
// */
// Timestamp getLastRegister();
//
// /**
// * @param lastRegister the last register
// */
// void setLastRegister(Timestamp lastRegister);
// }
//
// Path: src/main/java/javapns/devices/Devices.java
// public class Devices {
//
// private Devices() {}
//
// public static List<Device> asDevices(final Object rawList) {
// final List<Device> list = new ArrayList<>();
// if (rawList == null) {
// return list;
// }
//
// if (rawList instanceof List) {
// final List devices = (List) rawList;
// if (devices.isEmpty()) {
// return list;
// }
//
// final Object firstDevice = devices.get(0);
// if (firstDevice instanceof Device) {
// //noinspection unchecked
// return devices;
// } else if (firstDevice instanceof String) {
// for (final Object token : devices) {
// final BasicDevice device = new BasicDevice();
// device.setToken((String) token);
// list.add(device);
// }
// }
// } else if (rawList instanceof String[]) {
// final String[] tokens = (String[]) rawList;
// for (final String token : tokens) {
// final BasicDevice device = new BasicDevice();
// device.setToken(token);
// list.add(device);
// }
// } else if (rawList instanceof Device[]) {
// final Device[] dvs = (Device[]) rawList;
// return Arrays.asList(dvs);
// } else if (rawList instanceof String) {
// final BasicDevice device = new BasicDevice();
// device.setToken((String) rawList);
// list.add(device);
// } else if (rawList instanceof Device) {
// list.add((Device) rawList);
// } else {
// throw new IllegalArgumentException("Device list type not supported. Supported types are: String[], List<String>, Device[], List<Device>, String and Device");
// }
// return list;
// }
//
// public static List<PayloadPerDevice> asPayloadsPerDevices(final Object rawList) {
// final List<PayloadPerDevice> list = new ArrayList<>();
// if (rawList == null) {
// return list;
// }
// if (rawList instanceof List) {
// final List devices = (List) rawList;
// if (devices.isEmpty()) {
// return list;
// }
// //noinspection unchecked
// return devices;
// } else if (rawList instanceof PayloadPerDevice[]) {
// final PayloadPerDevice[] dvs = (PayloadPerDevice[]) rawList;
// return Arrays.asList(dvs);
// } else if (rawList instanceof PayloadPerDevice) {
// list.add((PayloadPerDevice) rawList);
// } else {
// throw new IllegalArgumentException("PayloadPerDevice list type not supported. Supported types are: PayloadPerDevice[], List<PayloadPerDevice> and PayloadPerDevice");
// }
// return list;
// }
// }
//
// Path: src/main/java/javapns/devices/exceptions/InvalidDeviceTokenFormatException.java
// public class InvalidDeviceTokenFormatException extends Exception {
//
// private static final long serialVersionUID = -8571997399252125457L;
//
// public InvalidDeviceTokenFormatException(final String message) {
// super(message);
// }
//
// public InvalidDeviceTokenFormatException(final String token, final String problem) {
// super(String.format("Device token cannot be parsed, most likely because it contains invalid hexadecimal characters: %s in %s", problem, token));
// }
//
// }
// Path: src/main/java/javapns/notification/transmission/NotificationThreads.java
import javapns.devices.Device;
import javapns.devices.Devices;
import javapns.devices.exceptions.InvalidDeviceTokenFormatException;
import javapns.notification.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import java.util.stream.Collectors;
package javapns.notification.transmission;
/**
* <h1>Pushes a payload to a large number of devices using multiple threads</h1>
* <p>
* <p>The list of devices is spread evenly into multiple {@link javapns.notification.transmission.NotificationThread}s.</p>
* <p>
* <p>Usage: once a NotificationThreads is created, invoke {@code start()} to start all {@link javapns.notification.transmission.NotificationThread} threads.</p>
* <p>You can provide a {@link javapns.notification.transmission.NotificationProgressListener} to receive events about the work being done.</p>
*
* @author Sylvain Pedneault
* @see NotificationThread.MODE
* @see NotificationThread
*/
public class NotificationThreads extends ThreadGroup implements PushQueue {
private static final long DEFAULT_DELAY_BETWEEN_THREADS = 500; // the number of milliseconds to wait between each thread startup
private static final String JAVAPNS_NOTIFICATION_THREADS = "javapns notification threads (";
private static final String THREADS = " threads)";
private final Object finishPoint = new Object();
private List<NotificationThread> threads = new ArrayList<>();
private NotificationProgressListener listener;
private boolean started = false;
private int threadsRunning = 0;
private int nextThread = 0;
private long delayBetweenThreads = DEFAULT_DELAY_BETWEEN_THREADS;
/**
* Create the specified number of notification threads and spread the devices evenly between the threads.
*
* @param server the server to push to
* @param payload the payload to push
* @param devices a very large list of devices
* @param numberOfThreads the number of threads to create to share the work
*/ | public NotificationThreads(final AppleNotificationServer server, final Payload payload, final List<Device> devices, final int numberOfThreads) { |
mlaccetti/JavaPNS | src/main/java/javapns/notification/transmission/NotificationThreads.java | // Path: src/main/java/javapns/devices/Device.java
// public interface Device {
// /**
// * An id representing a particular device.
// * <p>
// * Note that this is a local reference to the device,
// * which is not related to the actual device UUID or
// * other device-specific identification. Most of the
// * time, this deviceId should be the same as the token.
// *
// * @return the device id
// */
// String getDeviceId();
//
// /**
// * An id representing a particular device.
// * <p>
// * Note that this is a local reference to the device,
// * which is not related to the actual device UUID or
// * other device-specific identification. Most of the
// * time, this deviceId should be the same as the token.
// *
// * @param id the device id
// */
// void setDeviceId(String id);
//
// /**
// * A device token.
// *
// * @return the device token
// */
// String getToken();
//
// /**
// * Set the device token
// *
// * @param token
// */
// void setToken(String token);
//
// /**
// * @return the last register
// */
// Timestamp getLastRegister();
//
// /**
// * @param lastRegister the last register
// */
// void setLastRegister(Timestamp lastRegister);
// }
//
// Path: src/main/java/javapns/devices/Devices.java
// public class Devices {
//
// private Devices() {}
//
// public static List<Device> asDevices(final Object rawList) {
// final List<Device> list = new ArrayList<>();
// if (rawList == null) {
// return list;
// }
//
// if (rawList instanceof List) {
// final List devices = (List) rawList;
// if (devices.isEmpty()) {
// return list;
// }
//
// final Object firstDevice = devices.get(0);
// if (firstDevice instanceof Device) {
// //noinspection unchecked
// return devices;
// } else if (firstDevice instanceof String) {
// for (final Object token : devices) {
// final BasicDevice device = new BasicDevice();
// device.setToken((String) token);
// list.add(device);
// }
// }
// } else if (rawList instanceof String[]) {
// final String[] tokens = (String[]) rawList;
// for (final String token : tokens) {
// final BasicDevice device = new BasicDevice();
// device.setToken(token);
// list.add(device);
// }
// } else if (rawList instanceof Device[]) {
// final Device[] dvs = (Device[]) rawList;
// return Arrays.asList(dvs);
// } else if (rawList instanceof String) {
// final BasicDevice device = new BasicDevice();
// device.setToken((String) rawList);
// list.add(device);
// } else if (rawList instanceof Device) {
// list.add((Device) rawList);
// } else {
// throw new IllegalArgumentException("Device list type not supported. Supported types are: String[], List<String>, Device[], List<Device>, String and Device");
// }
// return list;
// }
//
// public static List<PayloadPerDevice> asPayloadsPerDevices(final Object rawList) {
// final List<PayloadPerDevice> list = new ArrayList<>();
// if (rawList == null) {
// return list;
// }
// if (rawList instanceof List) {
// final List devices = (List) rawList;
// if (devices.isEmpty()) {
// return list;
// }
// //noinspection unchecked
// return devices;
// } else if (rawList instanceof PayloadPerDevice[]) {
// final PayloadPerDevice[] dvs = (PayloadPerDevice[]) rawList;
// return Arrays.asList(dvs);
// } else if (rawList instanceof PayloadPerDevice) {
// list.add((PayloadPerDevice) rawList);
// } else {
// throw new IllegalArgumentException("PayloadPerDevice list type not supported. Supported types are: PayloadPerDevice[], List<PayloadPerDevice> and PayloadPerDevice");
// }
// return list;
// }
// }
//
// Path: src/main/java/javapns/devices/exceptions/InvalidDeviceTokenFormatException.java
// public class InvalidDeviceTokenFormatException extends Exception {
//
// private static final long serialVersionUID = -8571997399252125457L;
//
// public InvalidDeviceTokenFormatException(final String message) {
// super(message);
// }
//
// public InvalidDeviceTokenFormatException(final String token, final String problem) {
// super(String.format("Device token cannot be parsed, most likely because it contains invalid hexadecimal characters: %s in %s", problem, token));
// }
//
// }
| import javapns.devices.Device;
import javapns.devices.Devices;
import javapns.devices.exceptions.InvalidDeviceTokenFormatException;
import javapns.notification.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import java.util.stream.Collectors; | * Create groups of devices or payload/device pairs ready to be dispatched to worker threads.
*
* @param objects a large list of devices
* @param threads the number of threads to group devices for
* @return
*/
private static List<List<?>> makeGroups(final List<?> objects, final int threads) {
final List<List<?>> groups = new ArrayList<>(threads);
final int total = objects.size();
int devicesPerThread = total / threads;
if (total % threads > 0) {
devicesPerThread++;
}
for (int i = 0; i < threads; i++) {
final int firstObject = i * devicesPerThread;
if (firstObject >= total) {
break;
}
int lastObject = firstObject + devicesPerThread - 1;
if (lastObject >= total) {
lastObject = total - 1;
}
lastObject++;
final List threadObjects = objects.subList(firstObject, lastObject);
groups.add(threadObjects);
}
return groups;
}
| // Path: src/main/java/javapns/devices/Device.java
// public interface Device {
// /**
// * An id representing a particular device.
// * <p>
// * Note that this is a local reference to the device,
// * which is not related to the actual device UUID or
// * other device-specific identification. Most of the
// * time, this deviceId should be the same as the token.
// *
// * @return the device id
// */
// String getDeviceId();
//
// /**
// * An id representing a particular device.
// * <p>
// * Note that this is a local reference to the device,
// * which is not related to the actual device UUID or
// * other device-specific identification. Most of the
// * time, this deviceId should be the same as the token.
// *
// * @param id the device id
// */
// void setDeviceId(String id);
//
// /**
// * A device token.
// *
// * @return the device token
// */
// String getToken();
//
// /**
// * Set the device token
// *
// * @param token
// */
// void setToken(String token);
//
// /**
// * @return the last register
// */
// Timestamp getLastRegister();
//
// /**
// * @param lastRegister the last register
// */
// void setLastRegister(Timestamp lastRegister);
// }
//
// Path: src/main/java/javapns/devices/Devices.java
// public class Devices {
//
// private Devices() {}
//
// public static List<Device> asDevices(final Object rawList) {
// final List<Device> list = new ArrayList<>();
// if (rawList == null) {
// return list;
// }
//
// if (rawList instanceof List) {
// final List devices = (List) rawList;
// if (devices.isEmpty()) {
// return list;
// }
//
// final Object firstDevice = devices.get(0);
// if (firstDevice instanceof Device) {
// //noinspection unchecked
// return devices;
// } else if (firstDevice instanceof String) {
// for (final Object token : devices) {
// final BasicDevice device = new BasicDevice();
// device.setToken((String) token);
// list.add(device);
// }
// }
// } else if (rawList instanceof String[]) {
// final String[] tokens = (String[]) rawList;
// for (final String token : tokens) {
// final BasicDevice device = new BasicDevice();
// device.setToken(token);
// list.add(device);
// }
// } else if (rawList instanceof Device[]) {
// final Device[] dvs = (Device[]) rawList;
// return Arrays.asList(dvs);
// } else if (rawList instanceof String) {
// final BasicDevice device = new BasicDevice();
// device.setToken((String) rawList);
// list.add(device);
// } else if (rawList instanceof Device) {
// list.add((Device) rawList);
// } else {
// throw new IllegalArgumentException("Device list type not supported. Supported types are: String[], List<String>, Device[], List<Device>, String and Device");
// }
// return list;
// }
//
// public static List<PayloadPerDevice> asPayloadsPerDevices(final Object rawList) {
// final List<PayloadPerDevice> list = new ArrayList<>();
// if (rawList == null) {
// return list;
// }
// if (rawList instanceof List) {
// final List devices = (List) rawList;
// if (devices.isEmpty()) {
// return list;
// }
// //noinspection unchecked
// return devices;
// } else if (rawList instanceof PayloadPerDevice[]) {
// final PayloadPerDevice[] dvs = (PayloadPerDevice[]) rawList;
// return Arrays.asList(dvs);
// } else if (rawList instanceof PayloadPerDevice) {
// list.add((PayloadPerDevice) rawList);
// } else {
// throw new IllegalArgumentException("PayloadPerDevice list type not supported. Supported types are: PayloadPerDevice[], List<PayloadPerDevice> and PayloadPerDevice");
// }
// return list;
// }
// }
//
// Path: src/main/java/javapns/devices/exceptions/InvalidDeviceTokenFormatException.java
// public class InvalidDeviceTokenFormatException extends Exception {
//
// private static final long serialVersionUID = -8571997399252125457L;
//
// public InvalidDeviceTokenFormatException(final String message) {
// super(message);
// }
//
// public InvalidDeviceTokenFormatException(final String token, final String problem) {
// super(String.format("Device token cannot be parsed, most likely because it contains invalid hexadecimal characters: %s in %s", problem, token));
// }
//
// }
// Path: src/main/java/javapns/notification/transmission/NotificationThreads.java
import javapns.devices.Device;
import javapns.devices.Devices;
import javapns.devices.exceptions.InvalidDeviceTokenFormatException;
import javapns.notification.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import java.util.stream.Collectors;
* Create groups of devices or payload/device pairs ready to be dispatched to worker threads.
*
* @param objects a large list of devices
* @param threads the number of threads to group devices for
* @return
*/
private static List<List<?>> makeGroups(final List<?> objects, final int threads) {
final List<List<?>> groups = new ArrayList<>(threads);
final int total = objects.size();
int devicesPerThread = total / threads;
if (total % threads > 0) {
devicesPerThread++;
}
for (int i = 0; i < threads; i++) {
final int firstObject = i * devicesPerThread;
if (firstObject >= total) {
break;
}
int lastObject = firstObject + devicesPerThread - 1;
if (lastObject >= total) {
lastObject = total - 1;
}
lastObject++;
final List threadObjects = objects.subList(firstObject, lastObject);
groups.add(threadObjects);
}
return groups;
}
| public PushQueue add(final Payload payload, final String token) throws InvalidDeviceTokenFormatException { |
mlaccetti/JavaPNS | src/main/java/javapns/notification/PushNotificationPayload.java | // Path: src/main/java/javapns/notification/exceptions/PayloadAlertAlreadyExistsException.java
// public class PayloadAlertAlreadyExistsException extends JSONException {
//
// private static final long serialVersionUID = -4514511954076864373L;
//
// /**
// * Default constructor
// */
// public PayloadAlertAlreadyExistsException() {
// super("Payload alert already exists");
// }
//
// /**
// * Constructor with custom message
// *
// * @param message
// */
// public PayloadAlertAlreadyExistsException(final String message) {
// super(message);
// }
//
// }
| import javapns.notification.exceptions.PayloadAlertAlreadyExistsException;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.IllegalFormatException;
import java.util.List; | * Get the value of a given property, but only if it is of the expected class.
* If the value exists but is of a different class than expected, an
* exception is thrown.
* <p>
* This method is useful for properly supporting properties that can have a simple
* or complex value (such as "alert")
*
* @param <T> the property value's class
* @param propertyName the name of the property to get
* @param expectedClass the property value's expected (required) class
* @param exceptionMessage the exception message to throw if the value is not of the expected class
* @param dictionary the dictionary where to get the property from
* @return the property's value
* @throws JSONException
*/
@SuppressWarnings("unchecked")
private <T> T getCompatibleProperty(final String propertyName, final Class<T> expectedClass, String exceptionMessage, final JSONObject dictionary) throws JSONException {
Object propertyValue = null;
try {
propertyValue = dictionary.get(propertyName);
} catch (final Exception e) {
// empty
}
if (propertyValue == null) {
return null;
}
if (propertyValue.getClass().equals(expectedClass)) {
return (T) propertyValue;
}
try { | // Path: src/main/java/javapns/notification/exceptions/PayloadAlertAlreadyExistsException.java
// public class PayloadAlertAlreadyExistsException extends JSONException {
//
// private static final long serialVersionUID = -4514511954076864373L;
//
// /**
// * Default constructor
// */
// public PayloadAlertAlreadyExistsException() {
// super("Payload alert already exists");
// }
//
// /**
// * Constructor with custom message
// *
// * @param message
// */
// public PayloadAlertAlreadyExistsException(final String message) {
// super(message);
// }
//
// }
// Path: src/main/java/javapns/notification/PushNotificationPayload.java
import javapns.notification.exceptions.PayloadAlertAlreadyExistsException;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.IllegalFormatException;
import java.util.List;
* Get the value of a given property, but only if it is of the expected class.
* If the value exists but is of a different class than expected, an
* exception is thrown.
* <p>
* This method is useful for properly supporting properties that can have a simple
* or complex value (such as "alert")
*
* @param <T> the property value's class
* @param propertyName the name of the property to get
* @param expectedClass the property value's expected (required) class
* @param exceptionMessage the exception message to throw if the value is not of the expected class
* @param dictionary the dictionary where to get the property from
* @return the property's value
* @throws JSONException
*/
@SuppressWarnings("unchecked")
private <T> T getCompatibleProperty(final String propertyName, final Class<T> expectedClass, String exceptionMessage, final JSONObject dictionary) throws JSONException {
Object propertyValue = null;
try {
propertyValue = dictionary.get(propertyName);
} catch (final Exception e) {
// empty
}
if (propertyValue == null) {
return null;
}
if (propertyValue.getClass().equals(expectedClass)) {
return (T) propertyValue;
}
try { | throw new PayloadAlertAlreadyExistsException(String.format(exceptionMessage, propertyValue)); |
mlaccetti/JavaPNS | src/main/java/javapns/devices/DeviceFactory.java | // Path: src/main/java/javapns/devices/exceptions/DuplicateDeviceException.java
// public class DuplicateDeviceException extends Exception {
//
// private static final long serialVersionUID = -7116507420722667479L;
// /* Custom message for this exception */
// private final String message;
//
// /**
// * Constructor
// */
// public DuplicateDeviceException() {
// this.message = "Client already exists";
// }
//
// /**
// * Constructor with custom message
// *
// * @param message
// */
// public DuplicateDeviceException(final String message) {
// this.message = message;
// }
//
// /**
// * String representation
// */
// public String toString() {
// return this.message;
// }
// }
//
// Path: src/main/java/javapns/devices/exceptions/NullDeviceTokenException.java
// public class NullDeviceTokenException extends Exception {
//
// private static final long serialVersionUID = 208339461070934305L;
// /* Custom message for this exception */
// private final String message;
//
// /**
// * Constructor
// */
// public NullDeviceTokenException() {
// this.message = "Client already exists";
// }
//
// /**
// * Constructor with custom message
// *
// * @param message
// */
// public NullDeviceTokenException(final String message) {
// this.message = message;
// }
//
// /**
// * String representation
// */
// public String toString() {
// return this.message;
// }
// }
//
// Path: src/main/java/javapns/devices/exceptions/NullIdException.java
// public class NullIdException extends Exception {
//
// private static final long serialVersionUID = -2842793759970312540L;
// /* Custom message for this exception */
// private final String message;
//
// /**
// * Constructor
// */
// public NullIdException() {
// this.message = "Client already exists";
// }
//
// /**
// * Constructor with custom message
// *
// * @param message
// */
// public NullIdException(final String message) {
// this.message = message;
// }
//
// /**
// * String representation
// */
// public String toString() {
// return this.message;
// }
// }
//
// Path: src/main/java/javapns/devices/exceptions/UnknownDeviceException.java
// public class UnknownDeviceException extends Exception {
//
// private static final long serialVersionUID = -322193098126184434L;
// /* Custom message for this exception */
// private final String message;
//
// /**
// * Constructor
// */
// public UnknownDeviceException() {
// this.message = "Unknown client";
// }
//
// /**
// * Constructor with custom message
// *
// * @param message
// */
// public UnknownDeviceException(final String message) {
// this.message = message;
// }
//
// /**
// * String representation
// */
// public String toString() {
// return this.message;
// }
// }
| import javapns.devices.exceptions.DuplicateDeviceException;
import javapns.devices.exceptions.NullDeviceTokenException;
import javapns.devices.exceptions.NullIdException;
import javapns.devices.exceptions.UnknownDeviceException; | package javapns.devices;
/**
* This is the common interface for all DeviceFactories.
* It allows the PushNotificationManager to support multiple
* implementations of DeviceFactory (in-memory, JPA-backed, etc.)
*
* @author Sylvain Pedneault
* @deprecated Phasing out DeviceFactory because it has become irrelevant in the new library architecture
*/
@Deprecated
public interface DeviceFactory {
/**
* Add a device to the map
*
* @param id The local device id
* @param token The device token
* @return The device created
* @throws DuplicateDeviceException
* @throws NullIdException
* @throws NullDeviceTokenException
*/
Device addDevice(String id, String token) throws Exception;
/**
* Get a device according to his id
*
* @param id The local device id
* @return The device
* @throws UnknownDeviceException
* @throws NullIdException
*/ | // Path: src/main/java/javapns/devices/exceptions/DuplicateDeviceException.java
// public class DuplicateDeviceException extends Exception {
//
// private static final long serialVersionUID = -7116507420722667479L;
// /* Custom message for this exception */
// private final String message;
//
// /**
// * Constructor
// */
// public DuplicateDeviceException() {
// this.message = "Client already exists";
// }
//
// /**
// * Constructor with custom message
// *
// * @param message
// */
// public DuplicateDeviceException(final String message) {
// this.message = message;
// }
//
// /**
// * String representation
// */
// public String toString() {
// return this.message;
// }
// }
//
// Path: src/main/java/javapns/devices/exceptions/NullDeviceTokenException.java
// public class NullDeviceTokenException extends Exception {
//
// private static final long serialVersionUID = 208339461070934305L;
// /* Custom message for this exception */
// private final String message;
//
// /**
// * Constructor
// */
// public NullDeviceTokenException() {
// this.message = "Client already exists";
// }
//
// /**
// * Constructor with custom message
// *
// * @param message
// */
// public NullDeviceTokenException(final String message) {
// this.message = message;
// }
//
// /**
// * String representation
// */
// public String toString() {
// return this.message;
// }
// }
//
// Path: src/main/java/javapns/devices/exceptions/NullIdException.java
// public class NullIdException extends Exception {
//
// private static final long serialVersionUID = -2842793759970312540L;
// /* Custom message for this exception */
// private final String message;
//
// /**
// * Constructor
// */
// public NullIdException() {
// this.message = "Client already exists";
// }
//
// /**
// * Constructor with custom message
// *
// * @param message
// */
// public NullIdException(final String message) {
// this.message = message;
// }
//
// /**
// * String representation
// */
// public String toString() {
// return this.message;
// }
// }
//
// Path: src/main/java/javapns/devices/exceptions/UnknownDeviceException.java
// public class UnknownDeviceException extends Exception {
//
// private static final long serialVersionUID = -322193098126184434L;
// /* Custom message for this exception */
// private final String message;
//
// /**
// * Constructor
// */
// public UnknownDeviceException() {
// this.message = "Unknown client";
// }
//
// /**
// * Constructor with custom message
// *
// * @param message
// */
// public UnknownDeviceException(final String message) {
// this.message = message;
// }
//
// /**
// * String representation
// */
// public String toString() {
// return this.message;
// }
// }
// Path: src/main/java/javapns/devices/DeviceFactory.java
import javapns.devices.exceptions.DuplicateDeviceException;
import javapns.devices.exceptions.NullDeviceTokenException;
import javapns.devices.exceptions.NullIdException;
import javapns.devices.exceptions.UnknownDeviceException;
package javapns.devices;
/**
* This is the common interface for all DeviceFactories.
* It allows the PushNotificationManager to support multiple
* implementations of DeviceFactory (in-memory, JPA-backed, etc.)
*
* @author Sylvain Pedneault
* @deprecated Phasing out DeviceFactory because it has become irrelevant in the new library architecture
*/
@Deprecated
public interface DeviceFactory {
/**
* Add a device to the map
*
* @param id The local device id
* @param token The device token
* @return The device created
* @throws DuplicateDeviceException
* @throws NullIdException
* @throws NullDeviceTokenException
*/
Device addDevice(String id, String token) throws Exception;
/**
* Get a device according to his id
*
* @param id The local device id
* @return The device
* @throws UnknownDeviceException
* @throws NullIdException
*/ | Device getDevice(String id) throws UnknownDeviceException, NullIdException; |
mlaccetti/JavaPNS | src/main/java/javapns/devices/DeviceFactory.java | // Path: src/main/java/javapns/devices/exceptions/DuplicateDeviceException.java
// public class DuplicateDeviceException extends Exception {
//
// private static final long serialVersionUID = -7116507420722667479L;
// /* Custom message for this exception */
// private final String message;
//
// /**
// * Constructor
// */
// public DuplicateDeviceException() {
// this.message = "Client already exists";
// }
//
// /**
// * Constructor with custom message
// *
// * @param message
// */
// public DuplicateDeviceException(final String message) {
// this.message = message;
// }
//
// /**
// * String representation
// */
// public String toString() {
// return this.message;
// }
// }
//
// Path: src/main/java/javapns/devices/exceptions/NullDeviceTokenException.java
// public class NullDeviceTokenException extends Exception {
//
// private static final long serialVersionUID = 208339461070934305L;
// /* Custom message for this exception */
// private final String message;
//
// /**
// * Constructor
// */
// public NullDeviceTokenException() {
// this.message = "Client already exists";
// }
//
// /**
// * Constructor with custom message
// *
// * @param message
// */
// public NullDeviceTokenException(final String message) {
// this.message = message;
// }
//
// /**
// * String representation
// */
// public String toString() {
// return this.message;
// }
// }
//
// Path: src/main/java/javapns/devices/exceptions/NullIdException.java
// public class NullIdException extends Exception {
//
// private static final long serialVersionUID = -2842793759970312540L;
// /* Custom message for this exception */
// private final String message;
//
// /**
// * Constructor
// */
// public NullIdException() {
// this.message = "Client already exists";
// }
//
// /**
// * Constructor with custom message
// *
// * @param message
// */
// public NullIdException(final String message) {
// this.message = message;
// }
//
// /**
// * String representation
// */
// public String toString() {
// return this.message;
// }
// }
//
// Path: src/main/java/javapns/devices/exceptions/UnknownDeviceException.java
// public class UnknownDeviceException extends Exception {
//
// private static final long serialVersionUID = -322193098126184434L;
// /* Custom message for this exception */
// private final String message;
//
// /**
// * Constructor
// */
// public UnknownDeviceException() {
// this.message = "Unknown client";
// }
//
// /**
// * Constructor with custom message
// *
// * @param message
// */
// public UnknownDeviceException(final String message) {
// this.message = message;
// }
//
// /**
// * String representation
// */
// public String toString() {
// return this.message;
// }
// }
| import javapns.devices.exceptions.DuplicateDeviceException;
import javapns.devices.exceptions.NullDeviceTokenException;
import javapns.devices.exceptions.NullIdException;
import javapns.devices.exceptions.UnknownDeviceException; | package javapns.devices;
/**
* This is the common interface for all DeviceFactories.
* It allows the PushNotificationManager to support multiple
* implementations of DeviceFactory (in-memory, JPA-backed, etc.)
*
* @author Sylvain Pedneault
* @deprecated Phasing out DeviceFactory because it has become irrelevant in the new library architecture
*/
@Deprecated
public interface DeviceFactory {
/**
* Add a device to the map
*
* @param id The local device id
* @param token The device token
* @return The device created
* @throws DuplicateDeviceException
* @throws NullIdException
* @throws NullDeviceTokenException
*/
Device addDevice(String id, String token) throws Exception;
/**
* Get a device according to his id
*
* @param id The local device id
* @return The device
* @throws UnknownDeviceException
* @throws NullIdException
*/ | // Path: src/main/java/javapns/devices/exceptions/DuplicateDeviceException.java
// public class DuplicateDeviceException extends Exception {
//
// private static final long serialVersionUID = -7116507420722667479L;
// /* Custom message for this exception */
// private final String message;
//
// /**
// * Constructor
// */
// public DuplicateDeviceException() {
// this.message = "Client already exists";
// }
//
// /**
// * Constructor with custom message
// *
// * @param message
// */
// public DuplicateDeviceException(final String message) {
// this.message = message;
// }
//
// /**
// * String representation
// */
// public String toString() {
// return this.message;
// }
// }
//
// Path: src/main/java/javapns/devices/exceptions/NullDeviceTokenException.java
// public class NullDeviceTokenException extends Exception {
//
// private static final long serialVersionUID = 208339461070934305L;
// /* Custom message for this exception */
// private final String message;
//
// /**
// * Constructor
// */
// public NullDeviceTokenException() {
// this.message = "Client already exists";
// }
//
// /**
// * Constructor with custom message
// *
// * @param message
// */
// public NullDeviceTokenException(final String message) {
// this.message = message;
// }
//
// /**
// * String representation
// */
// public String toString() {
// return this.message;
// }
// }
//
// Path: src/main/java/javapns/devices/exceptions/NullIdException.java
// public class NullIdException extends Exception {
//
// private static final long serialVersionUID = -2842793759970312540L;
// /* Custom message for this exception */
// private final String message;
//
// /**
// * Constructor
// */
// public NullIdException() {
// this.message = "Client already exists";
// }
//
// /**
// * Constructor with custom message
// *
// * @param message
// */
// public NullIdException(final String message) {
// this.message = message;
// }
//
// /**
// * String representation
// */
// public String toString() {
// return this.message;
// }
// }
//
// Path: src/main/java/javapns/devices/exceptions/UnknownDeviceException.java
// public class UnknownDeviceException extends Exception {
//
// private static final long serialVersionUID = -322193098126184434L;
// /* Custom message for this exception */
// private final String message;
//
// /**
// * Constructor
// */
// public UnknownDeviceException() {
// this.message = "Unknown client";
// }
//
// /**
// * Constructor with custom message
// *
// * @param message
// */
// public UnknownDeviceException(final String message) {
// this.message = message;
// }
//
// /**
// * String representation
// */
// public String toString() {
// return this.message;
// }
// }
// Path: src/main/java/javapns/devices/DeviceFactory.java
import javapns.devices.exceptions.DuplicateDeviceException;
import javapns.devices.exceptions.NullDeviceTokenException;
import javapns.devices.exceptions.NullIdException;
import javapns.devices.exceptions.UnknownDeviceException;
package javapns.devices;
/**
* This is the common interface for all DeviceFactories.
* It allows the PushNotificationManager to support multiple
* implementations of DeviceFactory (in-memory, JPA-backed, etc.)
*
* @author Sylvain Pedneault
* @deprecated Phasing out DeviceFactory because it has become irrelevant in the new library architecture
*/
@Deprecated
public interface DeviceFactory {
/**
* Add a device to the map
*
* @param id The local device id
* @param token The device token
* @return The device created
* @throws DuplicateDeviceException
* @throws NullIdException
* @throws NullDeviceTokenException
*/
Device addDevice(String id, String token) throws Exception;
/**
* Get a device according to his id
*
* @param id The local device id
* @return The device
* @throws UnknownDeviceException
* @throws NullIdException
*/ | Device getDevice(String id) throws UnknownDeviceException, NullIdException; |
tfredrich/Domain-Eventing | core/test/java/com/strategicgains/eventing/DomainEventsTest.java | // Path: core/src/java/com/strategicgains/eventing/local/LocalEventBus.java
// public class LocalEventBus
// extends EventBus
// {
// public LocalEventBus(Collection<EventHandler> handlers, boolean shouldReraiseOnError, long pollDelayMillis)
// {
// super(new LocalEventTransport(handlers, shouldReraiseOnError, pollDelayMillis));
// }
//
// /**
// * @param value
// */
// public void retryOnError(boolean value)
// {
// ((LocalEventTransport) getTransport()).retryOnError(value);
// }
// }
//
// Path: core/src/java/com/strategicgains/eventing/local/LocalEventBusBuilder.java
// public class LocalEventBusBuilder
// implements EventBusBuilder<LocalEventBus, LocalEventBusBuilder>
// {
// private static final long DEFAULT_POLL_DELAY = 0L;
//
// private Set<EventHandler> subscribers = new LinkedHashSet<EventHandler>();
// private Set<Class<?>> publishableEventTypes = new HashSet<Class<?>>();
// private boolean shouldRepublishOnError = false;
// private long pollDelay = DEFAULT_POLL_DELAY;
//
// public LocalEventBusBuilder()
// {
// super();
// }
//
// @Override
// public LocalEventBus build()
// {
// assert(!subscribers.isEmpty());
//
// LocalEventBus bus = new LocalEventBus(subscribers, shouldRepublishOnError, pollDelay);
//
// for (Class<?> eventType : publishableEventTypes)
// {
// bus.addPublishableEventType(eventType);
// }
//
// return bus;
// }
//
// public LocalEventBusBuilder shouldRepublishOnError(boolean value)
// {
// this.shouldRepublishOnError = value;
// return this;
// }
//
// public LocalEventBusBuilder pollDelay(long millis)
// {
// this.pollDelay = millis;
// return this;
// }
//
// @Override
// public LocalEventBusBuilder subscribe(EventHandler handler)
// {
// if (!subscribers.contains(handler))
// {
// subscribers.add(handler);
// }
//
// return this;
// }
//
// @Override
// public LocalEventBusBuilder unsubscribe(EventHandler handler)
// {
// subscribers.remove(handler);
// return this;
// }
//
// public LocalEventBusBuilder addPublishableEventType(Class<?> eventType)
// {
// publishableEventTypes.add(eventType);
// return this;
// }
// }
| import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.strategicgains.eventing.local.LocalEventBus;
import com.strategicgains.eventing.local.LocalEventBusBuilder; | /*
Copyright 2011, Strategic Gains, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.strategicgains.eventing;
/**
* @author toddf
* @since May 18, 2011
*/
public class DomainEventsTest
{
private DomainEventsTestHandler handler = new DomainEventsTestHandler();
private DomainEventsTestIgnoredEventsHandler ignoredHandler = new DomainEventsTestIgnoredEventsHandler();
private DomainEventsTestLongEventHandler longHandler = new DomainEventsTestLongEventHandler();
@Before
public void setup()
{ | // Path: core/src/java/com/strategicgains/eventing/local/LocalEventBus.java
// public class LocalEventBus
// extends EventBus
// {
// public LocalEventBus(Collection<EventHandler> handlers, boolean shouldReraiseOnError, long pollDelayMillis)
// {
// super(new LocalEventTransport(handlers, shouldReraiseOnError, pollDelayMillis));
// }
//
// /**
// * @param value
// */
// public void retryOnError(boolean value)
// {
// ((LocalEventTransport) getTransport()).retryOnError(value);
// }
// }
//
// Path: core/src/java/com/strategicgains/eventing/local/LocalEventBusBuilder.java
// public class LocalEventBusBuilder
// implements EventBusBuilder<LocalEventBus, LocalEventBusBuilder>
// {
// private static final long DEFAULT_POLL_DELAY = 0L;
//
// private Set<EventHandler> subscribers = new LinkedHashSet<EventHandler>();
// private Set<Class<?>> publishableEventTypes = new HashSet<Class<?>>();
// private boolean shouldRepublishOnError = false;
// private long pollDelay = DEFAULT_POLL_DELAY;
//
// public LocalEventBusBuilder()
// {
// super();
// }
//
// @Override
// public LocalEventBus build()
// {
// assert(!subscribers.isEmpty());
//
// LocalEventBus bus = new LocalEventBus(subscribers, shouldRepublishOnError, pollDelay);
//
// for (Class<?> eventType : publishableEventTypes)
// {
// bus.addPublishableEventType(eventType);
// }
//
// return bus;
// }
//
// public LocalEventBusBuilder shouldRepublishOnError(boolean value)
// {
// this.shouldRepublishOnError = value;
// return this;
// }
//
// public LocalEventBusBuilder pollDelay(long millis)
// {
// this.pollDelay = millis;
// return this;
// }
//
// @Override
// public LocalEventBusBuilder subscribe(EventHandler handler)
// {
// if (!subscribers.contains(handler))
// {
// subscribers.add(handler);
// }
//
// return this;
// }
//
// @Override
// public LocalEventBusBuilder unsubscribe(EventHandler handler)
// {
// subscribers.remove(handler);
// return this;
// }
//
// public LocalEventBusBuilder addPublishableEventType(Class<?> eventType)
// {
// publishableEventTypes.add(eventType);
// return this;
// }
// }
// Path: core/test/java/com/strategicgains/eventing/DomainEventsTest.java
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.strategicgains.eventing.local.LocalEventBus;
import com.strategicgains.eventing.local.LocalEventBusBuilder;
/*
Copyright 2011, Strategic Gains, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.strategicgains.eventing;
/**
* @author toddf
* @since May 18, 2011
*/
public class DomainEventsTest
{
private DomainEventsTestHandler handler = new DomainEventsTestHandler();
private DomainEventsTestIgnoredEventsHandler ignoredHandler = new DomainEventsTestIgnoredEventsHandler();
private DomainEventsTestLongEventHandler longHandler = new DomainEventsTestLongEventHandler();
@Before
public void setup()
{ | EventBus q = new LocalEventBusBuilder() |
tfredrich/Domain-Eventing | core/test/java/com/strategicgains/eventing/DomainEventsTest.java | // Path: core/src/java/com/strategicgains/eventing/local/LocalEventBus.java
// public class LocalEventBus
// extends EventBus
// {
// public LocalEventBus(Collection<EventHandler> handlers, boolean shouldReraiseOnError, long pollDelayMillis)
// {
// super(new LocalEventTransport(handlers, shouldReraiseOnError, pollDelayMillis));
// }
//
// /**
// * @param value
// */
// public void retryOnError(boolean value)
// {
// ((LocalEventTransport) getTransport()).retryOnError(value);
// }
// }
//
// Path: core/src/java/com/strategicgains/eventing/local/LocalEventBusBuilder.java
// public class LocalEventBusBuilder
// implements EventBusBuilder<LocalEventBus, LocalEventBusBuilder>
// {
// private static final long DEFAULT_POLL_DELAY = 0L;
//
// private Set<EventHandler> subscribers = new LinkedHashSet<EventHandler>();
// private Set<Class<?>> publishableEventTypes = new HashSet<Class<?>>();
// private boolean shouldRepublishOnError = false;
// private long pollDelay = DEFAULT_POLL_DELAY;
//
// public LocalEventBusBuilder()
// {
// super();
// }
//
// @Override
// public LocalEventBus build()
// {
// assert(!subscribers.isEmpty());
//
// LocalEventBus bus = new LocalEventBus(subscribers, shouldRepublishOnError, pollDelay);
//
// for (Class<?> eventType : publishableEventTypes)
// {
// bus.addPublishableEventType(eventType);
// }
//
// return bus;
// }
//
// public LocalEventBusBuilder shouldRepublishOnError(boolean value)
// {
// this.shouldRepublishOnError = value;
// return this;
// }
//
// public LocalEventBusBuilder pollDelay(long millis)
// {
// this.pollDelay = millis;
// return this;
// }
//
// @Override
// public LocalEventBusBuilder subscribe(EventHandler handler)
// {
// if (!subscribers.contains(handler))
// {
// subscribers.add(handler);
// }
//
// return this;
// }
//
// @Override
// public LocalEventBusBuilder unsubscribe(EventHandler handler)
// {
// subscribers.remove(handler);
// return this;
// }
//
// public LocalEventBusBuilder addPublishableEventType(Class<?> eventType)
// {
// publishableEventTypes.add(eventType);
// return this;
// }
// }
| import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.strategicgains.eventing.local.LocalEventBus;
import com.strategicgains.eventing.local.LocalEventBusBuilder; | DomainEvents.publish(new HandledEvent());
DomainEvents.publish(new IgnoredEvent());
DomainEvents.publish(new HandledEvent());
DomainEvents.publish(new IgnoredEvent());
DomainEvents.publish(new HandledEvent());
DomainEvents.publish(new IgnoredEvent());
DomainEvents.publish(new HandledEvent());
DomainEvents.publish(new IgnoredEvent());
Thread.sleep(150);
assertEquals(5, handler.getCallCount());
assertEquals(5, ignoredHandler.getCallCount());
assertEquals(0, longHandler.getCallCount());
}
@Test
public void shouldNotNotifyEventHandler()
throws Exception
{
assertEquals(0, ignoredHandler.getCallCount());
DomainEvents.publish(new IgnoredEvent());
Thread.sleep(150);
assertEquals(0, handler.getCallCount());
assertEquals(1, ignoredHandler.getCallCount());
assertEquals(0, longHandler.getCallCount());
}
@Test
public void shouldRetryEventHandler()
throws Exception
{ | // Path: core/src/java/com/strategicgains/eventing/local/LocalEventBus.java
// public class LocalEventBus
// extends EventBus
// {
// public LocalEventBus(Collection<EventHandler> handlers, boolean shouldReraiseOnError, long pollDelayMillis)
// {
// super(new LocalEventTransport(handlers, shouldReraiseOnError, pollDelayMillis));
// }
//
// /**
// * @param value
// */
// public void retryOnError(boolean value)
// {
// ((LocalEventTransport) getTransport()).retryOnError(value);
// }
// }
//
// Path: core/src/java/com/strategicgains/eventing/local/LocalEventBusBuilder.java
// public class LocalEventBusBuilder
// implements EventBusBuilder<LocalEventBus, LocalEventBusBuilder>
// {
// private static final long DEFAULT_POLL_DELAY = 0L;
//
// private Set<EventHandler> subscribers = new LinkedHashSet<EventHandler>();
// private Set<Class<?>> publishableEventTypes = new HashSet<Class<?>>();
// private boolean shouldRepublishOnError = false;
// private long pollDelay = DEFAULT_POLL_DELAY;
//
// public LocalEventBusBuilder()
// {
// super();
// }
//
// @Override
// public LocalEventBus build()
// {
// assert(!subscribers.isEmpty());
//
// LocalEventBus bus = new LocalEventBus(subscribers, shouldRepublishOnError, pollDelay);
//
// for (Class<?> eventType : publishableEventTypes)
// {
// bus.addPublishableEventType(eventType);
// }
//
// return bus;
// }
//
// public LocalEventBusBuilder shouldRepublishOnError(boolean value)
// {
// this.shouldRepublishOnError = value;
// return this;
// }
//
// public LocalEventBusBuilder pollDelay(long millis)
// {
// this.pollDelay = millis;
// return this;
// }
//
// @Override
// public LocalEventBusBuilder subscribe(EventHandler handler)
// {
// if (!subscribers.contains(handler))
// {
// subscribers.add(handler);
// }
//
// return this;
// }
//
// @Override
// public LocalEventBusBuilder unsubscribe(EventHandler handler)
// {
// subscribers.remove(handler);
// return this;
// }
//
// public LocalEventBusBuilder addPublishableEventType(Class<?> eventType)
// {
// publishableEventTypes.add(eventType);
// return this;
// }
// }
// Path: core/test/java/com/strategicgains/eventing/DomainEventsTest.java
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.strategicgains.eventing.local.LocalEventBus;
import com.strategicgains.eventing.local.LocalEventBusBuilder;
DomainEvents.publish(new HandledEvent());
DomainEvents.publish(new IgnoredEvent());
DomainEvents.publish(new HandledEvent());
DomainEvents.publish(new IgnoredEvent());
DomainEvents.publish(new HandledEvent());
DomainEvents.publish(new IgnoredEvent());
DomainEvents.publish(new HandledEvent());
DomainEvents.publish(new IgnoredEvent());
Thread.sleep(150);
assertEquals(5, handler.getCallCount());
assertEquals(5, ignoredHandler.getCallCount());
assertEquals(0, longHandler.getCallCount());
}
@Test
public void shouldNotNotifyEventHandler()
throws Exception
{
assertEquals(0, ignoredHandler.getCallCount());
DomainEvents.publish(new IgnoredEvent());
Thread.sleep(150);
assertEquals(0, handler.getCallCount());
assertEquals(1, ignoredHandler.getCallCount());
assertEquals(0, longHandler.getCallCount());
}
@Test
public void shouldRetryEventHandler()
throws Exception
{ | ((LocalEventBus) DomainEvents.getBus("primary")).retryOnError(true); |
tfredrich/Domain-Eventing | akka/src/main/java/com/strategicgains/eventing/akka/EventHandlerActor.java | // Path: core/src/java/com/strategicgains/eventing/EventHandler.java
// public interface EventHandler
// {
// /**
// * Process the given event. Called by the EventMonitor when an event occurs.
// *
// * @param event
// * @throws Exception if something goes wrong
// */
// public void handle(Object event)
// throws Exception;
//
// /**
// * Answers whether this EventHandler can handle events of the given type.
// * If true is returned, the EventMonitor will call handle(), otherwise,
// * the EventMonitor will not ask this event handler to process the event.
// *
// * @param eventClass
// * @return
// */
// public boolean handles(Class<?> eventClass);
// }
| import akka.actor.Props;
import akka.actor.UntypedActor;
import akka.japi.Creator;
import com.strategicgains.eventing.EventHandler; | /*
Copyright 2015, Strategic Gains, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.strategicgains.eventing.akka;
/**
* @author tfredrich
* @since Jul 13, 2015
*/
public class EventHandlerActor
extends UntypedActor
{ | // Path: core/src/java/com/strategicgains/eventing/EventHandler.java
// public interface EventHandler
// {
// /**
// * Process the given event. Called by the EventMonitor when an event occurs.
// *
// * @param event
// * @throws Exception if something goes wrong
// */
// public void handle(Object event)
// throws Exception;
//
// /**
// * Answers whether this EventHandler can handle events of the given type.
// * If true is returned, the EventMonitor will call handle(), otherwise,
// * the EventMonitor will not ask this event handler to process the event.
// *
// * @param eventClass
// * @return
// */
// public boolean handles(Class<?> eventClass);
// }
// Path: akka/src/main/java/com/strategicgains/eventing/akka/EventHandlerActor.java
import akka.actor.Props;
import akka.actor.UntypedActor;
import akka.japi.Creator;
import com.strategicgains.eventing.EventHandler;
/*
Copyright 2015, Strategic Gains, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.strategicgains.eventing.akka;
/**
* @author tfredrich
* @since Jul 13, 2015
*/
public class EventHandlerActor
extends UntypedActor
{ | private EventHandler handler; |
tfredrich/Domain-Eventing | core/src/java/com/strategicgains/eventing/local/LocalEventBus.java | // Path: core/src/java/com/strategicgains/eventing/EventBus.java
// public abstract class EventBus
// {
// private EventTransport transport;
// private Set<Class<?>> publishableEventTypes = new HashSet<Class<?>>();
//
// public EventBus(EventTransport transport)
// {
// super();
// this.transport = transport;
// }
//
// public boolean addPublishableEventType(Class<?> eventType)
// {
// return publishableEventTypes.add(eventType);
// }
//
// public boolean canPublish(Class<?> eventType)
// {
// if (publishableEventTypes.isEmpty()) return true;
//
// return publishableEventTypes.contains(eventType);
// }
//
// public void publish(Object event)
// {
// if (!canPublish(event.getClass())) return;
//
// transport.publish(event);
// }
//
// public void shutdown()
// {
// transport.shutdown();
// }
//
// public boolean subscribe(EventHandler handler)
// {
// return transport.subscribe(handler);
// }
//
// public boolean unsubscribe(EventHandler handler)
// {
// return transport.unsubscribe(handler);
// }
//
// protected EventTransport getTransport()
// {
// return transport;
// }
// }
//
// Path: core/src/java/com/strategicgains/eventing/EventHandler.java
// public interface EventHandler
// {
// /**
// * Process the given event. Called by the EventMonitor when an event occurs.
// *
// * @param event
// * @throws Exception if something goes wrong
// */
// public void handle(Object event)
// throws Exception;
//
// /**
// * Answers whether this EventHandler can handle events of the given type.
// * If true is returned, the EventMonitor will call handle(), otherwise,
// * the EventMonitor will not ask this event handler to process the event.
// *
// * @param eventClass
// * @return
// */
// public boolean handles(Class<?> eventClass);
// }
| import java.util.Collection;
import com.strategicgains.eventing.EventBus;
import com.strategicgains.eventing.EventHandler; | /*
Copyright 2012, Strategic Gains, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.strategicgains.eventing.local;
/**
* @author toddf
* @since Feb 6, 2012
*/
public class LocalEventBus
extends EventBus
{ | // Path: core/src/java/com/strategicgains/eventing/EventBus.java
// public abstract class EventBus
// {
// private EventTransport transport;
// private Set<Class<?>> publishableEventTypes = new HashSet<Class<?>>();
//
// public EventBus(EventTransport transport)
// {
// super();
// this.transport = transport;
// }
//
// public boolean addPublishableEventType(Class<?> eventType)
// {
// return publishableEventTypes.add(eventType);
// }
//
// public boolean canPublish(Class<?> eventType)
// {
// if (publishableEventTypes.isEmpty()) return true;
//
// return publishableEventTypes.contains(eventType);
// }
//
// public void publish(Object event)
// {
// if (!canPublish(event.getClass())) return;
//
// transport.publish(event);
// }
//
// public void shutdown()
// {
// transport.shutdown();
// }
//
// public boolean subscribe(EventHandler handler)
// {
// return transport.subscribe(handler);
// }
//
// public boolean unsubscribe(EventHandler handler)
// {
// return transport.unsubscribe(handler);
// }
//
// protected EventTransport getTransport()
// {
// return transport;
// }
// }
//
// Path: core/src/java/com/strategicgains/eventing/EventHandler.java
// public interface EventHandler
// {
// /**
// * Process the given event. Called by the EventMonitor when an event occurs.
// *
// * @param event
// * @throws Exception if something goes wrong
// */
// public void handle(Object event)
// throws Exception;
//
// /**
// * Answers whether this EventHandler can handle events of the given type.
// * If true is returned, the EventMonitor will call handle(), otherwise,
// * the EventMonitor will not ask this event handler to process the event.
// *
// * @param eventClass
// * @return
// */
// public boolean handles(Class<?> eventClass);
// }
// Path: core/src/java/com/strategicgains/eventing/local/LocalEventBus.java
import java.util.Collection;
import com.strategicgains.eventing.EventBus;
import com.strategicgains.eventing.EventHandler;
/*
Copyright 2012, Strategic Gains, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.strategicgains.eventing.local;
/**
* @author toddf
* @since Feb 6, 2012
*/
public class LocalEventBus
extends EventBus
{ | public LocalEventBus(Collection<EventHandler> handlers, boolean shouldReraiseOnError, long pollDelayMillis) |
tfredrich/Domain-Eventing | hazelcast/src/java/com/strategicgains/eventing/hazelcast/HazelcastEventBusBuilder.java | // Path: core/src/java/com/strategicgains/eventing/EventBusBuilder.java
// public interface EventBusBuilder<T extends EventBus, B>
// {
// public B subscribe(EventHandler handler);
// public B unsubscribe(EventHandler handler);
// public T build();
// }
//
// Path: core/src/java/com/strategicgains/eventing/EventHandler.java
// public interface EventHandler
// {
// /**
// * Process the given event. Called by the EventMonitor when an event occurs.
// *
// * @param event
// * @throws Exception if something goes wrong
// */
// public void handle(Object event)
// throws Exception;
//
// /**
// * Answers whether this EventHandler can handle events of the given type.
// * If true is returned, the EventMonitor will call handle(), otherwise,
// * the EventMonitor will not ask this event handler to process the event.
// *
// * @param eventClass
// * @return
// */
// public boolean handles(Class<?> eventClass);
// }
| import java.io.Serializable;
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import com.hazelcast.config.Config;
import com.strategicgains.eventing.EventBusBuilder;
import com.strategicgains.eventing.EventHandler; | /*
Copyright 2012, Strategic Gains, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.strategicgains.eventing.hazelcast;
/**
* @author toddf
* @since Oct 5, 2012
*/
public class HazelcastEventBusBuilder<T extends Serializable>
implements EventBusBuilder<HazelcastEventBus<T>, HazelcastEventBusBuilder<T>>
{
private static final String DEFAULT_QUEUE_NAME = "domain-events";
private Config config = null;
private String queueName = DEFAULT_QUEUE_NAME; | // Path: core/src/java/com/strategicgains/eventing/EventBusBuilder.java
// public interface EventBusBuilder<T extends EventBus, B>
// {
// public B subscribe(EventHandler handler);
// public B unsubscribe(EventHandler handler);
// public T build();
// }
//
// Path: core/src/java/com/strategicgains/eventing/EventHandler.java
// public interface EventHandler
// {
// /**
// * Process the given event. Called by the EventMonitor when an event occurs.
// *
// * @param event
// * @throws Exception if something goes wrong
// */
// public void handle(Object event)
// throws Exception;
//
// /**
// * Answers whether this EventHandler can handle events of the given type.
// * If true is returned, the EventMonitor will call handle(), otherwise,
// * the EventMonitor will not ask this event handler to process the event.
// *
// * @param eventClass
// * @return
// */
// public boolean handles(Class<?> eventClass);
// }
// Path: hazelcast/src/java/com/strategicgains/eventing/hazelcast/HazelcastEventBusBuilder.java
import java.io.Serializable;
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import com.hazelcast.config.Config;
import com.strategicgains.eventing.EventBusBuilder;
import com.strategicgains.eventing.EventHandler;
/*
Copyright 2012, Strategic Gains, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.strategicgains.eventing.hazelcast;
/**
* @author toddf
* @since Oct 5, 2012
*/
public class HazelcastEventBusBuilder<T extends Serializable>
implements EventBusBuilder<HazelcastEventBus<T>, HazelcastEventBusBuilder<T>>
{
private static final String DEFAULT_QUEUE_NAME = "domain-events";
private Config config = null;
private String queueName = DEFAULT_QUEUE_NAME; | private Set<EventHandler> subscribers = new LinkedHashSet<EventHandler>(); |
tfredrich/Domain-Eventing | kafka/src/main/java/com/strategicgains/eventing/kafka/KafkaEventTransport.java | // Path: core/src/java/com/strategicgains/eventing/EventHandler.java
// public interface EventHandler
// {
// /**
// * Process the given event. Called by the EventMonitor when an event occurs.
// *
// * @param event
// * @throws Exception if something goes wrong
// */
// public void handle(Object event)
// throws Exception;
//
// /**
// * Answers whether this EventHandler can handle events of the given type.
// * If true is returned, the EventMonitor will call handle(), otherwise,
// * the EventMonitor will not ask this event handler to process the event.
// *
// * @param eventClass
// * @return
// */
// public boolean handles(Class<?> eventClass);
// }
//
// Path: core/src/java/com/strategicgains/eventing/EventTransport.java
// public interface EventTransport
// {
// public void publish(Object event);
// public boolean subscribe(EventHandler handler);
// public boolean unsubscribe(EventHandler handler);
// public void shutdown();
// }
| import java.util.Properties;
import java.util.concurrent.Future;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.Producer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.clients.producer.RecordMetadata;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.strategicgains.eventing.EventHandler;
import com.strategicgains.eventing.EventTransport; | /*
Copyright 2016, Ping Identity Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.strategicgains.eventing.kafka;
/**
* @author tfredrich
* @since 20 May 2016
*/
public class KafkaEventTransport
implements EventTransport
{
private String topic;
private Producer<String, String> producer;
private ObjectMapper mapper;
public KafkaEventTransport(Properties config, String topic)
{
this(config, topic, new ObjectMapper());
}
public KafkaEventTransport(Properties config, String topic, ObjectMapper mapper)
{
this.producer = new KafkaProducer<>(config);
this.topic = topic;
this.mapper = mapper;
}
@Override
public void publish(Object event)
{
try
{
Future<RecordMetadata> f = producer.send(new ProducerRecord<String, String>(topic, System.currentTimeMillis() + "", mapper.writeValueAsString(event)));
}
catch (JsonProcessingException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override | // Path: core/src/java/com/strategicgains/eventing/EventHandler.java
// public interface EventHandler
// {
// /**
// * Process the given event. Called by the EventMonitor when an event occurs.
// *
// * @param event
// * @throws Exception if something goes wrong
// */
// public void handle(Object event)
// throws Exception;
//
// /**
// * Answers whether this EventHandler can handle events of the given type.
// * If true is returned, the EventMonitor will call handle(), otherwise,
// * the EventMonitor will not ask this event handler to process the event.
// *
// * @param eventClass
// * @return
// */
// public boolean handles(Class<?> eventClass);
// }
//
// Path: core/src/java/com/strategicgains/eventing/EventTransport.java
// public interface EventTransport
// {
// public void publish(Object event);
// public boolean subscribe(EventHandler handler);
// public boolean unsubscribe(EventHandler handler);
// public void shutdown();
// }
// Path: kafka/src/main/java/com/strategicgains/eventing/kafka/KafkaEventTransport.java
import java.util.Properties;
import java.util.concurrent.Future;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.Producer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.clients.producer.RecordMetadata;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.strategicgains.eventing.EventHandler;
import com.strategicgains.eventing.EventTransport;
/*
Copyright 2016, Ping Identity Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.strategicgains.eventing.kafka;
/**
* @author tfredrich
* @since 20 May 2016
*/
public class KafkaEventTransport
implements EventTransport
{
private String topic;
private Producer<String, String> producer;
private ObjectMapper mapper;
public KafkaEventTransport(Properties config, String topic)
{
this(config, topic, new ObjectMapper());
}
public KafkaEventTransport(Properties config, String topic, ObjectMapper mapper)
{
this.producer = new KafkaProducer<>(config);
this.topic = topic;
this.mapper = mapper;
}
@Override
public void publish(Object event)
{
try
{
Future<RecordMetadata> f = producer.send(new ProducerRecord<String, String>(topic, System.currentTimeMillis() + "", mapper.writeValueAsString(event)));
}
catch (JsonProcessingException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override | public boolean subscribe(EventHandler handler) |
tfredrich/Domain-Eventing | hazelcast/test/java/com/strategicgains/eventing/hazelcast/HazelcastEventBusTest.java | // Path: core/src/java/com/strategicgains/eventing/EventHandler.java
// public interface EventHandler
// {
// /**
// * Process the given event. Called by the EventMonitor when an event occurs.
// *
// * @param event
// * @throws Exception if something goes wrong
// */
// public void handle(Object event)
// throws Exception;
//
// /**
// * Answers whether this EventHandler can handle events of the given type.
// * If true is returned, the EventMonitor will call handle(), otherwise,
// * the EventMonitor will not ask this event handler to process the event.
// *
// * @param eventClass
// * @return
// */
// public boolean handles(Class<?> eventClass);
// }
| import static org.junit.Assert.assertEquals;
import java.io.Serializable;
import java.util.Arrays;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.strategicgains.eventing.EventHandler; | }
@Test
public void shouldOnlyPublishSelected()
throws Exception
{
queue.addPublishableEventType(HandledEvent.class);
assertEquals(0, handler.getCallCount());
assertEquals(0, ignoredHandler.getCallCount());
queue.publish(new HandledEvent());
queue.publish(new IgnoredEvent());
queue.publish(new HandledEvent());
queue.publish(new IgnoredEvent());
queue.publish(new HandledEvent());
queue.publish(new IgnoredEvent());
queue.publish(new HandledEvent());
queue.publish(new IgnoredEvent());
queue.publish(new HandledEvent());
queue.publish(new IgnoredEvent());
Thread.sleep(50);
assertEquals(5, handler.getCallCount());
assertEquals(0, ignoredHandler.getCallCount());
assertEquals(0, longHandler.getCallCount());
}
// SECTION: INNER CLASSES
private static class DomainEventsTestHandler | // Path: core/src/java/com/strategicgains/eventing/EventHandler.java
// public interface EventHandler
// {
// /**
// * Process the given event. Called by the EventMonitor when an event occurs.
// *
// * @param event
// * @throws Exception if something goes wrong
// */
// public void handle(Object event)
// throws Exception;
//
// /**
// * Answers whether this EventHandler can handle events of the given type.
// * If true is returned, the EventMonitor will call handle(), otherwise,
// * the EventMonitor will not ask this event handler to process the event.
// *
// * @param eventClass
// * @return
// */
// public boolean handles(Class<?> eventClass);
// }
// Path: hazelcast/test/java/com/strategicgains/eventing/hazelcast/HazelcastEventBusTest.java
import static org.junit.Assert.assertEquals;
import java.io.Serializable;
import java.util.Arrays;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.strategicgains.eventing.EventHandler;
}
@Test
public void shouldOnlyPublishSelected()
throws Exception
{
queue.addPublishableEventType(HandledEvent.class);
assertEquals(0, handler.getCallCount());
assertEquals(0, ignoredHandler.getCallCount());
queue.publish(new HandledEvent());
queue.publish(new IgnoredEvent());
queue.publish(new HandledEvent());
queue.publish(new IgnoredEvent());
queue.publish(new HandledEvent());
queue.publish(new IgnoredEvent());
queue.publish(new HandledEvent());
queue.publish(new IgnoredEvent());
queue.publish(new HandledEvent());
queue.publish(new IgnoredEvent());
Thread.sleep(50);
assertEquals(5, handler.getCallCount());
assertEquals(0, ignoredHandler.getCallCount());
assertEquals(0, longHandler.getCallCount());
}
// SECTION: INNER CLASSES
private static class DomainEventsTestHandler | implements EventHandler |
tfredrich/Domain-Eventing | hazelcast/src/java/com/strategicgains/eventing/hazelcast/HazelcastEventBus.java | // Path: core/src/java/com/strategicgains/eventing/EventBus.java
// public abstract class EventBus
// {
// private EventTransport transport;
// private Set<Class<?>> publishableEventTypes = new HashSet<Class<?>>();
//
// public EventBus(EventTransport transport)
// {
// super();
// this.transport = transport;
// }
//
// public boolean addPublishableEventType(Class<?> eventType)
// {
// return publishableEventTypes.add(eventType);
// }
//
// public boolean canPublish(Class<?> eventType)
// {
// if (publishableEventTypes.isEmpty()) return true;
//
// return publishableEventTypes.contains(eventType);
// }
//
// public void publish(Object event)
// {
// if (!canPublish(event.getClass())) return;
//
// transport.publish(event);
// }
//
// public void shutdown()
// {
// transport.shutdown();
// }
//
// public boolean subscribe(EventHandler handler)
// {
// return transport.subscribe(handler);
// }
//
// public boolean unsubscribe(EventHandler handler)
// {
// return transport.unsubscribe(handler);
// }
//
// protected EventTransport getTransport()
// {
// return transport;
// }
// }
//
// Path: core/src/java/com/strategicgains/eventing/EventHandler.java
// public interface EventHandler
// {
// /**
// * Process the given event. Called by the EventMonitor when an event occurs.
// *
// * @param event
// * @throws Exception if something goes wrong
// */
// public void handle(Object event)
// throws Exception;
//
// /**
// * Answers whether this EventHandler can handle events of the given type.
// * If true is returned, the EventMonitor will call handle(), otherwise,
// * the EventMonitor will not ask this event handler to process the event.
// *
// * @param eventClass
// * @return
// */
// public boolean handles(Class<?> eventClass);
// }
| import java.io.Serializable;
import java.util.List;
import com.hazelcast.config.Config;
import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.HazelcastInstance;
import com.strategicgains.eventing.EventBus;
import com.strategicgains.eventing.EventHandler; | /*
Copyright 2012, Strategic Gains, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.strategicgains.eventing.hazelcast;
/**
* Leverages Hazelcast to create a distrubuted EventBus implementation to
* support intra-cluster eventing.
*
* @author toddf
* @since Jun 27, 2012
*/
public class HazelcastEventBus<T extends Serializable>
extends EventBus
{
private HazelcastInstance hazelcast;
| // Path: core/src/java/com/strategicgains/eventing/EventBus.java
// public abstract class EventBus
// {
// private EventTransport transport;
// private Set<Class<?>> publishableEventTypes = new HashSet<Class<?>>();
//
// public EventBus(EventTransport transport)
// {
// super();
// this.transport = transport;
// }
//
// public boolean addPublishableEventType(Class<?> eventType)
// {
// return publishableEventTypes.add(eventType);
// }
//
// public boolean canPublish(Class<?> eventType)
// {
// if (publishableEventTypes.isEmpty()) return true;
//
// return publishableEventTypes.contains(eventType);
// }
//
// public void publish(Object event)
// {
// if (!canPublish(event.getClass())) return;
//
// transport.publish(event);
// }
//
// public void shutdown()
// {
// transport.shutdown();
// }
//
// public boolean subscribe(EventHandler handler)
// {
// return transport.subscribe(handler);
// }
//
// public boolean unsubscribe(EventHandler handler)
// {
// return transport.unsubscribe(handler);
// }
//
// protected EventTransport getTransport()
// {
// return transport;
// }
// }
//
// Path: core/src/java/com/strategicgains/eventing/EventHandler.java
// public interface EventHandler
// {
// /**
// * Process the given event. Called by the EventMonitor when an event occurs.
// *
// * @param event
// * @throws Exception if something goes wrong
// */
// public void handle(Object event)
// throws Exception;
//
// /**
// * Answers whether this EventHandler can handle events of the given type.
// * If true is returned, the EventMonitor will call handle(), otherwise,
// * the EventMonitor will not ask this event handler to process the event.
// *
// * @param eventClass
// * @return
// */
// public boolean handles(Class<?> eventClass);
// }
// Path: hazelcast/src/java/com/strategicgains/eventing/hazelcast/HazelcastEventBus.java
import java.io.Serializable;
import java.util.List;
import com.hazelcast.config.Config;
import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.HazelcastInstance;
import com.strategicgains.eventing.EventBus;
import com.strategicgains.eventing.EventHandler;
/*
Copyright 2012, Strategic Gains, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.strategicgains.eventing.hazelcast;
/**
* Leverages Hazelcast to create a distrubuted EventBus implementation to
* support intra-cluster eventing.
*
* @author toddf
* @since Jun 27, 2012
*/
public class HazelcastEventBus<T extends Serializable>
extends EventBus
{
private HazelcastInstance hazelcast;
| public HazelcastEventBus(String queueName, List<EventHandler> subscribers) |
tfredrich/Domain-Eventing | core/src/java/com/strategicgains/eventing/local/EventMonitor.java | // Path: core/src/java/com/strategicgains/eventing/EventHandler.java
// public interface EventHandler
// {
// /**
// * Process the given event. Called by the EventMonitor when an event occurs.
// *
// * @param event
// * @throws Exception if something goes wrong
// */
// public void handle(Object event)
// throws Exception;
//
// /**
// * Answers whether this EventHandler can handle events of the given type.
// * If true is returned, the EventMonitor will call handle(), otherwise,
// * the EventMonitor will not ask this event handler to process the event.
// *
// * @param eventClass
// * @return
// */
// public boolean handles(Class<?> eventClass);
// }
| import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import com.strategicgains.eventing.EventHandler; | /*
Copyright 2011, Strategic Gains, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.strategicgains.eventing.local;
/**
* A thread that receives published events and sends them to subscribers.
* Registered event handlers will be called for whatever event types each can process.
*
* EventHandlers are called using an Executor pool that grows dynamically as needed, so
* they are run asynchronously.
*
* @author toddf
* @since May 17, 2011
*/
public class EventMonitor
extends Thread
{
// SECTION: CONSTANTS
private static final Executor EVENT_EXECUTOR = Executors.newCachedThreadPool();
// SECTION: INSTANCE METHODS
| // Path: core/src/java/com/strategicgains/eventing/EventHandler.java
// public interface EventHandler
// {
// /**
// * Process the given event. Called by the EventMonitor when an event occurs.
// *
// * @param event
// * @throws Exception if something goes wrong
// */
// public void handle(Object event)
// throws Exception;
//
// /**
// * Answers whether this EventHandler can handle events of the given type.
// * If true is returned, the EventMonitor will call handle(), otherwise,
// * the EventMonitor will not ask this event handler to process the event.
// *
// * @param eventClass
// * @return
// */
// public boolean handles(Class<?> eventClass);
// }
// Path: core/src/java/com/strategicgains/eventing/local/EventMonitor.java
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import com.strategicgains.eventing.EventHandler;
/*
Copyright 2011, Strategic Gains, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.strategicgains.eventing.local;
/**
* A thread that receives published events and sends them to subscribers.
* Registered event handlers will be called for whatever event types each can process.
*
* EventHandlers are called using an Executor pool that grows dynamically as needed, so
* they are run asynchronously.
*
* @author toddf
* @since May 17, 2011
*/
public class EventMonitor
extends Thread
{
// SECTION: CONSTANTS
private static final Executor EVENT_EXECUTOR = Executors.newCachedThreadPool();
// SECTION: INSTANCE METHODS
| private Map<Class<?>, List<EventHandler>> handlersByEvent = new ConcurrentHashMap<Class<?>, List<EventHandler>>(); |
tfredrich/Domain-Eventing | hazelcast/src/java/com/strategicgains/eventing/hazelcast/EventHandlerAdapter.java | // Path: core/src/java/com/strategicgains/eventing/EventHandler.java
// public interface EventHandler
// {
// /**
// * Process the given event. Called by the EventMonitor when an event occurs.
// *
// * @param event
// * @throws Exception if something goes wrong
// */
// public void handle(Object event)
// throws Exception;
//
// /**
// * Answers whether this EventHandler can handle events of the given type.
// * If true is returned, the EventMonitor will call handle(), otherwise,
// * the EventMonitor will not ask this event handler to process the event.
// *
// * @param eventClass
// * @return
// */
// public boolean handles(Class<?> eventClass);
// }
| import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import com.hazelcast.core.Message;
import com.hazelcast.core.MessageListener;
import com.strategicgains.eventing.EventHandler; | /*
Copyright 2012, Strategic Gains, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.strategicgains.eventing.hazelcast;
/**
* @author toddf
* @since Oct 5, 2012
*/
public class EventHandlerAdapter
implements MessageListener<Object>
{
// SECTION: CONSTANTS
private static final Executor EVENT_EXECUTOR = Executors.newCachedThreadPool();
// SECTION: INSTANCE VARIABLES
| // Path: core/src/java/com/strategicgains/eventing/EventHandler.java
// public interface EventHandler
// {
// /**
// * Process the given event. Called by the EventMonitor when an event occurs.
// *
// * @param event
// * @throws Exception if something goes wrong
// */
// public void handle(Object event)
// throws Exception;
//
// /**
// * Answers whether this EventHandler can handle events of the given type.
// * If true is returned, the EventMonitor will call handle(), otherwise,
// * the EventMonitor will not ask this event handler to process the event.
// *
// * @param eventClass
// * @return
// */
// public boolean handles(Class<?> eventClass);
// }
// Path: hazelcast/src/java/com/strategicgains/eventing/hazelcast/EventHandlerAdapter.java
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import com.hazelcast.core.Message;
import com.hazelcast.core.MessageListener;
import com.strategicgains.eventing.EventHandler;
/*
Copyright 2012, Strategic Gains, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.strategicgains.eventing.hazelcast;
/**
* @author toddf
* @since Oct 5, 2012
*/
public class EventHandlerAdapter
implements MessageListener<Object>
{
// SECTION: CONSTANTS
private static final Executor EVENT_EXECUTOR = Executors.newCachedThreadPool();
// SECTION: INSTANCE VARIABLES
| private EventHandler handler; |
tfredrich/Domain-Eventing | hazelcast/test/java/com/strategicgains/eventing/hazelcast/HazelcastEventBusBuilderTest.java | // Path: core/src/java/com/strategicgains/eventing/EventHandler.java
// public interface EventHandler
// {
// /**
// * Process the given event. Called by the EventMonitor when an event occurs.
// *
// * @param event
// * @throws Exception if something goes wrong
// */
// public void handle(Object event)
// throws Exception;
//
// /**
// * Answers whether this EventHandler can handle events of the given type.
// * If true is returned, the EventMonitor will call handle(), otherwise,
// * the EventMonitor will not ask this event handler to process the event.
// *
// * @param eventClass
// * @return
// */
// public boolean handles(Class<?> eventClass);
// }
| import static org.junit.Assert.assertEquals;
import java.io.Serializable;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.strategicgains.eventing.EventHandler; | {
assertEquals(0, handler.getCallCount());
queue.publish(new ErroredEvent());
Thread.sleep(50);
assertEquals(1, handler.getCallCount());
assertEquals(0, ignoredHandler.getCallCount());
assertEquals(0, longHandler.getCallCount());
}
@Test
public void shouldProcessInParallel()
throws Exception
{
assertEquals(0, longHandler.getCallCount());
queue.publish(new LongEvent());
queue.publish(new LongEvent());
queue.publish(new LongEvent());
queue.publish(new LongEvent());
queue.publish(new LongEvent());
Thread.sleep(50);
assertEquals(0, handler.getCallCount());
assertEquals(0, ignoredHandler.getCallCount());
// System.out.println("longHandler instance=" + longHandler.toString());
assertEquals(5, longHandler.getCallCount());
}
// SECTION: INNER CLASSES
private static class DomainEventsTestHandler | // Path: core/src/java/com/strategicgains/eventing/EventHandler.java
// public interface EventHandler
// {
// /**
// * Process the given event. Called by the EventMonitor when an event occurs.
// *
// * @param event
// * @throws Exception if something goes wrong
// */
// public void handle(Object event)
// throws Exception;
//
// /**
// * Answers whether this EventHandler can handle events of the given type.
// * If true is returned, the EventMonitor will call handle(), otherwise,
// * the EventMonitor will not ask this event handler to process the event.
// *
// * @param eventClass
// * @return
// */
// public boolean handles(Class<?> eventClass);
// }
// Path: hazelcast/test/java/com/strategicgains/eventing/hazelcast/HazelcastEventBusBuilderTest.java
import static org.junit.Assert.assertEquals;
import java.io.Serializable;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.strategicgains.eventing.EventHandler;
{
assertEquals(0, handler.getCallCount());
queue.publish(new ErroredEvent());
Thread.sleep(50);
assertEquals(1, handler.getCallCount());
assertEquals(0, ignoredHandler.getCallCount());
assertEquals(0, longHandler.getCallCount());
}
@Test
public void shouldProcessInParallel()
throws Exception
{
assertEquals(0, longHandler.getCallCount());
queue.publish(new LongEvent());
queue.publish(new LongEvent());
queue.publish(new LongEvent());
queue.publish(new LongEvent());
queue.publish(new LongEvent());
Thread.sleep(50);
assertEquals(0, handler.getCallCount());
assertEquals(0, ignoredHandler.getCallCount());
// System.out.println("longHandler instance=" + longHandler.toString());
assertEquals(5, longHandler.getCallCount());
}
// SECTION: INNER CLASSES
private static class DomainEventsTestHandler | implements EventHandler |
tfredrich/Domain-Eventing | akka/src/main/java/com/strategicgains/eventing/akka/AkkaEventBus.java | // Path: core/src/java/com/strategicgains/eventing/EventBus.java
// public abstract class EventBus
// {
// private EventTransport transport;
// private Set<Class<?>> publishableEventTypes = new HashSet<Class<?>>();
//
// public EventBus(EventTransport transport)
// {
// super();
// this.transport = transport;
// }
//
// public boolean addPublishableEventType(Class<?> eventType)
// {
// return publishableEventTypes.add(eventType);
// }
//
// public boolean canPublish(Class<?> eventType)
// {
// if (publishableEventTypes.isEmpty()) return true;
//
// return publishableEventTypes.contains(eventType);
// }
//
// public void publish(Object event)
// {
// if (!canPublish(event.getClass())) return;
//
// transport.publish(event);
// }
//
// public void shutdown()
// {
// transport.shutdown();
// }
//
// public boolean subscribe(EventHandler handler)
// {
// return transport.subscribe(handler);
// }
//
// public boolean unsubscribe(EventHandler handler)
// {
// return transport.unsubscribe(handler);
// }
//
// protected EventTransport getTransport()
// {
// return transport;
// }
// }
//
// Path: core/src/java/com/strategicgains/eventing/EventHandler.java
// public interface EventHandler
// {
// /**
// * Process the given event. Called by the EventMonitor when an event occurs.
// *
// * @param event
// * @throws Exception if something goes wrong
// */
// public void handle(Object event)
// throws Exception;
//
// /**
// * Answers whether this EventHandler can handle events of the given type.
// * If true is returned, the EventMonitor will call handle(), otherwise,
// * the EventMonitor will not ask this event handler to process the event.
// *
// * @param eventClass
// * @return
// */
// public boolean handles(Class<?> eventClass);
// }
| import java.util.List;
import akka.actor.ActorSystem;
import com.strategicgains.eventing.EventBus;
import com.strategicgains.eventing.EventHandler; | /*
Copyright 2015, Strategic Gains, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.strategicgains.eventing.akka;
/**
* @author tfredrich
* @since Jul 13, 2015
*/
public class AkkaEventBus
extends EventBus
{
public AkkaEventBus()
{
this(ActorSystem.create("AkkaDomainEventing"));
}
public AkkaEventBus(ActorSystem actorSystem)
{
super(new AkkaEventTransport(actorSystem));
}
| // Path: core/src/java/com/strategicgains/eventing/EventBus.java
// public abstract class EventBus
// {
// private EventTransport transport;
// private Set<Class<?>> publishableEventTypes = new HashSet<Class<?>>();
//
// public EventBus(EventTransport transport)
// {
// super();
// this.transport = transport;
// }
//
// public boolean addPublishableEventType(Class<?> eventType)
// {
// return publishableEventTypes.add(eventType);
// }
//
// public boolean canPublish(Class<?> eventType)
// {
// if (publishableEventTypes.isEmpty()) return true;
//
// return publishableEventTypes.contains(eventType);
// }
//
// public void publish(Object event)
// {
// if (!canPublish(event.getClass())) return;
//
// transport.publish(event);
// }
//
// public void shutdown()
// {
// transport.shutdown();
// }
//
// public boolean subscribe(EventHandler handler)
// {
// return transport.subscribe(handler);
// }
//
// public boolean unsubscribe(EventHandler handler)
// {
// return transport.unsubscribe(handler);
// }
//
// protected EventTransport getTransport()
// {
// return transport;
// }
// }
//
// Path: core/src/java/com/strategicgains/eventing/EventHandler.java
// public interface EventHandler
// {
// /**
// * Process the given event. Called by the EventMonitor when an event occurs.
// *
// * @param event
// * @throws Exception if something goes wrong
// */
// public void handle(Object event)
// throws Exception;
//
// /**
// * Answers whether this EventHandler can handle events of the given type.
// * If true is returned, the EventMonitor will call handle(), otherwise,
// * the EventMonitor will not ask this event handler to process the event.
// *
// * @param eventClass
// * @return
// */
// public boolean handles(Class<?> eventClass);
// }
// Path: akka/src/main/java/com/strategicgains/eventing/akka/AkkaEventBus.java
import java.util.List;
import akka.actor.ActorSystem;
import com.strategicgains.eventing.EventBus;
import com.strategicgains.eventing.EventHandler;
/*
Copyright 2015, Strategic Gains, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.strategicgains.eventing.akka;
/**
* @author tfredrich
* @since Jul 13, 2015
*/
public class AkkaEventBus
extends EventBus
{
public AkkaEventBus()
{
this(ActorSystem.create("AkkaDomainEventing"));
}
public AkkaEventBus(ActorSystem actorSystem)
{
super(new AkkaEventTransport(actorSystem));
}
| public void subscribeAll(List<EventHandler> handlers) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.