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
beerbong/com_beerbong_zipinst
src/com/beerbong/zipinst/ui/preference/UICheckBoxPreference.java
// Path: src/com/beerbong/zipinst/core/Core.java // public interface Core extends Serializable { // // public static final String PLUGIN_UI = "UIPlugin"; // public static final String PLUGIN_SUPERUSER = "SuperUserPlugin"; // public static final String PLUGIN_RECOVERY = "RecoveryPlugin"; // public static final String PLUGIN_STORAGE = "StoragePlugin"; // public static final String PLUGIN_REBOOT = "RebootPlugin"; // public static final String PLUGIN_LICENSE = "LicensePlugin"; // public static final String PLUGIN_UPDATE = "UpdatePlugin"; // // public interface CoreListener { // // public void pluginStarted(String name); // // public void pluginStopped(String name); // // public void coreMessage(int resId); // // public void coreStarted(); // // public void coreStopped(); // } // // public void destroy(); // // public boolean isStarted(); // // public Context getContext(); // // public void setContext(Context context); // // public Plugin getPlugin(String name); // // public Preferences getPreferences(); // // public CloudStorage getCloudStorage(); // // public void setCloudStorage(int cloudStorage); // // public ONandroid getONandroid(); // // public Version getVersion(); // // public void moveToInstall(); // } // // Path: src/com/beerbong/zipinst/core/CoreFactory.java // public class CoreFactory { // // private static Core sInstance; // // public static synchronized void init(Context context) { // init(context, null); // } // // public static synchronized void init(Context context, CoreListener listener) { // if (sInstance == null) { // sInstance = new CoreImpl(context, listener); // } else { // sInstance.setContext(context); // } // } // // public static Core getCore() { // return sInstance; // } // // } // // Path: src/com/beerbong/zipinst/core/plugins/ui/UIPlugin.java // public class UIPlugin extends Plugin { // // private static final String ROBOTO_THIN = "font/Roboto-Light.ttf"; // // private Map<String, UIInterface> mUiInterfaces; // private Typeface mRobotoThin; // // public UIPlugin(Core core) { // super(core, Core.PLUGIN_UI); // } // // @Override // public void start() { // ((CoreImpl) getCore()).setMessage(R.string.initializing_ui); // // // (new AsyncTask<Void, Void, Void>() { // // @Override // protected Void doInBackground(Void... params) { // mUiInterfaces = new HashMap<String, UIInterface>(); // // mRobotoThin = Typeface // .createFromAsset(getCore().getContext().getAssets(), ROBOTO_THIN); // return (Void) null; // } // // @Override // protected void onPostExecute(Void result) { // started(); // } // }).execute((Void) null); // } // // @Override // public void stop() { // stopped(); // } // // public void unregisterUI(UIInterface uIInterface) { // if (mUiInterfaces != null) { // mUiInterfaces.remove(uIInterface.getClass().getName()); // } // } // // public void registerUI(UIInterface uIInterface) { // boolean darkTheme = getCore().getPreferences().isDarkTheme(); // uIInterface.setTheme(darkTheme ? R.style.AppTheme_Dark // : R.style.AppTheme); // // redraw(uIInterface); // // if (mUiInterfaces != null) { // mUiInterfaces.put(uIInterface.getClass().getName(), uIInterface); // } // } // // public void redraw() { // Iterator<String> it = mUiInterfaces.keySet().iterator(); // while (it.hasNext()) { // String key = it.next(); // UIInterface uiInterface = mUiInterfaces.get(key); // redraw(uiInterface); // } // } // // public void redraw(UIInterface uIInterface) { // redraw(uIInterface.getMainView()); // } // // public void redraw(View view) { // setFont(view); // } // // private void setFont(View view) { // if (view == null) { // return; // } // if (view instanceof ViewGroup) { // int count = ((ViewGroup) view).getChildCount(); // for (int i = 0; i < count; i++) { // setFont(((ViewGroup) view).getChildAt(i)); // } // } else if (view instanceof TextView) { // ((TextView) view).setTypeface(mRobotoThin); // } // } // // }
import android.content.Context; import android.preference.CheckBoxPreference; import android.util.AttributeSet; import android.view.View; import com.beerbong.zipinst.core.Core; import com.beerbong.zipinst.core.CoreFactory; import com.beerbong.zipinst.core.plugins.ui.UIPlugin;
/* * Copyright 2014 ZipInstaller Project * * This file is part of ZipInstaller. * * ZipInstaller is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * ZipInstaller is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with ZipInstaller. If not, see <http://www.gnu.org/licenses/>. */ package com.beerbong.zipinst.ui.preference; public class UICheckBoxPreference extends CheckBoxPreference { public UICheckBoxPreference(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } public UICheckBoxPreference(Context context, AttributeSet attrs) { super(context, attrs); } public UICheckBoxPreference(Context context) { super(context); } @Override protected void onBindView(View view) { super.onBindView(view);
// Path: src/com/beerbong/zipinst/core/Core.java // public interface Core extends Serializable { // // public static final String PLUGIN_UI = "UIPlugin"; // public static final String PLUGIN_SUPERUSER = "SuperUserPlugin"; // public static final String PLUGIN_RECOVERY = "RecoveryPlugin"; // public static final String PLUGIN_STORAGE = "StoragePlugin"; // public static final String PLUGIN_REBOOT = "RebootPlugin"; // public static final String PLUGIN_LICENSE = "LicensePlugin"; // public static final String PLUGIN_UPDATE = "UpdatePlugin"; // // public interface CoreListener { // // public void pluginStarted(String name); // // public void pluginStopped(String name); // // public void coreMessage(int resId); // // public void coreStarted(); // // public void coreStopped(); // } // // public void destroy(); // // public boolean isStarted(); // // public Context getContext(); // // public void setContext(Context context); // // public Plugin getPlugin(String name); // // public Preferences getPreferences(); // // public CloudStorage getCloudStorage(); // // public void setCloudStorage(int cloudStorage); // // public ONandroid getONandroid(); // // public Version getVersion(); // // public void moveToInstall(); // } // // Path: src/com/beerbong/zipinst/core/CoreFactory.java // public class CoreFactory { // // private static Core sInstance; // // public static synchronized void init(Context context) { // init(context, null); // } // // public static synchronized void init(Context context, CoreListener listener) { // if (sInstance == null) { // sInstance = new CoreImpl(context, listener); // } else { // sInstance.setContext(context); // } // } // // public static Core getCore() { // return sInstance; // } // // } // // Path: src/com/beerbong/zipinst/core/plugins/ui/UIPlugin.java // public class UIPlugin extends Plugin { // // private static final String ROBOTO_THIN = "font/Roboto-Light.ttf"; // // private Map<String, UIInterface> mUiInterfaces; // private Typeface mRobotoThin; // // public UIPlugin(Core core) { // super(core, Core.PLUGIN_UI); // } // // @Override // public void start() { // ((CoreImpl) getCore()).setMessage(R.string.initializing_ui); // // // (new AsyncTask<Void, Void, Void>() { // // @Override // protected Void doInBackground(Void... params) { // mUiInterfaces = new HashMap<String, UIInterface>(); // // mRobotoThin = Typeface // .createFromAsset(getCore().getContext().getAssets(), ROBOTO_THIN); // return (Void) null; // } // // @Override // protected void onPostExecute(Void result) { // started(); // } // }).execute((Void) null); // } // // @Override // public void stop() { // stopped(); // } // // public void unregisterUI(UIInterface uIInterface) { // if (mUiInterfaces != null) { // mUiInterfaces.remove(uIInterface.getClass().getName()); // } // } // // public void registerUI(UIInterface uIInterface) { // boolean darkTheme = getCore().getPreferences().isDarkTheme(); // uIInterface.setTheme(darkTheme ? R.style.AppTheme_Dark // : R.style.AppTheme); // // redraw(uIInterface); // // if (mUiInterfaces != null) { // mUiInterfaces.put(uIInterface.getClass().getName(), uIInterface); // } // } // // public void redraw() { // Iterator<String> it = mUiInterfaces.keySet().iterator(); // while (it.hasNext()) { // String key = it.next(); // UIInterface uiInterface = mUiInterfaces.get(key); // redraw(uiInterface); // } // } // // public void redraw(UIInterface uIInterface) { // redraw(uIInterface.getMainView()); // } // // public void redraw(View view) { // setFont(view); // } // // private void setFont(View view) { // if (view == null) { // return; // } // if (view instanceof ViewGroup) { // int count = ((ViewGroup) view).getChildCount(); // for (int i = 0; i < count; i++) { // setFont(((ViewGroup) view).getChildAt(i)); // } // } else if (view instanceof TextView) { // ((TextView) view).setTypeface(mRobotoThin); // } // } // // } // Path: src/com/beerbong/zipinst/ui/preference/UICheckBoxPreference.java import android.content.Context; import android.preference.CheckBoxPreference; import android.util.AttributeSet; import android.view.View; import com.beerbong.zipinst.core.Core; import com.beerbong.zipinst.core.CoreFactory; import com.beerbong.zipinst.core.plugins.ui.UIPlugin; /* * Copyright 2014 ZipInstaller Project * * This file is part of ZipInstaller. * * ZipInstaller is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * ZipInstaller is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with ZipInstaller. If not, see <http://www.gnu.org/licenses/>. */ package com.beerbong.zipinst.ui.preference; public class UICheckBoxPreference extends CheckBoxPreference { public UICheckBoxPreference(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } public UICheckBoxPreference(Context context, AttributeSet attrs) { super(context, attrs); } public UICheckBoxPreference(Context context) { super(context); } @Override protected void onBindView(View view) { super.onBindView(view);
((UIPlugin) CoreFactory.getCore().getPlugin(Core.PLUGIN_UI)).redraw(view);
beerbong/com_beerbong_zipinst
src/com/beerbong/zipinst/ui/preference/UICheckBoxPreference.java
// Path: src/com/beerbong/zipinst/core/Core.java // public interface Core extends Serializable { // // public static final String PLUGIN_UI = "UIPlugin"; // public static final String PLUGIN_SUPERUSER = "SuperUserPlugin"; // public static final String PLUGIN_RECOVERY = "RecoveryPlugin"; // public static final String PLUGIN_STORAGE = "StoragePlugin"; // public static final String PLUGIN_REBOOT = "RebootPlugin"; // public static final String PLUGIN_LICENSE = "LicensePlugin"; // public static final String PLUGIN_UPDATE = "UpdatePlugin"; // // public interface CoreListener { // // public void pluginStarted(String name); // // public void pluginStopped(String name); // // public void coreMessage(int resId); // // public void coreStarted(); // // public void coreStopped(); // } // // public void destroy(); // // public boolean isStarted(); // // public Context getContext(); // // public void setContext(Context context); // // public Plugin getPlugin(String name); // // public Preferences getPreferences(); // // public CloudStorage getCloudStorage(); // // public void setCloudStorage(int cloudStorage); // // public ONandroid getONandroid(); // // public Version getVersion(); // // public void moveToInstall(); // } // // Path: src/com/beerbong/zipinst/core/CoreFactory.java // public class CoreFactory { // // private static Core sInstance; // // public static synchronized void init(Context context) { // init(context, null); // } // // public static synchronized void init(Context context, CoreListener listener) { // if (sInstance == null) { // sInstance = new CoreImpl(context, listener); // } else { // sInstance.setContext(context); // } // } // // public static Core getCore() { // return sInstance; // } // // } // // Path: src/com/beerbong/zipinst/core/plugins/ui/UIPlugin.java // public class UIPlugin extends Plugin { // // private static final String ROBOTO_THIN = "font/Roboto-Light.ttf"; // // private Map<String, UIInterface> mUiInterfaces; // private Typeface mRobotoThin; // // public UIPlugin(Core core) { // super(core, Core.PLUGIN_UI); // } // // @Override // public void start() { // ((CoreImpl) getCore()).setMessage(R.string.initializing_ui); // // // (new AsyncTask<Void, Void, Void>() { // // @Override // protected Void doInBackground(Void... params) { // mUiInterfaces = new HashMap<String, UIInterface>(); // // mRobotoThin = Typeface // .createFromAsset(getCore().getContext().getAssets(), ROBOTO_THIN); // return (Void) null; // } // // @Override // protected void onPostExecute(Void result) { // started(); // } // }).execute((Void) null); // } // // @Override // public void stop() { // stopped(); // } // // public void unregisterUI(UIInterface uIInterface) { // if (mUiInterfaces != null) { // mUiInterfaces.remove(uIInterface.getClass().getName()); // } // } // // public void registerUI(UIInterface uIInterface) { // boolean darkTheme = getCore().getPreferences().isDarkTheme(); // uIInterface.setTheme(darkTheme ? R.style.AppTheme_Dark // : R.style.AppTheme); // // redraw(uIInterface); // // if (mUiInterfaces != null) { // mUiInterfaces.put(uIInterface.getClass().getName(), uIInterface); // } // } // // public void redraw() { // Iterator<String> it = mUiInterfaces.keySet().iterator(); // while (it.hasNext()) { // String key = it.next(); // UIInterface uiInterface = mUiInterfaces.get(key); // redraw(uiInterface); // } // } // // public void redraw(UIInterface uIInterface) { // redraw(uIInterface.getMainView()); // } // // public void redraw(View view) { // setFont(view); // } // // private void setFont(View view) { // if (view == null) { // return; // } // if (view instanceof ViewGroup) { // int count = ((ViewGroup) view).getChildCount(); // for (int i = 0; i < count; i++) { // setFont(((ViewGroup) view).getChildAt(i)); // } // } else if (view instanceof TextView) { // ((TextView) view).setTypeface(mRobotoThin); // } // } // // }
import android.content.Context; import android.preference.CheckBoxPreference; import android.util.AttributeSet; import android.view.View; import com.beerbong.zipinst.core.Core; import com.beerbong.zipinst.core.CoreFactory; import com.beerbong.zipinst.core.plugins.ui.UIPlugin;
/* * Copyright 2014 ZipInstaller Project * * This file is part of ZipInstaller. * * ZipInstaller is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * ZipInstaller is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with ZipInstaller. If not, see <http://www.gnu.org/licenses/>. */ package com.beerbong.zipinst.ui.preference; public class UICheckBoxPreference extends CheckBoxPreference { public UICheckBoxPreference(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } public UICheckBoxPreference(Context context, AttributeSet attrs) { super(context, attrs); } public UICheckBoxPreference(Context context) { super(context); } @Override protected void onBindView(View view) { super.onBindView(view);
// Path: src/com/beerbong/zipinst/core/Core.java // public interface Core extends Serializable { // // public static final String PLUGIN_UI = "UIPlugin"; // public static final String PLUGIN_SUPERUSER = "SuperUserPlugin"; // public static final String PLUGIN_RECOVERY = "RecoveryPlugin"; // public static final String PLUGIN_STORAGE = "StoragePlugin"; // public static final String PLUGIN_REBOOT = "RebootPlugin"; // public static final String PLUGIN_LICENSE = "LicensePlugin"; // public static final String PLUGIN_UPDATE = "UpdatePlugin"; // // public interface CoreListener { // // public void pluginStarted(String name); // // public void pluginStopped(String name); // // public void coreMessage(int resId); // // public void coreStarted(); // // public void coreStopped(); // } // // public void destroy(); // // public boolean isStarted(); // // public Context getContext(); // // public void setContext(Context context); // // public Plugin getPlugin(String name); // // public Preferences getPreferences(); // // public CloudStorage getCloudStorage(); // // public void setCloudStorage(int cloudStorage); // // public ONandroid getONandroid(); // // public Version getVersion(); // // public void moveToInstall(); // } // // Path: src/com/beerbong/zipinst/core/CoreFactory.java // public class CoreFactory { // // private static Core sInstance; // // public static synchronized void init(Context context) { // init(context, null); // } // // public static synchronized void init(Context context, CoreListener listener) { // if (sInstance == null) { // sInstance = new CoreImpl(context, listener); // } else { // sInstance.setContext(context); // } // } // // public static Core getCore() { // return sInstance; // } // // } // // Path: src/com/beerbong/zipinst/core/plugins/ui/UIPlugin.java // public class UIPlugin extends Plugin { // // private static final String ROBOTO_THIN = "font/Roboto-Light.ttf"; // // private Map<String, UIInterface> mUiInterfaces; // private Typeface mRobotoThin; // // public UIPlugin(Core core) { // super(core, Core.PLUGIN_UI); // } // // @Override // public void start() { // ((CoreImpl) getCore()).setMessage(R.string.initializing_ui); // // // (new AsyncTask<Void, Void, Void>() { // // @Override // protected Void doInBackground(Void... params) { // mUiInterfaces = new HashMap<String, UIInterface>(); // // mRobotoThin = Typeface // .createFromAsset(getCore().getContext().getAssets(), ROBOTO_THIN); // return (Void) null; // } // // @Override // protected void onPostExecute(Void result) { // started(); // } // }).execute((Void) null); // } // // @Override // public void stop() { // stopped(); // } // // public void unregisterUI(UIInterface uIInterface) { // if (mUiInterfaces != null) { // mUiInterfaces.remove(uIInterface.getClass().getName()); // } // } // // public void registerUI(UIInterface uIInterface) { // boolean darkTheme = getCore().getPreferences().isDarkTheme(); // uIInterface.setTheme(darkTheme ? R.style.AppTheme_Dark // : R.style.AppTheme); // // redraw(uIInterface); // // if (mUiInterfaces != null) { // mUiInterfaces.put(uIInterface.getClass().getName(), uIInterface); // } // } // // public void redraw() { // Iterator<String> it = mUiInterfaces.keySet().iterator(); // while (it.hasNext()) { // String key = it.next(); // UIInterface uiInterface = mUiInterfaces.get(key); // redraw(uiInterface); // } // } // // public void redraw(UIInterface uIInterface) { // redraw(uIInterface.getMainView()); // } // // public void redraw(View view) { // setFont(view); // } // // private void setFont(View view) { // if (view == null) { // return; // } // if (view instanceof ViewGroup) { // int count = ((ViewGroup) view).getChildCount(); // for (int i = 0; i < count; i++) { // setFont(((ViewGroup) view).getChildAt(i)); // } // } else if (view instanceof TextView) { // ((TextView) view).setTypeface(mRobotoThin); // } // } // // } // Path: src/com/beerbong/zipinst/ui/preference/UICheckBoxPreference.java import android.content.Context; import android.preference.CheckBoxPreference; import android.util.AttributeSet; import android.view.View; import com.beerbong.zipinst.core.Core; import com.beerbong.zipinst.core.CoreFactory; import com.beerbong.zipinst.core.plugins.ui.UIPlugin; /* * Copyright 2014 ZipInstaller Project * * This file is part of ZipInstaller. * * ZipInstaller is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * ZipInstaller is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with ZipInstaller. If not, see <http://www.gnu.org/licenses/>. */ package com.beerbong.zipinst.ui.preference; public class UICheckBoxPreference extends CheckBoxPreference { public UICheckBoxPreference(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } public UICheckBoxPreference(Context context, AttributeSet attrs) { super(context, attrs); } public UICheckBoxPreference(Context context) { super(context); } @Override protected void onBindView(View view) { super.onBindView(view);
((UIPlugin) CoreFactory.getCore().getPlugin(Core.PLUGIN_UI)).redraw(view);
beerbong/com_beerbong_zipinst
src/com/beerbong/zipinst/ui/preference/UICheckBoxPreference.java
// Path: src/com/beerbong/zipinst/core/Core.java // public interface Core extends Serializable { // // public static final String PLUGIN_UI = "UIPlugin"; // public static final String PLUGIN_SUPERUSER = "SuperUserPlugin"; // public static final String PLUGIN_RECOVERY = "RecoveryPlugin"; // public static final String PLUGIN_STORAGE = "StoragePlugin"; // public static final String PLUGIN_REBOOT = "RebootPlugin"; // public static final String PLUGIN_LICENSE = "LicensePlugin"; // public static final String PLUGIN_UPDATE = "UpdatePlugin"; // // public interface CoreListener { // // public void pluginStarted(String name); // // public void pluginStopped(String name); // // public void coreMessage(int resId); // // public void coreStarted(); // // public void coreStopped(); // } // // public void destroy(); // // public boolean isStarted(); // // public Context getContext(); // // public void setContext(Context context); // // public Plugin getPlugin(String name); // // public Preferences getPreferences(); // // public CloudStorage getCloudStorage(); // // public void setCloudStorage(int cloudStorage); // // public ONandroid getONandroid(); // // public Version getVersion(); // // public void moveToInstall(); // } // // Path: src/com/beerbong/zipinst/core/CoreFactory.java // public class CoreFactory { // // private static Core sInstance; // // public static synchronized void init(Context context) { // init(context, null); // } // // public static synchronized void init(Context context, CoreListener listener) { // if (sInstance == null) { // sInstance = new CoreImpl(context, listener); // } else { // sInstance.setContext(context); // } // } // // public static Core getCore() { // return sInstance; // } // // } // // Path: src/com/beerbong/zipinst/core/plugins/ui/UIPlugin.java // public class UIPlugin extends Plugin { // // private static final String ROBOTO_THIN = "font/Roboto-Light.ttf"; // // private Map<String, UIInterface> mUiInterfaces; // private Typeface mRobotoThin; // // public UIPlugin(Core core) { // super(core, Core.PLUGIN_UI); // } // // @Override // public void start() { // ((CoreImpl) getCore()).setMessage(R.string.initializing_ui); // // // (new AsyncTask<Void, Void, Void>() { // // @Override // protected Void doInBackground(Void... params) { // mUiInterfaces = new HashMap<String, UIInterface>(); // // mRobotoThin = Typeface // .createFromAsset(getCore().getContext().getAssets(), ROBOTO_THIN); // return (Void) null; // } // // @Override // protected void onPostExecute(Void result) { // started(); // } // }).execute((Void) null); // } // // @Override // public void stop() { // stopped(); // } // // public void unregisterUI(UIInterface uIInterface) { // if (mUiInterfaces != null) { // mUiInterfaces.remove(uIInterface.getClass().getName()); // } // } // // public void registerUI(UIInterface uIInterface) { // boolean darkTheme = getCore().getPreferences().isDarkTheme(); // uIInterface.setTheme(darkTheme ? R.style.AppTheme_Dark // : R.style.AppTheme); // // redraw(uIInterface); // // if (mUiInterfaces != null) { // mUiInterfaces.put(uIInterface.getClass().getName(), uIInterface); // } // } // // public void redraw() { // Iterator<String> it = mUiInterfaces.keySet().iterator(); // while (it.hasNext()) { // String key = it.next(); // UIInterface uiInterface = mUiInterfaces.get(key); // redraw(uiInterface); // } // } // // public void redraw(UIInterface uIInterface) { // redraw(uIInterface.getMainView()); // } // // public void redraw(View view) { // setFont(view); // } // // private void setFont(View view) { // if (view == null) { // return; // } // if (view instanceof ViewGroup) { // int count = ((ViewGroup) view).getChildCount(); // for (int i = 0; i < count; i++) { // setFont(((ViewGroup) view).getChildAt(i)); // } // } else if (view instanceof TextView) { // ((TextView) view).setTypeface(mRobotoThin); // } // } // // }
import android.content.Context; import android.preference.CheckBoxPreference; import android.util.AttributeSet; import android.view.View; import com.beerbong.zipinst.core.Core; import com.beerbong.zipinst.core.CoreFactory; import com.beerbong.zipinst.core.plugins.ui.UIPlugin;
/* * Copyright 2014 ZipInstaller Project * * This file is part of ZipInstaller. * * ZipInstaller is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * ZipInstaller is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with ZipInstaller. If not, see <http://www.gnu.org/licenses/>. */ package com.beerbong.zipinst.ui.preference; public class UICheckBoxPreference extends CheckBoxPreference { public UICheckBoxPreference(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } public UICheckBoxPreference(Context context, AttributeSet attrs) { super(context, attrs); } public UICheckBoxPreference(Context context) { super(context); } @Override protected void onBindView(View view) { super.onBindView(view);
// Path: src/com/beerbong/zipinst/core/Core.java // public interface Core extends Serializable { // // public static final String PLUGIN_UI = "UIPlugin"; // public static final String PLUGIN_SUPERUSER = "SuperUserPlugin"; // public static final String PLUGIN_RECOVERY = "RecoveryPlugin"; // public static final String PLUGIN_STORAGE = "StoragePlugin"; // public static final String PLUGIN_REBOOT = "RebootPlugin"; // public static final String PLUGIN_LICENSE = "LicensePlugin"; // public static final String PLUGIN_UPDATE = "UpdatePlugin"; // // public interface CoreListener { // // public void pluginStarted(String name); // // public void pluginStopped(String name); // // public void coreMessage(int resId); // // public void coreStarted(); // // public void coreStopped(); // } // // public void destroy(); // // public boolean isStarted(); // // public Context getContext(); // // public void setContext(Context context); // // public Plugin getPlugin(String name); // // public Preferences getPreferences(); // // public CloudStorage getCloudStorage(); // // public void setCloudStorage(int cloudStorage); // // public ONandroid getONandroid(); // // public Version getVersion(); // // public void moveToInstall(); // } // // Path: src/com/beerbong/zipinst/core/CoreFactory.java // public class CoreFactory { // // private static Core sInstance; // // public static synchronized void init(Context context) { // init(context, null); // } // // public static synchronized void init(Context context, CoreListener listener) { // if (sInstance == null) { // sInstance = new CoreImpl(context, listener); // } else { // sInstance.setContext(context); // } // } // // public static Core getCore() { // return sInstance; // } // // } // // Path: src/com/beerbong/zipinst/core/plugins/ui/UIPlugin.java // public class UIPlugin extends Plugin { // // private static final String ROBOTO_THIN = "font/Roboto-Light.ttf"; // // private Map<String, UIInterface> mUiInterfaces; // private Typeface mRobotoThin; // // public UIPlugin(Core core) { // super(core, Core.PLUGIN_UI); // } // // @Override // public void start() { // ((CoreImpl) getCore()).setMessage(R.string.initializing_ui); // // // (new AsyncTask<Void, Void, Void>() { // // @Override // protected Void doInBackground(Void... params) { // mUiInterfaces = new HashMap<String, UIInterface>(); // // mRobotoThin = Typeface // .createFromAsset(getCore().getContext().getAssets(), ROBOTO_THIN); // return (Void) null; // } // // @Override // protected void onPostExecute(Void result) { // started(); // } // }).execute((Void) null); // } // // @Override // public void stop() { // stopped(); // } // // public void unregisterUI(UIInterface uIInterface) { // if (mUiInterfaces != null) { // mUiInterfaces.remove(uIInterface.getClass().getName()); // } // } // // public void registerUI(UIInterface uIInterface) { // boolean darkTheme = getCore().getPreferences().isDarkTheme(); // uIInterface.setTheme(darkTheme ? R.style.AppTheme_Dark // : R.style.AppTheme); // // redraw(uIInterface); // // if (mUiInterfaces != null) { // mUiInterfaces.put(uIInterface.getClass().getName(), uIInterface); // } // } // // public void redraw() { // Iterator<String> it = mUiInterfaces.keySet().iterator(); // while (it.hasNext()) { // String key = it.next(); // UIInterface uiInterface = mUiInterfaces.get(key); // redraw(uiInterface); // } // } // // public void redraw(UIInterface uIInterface) { // redraw(uIInterface.getMainView()); // } // // public void redraw(View view) { // setFont(view); // } // // private void setFont(View view) { // if (view == null) { // return; // } // if (view instanceof ViewGroup) { // int count = ((ViewGroup) view).getChildCount(); // for (int i = 0; i < count; i++) { // setFont(((ViewGroup) view).getChildAt(i)); // } // } else if (view instanceof TextView) { // ((TextView) view).setTypeface(mRobotoThin); // } // } // // } // Path: src/com/beerbong/zipinst/ui/preference/UICheckBoxPreference.java import android.content.Context; import android.preference.CheckBoxPreference; import android.util.AttributeSet; import android.view.View; import com.beerbong.zipinst.core.Core; import com.beerbong.zipinst.core.CoreFactory; import com.beerbong.zipinst.core.plugins.ui.UIPlugin; /* * Copyright 2014 ZipInstaller Project * * This file is part of ZipInstaller. * * ZipInstaller is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * ZipInstaller is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with ZipInstaller. If not, see <http://www.gnu.org/licenses/>. */ package com.beerbong.zipinst.ui.preference; public class UICheckBoxPreference extends CheckBoxPreference { public UICheckBoxPreference(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } public UICheckBoxPreference(Context context, AttributeSet attrs) { super(context, attrs); } public UICheckBoxPreference(Context context) { super(context); } @Override protected void onBindView(View view) { super.onBindView(view);
((UIPlugin) CoreFactory.getCore().getPlugin(Core.PLUGIN_UI)).redraw(view);
beerbong/com_beerbong_zipinst
src/com/beerbong/zipinst/ui/preference/UIPreference.java
// Path: src/com/beerbong/zipinst/core/Core.java // public interface Core extends Serializable { // // public static final String PLUGIN_UI = "UIPlugin"; // public static final String PLUGIN_SUPERUSER = "SuperUserPlugin"; // public static final String PLUGIN_RECOVERY = "RecoveryPlugin"; // public static final String PLUGIN_STORAGE = "StoragePlugin"; // public static final String PLUGIN_REBOOT = "RebootPlugin"; // public static final String PLUGIN_LICENSE = "LicensePlugin"; // public static final String PLUGIN_UPDATE = "UpdatePlugin"; // // public interface CoreListener { // // public void pluginStarted(String name); // // public void pluginStopped(String name); // // public void coreMessage(int resId); // // public void coreStarted(); // // public void coreStopped(); // } // // public void destroy(); // // public boolean isStarted(); // // public Context getContext(); // // public void setContext(Context context); // // public Plugin getPlugin(String name); // // public Preferences getPreferences(); // // public CloudStorage getCloudStorage(); // // public void setCloudStorage(int cloudStorage); // // public ONandroid getONandroid(); // // public Version getVersion(); // // public void moveToInstall(); // } // // Path: src/com/beerbong/zipinst/core/CoreFactory.java // public class CoreFactory { // // private static Core sInstance; // // public static synchronized void init(Context context) { // init(context, null); // } // // public static synchronized void init(Context context, CoreListener listener) { // if (sInstance == null) { // sInstance = new CoreImpl(context, listener); // } else { // sInstance.setContext(context); // } // } // // public static Core getCore() { // return sInstance; // } // // } // // Path: src/com/beerbong/zipinst/core/plugins/ui/UIPlugin.java // public class UIPlugin extends Plugin { // // private static final String ROBOTO_THIN = "font/Roboto-Light.ttf"; // // private Map<String, UIInterface> mUiInterfaces; // private Typeface mRobotoThin; // // public UIPlugin(Core core) { // super(core, Core.PLUGIN_UI); // } // // @Override // public void start() { // ((CoreImpl) getCore()).setMessage(R.string.initializing_ui); // // // (new AsyncTask<Void, Void, Void>() { // // @Override // protected Void doInBackground(Void... params) { // mUiInterfaces = new HashMap<String, UIInterface>(); // // mRobotoThin = Typeface // .createFromAsset(getCore().getContext().getAssets(), ROBOTO_THIN); // return (Void) null; // } // // @Override // protected void onPostExecute(Void result) { // started(); // } // }).execute((Void) null); // } // // @Override // public void stop() { // stopped(); // } // // public void unregisterUI(UIInterface uIInterface) { // if (mUiInterfaces != null) { // mUiInterfaces.remove(uIInterface.getClass().getName()); // } // } // // public void registerUI(UIInterface uIInterface) { // boolean darkTheme = getCore().getPreferences().isDarkTheme(); // uIInterface.setTheme(darkTheme ? R.style.AppTheme_Dark // : R.style.AppTheme); // // redraw(uIInterface); // // if (mUiInterfaces != null) { // mUiInterfaces.put(uIInterface.getClass().getName(), uIInterface); // } // } // // public void redraw() { // Iterator<String> it = mUiInterfaces.keySet().iterator(); // while (it.hasNext()) { // String key = it.next(); // UIInterface uiInterface = mUiInterfaces.get(key); // redraw(uiInterface); // } // } // // public void redraw(UIInterface uIInterface) { // redraw(uIInterface.getMainView()); // } // // public void redraw(View view) { // setFont(view); // } // // private void setFont(View view) { // if (view == null) { // return; // } // if (view instanceof ViewGroup) { // int count = ((ViewGroup) view).getChildCount(); // for (int i = 0; i < count; i++) { // setFont(((ViewGroup) view).getChildAt(i)); // } // } else if (view instanceof TextView) { // ((TextView) view).setTypeface(mRobotoThin); // } // } // // }
import android.content.Context; import android.preference.Preference; import android.util.AttributeSet; import android.view.View; import com.beerbong.zipinst.core.Core; import com.beerbong.zipinst.core.CoreFactory; import com.beerbong.zipinst.core.plugins.ui.UIPlugin;
/* * Copyright 2014 ZipInstaller Project * * This file is part of ZipInstaller. * * ZipInstaller is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * ZipInstaller is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with ZipInstaller. If not, see <http://www.gnu.org/licenses/>. */ package com.beerbong.zipinst.ui.preference; public class UIPreference extends Preference { public UIPreference(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } public UIPreference(Context context, AttributeSet attrs) { super(context, attrs); } public UIPreference(Context context) { super(context); } @Override protected void onBindView(View view) { super.onBindView(view);
// Path: src/com/beerbong/zipinst/core/Core.java // public interface Core extends Serializable { // // public static final String PLUGIN_UI = "UIPlugin"; // public static final String PLUGIN_SUPERUSER = "SuperUserPlugin"; // public static final String PLUGIN_RECOVERY = "RecoveryPlugin"; // public static final String PLUGIN_STORAGE = "StoragePlugin"; // public static final String PLUGIN_REBOOT = "RebootPlugin"; // public static final String PLUGIN_LICENSE = "LicensePlugin"; // public static final String PLUGIN_UPDATE = "UpdatePlugin"; // // public interface CoreListener { // // public void pluginStarted(String name); // // public void pluginStopped(String name); // // public void coreMessage(int resId); // // public void coreStarted(); // // public void coreStopped(); // } // // public void destroy(); // // public boolean isStarted(); // // public Context getContext(); // // public void setContext(Context context); // // public Plugin getPlugin(String name); // // public Preferences getPreferences(); // // public CloudStorage getCloudStorage(); // // public void setCloudStorage(int cloudStorage); // // public ONandroid getONandroid(); // // public Version getVersion(); // // public void moveToInstall(); // } // // Path: src/com/beerbong/zipinst/core/CoreFactory.java // public class CoreFactory { // // private static Core sInstance; // // public static synchronized void init(Context context) { // init(context, null); // } // // public static synchronized void init(Context context, CoreListener listener) { // if (sInstance == null) { // sInstance = new CoreImpl(context, listener); // } else { // sInstance.setContext(context); // } // } // // public static Core getCore() { // return sInstance; // } // // } // // Path: src/com/beerbong/zipinst/core/plugins/ui/UIPlugin.java // public class UIPlugin extends Plugin { // // private static final String ROBOTO_THIN = "font/Roboto-Light.ttf"; // // private Map<String, UIInterface> mUiInterfaces; // private Typeface mRobotoThin; // // public UIPlugin(Core core) { // super(core, Core.PLUGIN_UI); // } // // @Override // public void start() { // ((CoreImpl) getCore()).setMessage(R.string.initializing_ui); // // // (new AsyncTask<Void, Void, Void>() { // // @Override // protected Void doInBackground(Void... params) { // mUiInterfaces = new HashMap<String, UIInterface>(); // // mRobotoThin = Typeface // .createFromAsset(getCore().getContext().getAssets(), ROBOTO_THIN); // return (Void) null; // } // // @Override // protected void onPostExecute(Void result) { // started(); // } // }).execute((Void) null); // } // // @Override // public void stop() { // stopped(); // } // // public void unregisterUI(UIInterface uIInterface) { // if (mUiInterfaces != null) { // mUiInterfaces.remove(uIInterface.getClass().getName()); // } // } // // public void registerUI(UIInterface uIInterface) { // boolean darkTheme = getCore().getPreferences().isDarkTheme(); // uIInterface.setTheme(darkTheme ? R.style.AppTheme_Dark // : R.style.AppTheme); // // redraw(uIInterface); // // if (mUiInterfaces != null) { // mUiInterfaces.put(uIInterface.getClass().getName(), uIInterface); // } // } // // public void redraw() { // Iterator<String> it = mUiInterfaces.keySet().iterator(); // while (it.hasNext()) { // String key = it.next(); // UIInterface uiInterface = mUiInterfaces.get(key); // redraw(uiInterface); // } // } // // public void redraw(UIInterface uIInterface) { // redraw(uIInterface.getMainView()); // } // // public void redraw(View view) { // setFont(view); // } // // private void setFont(View view) { // if (view == null) { // return; // } // if (view instanceof ViewGroup) { // int count = ((ViewGroup) view).getChildCount(); // for (int i = 0; i < count; i++) { // setFont(((ViewGroup) view).getChildAt(i)); // } // } else if (view instanceof TextView) { // ((TextView) view).setTypeface(mRobotoThin); // } // } // // } // Path: src/com/beerbong/zipinst/ui/preference/UIPreference.java import android.content.Context; import android.preference.Preference; import android.util.AttributeSet; import android.view.View; import com.beerbong.zipinst.core.Core; import com.beerbong.zipinst.core.CoreFactory; import com.beerbong.zipinst.core.plugins.ui.UIPlugin; /* * Copyright 2014 ZipInstaller Project * * This file is part of ZipInstaller. * * ZipInstaller is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * ZipInstaller is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with ZipInstaller. If not, see <http://www.gnu.org/licenses/>. */ package com.beerbong.zipinst.ui.preference; public class UIPreference extends Preference { public UIPreference(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } public UIPreference(Context context, AttributeSet attrs) { super(context, attrs); } public UIPreference(Context context) { super(context); } @Override protected void onBindView(View view) { super.onBindView(view);
((UIPlugin) CoreFactory.getCore().getPlugin(Core.PLUGIN_UI)).redraw(view);
beerbong/com_beerbong_zipinst
src/com/beerbong/zipinst/ui/preference/UIPreference.java
// Path: src/com/beerbong/zipinst/core/Core.java // public interface Core extends Serializable { // // public static final String PLUGIN_UI = "UIPlugin"; // public static final String PLUGIN_SUPERUSER = "SuperUserPlugin"; // public static final String PLUGIN_RECOVERY = "RecoveryPlugin"; // public static final String PLUGIN_STORAGE = "StoragePlugin"; // public static final String PLUGIN_REBOOT = "RebootPlugin"; // public static final String PLUGIN_LICENSE = "LicensePlugin"; // public static final String PLUGIN_UPDATE = "UpdatePlugin"; // // public interface CoreListener { // // public void pluginStarted(String name); // // public void pluginStopped(String name); // // public void coreMessage(int resId); // // public void coreStarted(); // // public void coreStopped(); // } // // public void destroy(); // // public boolean isStarted(); // // public Context getContext(); // // public void setContext(Context context); // // public Plugin getPlugin(String name); // // public Preferences getPreferences(); // // public CloudStorage getCloudStorage(); // // public void setCloudStorage(int cloudStorage); // // public ONandroid getONandroid(); // // public Version getVersion(); // // public void moveToInstall(); // } // // Path: src/com/beerbong/zipinst/core/CoreFactory.java // public class CoreFactory { // // private static Core sInstance; // // public static synchronized void init(Context context) { // init(context, null); // } // // public static synchronized void init(Context context, CoreListener listener) { // if (sInstance == null) { // sInstance = new CoreImpl(context, listener); // } else { // sInstance.setContext(context); // } // } // // public static Core getCore() { // return sInstance; // } // // } // // Path: src/com/beerbong/zipinst/core/plugins/ui/UIPlugin.java // public class UIPlugin extends Plugin { // // private static final String ROBOTO_THIN = "font/Roboto-Light.ttf"; // // private Map<String, UIInterface> mUiInterfaces; // private Typeface mRobotoThin; // // public UIPlugin(Core core) { // super(core, Core.PLUGIN_UI); // } // // @Override // public void start() { // ((CoreImpl) getCore()).setMessage(R.string.initializing_ui); // // // (new AsyncTask<Void, Void, Void>() { // // @Override // protected Void doInBackground(Void... params) { // mUiInterfaces = new HashMap<String, UIInterface>(); // // mRobotoThin = Typeface // .createFromAsset(getCore().getContext().getAssets(), ROBOTO_THIN); // return (Void) null; // } // // @Override // protected void onPostExecute(Void result) { // started(); // } // }).execute((Void) null); // } // // @Override // public void stop() { // stopped(); // } // // public void unregisterUI(UIInterface uIInterface) { // if (mUiInterfaces != null) { // mUiInterfaces.remove(uIInterface.getClass().getName()); // } // } // // public void registerUI(UIInterface uIInterface) { // boolean darkTheme = getCore().getPreferences().isDarkTheme(); // uIInterface.setTheme(darkTheme ? R.style.AppTheme_Dark // : R.style.AppTheme); // // redraw(uIInterface); // // if (mUiInterfaces != null) { // mUiInterfaces.put(uIInterface.getClass().getName(), uIInterface); // } // } // // public void redraw() { // Iterator<String> it = mUiInterfaces.keySet().iterator(); // while (it.hasNext()) { // String key = it.next(); // UIInterface uiInterface = mUiInterfaces.get(key); // redraw(uiInterface); // } // } // // public void redraw(UIInterface uIInterface) { // redraw(uIInterface.getMainView()); // } // // public void redraw(View view) { // setFont(view); // } // // private void setFont(View view) { // if (view == null) { // return; // } // if (view instanceof ViewGroup) { // int count = ((ViewGroup) view).getChildCount(); // for (int i = 0; i < count; i++) { // setFont(((ViewGroup) view).getChildAt(i)); // } // } else if (view instanceof TextView) { // ((TextView) view).setTypeface(mRobotoThin); // } // } // // }
import android.content.Context; import android.preference.Preference; import android.util.AttributeSet; import android.view.View; import com.beerbong.zipinst.core.Core; import com.beerbong.zipinst.core.CoreFactory; import com.beerbong.zipinst.core.plugins.ui.UIPlugin;
/* * Copyright 2014 ZipInstaller Project * * This file is part of ZipInstaller. * * ZipInstaller is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * ZipInstaller is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with ZipInstaller. If not, see <http://www.gnu.org/licenses/>. */ package com.beerbong.zipinst.ui.preference; public class UIPreference extends Preference { public UIPreference(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } public UIPreference(Context context, AttributeSet attrs) { super(context, attrs); } public UIPreference(Context context) { super(context); } @Override protected void onBindView(View view) { super.onBindView(view);
// Path: src/com/beerbong/zipinst/core/Core.java // public interface Core extends Serializable { // // public static final String PLUGIN_UI = "UIPlugin"; // public static final String PLUGIN_SUPERUSER = "SuperUserPlugin"; // public static final String PLUGIN_RECOVERY = "RecoveryPlugin"; // public static final String PLUGIN_STORAGE = "StoragePlugin"; // public static final String PLUGIN_REBOOT = "RebootPlugin"; // public static final String PLUGIN_LICENSE = "LicensePlugin"; // public static final String PLUGIN_UPDATE = "UpdatePlugin"; // // public interface CoreListener { // // public void pluginStarted(String name); // // public void pluginStopped(String name); // // public void coreMessage(int resId); // // public void coreStarted(); // // public void coreStopped(); // } // // public void destroy(); // // public boolean isStarted(); // // public Context getContext(); // // public void setContext(Context context); // // public Plugin getPlugin(String name); // // public Preferences getPreferences(); // // public CloudStorage getCloudStorage(); // // public void setCloudStorage(int cloudStorage); // // public ONandroid getONandroid(); // // public Version getVersion(); // // public void moveToInstall(); // } // // Path: src/com/beerbong/zipinst/core/CoreFactory.java // public class CoreFactory { // // private static Core sInstance; // // public static synchronized void init(Context context) { // init(context, null); // } // // public static synchronized void init(Context context, CoreListener listener) { // if (sInstance == null) { // sInstance = new CoreImpl(context, listener); // } else { // sInstance.setContext(context); // } // } // // public static Core getCore() { // return sInstance; // } // // } // // Path: src/com/beerbong/zipinst/core/plugins/ui/UIPlugin.java // public class UIPlugin extends Plugin { // // private static final String ROBOTO_THIN = "font/Roboto-Light.ttf"; // // private Map<String, UIInterface> mUiInterfaces; // private Typeface mRobotoThin; // // public UIPlugin(Core core) { // super(core, Core.PLUGIN_UI); // } // // @Override // public void start() { // ((CoreImpl) getCore()).setMessage(R.string.initializing_ui); // // // (new AsyncTask<Void, Void, Void>() { // // @Override // protected Void doInBackground(Void... params) { // mUiInterfaces = new HashMap<String, UIInterface>(); // // mRobotoThin = Typeface // .createFromAsset(getCore().getContext().getAssets(), ROBOTO_THIN); // return (Void) null; // } // // @Override // protected void onPostExecute(Void result) { // started(); // } // }).execute((Void) null); // } // // @Override // public void stop() { // stopped(); // } // // public void unregisterUI(UIInterface uIInterface) { // if (mUiInterfaces != null) { // mUiInterfaces.remove(uIInterface.getClass().getName()); // } // } // // public void registerUI(UIInterface uIInterface) { // boolean darkTheme = getCore().getPreferences().isDarkTheme(); // uIInterface.setTheme(darkTheme ? R.style.AppTheme_Dark // : R.style.AppTheme); // // redraw(uIInterface); // // if (mUiInterfaces != null) { // mUiInterfaces.put(uIInterface.getClass().getName(), uIInterface); // } // } // // public void redraw() { // Iterator<String> it = mUiInterfaces.keySet().iterator(); // while (it.hasNext()) { // String key = it.next(); // UIInterface uiInterface = mUiInterfaces.get(key); // redraw(uiInterface); // } // } // // public void redraw(UIInterface uIInterface) { // redraw(uIInterface.getMainView()); // } // // public void redraw(View view) { // setFont(view); // } // // private void setFont(View view) { // if (view == null) { // return; // } // if (view instanceof ViewGroup) { // int count = ((ViewGroup) view).getChildCount(); // for (int i = 0; i < count; i++) { // setFont(((ViewGroup) view).getChildAt(i)); // } // } else if (view instanceof TextView) { // ((TextView) view).setTypeface(mRobotoThin); // } // } // // } // Path: src/com/beerbong/zipinst/ui/preference/UIPreference.java import android.content.Context; import android.preference.Preference; import android.util.AttributeSet; import android.view.View; import com.beerbong.zipinst.core.Core; import com.beerbong.zipinst.core.CoreFactory; import com.beerbong.zipinst.core.plugins.ui.UIPlugin; /* * Copyright 2014 ZipInstaller Project * * This file is part of ZipInstaller. * * ZipInstaller is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * ZipInstaller is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with ZipInstaller. If not, see <http://www.gnu.org/licenses/>. */ package com.beerbong.zipinst.ui.preference; public class UIPreference extends Preference { public UIPreference(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } public UIPreference(Context context, AttributeSet attrs) { super(context, attrs); } public UIPreference(Context context) { super(context); } @Override protected void onBindView(View view) { super.onBindView(view);
((UIPlugin) CoreFactory.getCore().getPlugin(Core.PLUGIN_UI)).redraw(view);
beerbong/com_beerbong_zipinst
src/com/beerbong/zipinst/ui/preference/UIPreference.java
// Path: src/com/beerbong/zipinst/core/Core.java // public interface Core extends Serializable { // // public static final String PLUGIN_UI = "UIPlugin"; // public static final String PLUGIN_SUPERUSER = "SuperUserPlugin"; // public static final String PLUGIN_RECOVERY = "RecoveryPlugin"; // public static final String PLUGIN_STORAGE = "StoragePlugin"; // public static final String PLUGIN_REBOOT = "RebootPlugin"; // public static final String PLUGIN_LICENSE = "LicensePlugin"; // public static final String PLUGIN_UPDATE = "UpdatePlugin"; // // public interface CoreListener { // // public void pluginStarted(String name); // // public void pluginStopped(String name); // // public void coreMessage(int resId); // // public void coreStarted(); // // public void coreStopped(); // } // // public void destroy(); // // public boolean isStarted(); // // public Context getContext(); // // public void setContext(Context context); // // public Plugin getPlugin(String name); // // public Preferences getPreferences(); // // public CloudStorage getCloudStorage(); // // public void setCloudStorage(int cloudStorage); // // public ONandroid getONandroid(); // // public Version getVersion(); // // public void moveToInstall(); // } // // Path: src/com/beerbong/zipinst/core/CoreFactory.java // public class CoreFactory { // // private static Core sInstance; // // public static synchronized void init(Context context) { // init(context, null); // } // // public static synchronized void init(Context context, CoreListener listener) { // if (sInstance == null) { // sInstance = new CoreImpl(context, listener); // } else { // sInstance.setContext(context); // } // } // // public static Core getCore() { // return sInstance; // } // // } // // Path: src/com/beerbong/zipinst/core/plugins/ui/UIPlugin.java // public class UIPlugin extends Plugin { // // private static final String ROBOTO_THIN = "font/Roboto-Light.ttf"; // // private Map<String, UIInterface> mUiInterfaces; // private Typeface mRobotoThin; // // public UIPlugin(Core core) { // super(core, Core.PLUGIN_UI); // } // // @Override // public void start() { // ((CoreImpl) getCore()).setMessage(R.string.initializing_ui); // // // (new AsyncTask<Void, Void, Void>() { // // @Override // protected Void doInBackground(Void... params) { // mUiInterfaces = new HashMap<String, UIInterface>(); // // mRobotoThin = Typeface // .createFromAsset(getCore().getContext().getAssets(), ROBOTO_THIN); // return (Void) null; // } // // @Override // protected void onPostExecute(Void result) { // started(); // } // }).execute((Void) null); // } // // @Override // public void stop() { // stopped(); // } // // public void unregisterUI(UIInterface uIInterface) { // if (mUiInterfaces != null) { // mUiInterfaces.remove(uIInterface.getClass().getName()); // } // } // // public void registerUI(UIInterface uIInterface) { // boolean darkTheme = getCore().getPreferences().isDarkTheme(); // uIInterface.setTheme(darkTheme ? R.style.AppTheme_Dark // : R.style.AppTheme); // // redraw(uIInterface); // // if (mUiInterfaces != null) { // mUiInterfaces.put(uIInterface.getClass().getName(), uIInterface); // } // } // // public void redraw() { // Iterator<String> it = mUiInterfaces.keySet().iterator(); // while (it.hasNext()) { // String key = it.next(); // UIInterface uiInterface = mUiInterfaces.get(key); // redraw(uiInterface); // } // } // // public void redraw(UIInterface uIInterface) { // redraw(uIInterface.getMainView()); // } // // public void redraw(View view) { // setFont(view); // } // // private void setFont(View view) { // if (view == null) { // return; // } // if (view instanceof ViewGroup) { // int count = ((ViewGroup) view).getChildCount(); // for (int i = 0; i < count; i++) { // setFont(((ViewGroup) view).getChildAt(i)); // } // } else if (view instanceof TextView) { // ((TextView) view).setTypeface(mRobotoThin); // } // } // // }
import android.content.Context; import android.preference.Preference; import android.util.AttributeSet; import android.view.View; import com.beerbong.zipinst.core.Core; import com.beerbong.zipinst.core.CoreFactory; import com.beerbong.zipinst.core.plugins.ui.UIPlugin;
/* * Copyright 2014 ZipInstaller Project * * This file is part of ZipInstaller. * * ZipInstaller is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * ZipInstaller is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with ZipInstaller. If not, see <http://www.gnu.org/licenses/>. */ package com.beerbong.zipinst.ui.preference; public class UIPreference extends Preference { public UIPreference(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } public UIPreference(Context context, AttributeSet attrs) { super(context, attrs); } public UIPreference(Context context) { super(context); } @Override protected void onBindView(View view) { super.onBindView(view);
// Path: src/com/beerbong/zipinst/core/Core.java // public interface Core extends Serializable { // // public static final String PLUGIN_UI = "UIPlugin"; // public static final String PLUGIN_SUPERUSER = "SuperUserPlugin"; // public static final String PLUGIN_RECOVERY = "RecoveryPlugin"; // public static final String PLUGIN_STORAGE = "StoragePlugin"; // public static final String PLUGIN_REBOOT = "RebootPlugin"; // public static final String PLUGIN_LICENSE = "LicensePlugin"; // public static final String PLUGIN_UPDATE = "UpdatePlugin"; // // public interface CoreListener { // // public void pluginStarted(String name); // // public void pluginStopped(String name); // // public void coreMessage(int resId); // // public void coreStarted(); // // public void coreStopped(); // } // // public void destroy(); // // public boolean isStarted(); // // public Context getContext(); // // public void setContext(Context context); // // public Plugin getPlugin(String name); // // public Preferences getPreferences(); // // public CloudStorage getCloudStorage(); // // public void setCloudStorage(int cloudStorage); // // public ONandroid getONandroid(); // // public Version getVersion(); // // public void moveToInstall(); // } // // Path: src/com/beerbong/zipinst/core/CoreFactory.java // public class CoreFactory { // // private static Core sInstance; // // public static synchronized void init(Context context) { // init(context, null); // } // // public static synchronized void init(Context context, CoreListener listener) { // if (sInstance == null) { // sInstance = new CoreImpl(context, listener); // } else { // sInstance.setContext(context); // } // } // // public static Core getCore() { // return sInstance; // } // // } // // Path: src/com/beerbong/zipinst/core/plugins/ui/UIPlugin.java // public class UIPlugin extends Plugin { // // private static final String ROBOTO_THIN = "font/Roboto-Light.ttf"; // // private Map<String, UIInterface> mUiInterfaces; // private Typeface mRobotoThin; // // public UIPlugin(Core core) { // super(core, Core.PLUGIN_UI); // } // // @Override // public void start() { // ((CoreImpl) getCore()).setMessage(R.string.initializing_ui); // // // (new AsyncTask<Void, Void, Void>() { // // @Override // protected Void doInBackground(Void... params) { // mUiInterfaces = new HashMap<String, UIInterface>(); // // mRobotoThin = Typeface // .createFromAsset(getCore().getContext().getAssets(), ROBOTO_THIN); // return (Void) null; // } // // @Override // protected void onPostExecute(Void result) { // started(); // } // }).execute((Void) null); // } // // @Override // public void stop() { // stopped(); // } // // public void unregisterUI(UIInterface uIInterface) { // if (mUiInterfaces != null) { // mUiInterfaces.remove(uIInterface.getClass().getName()); // } // } // // public void registerUI(UIInterface uIInterface) { // boolean darkTheme = getCore().getPreferences().isDarkTheme(); // uIInterface.setTheme(darkTheme ? R.style.AppTheme_Dark // : R.style.AppTheme); // // redraw(uIInterface); // // if (mUiInterfaces != null) { // mUiInterfaces.put(uIInterface.getClass().getName(), uIInterface); // } // } // // public void redraw() { // Iterator<String> it = mUiInterfaces.keySet().iterator(); // while (it.hasNext()) { // String key = it.next(); // UIInterface uiInterface = mUiInterfaces.get(key); // redraw(uiInterface); // } // } // // public void redraw(UIInterface uIInterface) { // redraw(uIInterface.getMainView()); // } // // public void redraw(View view) { // setFont(view); // } // // private void setFont(View view) { // if (view == null) { // return; // } // if (view instanceof ViewGroup) { // int count = ((ViewGroup) view).getChildCount(); // for (int i = 0; i < count; i++) { // setFont(((ViewGroup) view).getChildAt(i)); // } // } else if (view instanceof TextView) { // ((TextView) view).setTypeface(mRobotoThin); // } // } // // } // Path: src/com/beerbong/zipinst/ui/preference/UIPreference.java import android.content.Context; import android.preference.Preference; import android.util.AttributeSet; import android.view.View; import com.beerbong.zipinst.core.Core; import com.beerbong.zipinst.core.CoreFactory; import com.beerbong.zipinst.core.plugins.ui.UIPlugin; /* * Copyright 2014 ZipInstaller Project * * This file is part of ZipInstaller. * * ZipInstaller is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * ZipInstaller is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with ZipInstaller. If not, see <http://www.gnu.org/licenses/>. */ package com.beerbong.zipinst.ui.preference; public class UIPreference extends Preference { public UIPreference(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } public UIPreference(Context context, AttributeSet attrs) { super(context, attrs); } public UIPreference(Context context) { super(context); } @Override protected void onBindView(View view) { super.onBindView(view);
((UIPlugin) CoreFactory.getCore().getPlugin(Core.PLUGIN_UI)).redraw(view);
beerbong/com_beerbong_zipinst
src/com/beerbong/zipinst/ui/UIActivity.java
// Path: src/com/beerbong/zipinst/core/Core.java // public interface Core extends Serializable { // // public static final String PLUGIN_UI = "UIPlugin"; // public static final String PLUGIN_SUPERUSER = "SuperUserPlugin"; // public static final String PLUGIN_RECOVERY = "RecoveryPlugin"; // public static final String PLUGIN_STORAGE = "StoragePlugin"; // public static final String PLUGIN_REBOOT = "RebootPlugin"; // public static final String PLUGIN_LICENSE = "LicensePlugin"; // public static final String PLUGIN_UPDATE = "UpdatePlugin"; // // public interface CoreListener { // // public void pluginStarted(String name); // // public void pluginStopped(String name); // // public void coreMessage(int resId); // // public void coreStarted(); // // public void coreStopped(); // } // // public void destroy(); // // public boolean isStarted(); // // public Context getContext(); // // public void setContext(Context context); // // public Plugin getPlugin(String name); // // public Preferences getPreferences(); // // public CloudStorage getCloudStorage(); // // public void setCloudStorage(int cloudStorage); // // public ONandroid getONandroid(); // // public Version getVersion(); // // public void moveToInstall(); // } // // Path: src/com/beerbong/zipinst/core/CoreFactory.java // public class CoreFactory { // // private static Core sInstance; // // public static synchronized void init(Context context) { // init(context, null); // } // // public static synchronized void init(Context context, CoreListener listener) { // if (sInstance == null) { // sInstance = new CoreImpl(context, listener); // } else { // sInstance.setContext(context); // } // } // // public static Core getCore() { // return sInstance; // } // // } // // Path: src/com/beerbong/zipinst/core/plugins/ui/UIPlugin.java // public class UIPlugin extends Plugin { // // private static final String ROBOTO_THIN = "font/Roboto-Light.ttf"; // // private Map<String, UIInterface> mUiInterfaces; // private Typeface mRobotoThin; // // public UIPlugin(Core core) { // super(core, Core.PLUGIN_UI); // } // // @Override // public void start() { // ((CoreImpl) getCore()).setMessage(R.string.initializing_ui); // // // (new AsyncTask<Void, Void, Void>() { // // @Override // protected Void doInBackground(Void... params) { // mUiInterfaces = new HashMap<String, UIInterface>(); // // mRobotoThin = Typeface // .createFromAsset(getCore().getContext().getAssets(), ROBOTO_THIN); // return (Void) null; // } // // @Override // protected void onPostExecute(Void result) { // started(); // } // }).execute((Void) null); // } // // @Override // public void stop() { // stopped(); // } // // public void unregisterUI(UIInterface uIInterface) { // if (mUiInterfaces != null) { // mUiInterfaces.remove(uIInterface.getClass().getName()); // } // } // // public void registerUI(UIInterface uIInterface) { // boolean darkTheme = getCore().getPreferences().isDarkTheme(); // uIInterface.setTheme(darkTheme ? R.style.AppTheme_Dark // : R.style.AppTheme); // // redraw(uIInterface); // // if (mUiInterfaces != null) { // mUiInterfaces.put(uIInterface.getClass().getName(), uIInterface); // } // } // // public void redraw() { // Iterator<String> it = mUiInterfaces.keySet().iterator(); // while (it.hasNext()) { // String key = it.next(); // UIInterface uiInterface = mUiInterfaces.get(key); // redraw(uiInterface); // } // } // // public void redraw(UIInterface uIInterface) { // redraw(uIInterface.getMainView()); // } // // public void redraw(View view) { // setFont(view); // } // // private void setFont(View view) { // if (view == null) { // return; // } // if (view instanceof ViewGroup) { // int count = ((ViewGroup) view).getChildCount(); // for (int i = 0; i < count; i++) { // setFont(((ViewGroup) view).getChildAt(i)); // } // } else if (view instanceof TextView) { // ((TextView) view).setTypeface(mRobotoThin); // } // } // // }
import java.io.Serializable; import android.app.Activity; import android.os.Bundle; import android.view.View; import com.beerbong.zipinst.core.Core; import com.beerbong.zipinst.core.CoreFactory; import com.beerbong.zipinst.core.plugins.ui.UIPlugin;
/* * Copyright 2014 ZipInstaller Project * * This file is part of ZipInstaller. * * ZipInstaller is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * ZipInstaller is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with ZipInstaller. If not, see <http://www.gnu.org/licenses/>. */ package com.beerbong.zipinst.ui; public abstract class UIActivity extends Activity implements UIInterface, Serializable { private Core mCore; @Override protected void onCreate(Bundle savedInstanceState) {
// Path: src/com/beerbong/zipinst/core/Core.java // public interface Core extends Serializable { // // public static final String PLUGIN_UI = "UIPlugin"; // public static final String PLUGIN_SUPERUSER = "SuperUserPlugin"; // public static final String PLUGIN_RECOVERY = "RecoveryPlugin"; // public static final String PLUGIN_STORAGE = "StoragePlugin"; // public static final String PLUGIN_REBOOT = "RebootPlugin"; // public static final String PLUGIN_LICENSE = "LicensePlugin"; // public static final String PLUGIN_UPDATE = "UpdatePlugin"; // // public interface CoreListener { // // public void pluginStarted(String name); // // public void pluginStopped(String name); // // public void coreMessage(int resId); // // public void coreStarted(); // // public void coreStopped(); // } // // public void destroy(); // // public boolean isStarted(); // // public Context getContext(); // // public void setContext(Context context); // // public Plugin getPlugin(String name); // // public Preferences getPreferences(); // // public CloudStorage getCloudStorage(); // // public void setCloudStorage(int cloudStorage); // // public ONandroid getONandroid(); // // public Version getVersion(); // // public void moveToInstall(); // } // // Path: src/com/beerbong/zipinst/core/CoreFactory.java // public class CoreFactory { // // private static Core sInstance; // // public static synchronized void init(Context context) { // init(context, null); // } // // public static synchronized void init(Context context, CoreListener listener) { // if (sInstance == null) { // sInstance = new CoreImpl(context, listener); // } else { // sInstance.setContext(context); // } // } // // public static Core getCore() { // return sInstance; // } // // } // // Path: src/com/beerbong/zipinst/core/plugins/ui/UIPlugin.java // public class UIPlugin extends Plugin { // // private static final String ROBOTO_THIN = "font/Roboto-Light.ttf"; // // private Map<String, UIInterface> mUiInterfaces; // private Typeface mRobotoThin; // // public UIPlugin(Core core) { // super(core, Core.PLUGIN_UI); // } // // @Override // public void start() { // ((CoreImpl) getCore()).setMessage(R.string.initializing_ui); // // // (new AsyncTask<Void, Void, Void>() { // // @Override // protected Void doInBackground(Void... params) { // mUiInterfaces = new HashMap<String, UIInterface>(); // // mRobotoThin = Typeface // .createFromAsset(getCore().getContext().getAssets(), ROBOTO_THIN); // return (Void) null; // } // // @Override // protected void onPostExecute(Void result) { // started(); // } // }).execute((Void) null); // } // // @Override // public void stop() { // stopped(); // } // // public void unregisterUI(UIInterface uIInterface) { // if (mUiInterfaces != null) { // mUiInterfaces.remove(uIInterface.getClass().getName()); // } // } // // public void registerUI(UIInterface uIInterface) { // boolean darkTheme = getCore().getPreferences().isDarkTheme(); // uIInterface.setTheme(darkTheme ? R.style.AppTheme_Dark // : R.style.AppTheme); // // redraw(uIInterface); // // if (mUiInterfaces != null) { // mUiInterfaces.put(uIInterface.getClass().getName(), uIInterface); // } // } // // public void redraw() { // Iterator<String> it = mUiInterfaces.keySet().iterator(); // while (it.hasNext()) { // String key = it.next(); // UIInterface uiInterface = mUiInterfaces.get(key); // redraw(uiInterface); // } // } // // public void redraw(UIInterface uIInterface) { // redraw(uIInterface.getMainView()); // } // // public void redraw(View view) { // setFont(view); // } // // private void setFont(View view) { // if (view == null) { // return; // } // if (view instanceof ViewGroup) { // int count = ((ViewGroup) view).getChildCount(); // for (int i = 0; i < count; i++) { // setFont(((ViewGroup) view).getChildAt(i)); // } // } else if (view instanceof TextView) { // ((TextView) view).setTypeface(mRobotoThin); // } // } // // } // Path: src/com/beerbong/zipinst/ui/UIActivity.java import java.io.Serializable; import android.app.Activity; import android.os.Bundle; import android.view.View; import com.beerbong.zipinst.core.Core; import com.beerbong.zipinst.core.CoreFactory; import com.beerbong.zipinst.core.plugins.ui.UIPlugin; /* * Copyright 2014 ZipInstaller Project * * This file is part of ZipInstaller. * * ZipInstaller is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * ZipInstaller is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with ZipInstaller. If not, see <http://www.gnu.org/licenses/>. */ package com.beerbong.zipinst.ui; public abstract class UIActivity extends Activity implements UIInterface, Serializable { private Core mCore; @Override protected void onCreate(Bundle savedInstanceState) {
CoreFactory.init(this);
beerbong/com_beerbong_zipinst
src/com/beerbong/zipinst/ui/UIActivity.java
// Path: src/com/beerbong/zipinst/core/Core.java // public interface Core extends Serializable { // // public static final String PLUGIN_UI = "UIPlugin"; // public static final String PLUGIN_SUPERUSER = "SuperUserPlugin"; // public static final String PLUGIN_RECOVERY = "RecoveryPlugin"; // public static final String PLUGIN_STORAGE = "StoragePlugin"; // public static final String PLUGIN_REBOOT = "RebootPlugin"; // public static final String PLUGIN_LICENSE = "LicensePlugin"; // public static final String PLUGIN_UPDATE = "UpdatePlugin"; // // public interface CoreListener { // // public void pluginStarted(String name); // // public void pluginStopped(String name); // // public void coreMessage(int resId); // // public void coreStarted(); // // public void coreStopped(); // } // // public void destroy(); // // public boolean isStarted(); // // public Context getContext(); // // public void setContext(Context context); // // public Plugin getPlugin(String name); // // public Preferences getPreferences(); // // public CloudStorage getCloudStorage(); // // public void setCloudStorage(int cloudStorage); // // public ONandroid getONandroid(); // // public Version getVersion(); // // public void moveToInstall(); // } // // Path: src/com/beerbong/zipinst/core/CoreFactory.java // public class CoreFactory { // // private static Core sInstance; // // public static synchronized void init(Context context) { // init(context, null); // } // // public static synchronized void init(Context context, CoreListener listener) { // if (sInstance == null) { // sInstance = new CoreImpl(context, listener); // } else { // sInstance.setContext(context); // } // } // // public static Core getCore() { // return sInstance; // } // // } // // Path: src/com/beerbong/zipinst/core/plugins/ui/UIPlugin.java // public class UIPlugin extends Plugin { // // private static final String ROBOTO_THIN = "font/Roboto-Light.ttf"; // // private Map<String, UIInterface> mUiInterfaces; // private Typeface mRobotoThin; // // public UIPlugin(Core core) { // super(core, Core.PLUGIN_UI); // } // // @Override // public void start() { // ((CoreImpl) getCore()).setMessage(R.string.initializing_ui); // // // (new AsyncTask<Void, Void, Void>() { // // @Override // protected Void doInBackground(Void... params) { // mUiInterfaces = new HashMap<String, UIInterface>(); // // mRobotoThin = Typeface // .createFromAsset(getCore().getContext().getAssets(), ROBOTO_THIN); // return (Void) null; // } // // @Override // protected void onPostExecute(Void result) { // started(); // } // }).execute((Void) null); // } // // @Override // public void stop() { // stopped(); // } // // public void unregisterUI(UIInterface uIInterface) { // if (mUiInterfaces != null) { // mUiInterfaces.remove(uIInterface.getClass().getName()); // } // } // // public void registerUI(UIInterface uIInterface) { // boolean darkTheme = getCore().getPreferences().isDarkTheme(); // uIInterface.setTheme(darkTheme ? R.style.AppTheme_Dark // : R.style.AppTheme); // // redraw(uIInterface); // // if (mUiInterfaces != null) { // mUiInterfaces.put(uIInterface.getClass().getName(), uIInterface); // } // } // // public void redraw() { // Iterator<String> it = mUiInterfaces.keySet().iterator(); // while (it.hasNext()) { // String key = it.next(); // UIInterface uiInterface = mUiInterfaces.get(key); // redraw(uiInterface); // } // } // // public void redraw(UIInterface uIInterface) { // redraw(uIInterface.getMainView()); // } // // public void redraw(View view) { // setFont(view); // } // // private void setFont(View view) { // if (view == null) { // return; // } // if (view instanceof ViewGroup) { // int count = ((ViewGroup) view).getChildCount(); // for (int i = 0; i < count; i++) { // setFont(((ViewGroup) view).getChildAt(i)); // } // } else if (view instanceof TextView) { // ((TextView) view).setTypeface(mRobotoThin); // } // } // // }
import java.io.Serializable; import android.app.Activity; import android.os.Bundle; import android.view.View; import com.beerbong.zipinst.core.Core; import com.beerbong.zipinst.core.CoreFactory; import com.beerbong.zipinst.core.plugins.ui.UIPlugin;
/* * Copyright 2014 ZipInstaller Project * * This file is part of ZipInstaller. * * ZipInstaller is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * ZipInstaller is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with ZipInstaller. If not, see <http://www.gnu.org/licenses/>. */ package com.beerbong.zipinst.ui; public abstract class UIActivity extends Activity implements UIInterface, Serializable { private Core mCore; @Override protected void onCreate(Bundle savedInstanceState) { CoreFactory.init(this); mCore = CoreFactory.getCore();
// Path: src/com/beerbong/zipinst/core/Core.java // public interface Core extends Serializable { // // public static final String PLUGIN_UI = "UIPlugin"; // public static final String PLUGIN_SUPERUSER = "SuperUserPlugin"; // public static final String PLUGIN_RECOVERY = "RecoveryPlugin"; // public static final String PLUGIN_STORAGE = "StoragePlugin"; // public static final String PLUGIN_REBOOT = "RebootPlugin"; // public static final String PLUGIN_LICENSE = "LicensePlugin"; // public static final String PLUGIN_UPDATE = "UpdatePlugin"; // // public interface CoreListener { // // public void pluginStarted(String name); // // public void pluginStopped(String name); // // public void coreMessage(int resId); // // public void coreStarted(); // // public void coreStopped(); // } // // public void destroy(); // // public boolean isStarted(); // // public Context getContext(); // // public void setContext(Context context); // // public Plugin getPlugin(String name); // // public Preferences getPreferences(); // // public CloudStorage getCloudStorage(); // // public void setCloudStorage(int cloudStorage); // // public ONandroid getONandroid(); // // public Version getVersion(); // // public void moveToInstall(); // } // // Path: src/com/beerbong/zipinst/core/CoreFactory.java // public class CoreFactory { // // private static Core sInstance; // // public static synchronized void init(Context context) { // init(context, null); // } // // public static synchronized void init(Context context, CoreListener listener) { // if (sInstance == null) { // sInstance = new CoreImpl(context, listener); // } else { // sInstance.setContext(context); // } // } // // public static Core getCore() { // return sInstance; // } // // } // // Path: src/com/beerbong/zipinst/core/plugins/ui/UIPlugin.java // public class UIPlugin extends Plugin { // // private static final String ROBOTO_THIN = "font/Roboto-Light.ttf"; // // private Map<String, UIInterface> mUiInterfaces; // private Typeface mRobotoThin; // // public UIPlugin(Core core) { // super(core, Core.PLUGIN_UI); // } // // @Override // public void start() { // ((CoreImpl) getCore()).setMessage(R.string.initializing_ui); // // // (new AsyncTask<Void, Void, Void>() { // // @Override // protected Void doInBackground(Void... params) { // mUiInterfaces = new HashMap<String, UIInterface>(); // // mRobotoThin = Typeface // .createFromAsset(getCore().getContext().getAssets(), ROBOTO_THIN); // return (Void) null; // } // // @Override // protected void onPostExecute(Void result) { // started(); // } // }).execute((Void) null); // } // // @Override // public void stop() { // stopped(); // } // // public void unregisterUI(UIInterface uIInterface) { // if (mUiInterfaces != null) { // mUiInterfaces.remove(uIInterface.getClass().getName()); // } // } // // public void registerUI(UIInterface uIInterface) { // boolean darkTheme = getCore().getPreferences().isDarkTheme(); // uIInterface.setTheme(darkTheme ? R.style.AppTheme_Dark // : R.style.AppTheme); // // redraw(uIInterface); // // if (mUiInterfaces != null) { // mUiInterfaces.put(uIInterface.getClass().getName(), uIInterface); // } // } // // public void redraw() { // Iterator<String> it = mUiInterfaces.keySet().iterator(); // while (it.hasNext()) { // String key = it.next(); // UIInterface uiInterface = mUiInterfaces.get(key); // redraw(uiInterface); // } // } // // public void redraw(UIInterface uIInterface) { // redraw(uIInterface.getMainView()); // } // // public void redraw(View view) { // setFont(view); // } // // private void setFont(View view) { // if (view == null) { // return; // } // if (view instanceof ViewGroup) { // int count = ((ViewGroup) view).getChildCount(); // for (int i = 0; i < count; i++) { // setFont(((ViewGroup) view).getChildAt(i)); // } // } else if (view instanceof TextView) { // ((TextView) view).setTypeface(mRobotoThin); // } // } // // } // Path: src/com/beerbong/zipinst/ui/UIActivity.java import java.io.Serializable; import android.app.Activity; import android.os.Bundle; import android.view.View; import com.beerbong.zipinst.core.Core; import com.beerbong.zipinst.core.CoreFactory; import com.beerbong.zipinst.core.plugins.ui.UIPlugin; /* * Copyright 2014 ZipInstaller Project * * This file is part of ZipInstaller. * * ZipInstaller is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * ZipInstaller is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with ZipInstaller. If not, see <http://www.gnu.org/licenses/>. */ package com.beerbong.zipinst.ui; public abstract class UIActivity extends Activity implements UIInterface, Serializable { private Core mCore; @Override protected void onCreate(Bundle savedInstanceState) { CoreFactory.init(this); mCore = CoreFactory.getCore();
((UIPlugin) mCore.getPlugin(Core.PLUGIN_UI)).registerUI(this);
beerbong/com_beerbong_zipinst
src/com/beerbong/zipinst/core/CoreFactory.java
// Path: src/com/beerbong/zipinst/core/Core.java // public interface CoreListener { // // public void pluginStarted(String name); // // public void pluginStopped(String name); // // public void coreMessage(int resId); // // public void coreStarted(); // // public void coreStopped(); // }
import com.beerbong.zipinst.core.Core.CoreListener; import android.content.Context;
/* * Copyright 2014 ZipInstaller Project * * This file is part of ZipInstaller. * * ZipInstaller is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * ZipInstaller is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with ZipInstaller. If not, see <http://www.gnu.org/licenses/>. */ package com.beerbong.zipinst.core; public class CoreFactory { private static Core sInstance; public static synchronized void init(Context context) { init(context, null); }
// Path: src/com/beerbong/zipinst/core/Core.java // public interface CoreListener { // // public void pluginStarted(String name); // // public void pluginStopped(String name); // // public void coreMessage(int resId); // // public void coreStarted(); // // public void coreStopped(); // } // Path: src/com/beerbong/zipinst/core/CoreFactory.java import com.beerbong.zipinst.core.Core.CoreListener; import android.content.Context; /* * Copyright 2014 ZipInstaller Project * * This file is part of ZipInstaller. * * ZipInstaller is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * ZipInstaller is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with ZipInstaller. If not, see <http://www.gnu.org/licenses/>. */ package com.beerbong.zipinst.core; public class CoreFactory { private static Core sInstance; public static synchronized void init(Context context) { init(context, null); }
public static synchronized void init(Context context, CoreListener listener) {
beerbong/com_beerbong_zipinst
src/com/beerbong/zipinst/ui/preference/UIListPreference.java
// Path: src/com/beerbong/zipinst/core/Core.java // public interface Core extends Serializable { // // public static final String PLUGIN_UI = "UIPlugin"; // public static final String PLUGIN_SUPERUSER = "SuperUserPlugin"; // public static final String PLUGIN_RECOVERY = "RecoveryPlugin"; // public static final String PLUGIN_STORAGE = "StoragePlugin"; // public static final String PLUGIN_REBOOT = "RebootPlugin"; // public static final String PLUGIN_LICENSE = "LicensePlugin"; // public static final String PLUGIN_UPDATE = "UpdatePlugin"; // // public interface CoreListener { // // public void pluginStarted(String name); // // public void pluginStopped(String name); // // public void coreMessage(int resId); // // public void coreStarted(); // // public void coreStopped(); // } // // public void destroy(); // // public boolean isStarted(); // // public Context getContext(); // // public void setContext(Context context); // // public Plugin getPlugin(String name); // // public Preferences getPreferences(); // // public CloudStorage getCloudStorage(); // // public void setCloudStorage(int cloudStorage); // // public ONandroid getONandroid(); // // public Version getVersion(); // // public void moveToInstall(); // } // // Path: src/com/beerbong/zipinst/core/CoreFactory.java // public class CoreFactory { // // private static Core sInstance; // // public static synchronized void init(Context context) { // init(context, null); // } // // public static synchronized void init(Context context, CoreListener listener) { // if (sInstance == null) { // sInstance = new CoreImpl(context, listener); // } else { // sInstance.setContext(context); // } // } // // public static Core getCore() { // return sInstance; // } // // } // // Path: src/com/beerbong/zipinst/core/plugins/ui/UIPlugin.java // public class UIPlugin extends Plugin { // // private static final String ROBOTO_THIN = "font/Roboto-Light.ttf"; // // private Map<String, UIInterface> mUiInterfaces; // private Typeface mRobotoThin; // // public UIPlugin(Core core) { // super(core, Core.PLUGIN_UI); // } // // @Override // public void start() { // ((CoreImpl) getCore()).setMessage(R.string.initializing_ui); // // // (new AsyncTask<Void, Void, Void>() { // // @Override // protected Void doInBackground(Void... params) { // mUiInterfaces = new HashMap<String, UIInterface>(); // // mRobotoThin = Typeface // .createFromAsset(getCore().getContext().getAssets(), ROBOTO_THIN); // return (Void) null; // } // // @Override // protected void onPostExecute(Void result) { // started(); // } // }).execute((Void) null); // } // // @Override // public void stop() { // stopped(); // } // // public void unregisterUI(UIInterface uIInterface) { // if (mUiInterfaces != null) { // mUiInterfaces.remove(uIInterface.getClass().getName()); // } // } // // public void registerUI(UIInterface uIInterface) { // boolean darkTheme = getCore().getPreferences().isDarkTheme(); // uIInterface.setTheme(darkTheme ? R.style.AppTheme_Dark // : R.style.AppTheme); // // redraw(uIInterface); // // if (mUiInterfaces != null) { // mUiInterfaces.put(uIInterface.getClass().getName(), uIInterface); // } // } // // public void redraw() { // Iterator<String> it = mUiInterfaces.keySet().iterator(); // while (it.hasNext()) { // String key = it.next(); // UIInterface uiInterface = mUiInterfaces.get(key); // redraw(uiInterface); // } // } // // public void redraw(UIInterface uIInterface) { // redraw(uIInterface.getMainView()); // } // // public void redraw(View view) { // setFont(view); // } // // private void setFont(View view) { // if (view == null) { // return; // } // if (view instanceof ViewGroup) { // int count = ((ViewGroup) view).getChildCount(); // for (int i = 0; i < count; i++) { // setFont(((ViewGroup) view).getChildAt(i)); // } // } else if (view instanceof TextView) { // ((TextView) view).setTypeface(mRobotoThin); // } // } // // }
import android.content.Context; import android.preference.ListPreference; import android.util.AttributeSet; import android.view.View; import com.beerbong.zipinst.core.Core; import com.beerbong.zipinst.core.CoreFactory; import com.beerbong.zipinst.core.plugins.ui.UIPlugin;
/* * Copyright 2014 ZipInstaller Project * * This file is part of ZipInstaller. * * ZipInstaller is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * ZipInstaller is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with ZipInstaller. If not, see <http://www.gnu.org/licenses/>. */ package com.beerbong.zipinst.ui.preference; public class UIListPreference extends ListPreference { public UIListPreference(Context context, AttributeSet attrs) { super(context, attrs); } public UIListPreference(Context context) { super(context); } @Override protected void onBindView(View view) { super.onBindView(view);
// Path: src/com/beerbong/zipinst/core/Core.java // public interface Core extends Serializable { // // public static final String PLUGIN_UI = "UIPlugin"; // public static final String PLUGIN_SUPERUSER = "SuperUserPlugin"; // public static final String PLUGIN_RECOVERY = "RecoveryPlugin"; // public static final String PLUGIN_STORAGE = "StoragePlugin"; // public static final String PLUGIN_REBOOT = "RebootPlugin"; // public static final String PLUGIN_LICENSE = "LicensePlugin"; // public static final String PLUGIN_UPDATE = "UpdatePlugin"; // // public interface CoreListener { // // public void pluginStarted(String name); // // public void pluginStopped(String name); // // public void coreMessage(int resId); // // public void coreStarted(); // // public void coreStopped(); // } // // public void destroy(); // // public boolean isStarted(); // // public Context getContext(); // // public void setContext(Context context); // // public Plugin getPlugin(String name); // // public Preferences getPreferences(); // // public CloudStorage getCloudStorage(); // // public void setCloudStorage(int cloudStorage); // // public ONandroid getONandroid(); // // public Version getVersion(); // // public void moveToInstall(); // } // // Path: src/com/beerbong/zipinst/core/CoreFactory.java // public class CoreFactory { // // private static Core sInstance; // // public static synchronized void init(Context context) { // init(context, null); // } // // public static synchronized void init(Context context, CoreListener listener) { // if (sInstance == null) { // sInstance = new CoreImpl(context, listener); // } else { // sInstance.setContext(context); // } // } // // public static Core getCore() { // return sInstance; // } // // } // // Path: src/com/beerbong/zipinst/core/plugins/ui/UIPlugin.java // public class UIPlugin extends Plugin { // // private static final String ROBOTO_THIN = "font/Roboto-Light.ttf"; // // private Map<String, UIInterface> mUiInterfaces; // private Typeface mRobotoThin; // // public UIPlugin(Core core) { // super(core, Core.PLUGIN_UI); // } // // @Override // public void start() { // ((CoreImpl) getCore()).setMessage(R.string.initializing_ui); // // // (new AsyncTask<Void, Void, Void>() { // // @Override // protected Void doInBackground(Void... params) { // mUiInterfaces = new HashMap<String, UIInterface>(); // // mRobotoThin = Typeface // .createFromAsset(getCore().getContext().getAssets(), ROBOTO_THIN); // return (Void) null; // } // // @Override // protected void onPostExecute(Void result) { // started(); // } // }).execute((Void) null); // } // // @Override // public void stop() { // stopped(); // } // // public void unregisterUI(UIInterface uIInterface) { // if (mUiInterfaces != null) { // mUiInterfaces.remove(uIInterface.getClass().getName()); // } // } // // public void registerUI(UIInterface uIInterface) { // boolean darkTheme = getCore().getPreferences().isDarkTheme(); // uIInterface.setTheme(darkTheme ? R.style.AppTheme_Dark // : R.style.AppTheme); // // redraw(uIInterface); // // if (mUiInterfaces != null) { // mUiInterfaces.put(uIInterface.getClass().getName(), uIInterface); // } // } // // public void redraw() { // Iterator<String> it = mUiInterfaces.keySet().iterator(); // while (it.hasNext()) { // String key = it.next(); // UIInterface uiInterface = mUiInterfaces.get(key); // redraw(uiInterface); // } // } // // public void redraw(UIInterface uIInterface) { // redraw(uIInterface.getMainView()); // } // // public void redraw(View view) { // setFont(view); // } // // private void setFont(View view) { // if (view == null) { // return; // } // if (view instanceof ViewGroup) { // int count = ((ViewGroup) view).getChildCount(); // for (int i = 0; i < count; i++) { // setFont(((ViewGroup) view).getChildAt(i)); // } // } else if (view instanceof TextView) { // ((TextView) view).setTypeface(mRobotoThin); // } // } // // } // Path: src/com/beerbong/zipinst/ui/preference/UIListPreference.java import android.content.Context; import android.preference.ListPreference; import android.util.AttributeSet; import android.view.View; import com.beerbong.zipinst.core.Core; import com.beerbong.zipinst.core.CoreFactory; import com.beerbong.zipinst.core.plugins.ui.UIPlugin; /* * Copyright 2014 ZipInstaller Project * * This file is part of ZipInstaller. * * ZipInstaller is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * ZipInstaller is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with ZipInstaller. If not, see <http://www.gnu.org/licenses/>. */ package com.beerbong.zipinst.ui.preference; public class UIListPreference extends ListPreference { public UIListPreference(Context context, AttributeSet attrs) { super(context, attrs); } public UIListPreference(Context context) { super(context); } @Override protected void onBindView(View view) { super.onBindView(view);
((UIPlugin) CoreFactory.getCore().getPlugin(Core.PLUGIN_UI)).redraw(view);
beerbong/com_beerbong_zipinst
src/com/beerbong/zipinst/ui/preference/UIListPreference.java
// Path: src/com/beerbong/zipinst/core/Core.java // public interface Core extends Serializable { // // public static final String PLUGIN_UI = "UIPlugin"; // public static final String PLUGIN_SUPERUSER = "SuperUserPlugin"; // public static final String PLUGIN_RECOVERY = "RecoveryPlugin"; // public static final String PLUGIN_STORAGE = "StoragePlugin"; // public static final String PLUGIN_REBOOT = "RebootPlugin"; // public static final String PLUGIN_LICENSE = "LicensePlugin"; // public static final String PLUGIN_UPDATE = "UpdatePlugin"; // // public interface CoreListener { // // public void pluginStarted(String name); // // public void pluginStopped(String name); // // public void coreMessage(int resId); // // public void coreStarted(); // // public void coreStopped(); // } // // public void destroy(); // // public boolean isStarted(); // // public Context getContext(); // // public void setContext(Context context); // // public Plugin getPlugin(String name); // // public Preferences getPreferences(); // // public CloudStorage getCloudStorage(); // // public void setCloudStorage(int cloudStorage); // // public ONandroid getONandroid(); // // public Version getVersion(); // // public void moveToInstall(); // } // // Path: src/com/beerbong/zipinst/core/CoreFactory.java // public class CoreFactory { // // private static Core sInstance; // // public static synchronized void init(Context context) { // init(context, null); // } // // public static synchronized void init(Context context, CoreListener listener) { // if (sInstance == null) { // sInstance = new CoreImpl(context, listener); // } else { // sInstance.setContext(context); // } // } // // public static Core getCore() { // return sInstance; // } // // } // // Path: src/com/beerbong/zipinst/core/plugins/ui/UIPlugin.java // public class UIPlugin extends Plugin { // // private static final String ROBOTO_THIN = "font/Roboto-Light.ttf"; // // private Map<String, UIInterface> mUiInterfaces; // private Typeface mRobotoThin; // // public UIPlugin(Core core) { // super(core, Core.PLUGIN_UI); // } // // @Override // public void start() { // ((CoreImpl) getCore()).setMessage(R.string.initializing_ui); // // // (new AsyncTask<Void, Void, Void>() { // // @Override // protected Void doInBackground(Void... params) { // mUiInterfaces = new HashMap<String, UIInterface>(); // // mRobotoThin = Typeface // .createFromAsset(getCore().getContext().getAssets(), ROBOTO_THIN); // return (Void) null; // } // // @Override // protected void onPostExecute(Void result) { // started(); // } // }).execute((Void) null); // } // // @Override // public void stop() { // stopped(); // } // // public void unregisterUI(UIInterface uIInterface) { // if (mUiInterfaces != null) { // mUiInterfaces.remove(uIInterface.getClass().getName()); // } // } // // public void registerUI(UIInterface uIInterface) { // boolean darkTheme = getCore().getPreferences().isDarkTheme(); // uIInterface.setTheme(darkTheme ? R.style.AppTheme_Dark // : R.style.AppTheme); // // redraw(uIInterface); // // if (mUiInterfaces != null) { // mUiInterfaces.put(uIInterface.getClass().getName(), uIInterface); // } // } // // public void redraw() { // Iterator<String> it = mUiInterfaces.keySet().iterator(); // while (it.hasNext()) { // String key = it.next(); // UIInterface uiInterface = mUiInterfaces.get(key); // redraw(uiInterface); // } // } // // public void redraw(UIInterface uIInterface) { // redraw(uIInterface.getMainView()); // } // // public void redraw(View view) { // setFont(view); // } // // private void setFont(View view) { // if (view == null) { // return; // } // if (view instanceof ViewGroup) { // int count = ((ViewGroup) view).getChildCount(); // for (int i = 0; i < count; i++) { // setFont(((ViewGroup) view).getChildAt(i)); // } // } else if (view instanceof TextView) { // ((TextView) view).setTypeface(mRobotoThin); // } // } // // }
import android.content.Context; import android.preference.ListPreference; import android.util.AttributeSet; import android.view.View; import com.beerbong.zipinst.core.Core; import com.beerbong.zipinst.core.CoreFactory; import com.beerbong.zipinst.core.plugins.ui.UIPlugin;
/* * Copyright 2014 ZipInstaller Project * * This file is part of ZipInstaller. * * ZipInstaller is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * ZipInstaller is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with ZipInstaller. If not, see <http://www.gnu.org/licenses/>. */ package com.beerbong.zipinst.ui.preference; public class UIListPreference extends ListPreference { public UIListPreference(Context context, AttributeSet attrs) { super(context, attrs); } public UIListPreference(Context context) { super(context); } @Override protected void onBindView(View view) { super.onBindView(view);
// Path: src/com/beerbong/zipinst/core/Core.java // public interface Core extends Serializable { // // public static final String PLUGIN_UI = "UIPlugin"; // public static final String PLUGIN_SUPERUSER = "SuperUserPlugin"; // public static final String PLUGIN_RECOVERY = "RecoveryPlugin"; // public static final String PLUGIN_STORAGE = "StoragePlugin"; // public static final String PLUGIN_REBOOT = "RebootPlugin"; // public static final String PLUGIN_LICENSE = "LicensePlugin"; // public static final String PLUGIN_UPDATE = "UpdatePlugin"; // // public interface CoreListener { // // public void pluginStarted(String name); // // public void pluginStopped(String name); // // public void coreMessage(int resId); // // public void coreStarted(); // // public void coreStopped(); // } // // public void destroy(); // // public boolean isStarted(); // // public Context getContext(); // // public void setContext(Context context); // // public Plugin getPlugin(String name); // // public Preferences getPreferences(); // // public CloudStorage getCloudStorage(); // // public void setCloudStorage(int cloudStorage); // // public ONandroid getONandroid(); // // public Version getVersion(); // // public void moveToInstall(); // } // // Path: src/com/beerbong/zipinst/core/CoreFactory.java // public class CoreFactory { // // private static Core sInstance; // // public static synchronized void init(Context context) { // init(context, null); // } // // public static synchronized void init(Context context, CoreListener listener) { // if (sInstance == null) { // sInstance = new CoreImpl(context, listener); // } else { // sInstance.setContext(context); // } // } // // public static Core getCore() { // return sInstance; // } // // } // // Path: src/com/beerbong/zipinst/core/plugins/ui/UIPlugin.java // public class UIPlugin extends Plugin { // // private static final String ROBOTO_THIN = "font/Roboto-Light.ttf"; // // private Map<String, UIInterface> mUiInterfaces; // private Typeface mRobotoThin; // // public UIPlugin(Core core) { // super(core, Core.PLUGIN_UI); // } // // @Override // public void start() { // ((CoreImpl) getCore()).setMessage(R.string.initializing_ui); // // // (new AsyncTask<Void, Void, Void>() { // // @Override // protected Void doInBackground(Void... params) { // mUiInterfaces = new HashMap<String, UIInterface>(); // // mRobotoThin = Typeface // .createFromAsset(getCore().getContext().getAssets(), ROBOTO_THIN); // return (Void) null; // } // // @Override // protected void onPostExecute(Void result) { // started(); // } // }).execute((Void) null); // } // // @Override // public void stop() { // stopped(); // } // // public void unregisterUI(UIInterface uIInterface) { // if (mUiInterfaces != null) { // mUiInterfaces.remove(uIInterface.getClass().getName()); // } // } // // public void registerUI(UIInterface uIInterface) { // boolean darkTheme = getCore().getPreferences().isDarkTheme(); // uIInterface.setTheme(darkTheme ? R.style.AppTheme_Dark // : R.style.AppTheme); // // redraw(uIInterface); // // if (mUiInterfaces != null) { // mUiInterfaces.put(uIInterface.getClass().getName(), uIInterface); // } // } // // public void redraw() { // Iterator<String> it = mUiInterfaces.keySet().iterator(); // while (it.hasNext()) { // String key = it.next(); // UIInterface uiInterface = mUiInterfaces.get(key); // redraw(uiInterface); // } // } // // public void redraw(UIInterface uIInterface) { // redraw(uIInterface.getMainView()); // } // // public void redraw(View view) { // setFont(view); // } // // private void setFont(View view) { // if (view == null) { // return; // } // if (view instanceof ViewGroup) { // int count = ((ViewGroup) view).getChildCount(); // for (int i = 0; i < count; i++) { // setFont(((ViewGroup) view).getChildAt(i)); // } // } else if (view instanceof TextView) { // ((TextView) view).setTypeface(mRobotoThin); // } // } // // } // Path: src/com/beerbong/zipinst/ui/preference/UIListPreference.java import android.content.Context; import android.preference.ListPreference; import android.util.AttributeSet; import android.view.View; import com.beerbong.zipinst.core.Core; import com.beerbong.zipinst.core.CoreFactory; import com.beerbong.zipinst.core.plugins.ui.UIPlugin; /* * Copyright 2014 ZipInstaller Project * * This file is part of ZipInstaller. * * ZipInstaller is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * ZipInstaller is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with ZipInstaller. If not, see <http://www.gnu.org/licenses/>. */ package com.beerbong.zipinst.ui.preference; public class UIListPreference extends ListPreference { public UIListPreference(Context context, AttributeSet attrs) { super(context, attrs); } public UIListPreference(Context context) { super(context); } @Override protected void onBindView(View view) { super.onBindView(view);
((UIPlugin) CoreFactory.getCore().getPlugin(Core.PLUGIN_UI)).redraw(view);
beerbong/com_beerbong_zipinst
src/com/beerbong/zipinst/ui/preference/UIListPreference.java
// Path: src/com/beerbong/zipinst/core/Core.java // public interface Core extends Serializable { // // public static final String PLUGIN_UI = "UIPlugin"; // public static final String PLUGIN_SUPERUSER = "SuperUserPlugin"; // public static final String PLUGIN_RECOVERY = "RecoveryPlugin"; // public static final String PLUGIN_STORAGE = "StoragePlugin"; // public static final String PLUGIN_REBOOT = "RebootPlugin"; // public static final String PLUGIN_LICENSE = "LicensePlugin"; // public static final String PLUGIN_UPDATE = "UpdatePlugin"; // // public interface CoreListener { // // public void pluginStarted(String name); // // public void pluginStopped(String name); // // public void coreMessage(int resId); // // public void coreStarted(); // // public void coreStopped(); // } // // public void destroy(); // // public boolean isStarted(); // // public Context getContext(); // // public void setContext(Context context); // // public Plugin getPlugin(String name); // // public Preferences getPreferences(); // // public CloudStorage getCloudStorage(); // // public void setCloudStorage(int cloudStorage); // // public ONandroid getONandroid(); // // public Version getVersion(); // // public void moveToInstall(); // } // // Path: src/com/beerbong/zipinst/core/CoreFactory.java // public class CoreFactory { // // private static Core sInstance; // // public static synchronized void init(Context context) { // init(context, null); // } // // public static synchronized void init(Context context, CoreListener listener) { // if (sInstance == null) { // sInstance = new CoreImpl(context, listener); // } else { // sInstance.setContext(context); // } // } // // public static Core getCore() { // return sInstance; // } // // } // // Path: src/com/beerbong/zipinst/core/plugins/ui/UIPlugin.java // public class UIPlugin extends Plugin { // // private static final String ROBOTO_THIN = "font/Roboto-Light.ttf"; // // private Map<String, UIInterface> mUiInterfaces; // private Typeface mRobotoThin; // // public UIPlugin(Core core) { // super(core, Core.PLUGIN_UI); // } // // @Override // public void start() { // ((CoreImpl) getCore()).setMessage(R.string.initializing_ui); // // // (new AsyncTask<Void, Void, Void>() { // // @Override // protected Void doInBackground(Void... params) { // mUiInterfaces = new HashMap<String, UIInterface>(); // // mRobotoThin = Typeface // .createFromAsset(getCore().getContext().getAssets(), ROBOTO_THIN); // return (Void) null; // } // // @Override // protected void onPostExecute(Void result) { // started(); // } // }).execute((Void) null); // } // // @Override // public void stop() { // stopped(); // } // // public void unregisterUI(UIInterface uIInterface) { // if (mUiInterfaces != null) { // mUiInterfaces.remove(uIInterface.getClass().getName()); // } // } // // public void registerUI(UIInterface uIInterface) { // boolean darkTheme = getCore().getPreferences().isDarkTheme(); // uIInterface.setTheme(darkTheme ? R.style.AppTheme_Dark // : R.style.AppTheme); // // redraw(uIInterface); // // if (mUiInterfaces != null) { // mUiInterfaces.put(uIInterface.getClass().getName(), uIInterface); // } // } // // public void redraw() { // Iterator<String> it = mUiInterfaces.keySet().iterator(); // while (it.hasNext()) { // String key = it.next(); // UIInterface uiInterface = mUiInterfaces.get(key); // redraw(uiInterface); // } // } // // public void redraw(UIInterface uIInterface) { // redraw(uIInterface.getMainView()); // } // // public void redraw(View view) { // setFont(view); // } // // private void setFont(View view) { // if (view == null) { // return; // } // if (view instanceof ViewGroup) { // int count = ((ViewGroup) view).getChildCount(); // for (int i = 0; i < count; i++) { // setFont(((ViewGroup) view).getChildAt(i)); // } // } else if (view instanceof TextView) { // ((TextView) view).setTypeface(mRobotoThin); // } // } // // }
import android.content.Context; import android.preference.ListPreference; import android.util.AttributeSet; import android.view.View; import com.beerbong.zipinst.core.Core; import com.beerbong.zipinst.core.CoreFactory; import com.beerbong.zipinst.core.plugins.ui.UIPlugin;
/* * Copyright 2014 ZipInstaller Project * * This file is part of ZipInstaller. * * ZipInstaller is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * ZipInstaller is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with ZipInstaller. If not, see <http://www.gnu.org/licenses/>. */ package com.beerbong.zipinst.ui.preference; public class UIListPreference extends ListPreference { public UIListPreference(Context context, AttributeSet attrs) { super(context, attrs); } public UIListPreference(Context context) { super(context); } @Override protected void onBindView(View view) { super.onBindView(view);
// Path: src/com/beerbong/zipinst/core/Core.java // public interface Core extends Serializable { // // public static final String PLUGIN_UI = "UIPlugin"; // public static final String PLUGIN_SUPERUSER = "SuperUserPlugin"; // public static final String PLUGIN_RECOVERY = "RecoveryPlugin"; // public static final String PLUGIN_STORAGE = "StoragePlugin"; // public static final String PLUGIN_REBOOT = "RebootPlugin"; // public static final String PLUGIN_LICENSE = "LicensePlugin"; // public static final String PLUGIN_UPDATE = "UpdatePlugin"; // // public interface CoreListener { // // public void pluginStarted(String name); // // public void pluginStopped(String name); // // public void coreMessage(int resId); // // public void coreStarted(); // // public void coreStopped(); // } // // public void destroy(); // // public boolean isStarted(); // // public Context getContext(); // // public void setContext(Context context); // // public Plugin getPlugin(String name); // // public Preferences getPreferences(); // // public CloudStorage getCloudStorage(); // // public void setCloudStorage(int cloudStorage); // // public ONandroid getONandroid(); // // public Version getVersion(); // // public void moveToInstall(); // } // // Path: src/com/beerbong/zipinst/core/CoreFactory.java // public class CoreFactory { // // private static Core sInstance; // // public static synchronized void init(Context context) { // init(context, null); // } // // public static synchronized void init(Context context, CoreListener listener) { // if (sInstance == null) { // sInstance = new CoreImpl(context, listener); // } else { // sInstance.setContext(context); // } // } // // public static Core getCore() { // return sInstance; // } // // } // // Path: src/com/beerbong/zipinst/core/plugins/ui/UIPlugin.java // public class UIPlugin extends Plugin { // // private static final String ROBOTO_THIN = "font/Roboto-Light.ttf"; // // private Map<String, UIInterface> mUiInterfaces; // private Typeface mRobotoThin; // // public UIPlugin(Core core) { // super(core, Core.PLUGIN_UI); // } // // @Override // public void start() { // ((CoreImpl) getCore()).setMessage(R.string.initializing_ui); // // // (new AsyncTask<Void, Void, Void>() { // // @Override // protected Void doInBackground(Void... params) { // mUiInterfaces = new HashMap<String, UIInterface>(); // // mRobotoThin = Typeface // .createFromAsset(getCore().getContext().getAssets(), ROBOTO_THIN); // return (Void) null; // } // // @Override // protected void onPostExecute(Void result) { // started(); // } // }).execute((Void) null); // } // // @Override // public void stop() { // stopped(); // } // // public void unregisterUI(UIInterface uIInterface) { // if (mUiInterfaces != null) { // mUiInterfaces.remove(uIInterface.getClass().getName()); // } // } // // public void registerUI(UIInterface uIInterface) { // boolean darkTheme = getCore().getPreferences().isDarkTheme(); // uIInterface.setTheme(darkTheme ? R.style.AppTheme_Dark // : R.style.AppTheme); // // redraw(uIInterface); // // if (mUiInterfaces != null) { // mUiInterfaces.put(uIInterface.getClass().getName(), uIInterface); // } // } // // public void redraw() { // Iterator<String> it = mUiInterfaces.keySet().iterator(); // while (it.hasNext()) { // String key = it.next(); // UIInterface uiInterface = mUiInterfaces.get(key); // redraw(uiInterface); // } // } // // public void redraw(UIInterface uIInterface) { // redraw(uIInterface.getMainView()); // } // // public void redraw(View view) { // setFont(view); // } // // private void setFont(View view) { // if (view == null) { // return; // } // if (view instanceof ViewGroup) { // int count = ((ViewGroup) view).getChildCount(); // for (int i = 0; i < count; i++) { // setFont(((ViewGroup) view).getChildAt(i)); // } // } else if (view instanceof TextView) { // ((TextView) view).setTypeface(mRobotoThin); // } // } // // } // Path: src/com/beerbong/zipinst/ui/preference/UIListPreference.java import android.content.Context; import android.preference.ListPreference; import android.util.AttributeSet; import android.view.View; import com.beerbong.zipinst.core.Core; import com.beerbong.zipinst.core.CoreFactory; import com.beerbong.zipinst.core.plugins.ui.UIPlugin; /* * Copyright 2014 ZipInstaller Project * * This file is part of ZipInstaller. * * ZipInstaller is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * ZipInstaller is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with ZipInstaller. If not, see <http://www.gnu.org/licenses/>. */ package com.beerbong.zipinst.ui.preference; public class UIListPreference extends ListPreference { public UIListPreference(Context context, AttributeSet attrs) { super(context, attrs); } public UIListPreference(Context context) { super(context); } @Override protected void onBindView(View view) { super.onBindView(view);
((UIPlugin) CoreFactory.getCore().getPlugin(Core.PLUGIN_UI)).redraw(view);
immibis/bearded-octo-nemesis
immibis/bon/io/ClassCollectionFactory.java
// Path: immibis/bon/ClassCollection.java // public class ClassCollection implements Cloneable { // public ClassCollection(NameSet nameSet, Collection<ClassNode> classes) { // this.nameSet = nameSet; // this.classes.addAll(classes); // } // // private NameSet nameSet; // private Collection<ClassNode> classes = new ArrayList<>(); // private Map<String, byte[]> extraFiles = new HashMap<>(); // // public Collection<ClassNode> getAllClasses() { // return classes; // } // // public NameSet getNameSet() { // return nameSet; // } // // @Override // public ClassCollection clone() { // try { // ClassCollection clone = (ClassCollection)super.clone(); // clone.classes = new ArrayList<>(); // // for(ClassNode ocn : classes) { // // clone the ClassNode // ClassNode ncn = new ClassNode(); // ocn.accept(ncn); // clone.classes.add(ncn); // } // // // copy map, but don't copy data // clone.extraFiles = new HashMap<>(extraFiles); // // return clone; // // } catch(CloneNotSupportedException e) { // throw new RuntimeException("This can't happen", e); // } // } // // public ClassCollection cloneWithNameSet(NameSet newNS) { // ClassCollection rv = clone(); // rv.nameSet = newNS; // return rv; // } // // public Map<String, ClassNode> getClassMap() { // Map<String, ClassNode> rv = new HashMap<String, ClassNode>(); // for(ClassNode cn : classes) // rv.put(cn.name, cn); // return rv; // } // // public Map<String, byte[]> getExtraFiles() { // return extraFiles; // } // // // } // // Path: immibis/bon/ClassFormatException.java // public class ClassFormatException extends Exception { // private static final long serialVersionUID = 1L; // // public ClassFormatException(String message) { // super(message); // } // // public ClassFormatException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: immibis/bon/IProgressListener.java // public interface IProgressListener { // public void start(int max, String text); // public void set(int value); // public void setMax(int max); // } // // Path: immibis/bon/NameSet.java // public abstract class NameSet { // public abstract boolean equals(Object o); // public abstract int hashCode(); // public abstract String toString(); // }
import immibis.bon.ClassCollection; import immibis.bon.ClassFormatException; import immibis.bon.IProgressListener; import immibis.bon.NameSet; import java.io.File; import java.io.IOException;
package immibis.bon.io; @Deprecated public class ClassCollectionFactory {
// Path: immibis/bon/ClassCollection.java // public class ClassCollection implements Cloneable { // public ClassCollection(NameSet nameSet, Collection<ClassNode> classes) { // this.nameSet = nameSet; // this.classes.addAll(classes); // } // // private NameSet nameSet; // private Collection<ClassNode> classes = new ArrayList<>(); // private Map<String, byte[]> extraFiles = new HashMap<>(); // // public Collection<ClassNode> getAllClasses() { // return classes; // } // // public NameSet getNameSet() { // return nameSet; // } // // @Override // public ClassCollection clone() { // try { // ClassCollection clone = (ClassCollection)super.clone(); // clone.classes = new ArrayList<>(); // // for(ClassNode ocn : classes) { // // clone the ClassNode // ClassNode ncn = new ClassNode(); // ocn.accept(ncn); // clone.classes.add(ncn); // } // // // copy map, but don't copy data // clone.extraFiles = new HashMap<>(extraFiles); // // return clone; // // } catch(CloneNotSupportedException e) { // throw new RuntimeException("This can't happen", e); // } // } // // public ClassCollection cloneWithNameSet(NameSet newNS) { // ClassCollection rv = clone(); // rv.nameSet = newNS; // return rv; // } // // public Map<String, ClassNode> getClassMap() { // Map<String, ClassNode> rv = new HashMap<String, ClassNode>(); // for(ClassNode cn : classes) // rv.put(cn.name, cn); // return rv; // } // // public Map<String, byte[]> getExtraFiles() { // return extraFiles; // } // // // } // // Path: immibis/bon/ClassFormatException.java // public class ClassFormatException extends Exception { // private static final long serialVersionUID = 1L; // // public ClassFormatException(String message) { // super(message); // } // // public ClassFormatException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: immibis/bon/IProgressListener.java // public interface IProgressListener { // public void start(int max, String text); // public void set(int value); // public void setMax(int max); // } // // Path: immibis/bon/NameSet.java // public abstract class NameSet { // public abstract boolean equals(Object o); // public abstract int hashCode(); // public abstract String toString(); // } // Path: immibis/bon/io/ClassCollectionFactory.java import immibis.bon.ClassCollection; import immibis.bon.ClassFormatException; import immibis.bon.IProgressListener; import immibis.bon.NameSet; import java.io.File; import java.io.IOException; package immibis.bon.io; @Deprecated public class ClassCollectionFactory {
public static ClassCollection loadClassCollection(NameSet ns, File from, IProgressListener progress) throws IOException, ClassFormatException {
immibis/bearded-octo-nemesis
immibis/bon/io/ClassCollectionFactory.java
// Path: immibis/bon/ClassCollection.java // public class ClassCollection implements Cloneable { // public ClassCollection(NameSet nameSet, Collection<ClassNode> classes) { // this.nameSet = nameSet; // this.classes.addAll(classes); // } // // private NameSet nameSet; // private Collection<ClassNode> classes = new ArrayList<>(); // private Map<String, byte[]> extraFiles = new HashMap<>(); // // public Collection<ClassNode> getAllClasses() { // return classes; // } // // public NameSet getNameSet() { // return nameSet; // } // // @Override // public ClassCollection clone() { // try { // ClassCollection clone = (ClassCollection)super.clone(); // clone.classes = new ArrayList<>(); // // for(ClassNode ocn : classes) { // // clone the ClassNode // ClassNode ncn = new ClassNode(); // ocn.accept(ncn); // clone.classes.add(ncn); // } // // // copy map, but don't copy data // clone.extraFiles = new HashMap<>(extraFiles); // // return clone; // // } catch(CloneNotSupportedException e) { // throw new RuntimeException("This can't happen", e); // } // } // // public ClassCollection cloneWithNameSet(NameSet newNS) { // ClassCollection rv = clone(); // rv.nameSet = newNS; // return rv; // } // // public Map<String, ClassNode> getClassMap() { // Map<String, ClassNode> rv = new HashMap<String, ClassNode>(); // for(ClassNode cn : classes) // rv.put(cn.name, cn); // return rv; // } // // public Map<String, byte[]> getExtraFiles() { // return extraFiles; // } // // // } // // Path: immibis/bon/ClassFormatException.java // public class ClassFormatException extends Exception { // private static final long serialVersionUID = 1L; // // public ClassFormatException(String message) { // super(message); // } // // public ClassFormatException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: immibis/bon/IProgressListener.java // public interface IProgressListener { // public void start(int max, String text); // public void set(int value); // public void setMax(int max); // } // // Path: immibis/bon/NameSet.java // public abstract class NameSet { // public abstract boolean equals(Object o); // public abstract int hashCode(); // public abstract String toString(); // }
import immibis.bon.ClassCollection; import immibis.bon.ClassFormatException; import immibis.bon.IProgressListener; import immibis.bon.NameSet; import java.io.File; import java.io.IOException;
package immibis.bon.io; @Deprecated public class ClassCollectionFactory {
// Path: immibis/bon/ClassCollection.java // public class ClassCollection implements Cloneable { // public ClassCollection(NameSet nameSet, Collection<ClassNode> classes) { // this.nameSet = nameSet; // this.classes.addAll(classes); // } // // private NameSet nameSet; // private Collection<ClassNode> classes = new ArrayList<>(); // private Map<String, byte[]> extraFiles = new HashMap<>(); // // public Collection<ClassNode> getAllClasses() { // return classes; // } // // public NameSet getNameSet() { // return nameSet; // } // // @Override // public ClassCollection clone() { // try { // ClassCollection clone = (ClassCollection)super.clone(); // clone.classes = new ArrayList<>(); // // for(ClassNode ocn : classes) { // // clone the ClassNode // ClassNode ncn = new ClassNode(); // ocn.accept(ncn); // clone.classes.add(ncn); // } // // // copy map, but don't copy data // clone.extraFiles = new HashMap<>(extraFiles); // // return clone; // // } catch(CloneNotSupportedException e) { // throw new RuntimeException("This can't happen", e); // } // } // // public ClassCollection cloneWithNameSet(NameSet newNS) { // ClassCollection rv = clone(); // rv.nameSet = newNS; // return rv; // } // // public Map<String, ClassNode> getClassMap() { // Map<String, ClassNode> rv = new HashMap<String, ClassNode>(); // for(ClassNode cn : classes) // rv.put(cn.name, cn); // return rv; // } // // public Map<String, byte[]> getExtraFiles() { // return extraFiles; // } // // // } // // Path: immibis/bon/ClassFormatException.java // public class ClassFormatException extends Exception { // private static final long serialVersionUID = 1L; // // public ClassFormatException(String message) { // super(message); // } // // public ClassFormatException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: immibis/bon/IProgressListener.java // public interface IProgressListener { // public void start(int max, String text); // public void set(int value); // public void setMax(int max); // } // // Path: immibis/bon/NameSet.java // public abstract class NameSet { // public abstract boolean equals(Object o); // public abstract int hashCode(); // public abstract String toString(); // } // Path: immibis/bon/io/ClassCollectionFactory.java import immibis.bon.ClassCollection; import immibis.bon.ClassFormatException; import immibis.bon.IProgressListener; import immibis.bon.NameSet; import java.io.File; import java.io.IOException; package immibis.bon.io; @Deprecated public class ClassCollectionFactory {
public static ClassCollection loadClassCollection(NameSet ns, File from, IProgressListener progress) throws IOException, ClassFormatException {
immibis/bearded-octo-nemesis
immibis/bon/io/ClassCollectionFactory.java
// Path: immibis/bon/ClassCollection.java // public class ClassCollection implements Cloneable { // public ClassCollection(NameSet nameSet, Collection<ClassNode> classes) { // this.nameSet = nameSet; // this.classes.addAll(classes); // } // // private NameSet nameSet; // private Collection<ClassNode> classes = new ArrayList<>(); // private Map<String, byte[]> extraFiles = new HashMap<>(); // // public Collection<ClassNode> getAllClasses() { // return classes; // } // // public NameSet getNameSet() { // return nameSet; // } // // @Override // public ClassCollection clone() { // try { // ClassCollection clone = (ClassCollection)super.clone(); // clone.classes = new ArrayList<>(); // // for(ClassNode ocn : classes) { // // clone the ClassNode // ClassNode ncn = new ClassNode(); // ocn.accept(ncn); // clone.classes.add(ncn); // } // // // copy map, but don't copy data // clone.extraFiles = new HashMap<>(extraFiles); // // return clone; // // } catch(CloneNotSupportedException e) { // throw new RuntimeException("This can't happen", e); // } // } // // public ClassCollection cloneWithNameSet(NameSet newNS) { // ClassCollection rv = clone(); // rv.nameSet = newNS; // return rv; // } // // public Map<String, ClassNode> getClassMap() { // Map<String, ClassNode> rv = new HashMap<String, ClassNode>(); // for(ClassNode cn : classes) // rv.put(cn.name, cn); // return rv; // } // // public Map<String, byte[]> getExtraFiles() { // return extraFiles; // } // // // } // // Path: immibis/bon/ClassFormatException.java // public class ClassFormatException extends Exception { // private static final long serialVersionUID = 1L; // // public ClassFormatException(String message) { // super(message); // } // // public ClassFormatException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: immibis/bon/IProgressListener.java // public interface IProgressListener { // public void start(int max, String text); // public void set(int value); // public void setMax(int max); // } // // Path: immibis/bon/NameSet.java // public abstract class NameSet { // public abstract boolean equals(Object o); // public abstract int hashCode(); // public abstract String toString(); // }
import immibis.bon.ClassCollection; import immibis.bon.ClassFormatException; import immibis.bon.IProgressListener; import immibis.bon.NameSet; import java.io.File; import java.io.IOException;
package immibis.bon.io; @Deprecated public class ClassCollectionFactory {
// Path: immibis/bon/ClassCollection.java // public class ClassCollection implements Cloneable { // public ClassCollection(NameSet nameSet, Collection<ClassNode> classes) { // this.nameSet = nameSet; // this.classes.addAll(classes); // } // // private NameSet nameSet; // private Collection<ClassNode> classes = new ArrayList<>(); // private Map<String, byte[]> extraFiles = new HashMap<>(); // // public Collection<ClassNode> getAllClasses() { // return classes; // } // // public NameSet getNameSet() { // return nameSet; // } // // @Override // public ClassCollection clone() { // try { // ClassCollection clone = (ClassCollection)super.clone(); // clone.classes = new ArrayList<>(); // // for(ClassNode ocn : classes) { // // clone the ClassNode // ClassNode ncn = new ClassNode(); // ocn.accept(ncn); // clone.classes.add(ncn); // } // // // copy map, but don't copy data // clone.extraFiles = new HashMap<>(extraFiles); // // return clone; // // } catch(CloneNotSupportedException e) { // throw new RuntimeException("This can't happen", e); // } // } // // public ClassCollection cloneWithNameSet(NameSet newNS) { // ClassCollection rv = clone(); // rv.nameSet = newNS; // return rv; // } // // public Map<String, ClassNode> getClassMap() { // Map<String, ClassNode> rv = new HashMap<String, ClassNode>(); // for(ClassNode cn : classes) // rv.put(cn.name, cn); // return rv; // } // // public Map<String, byte[]> getExtraFiles() { // return extraFiles; // } // // // } // // Path: immibis/bon/ClassFormatException.java // public class ClassFormatException extends Exception { // private static final long serialVersionUID = 1L; // // public ClassFormatException(String message) { // super(message); // } // // public ClassFormatException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: immibis/bon/IProgressListener.java // public interface IProgressListener { // public void start(int max, String text); // public void set(int value); // public void setMax(int max); // } // // Path: immibis/bon/NameSet.java // public abstract class NameSet { // public abstract boolean equals(Object o); // public abstract int hashCode(); // public abstract String toString(); // } // Path: immibis/bon/io/ClassCollectionFactory.java import immibis.bon.ClassCollection; import immibis.bon.ClassFormatException; import immibis.bon.IProgressListener; import immibis.bon.NameSet; import java.io.File; import java.io.IOException; package immibis.bon.io; @Deprecated public class ClassCollectionFactory {
public static ClassCollection loadClassCollection(NameSet ns, File from, IProgressListener progress) throws IOException, ClassFormatException {
immibis/bearded-octo-nemesis
immibis/bon/io/ClassCollectionFactory.java
// Path: immibis/bon/ClassCollection.java // public class ClassCollection implements Cloneable { // public ClassCollection(NameSet nameSet, Collection<ClassNode> classes) { // this.nameSet = nameSet; // this.classes.addAll(classes); // } // // private NameSet nameSet; // private Collection<ClassNode> classes = new ArrayList<>(); // private Map<String, byte[]> extraFiles = new HashMap<>(); // // public Collection<ClassNode> getAllClasses() { // return classes; // } // // public NameSet getNameSet() { // return nameSet; // } // // @Override // public ClassCollection clone() { // try { // ClassCollection clone = (ClassCollection)super.clone(); // clone.classes = new ArrayList<>(); // // for(ClassNode ocn : classes) { // // clone the ClassNode // ClassNode ncn = new ClassNode(); // ocn.accept(ncn); // clone.classes.add(ncn); // } // // // copy map, but don't copy data // clone.extraFiles = new HashMap<>(extraFiles); // // return clone; // // } catch(CloneNotSupportedException e) { // throw new RuntimeException("This can't happen", e); // } // } // // public ClassCollection cloneWithNameSet(NameSet newNS) { // ClassCollection rv = clone(); // rv.nameSet = newNS; // return rv; // } // // public Map<String, ClassNode> getClassMap() { // Map<String, ClassNode> rv = new HashMap<String, ClassNode>(); // for(ClassNode cn : classes) // rv.put(cn.name, cn); // return rv; // } // // public Map<String, byte[]> getExtraFiles() { // return extraFiles; // } // // // } // // Path: immibis/bon/ClassFormatException.java // public class ClassFormatException extends Exception { // private static final long serialVersionUID = 1L; // // public ClassFormatException(String message) { // super(message); // } // // public ClassFormatException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: immibis/bon/IProgressListener.java // public interface IProgressListener { // public void start(int max, String text); // public void set(int value); // public void setMax(int max); // } // // Path: immibis/bon/NameSet.java // public abstract class NameSet { // public abstract boolean equals(Object o); // public abstract int hashCode(); // public abstract String toString(); // }
import immibis.bon.ClassCollection; import immibis.bon.ClassFormatException; import immibis.bon.IProgressListener; import immibis.bon.NameSet; import java.io.File; import java.io.IOException;
package immibis.bon.io; @Deprecated public class ClassCollectionFactory {
// Path: immibis/bon/ClassCollection.java // public class ClassCollection implements Cloneable { // public ClassCollection(NameSet nameSet, Collection<ClassNode> classes) { // this.nameSet = nameSet; // this.classes.addAll(classes); // } // // private NameSet nameSet; // private Collection<ClassNode> classes = new ArrayList<>(); // private Map<String, byte[]> extraFiles = new HashMap<>(); // // public Collection<ClassNode> getAllClasses() { // return classes; // } // // public NameSet getNameSet() { // return nameSet; // } // // @Override // public ClassCollection clone() { // try { // ClassCollection clone = (ClassCollection)super.clone(); // clone.classes = new ArrayList<>(); // // for(ClassNode ocn : classes) { // // clone the ClassNode // ClassNode ncn = new ClassNode(); // ocn.accept(ncn); // clone.classes.add(ncn); // } // // // copy map, but don't copy data // clone.extraFiles = new HashMap<>(extraFiles); // // return clone; // // } catch(CloneNotSupportedException e) { // throw new RuntimeException("This can't happen", e); // } // } // // public ClassCollection cloneWithNameSet(NameSet newNS) { // ClassCollection rv = clone(); // rv.nameSet = newNS; // return rv; // } // // public Map<String, ClassNode> getClassMap() { // Map<String, ClassNode> rv = new HashMap<String, ClassNode>(); // for(ClassNode cn : classes) // rv.put(cn.name, cn); // return rv; // } // // public Map<String, byte[]> getExtraFiles() { // return extraFiles; // } // // // } // // Path: immibis/bon/ClassFormatException.java // public class ClassFormatException extends Exception { // private static final long serialVersionUID = 1L; // // public ClassFormatException(String message) { // super(message); // } // // public ClassFormatException(String message, Throwable cause) { // super(message, cause); // } // } // // Path: immibis/bon/IProgressListener.java // public interface IProgressListener { // public void start(int max, String text); // public void set(int value); // public void setMax(int max); // } // // Path: immibis/bon/NameSet.java // public abstract class NameSet { // public abstract boolean equals(Object o); // public abstract int hashCode(); // public abstract String toString(); // } // Path: immibis/bon/io/ClassCollectionFactory.java import immibis.bon.ClassCollection; import immibis.bon.ClassFormatException; import immibis.bon.IProgressListener; import immibis.bon.NameSet; import java.io.File; import java.io.IOException; package immibis.bon.io; @Deprecated public class ClassCollectionFactory {
public static ClassCollection loadClassCollection(NameSet ns, File from, IProgressListener progress) throws IOException, ClassFormatException {
opencog/destin
Destin/Bindings/Java/src/javadestin/NetworkFactory.java
// Path: Destin/Bindings/Java/src/callbacks/BeliefGraphCallback.java // public class BeliefGraphCallback extends DestinIterationFinishedCallback { // private FPSCallback fps = new FPSCallback(0); // private DecimalFormat df = new DecimalFormat("0.0000"); // // @Override // public void callback(INetwork network) { // int layer = 7; // int states = network.getBeliefsPerNode(layer); // float [] beliefs = Util.toJavaArray(network.getNodeBeliefs(layer, 0, 0), states); // // int beliefWidth = 80; // how many character columns in chart line, doesn't // // have to match the size of the belief vector // System.out.print("\033[2J");//clearscreen // System.out.flush(); // // System.out.println("states:"+states); // fps.callback(network); // // for(int s = 0 ; s < states; s++){ // int b = (int)(beliefs[s] * beliefWidth); // System.out.print(s+":"+df.format(beliefs[s])+":"); // for(int i = 0 ; i < b ; i++){ // System.out.print("X"); // } // System.out.println(); // } // System.out.println("-------------------"); // // } // // }
import callbacks.BeliefGraphCallback;
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package javadestin; /** * * @author teds */ public class NetworkFactory implements INetworkFactory { @Override public INetwork create() { INetwork n = new NetworkAlt(SupportedImageWidths.W512, 8, new long[]{20, 16, 14, 12, 10, 8, 6, 2}, true);
// Path: Destin/Bindings/Java/src/callbacks/BeliefGraphCallback.java // public class BeliefGraphCallback extends DestinIterationFinishedCallback { // private FPSCallback fps = new FPSCallback(0); // private DecimalFormat df = new DecimalFormat("0.0000"); // // @Override // public void callback(INetwork network) { // int layer = 7; // int states = network.getBeliefsPerNode(layer); // float [] beliefs = Util.toJavaArray(network.getNodeBeliefs(layer, 0, 0), states); // // int beliefWidth = 80; // how many character columns in chart line, doesn't // // have to match the size of the belief vector // System.out.print("\033[2J");//clearscreen // System.out.flush(); // // System.out.println("states:"+states); // fps.callback(network); // // for(int s = 0 ; s < states; s++){ // int b = (int)(beliefs[s] * beliefWidth); // System.out.print(s+":"+df.format(beliefs[s])+":"); // for(int i = 0 ; i < b ; i++){ // System.out.print("X"); // } // System.out.println(); // } // System.out.println("-------------------"); // // } // // } // Path: Destin/Bindings/Java/src/javadestin/NetworkFactory.java import callbacks.BeliefGraphCallback; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package javadestin; /** * * @author teds */ public class NetworkFactory implements INetworkFactory { @Override public INetwork create() { INetwork n = new NetworkAlt(SupportedImageWidths.W512, 8, new long[]{20, 16, 14, 12, 10, 8, 6, 2}, true);
n.setIterationFinishedCallback(new BeliefGraphCallback());
berkesa/datatree
src/test/java/io/datatree/CacheTest.java
// Path: src/main/java/io/datatree/dom/Cache.java // public class Cache<K, V> { // // // --- INTERNAL VARIABLES --- // // protected final ReadLock readLock; // protected final WriteLock writeLock; // // protected final LinkedHashMap<K, V> map; // // // --- CONSTRUCTORS --- // // /** // * Creates a cache with the specified capacity. // * // * @param capacity // * maximum capacity of the cache // */ // public Cache(int capacity) { // // // Insertion-order is thread safe, access-order is not // map = new LinkedHashMap<K, V>(capacity, 1.0f, false) { // // private static final long serialVersionUID = 5994447707758047152L; // // protected final boolean removeEldestEntry(Map.Entry<K, V> entry) { // return size() > capacity; // }; // }; // // // Create locks // ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); // readLock = lock.readLock(); // writeLock = lock.writeLock(); // } // // // --- GET / PUT / ETC --- // // public V get(K key) { // V value = null; // readLock.lock(); // try { // value = map.get(key); // } finally { // readLock.unlock(); // } // return value; // } // // public void put(K key, V value) { // writeLock.lock(); // try { // map.put(key, value); // } finally { // writeLock.unlock(); // } // } // // public V putIfAbsent(K key, V value) { // V prev; // writeLock.lock(); // try { // prev = map.putIfAbsent(key, value); // } finally { // writeLock.unlock(); // } // if (prev == null) { // return value; // } // return prev; // } // // public void remove(K key) { // writeLock.lock(); // try { // map.remove(key); // } finally { // writeLock.unlock(); // } // } // // public void clear() { // writeLock.lock(); // try { // map.clear(); // } finally { // writeLock.unlock(); // } // } // // public int size() { // return map.size(); // } // // }
import org.junit.Test; import io.datatree.dom.Cache; import junit.framework.TestCase;
/** * This software is licensed under the Apache 2 license, quoted below.<br> * <br> * Copyright 2018 Andras Berkes [andras.berkes@programmer.net]<br> * <br> * 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<br> * <br> * http://www.apache.org/licenses/LICENSE-2.0<br> * <br> * 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 io.datatree; /** * Memory cache tests. * * @author Andras Berkes [andras.berkes@programmer.net] */ public class CacheTest extends TestCase { @Test public void testCache() throws Exception {
// Path: src/main/java/io/datatree/dom/Cache.java // public class Cache<K, V> { // // // --- INTERNAL VARIABLES --- // // protected final ReadLock readLock; // protected final WriteLock writeLock; // // protected final LinkedHashMap<K, V> map; // // // --- CONSTRUCTORS --- // // /** // * Creates a cache with the specified capacity. // * // * @param capacity // * maximum capacity of the cache // */ // public Cache(int capacity) { // // // Insertion-order is thread safe, access-order is not // map = new LinkedHashMap<K, V>(capacity, 1.0f, false) { // // private static final long serialVersionUID = 5994447707758047152L; // // protected final boolean removeEldestEntry(Map.Entry<K, V> entry) { // return size() > capacity; // }; // }; // // // Create locks // ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); // readLock = lock.readLock(); // writeLock = lock.writeLock(); // } // // // --- GET / PUT / ETC --- // // public V get(K key) { // V value = null; // readLock.lock(); // try { // value = map.get(key); // } finally { // readLock.unlock(); // } // return value; // } // // public void put(K key, V value) { // writeLock.lock(); // try { // map.put(key, value); // } finally { // writeLock.unlock(); // } // } // // public V putIfAbsent(K key, V value) { // V prev; // writeLock.lock(); // try { // prev = map.putIfAbsent(key, value); // } finally { // writeLock.unlock(); // } // if (prev == null) { // return value; // } // return prev; // } // // public void remove(K key) { // writeLock.lock(); // try { // map.remove(key); // } finally { // writeLock.unlock(); // } // } // // public void clear() { // writeLock.lock(); // try { // map.clear(); // } finally { // writeLock.unlock(); // } // } // // public int size() { // return map.size(); // } // // } // Path: src/test/java/io/datatree/CacheTest.java import org.junit.Test; import io.datatree.dom.Cache; import junit.framework.TestCase; /** * This software is licensed under the Apache 2 license, quoted below.<br> * <br> * Copyright 2018 Andras Berkes [andras.berkes@programmer.net]<br> * <br> * 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<br> * <br> * http://www.apache.org/licenses/LICENSE-2.0<br> * <br> * 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 io.datatree; /** * Memory cache tests. * * @author Andras Berkes [andras.berkes@programmer.net] */ public class CacheTest extends TestCase { @Test public void testCache() throws Exception {
Cache<Integer, Integer> c = new Cache<>(5);
IHTSDO/rf2-to-json-conversion
src/main/java/org/ihtsdo/json/utils/TClosure.java
// Path: src/main/java/org/ihtsdo/json/model/LightRelationship.java // public class LightRelationship extends Component { // // private String type; // private String target; // private String sourceId; // private Integer groupId; // private String charType; // private String modifier; // public String getType() { // return type; // } // public void setType(String type) { // this.type = type; // } // public String getTarget() { // return target; // } // public void setTarget(String target) { // this.target = target; // } // public String getSourceId() { // return sourceId; // } // public void setSourceId(String sourceId) { // this.sourceId = sourceId; // } // public Integer getGroupId() { // return groupId; // } // public void setGroupId(Integer groupId) { // this.groupId = groupId; // } // public String getCharType() { // return charType; // } // public void setCharType(String charType) { // this.charType = charType; // } // public String getModifier() { // return modifier; // } // public void setModifier(String modifier) { // this.modifier = modifier; // } // // // // }
import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import org.ihtsdo.json.model.LightRelationship;
package org.ihtsdo.json.utils; public class TClosure { // HashMap<Long,HashSet<Long>>parentHier; HashMap<Long,HashSet<Long>>childrenHier; // private long ISARELATIONSHIPTYPEID=116680003l; private String ISA_SCTID="116680003"; private String ROOT_CONCEPT = "138875005"; String rf2Rels; private HashSet<Long> hControl; public TClosure(String rf2Rels) throws FileNotFoundException, IOException{ // parentHier=new HashMap<Long,HashSet<Long>>(); childrenHier=new HashMap<Long,HashSet<Long>>(); this.rf2Rels=rf2Rels; loadIsas(); }
// Path: src/main/java/org/ihtsdo/json/model/LightRelationship.java // public class LightRelationship extends Component { // // private String type; // private String target; // private String sourceId; // private Integer groupId; // private String charType; // private String modifier; // public String getType() { // return type; // } // public void setType(String type) { // this.type = type; // } // public String getTarget() { // return target; // } // public void setTarget(String target) { // this.target = target; // } // public String getSourceId() { // return sourceId; // } // public void setSourceId(String sourceId) { // this.sourceId = sourceId; // } // public Integer getGroupId() { // return groupId; // } // public void setGroupId(Integer groupId) { // this.groupId = groupId; // } // public String getCharType() { // return charType; // } // public void setCharType(String charType) { // this.charType = charType; // } // public String getModifier() { // return modifier; // } // public void setModifier(String modifier) { // this.modifier = modifier; // } // // // // } // Path: src/main/java/org/ihtsdo/json/utils/TClosure.java import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import org.ihtsdo.json.model.LightRelationship; package org.ihtsdo.json.utils; public class TClosure { // HashMap<Long,HashSet<Long>>parentHier; HashMap<Long,HashSet<Long>>childrenHier; // private long ISARELATIONSHIPTYPEID=116680003l; private String ISA_SCTID="116680003"; private String ROOT_CONCEPT = "138875005"; String rf2Rels; private HashSet<Long> hControl; public TClosure(String rf2Rels) throws FileNotFoundException, IOException{ // parentHier=new HashMap<Long,HashSet<Long>>(); childrenHier=new HashMap<Long,HashSet<Long>>(); this.rf2Rels=rf2Rels; loadIsas(); }
public TClosure(Map<String, List<LightRelationship>> relationships,String charType) throws FileNotFoundException, IOException {
wilds/pi-copter
remote_controller/app/src/main/java/org/wilds/quadcontroller/app/communication/UDPProtocol.java
// Path: remote_controller/app/src/main/java/org/wilds/quadcontroller/app/communication/packet/HelloPacket.java // public class HelloPacket extends Packet { // // protected String from; // // public HelloPacket(String from) { // this.setType(TYPE_HELLO); // setFrom(from); // } // // public String getFrom() { // return from; // } // // protected void setFrom(String from) { // this.from = from; // } // // @Override // public boolean waitReply() { // return true; // } // // @Override // public String toString() { // return TYPE_HELLO + " " + from; // } // } // // Path: remote_controller/app/src/main/java/org/wilds/quadcontroller/app/communication/packet/Packet.java // public abstract class Packet { // // public static final String TYPE_HELLO = "hello"; // public static final String TYPE_MOTION = "rcinput"; // public static final String TYPE_HEARTBEAT = "heartbeat"; // public static final String TYPE_TEST_MOTOR = "tm"; // // protected String type; // // public String getType() { // return type; // } // // protected void setType(String type) { // this.type = type; // } // // public boolean waitReply() { // return false; // } // // @Override // public String toString() { // return type; // } // // public byte[] getByte() { return this.toString().getBytes(); } // // public int getLength() { // return this.toString().length(); // } // }
import android.util.Log; import org.wilds.quadcontroller.app.communication.packet.HelloPacket; import org.wilds.quadcontroller.app.communication.packet.Packet; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException; import java.net.UnknownHostException;
package org.wilds.quadcontroller.app.communication; /** * Created by Wilds on 14/04/2014. */ public class UDPProtocol implements Protocol { // protected DatagramSocket sendSocked; protected int sendPort = 58000; protected InetAddress sendTo; // Listening vars /* protected Thread listenThread; protected int listenPort = 57001; protected boolean listening = true; */ protected OnReceiveListener onReceiveListener; public UDPProtocol(int sendPort /*, int listenPort*/) { this.sendPort = sendPort; //this.listenPort = listenPort; try { sendSocked = new DatagramSocket(sendPort); } catch (SocketException e) { e.printStackTrace(); } // startListening(); } @Override public void setOnReceiveListener(OnReceiveListener listener) { this.onReceiveListener = listener; } /* protected void startListening() { listenThread = new Thread(new Runnable() { @Override public void run() { try { DatagramSocket sock = new DatagramSocket(listenPort); while (listening) { byte[] message = new byte[1500]; DatagramPacket p = new DatagramPacket(message, message.length); sock.receive(p); String text = new String(message, 0, p.getLength()); //TODO handle quadcopter response at hello packet onReceiveListener.onReceive(text); } sock.close(); } catch (SocketException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }); listenThread.start(); } */ @Override
// Path: remote_controller/app/src/main/java/org/wilds/quadcontroller/app/communication/packet/HelloPacket.java // public class HelloPacket extends Packet { // // protected String from; // // public HelloPacket(String from) { // this.setType(TYPE_HELLO); // setFrom(from); // } // // public String getFrom() { // return from; // } // // protected void setFrom(String from) { // this.from = from; // } // // @Override // public boolean waitReply() { // return true; // } // // @Override // public String toString() { // return TYPE_HELLO + " " + from; // } // } // // Path: remote_controller/app/src/main/java/org/wilds/quadcontroller/app/communication/packet/Packet.java // public abstract class Packet { // // public static final String TYPE_HELLO = "hello"; // public static final String TYPE_MOTION = "rcinput"; // public static final String TYPE_HEARTBEAT = "heartbeat"; // public static final String TYPE_TEST_MOTOR = "tm"; // // protected String type; // // public String getType() { // return type; // } // // protected void setType(String type) { // this.type = type; // } // // public boolean waitReply() { // return false; // } // // @Override // public String toString() { // return type; // } // // public byte[] getByte() { return this.toString().getBytes(); } // // public int getLength() { // return this.toString().length(); // } // } // Path: remote_controller/app/src/main/java/org/wilds/quadcontroller/app/communication/UDPProtocol.java import android.util.Log; import org.wilds.quadcontroller.app.communication.packet.HelloPacket; import org.wilds.quadcontroller.app.communication.packet.Packet; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException; import java.net.UnknownHostException; package org.wilds.quadcontroller.app.communication; /** * Created by Wilds on 14/04/2014. */ public class UDPProtocol implements Protocol { // protected DatagramSocket sendSocked; protected int sendPort = 58000; protected InetAddress sendTo; // Listening vars /* protected Thread listenThread; protected int listenPort = 57001; protected boolean listening = true; */ protected OnReceiveListener onReceiveListener; public UDPProtocol(int sendPort /*, int listenPort*/) { this.sendPort = sendPort; //this.listenPort = listenPort; try { sendSocked = new DatagramSocket(sendPort); } catch (SocketException e) { e.printStackTrace(); } // startListening(); } @Override public void setOnReceiveListener(OnReceiveListener listener) { this.onReceiveListener = listener; } /* protected void startListening() { listenThread = new Thread(new Runnable() { @Override public void run() { try { DatagramSocket sock = new DatagramSocket(listenPort); while (listening) { byte[] message = new byte[1500]; DatagramPacket p = new DatagramPacket(message, message.length); sock.receive(p); String text = new String(message, 0, p.getLength()); //TODO handle quadcopter response at hello packet onReceiveListener.onReceive(text); } sock.close(); } catch (SocketException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }); listenThread.start(); } */ @Override
public boolean sendPacket(final Packet packet) { // TODO convertire in async task
wilds/pi-copter
remote_controller/app/src/main/java/org/wilds/quadcontroller/app/communication/UDPProtocol.java
// Path: remote_controller/app/src/main/java/org/wilds/quadcontroller/app/communication/packet/HelloPacket.java // public class HelloPacket extends Packet { // // protected String from; // // public HelloPacket(String from) { // this.setType(TYPE_HELLO); // setFrom(from); // } // // public String getFrom() { // return from; // } // // protected void setFrom(String from) { // this.from = from; // } // // @Override // public boolean waitReply() { // return true; // } // // @Override // public String toString() { // return TYPE_HELLO + " " + from; // } // } // // Path: remote_controller/app/src/main/java/org/wilds/quadcontroller/app/communication/packet/Packet.java // public abstract class Packet { // // public static final String TYPE_HELLO = "hello"; // public static final String TYPE_MOTION = "rcinput"; // public static final String TYPE_HEARTBEAT = "heartbeat"; // public static final String TYPE_TEST_MOTOR = "tm"; // // protected String type; // // public String getType() { // return type; // } // // protected void setType(String type) { // this.type = type; // } // // public boolean waitReply() { // return false; // } // // @Override // public String toString() { // return type; // } // // public byte[] getByte() { return this.toString().getBytes(); } // // public int getLength() { // return this.toString().length(); // } // }
import android.util.Log; import org.wilds.quadcontroller.app.communication.packet.HelloPacket; import org.wilds.quadcontroller.app.communication.packet.Packet; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException; import java.net.UnknownHostException;
sendSocked.send(new DatagramPacket(packet.getByte(), packet.getLength(), sendTo, sendPort)); if (packet.waitReply()) { byte[] message = new byte[1024]; DatagramPacket p = new DatagramPacket(message, message.length); sendSocked.receive(p); String text = new String(message, 0, p.getLength()); //TODO handle quadcopter response if (onReceiveListener != null) onReceiveListener.onReceive(packet.getType(), text); } //return true; } catch (IOException e) { e.printStackTrace(); //return false; } } }).start(); return true; } @Override public boolean searchForQuadcopter() { // TODO convertire in async task new Thread(new Runnable() { @Override public void run() { try {
// Path: remote_controller/app/src/main/java/org/wilds/quadcontroller/app/communication/packet/HelloPacket.java // public class HelloPacket extends Packet { // // protected String from; // // public HelloPacket(String from) { // this.setType(TYPE_HELLO); // setFrom(from); // } // // public String getFrom() { // return from; // } // // protected void setFrom(String from) { // this.from = from; // } // // @Override // public boolean waitReply() { // return true; // } // // @Override // public String toString() { // return TYPE_HELLO + " " + from; // } // } // // Path: remote_controller/app/src/main/java/org/wilds/quadcontroller/app/communication/packet/Packet.java // public abstract class Packet { // // public static final String TYPE_HELLO = "hello"; // public static final String TYPE_MOTION = "rcinput"; // public static final String TYPE_HEARTBEAT = "heartbeat"; // public static final String TYPE_TEST_MOTOR = "tm"; // // protected String type; // // public String getType() { // return type; // } // // protected void setType(String type) { // this.type = type; // } // // public boolean waitReply() { // return false; // } // // @Override // public String toString() { // return type; // } // // public byte[] getByte() { return this.toString().getBytes(); } // // public int getLength() { // return this.toString().length(); // } // } // Path: remote_controller/app/src/main/java/org/wilds/quadcontroller/app/communication/UDPProtocol.java import android.util.Log; import org.wilds.quadcontroller.app.communication.packet.HelloPacket; import org.wilds.quadcontroller.app.communication.packet.Packet; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException; import java.net.UnknownHostException; sendSocked.send(new DatagramPacket(packet.getByte(), packet.getLength(), sendTo, sendPort)); if (packet.waitReply()) { byte[] message = new byte[1024]; DatagramPacket p = new DatagramPacket(message, message.length); sendSocked.receive(p); String text = new String(message, 0, p.getLength()); //TODO handle quadcopter response if (onReceiveListener != null) onReceiveListener.onReceive(packet.getType(), text); } //return true; } catch (IOException e) { e.printStackTrace(); //return false; } } }).start(); return true; } @Override public boolean searchForQuadcopter() { // TODO convertire in async task new Thread(new Runnable() { @Override public void run() { try {
Packet packet = new HelloPacket(InetAddress.getLocalHost().getHostAddress());
wilds/pi-copter
remote_controller/app/src/main/java/org/wilds/quadcontroller/app/communication/Protocol.java
// Path: remote_controller/app/src/main/java/org/wilds/quadcontroller/app/communication/packet/Packet.java // public abstract class Packet { // // public static final String TYPE_HELLO = "hello"; // public static final String TYPE_MOTION = "rcinput"; // public static final String TYPE_HEARTBEAT = "heartbeat"; // public static final String TYPE_TEST_MOTOR = "tm"; // // protected String type; // // public String getType() { // return type; // } // // protected void setType(String type) { // this.type = type; // } // // public boolean waitReply() { // return false; // } // // @Override // public String toString() { // return type; // } // // public byte[] getByte() { return this.toString().getBytes(); } // // public int getLength() { // return this.toString().length(); // } // }
import org.wilds.quadcontroller.app.communication.packet.Packet;
package org.wilds.quadcontroller.app.communication; /** * Created by Wilds on 14/04/2014. */ public interface Protocol { public boolean isConnected(); public boolean searchForQuadcopter(); // send broadcast udp packet public boolean connectToQuadcopter(String id); // connect to quadcopter
// Path: remote_controller/app/src/main/java/org/wilds/quadcontroller/app/communication/packet/Packet.java // public abstract class Packet { // // public static final String TYPE_HELLO = "hello"; // public static final String TYPE_MOTION = "rcinput"; // public static final String TYPE_HEARTBEAT = "heartbeat"; // public static final String TYPE_TEST_MOTOR = "tm"; // // protected String type; // // public String getType() { // return type; // } // // protected void setType(String type) { // this.type = type; // } // // public boolean waitReply() { // return false; // } // // @Override // public String toString() { // return type; // } // // public byte[] getByte() { return this.toString().getBytes(); } // // public int getLength() { // return this.toString().length(); // } // } // Path: remote_controller/app/src/main/java/org/wilds/quadcontroller/app/communication/Protocol.java import org.wilds.quadcontroller.app.communication.packet.Packet; package org.wilds.quadcontroller.app.communication; /** * Created by Wilds on 14/04/2014. */ public interface Protocol { public boolean isConnected(); public boolean searchForQuadcopter(); // send broadcast udp packet public boolean connectToQuadcopter(String id); // connect to quadcopter
public boolean sendPacket(Packet packet);
lacimarsik/harmony-analyser
src/main/java/org/harmony_analyser/jharmonyanalyser/plugins/chromanal_plugins/ChromaAnalyserPlugin.java
// Path: src/main/java/org/harmony_analyser/jharmonyanalyser/chroma_analyser/Chroma.java // @SuppressWarnings({"SameParameterValue", "WeakerAccess"}) // // public class Chroma { // public final float[] values; // // public static final Chroma EMPTY_CHROMA = new Chroma(); // // /* Exceptions */ // // public class WrongChromaSize extends Exception { // public WrongChromaSize(String message) { // super(message); // } // } // // public Chroma() { // this.values = new float[0]; // } // // public Chroma(float[] chroma) throws WrongChromaSize { // this.values = new float[Chromanal.CHROMA_LENGTH]; // if (chroma.length != Chromanal.CHROMA_LENGTH) { // throw new WrongChromaSize("Wrong Chroma size"); // } // System.arraycopy(chroma, 0, values, 0, Chromanal.CHROMA_LENGTH - 1); // } // // /* Public / Package methods */ // // /* Private methods */ // } // // Path: src/main/java/org/harmony_analyser/jharmonyanalyser/plugins/LineChartPlugin.java // @SuppressWarnings("SameParameterValue") // // public abstract class LineChartPlugin extends AnalysisPlugin { // public VisualizationData getDataFromOutput(String inputWavFile) throws IOException, AudioAnalyser.OutputNotReady, AudioAnalyser.ParseOutputError, AudioAnalyser.IncorrectInputException, AudioAnalyser.OutputAlreadyExists { // VisualizationData data = super.prepareVisualizationData(); // List<Float> timestamps = new ArrayList<>(); // List<Float> values = new ArrayList<>(); // List<String> linesList = readOutputFile(inputWavFile); // // float timestamp, value; // // /* Plugin-specific parsing of the result */ // try { // for (String line : linesList) { // timestamp = AudioAnalysisHelper.getTimestampFromLine(line); // value = Float.parseFloat(AudioAnalysisHelper.getLabelFromLine(line)); // timestamps.add(timestamp); // values.add(value); // } // } catch (NumberFormatException e) { // throw new AudioAnalyser.ParseOutputError("Output did not have the required fields"); // } // data.setTimestamps(timestamps); // data.setValues(values); // return data; // } // }
import org.harmony_analyser.jharmonyanalyser.services.*; import org.harmony_analyser.jharmonyanalyser.chroma_analyser.Chroma; import org.harmony_analyser.jharmonyanalyser.plugins.LineChartPlugin; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; import java.util.ArrayList; import java.util.List;
package org.harmony_analyser.jharmonyanalyser.plugins.chromanal_plugins; /** * Abstract class for chrama complexity plugins */ @SuppressWarnings("SameParameterValue") abstract class ChromaAnalyserPlugin extends LineChartPlugin { protected static float audibleThreshold = (float) 0.07; // used to filter chroma activations that we consider not audible /** * Analyzes the song: converts chroma information to chroma complexity descriptors * * @param inputFile [String] name of the WAV audio file * These additional files are expected in the folder * - chromaFile: name of the file containing chroma information (suffix: -chromas.txt) */
// Path: src/main/java/org/harmony_analyser/jharmonyanalyser/chroma_analyser/Chroma.java // @SuppressWarnings({"SameParameterValue", "WeakerAccess"}) // // public class Chroma { // public final float[] values; // // public static final Chroma EMPTY_CHROMA = new Chroma(); // // /* Exceptions */ // // public class WrongChromaSize extends Exception { // public WrongChromaSize(String message) { // super(message); // } // } // // public Chroma() { // this.values = new float[0]; // } // // public Chroma(float[] chroma) throws WrongChromaSize { // this.values = new float[Chromanal.CHROMA_LENGTH]; // if (chroma.length != Chromanal.CHROMA_LENGTH) { // throw new WrongChromaSize("Wrong Chroma size"); // } // System.arraycopy(chroma, 0, values, 0, Chromanal.CHROMA_LENGTH - 1); // } // // /* Public / Package methods */ // // /* Private methods */ // } // // Path: src/main/java/org/harmony_analyser/jharmonyanalyser/plugins/LineChartPlugin.java // @SuppressWarnings("SameParameterValue") // // public abstract class LineChartPlugin extends AnalysisPlugin { // public VisualizationData getDataFromOutput(String inputWavFile) throws IOException, AudioAnalyser.OutputNotReady, AudioAnalyser.ParseOutputError, AudioAnalyser.IncorrectInputException, AudioAnalyser.OutputAlreadyExists { // VisualizationData data = super.prepareVisualizationData(); // List<Float> timestamps = new ArrayList<>(); // List<Float> values = new ArrayList<>(); // List<String> linesList = readOutputFile(inputWavFile); // // float timestamp, value; // // /* Plugin-specific parsing of the result */ // try { // for (String line : linesList) { // timestamp = AudioAnalysisHelper.getTimestampFromLine(line); // value = Float.parseFloat(AudioAnalysisHelper.getLabelFromLine(line)); // timestamps.add(timestamp); // values.add(value); // } // } catch (NumberFormatException e) { // throw new AudioAnalyser.ParseOutputError("Output did not have the required fields"); // } // data.setTimestamps(timestamps); // data.setValues(values); // return data; // } // } // Path: src/main/java/org/harmony_analyser/jharmonyanalyser/plugins/chromanal_plugins/ChromaAnalyserPlugin.java import org.harmony_analyser.jharmonyanalyser.services.*; import org.harmony_analyser.jharmonyanalyser.chroma_analyser.Chroma; import org.harmony_analyser.jharmonyanalyser.plugins.LineChartPlugin; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; import java.util.ArrayList; import java.util.List; package org.harmony_analyser.jharmonyanalyser.plugins.chromanal_plugins; /** * Abstract class for chrama complexity plugins */ @SuppressWarnings("SameParameterValue") abstract class ChromaAnalyserPlugin extends LineChartPlugin { protected static float audibleThreshold = (float) 0.07; // used to filter chroma activations that we consider not audible /** * Analyzes the song: converts chroma information to chroma complexity descriptors * * @param inputFile [String] name of the WAV audio file * These additional files are expected in the folder * - chromaFile: name of the file containing chroma information (suffix: -chromas.txt) */
public String analyse(String inputFile, boolean force) throws IOException, AudioAnalyser.IncorrectInputException, AudioAnalyser.OutputAlreadyExists, Chroma.WrongChromaSize {
lacimarsik/harmony-analyser
src/main/java/org/harmony_analyser/jharmonyanalyser/plugins/LineChartPlugin.java
// Path: src/main/java/org/harmony_analyser/application/visualizations/VisualizationData.java // public class VisualizationData { // private String pluginName; // private List<Float> timestamps; // private List<Float> values; // private List<String> labels; // // public final static VisualizationData EMPTY_VISUALIZATION_DATA = new VisualizationData(); // // public VisualizationData() { // setTimestamps(new ArrayList<>()); // setValues(new ArrayList<>()); // setLabels(new ArrayList<>()); // } // // List<Float> getTimestamps() { // return timestamps; // } // // public List<Float> getValues() { // return values; // } // // List<String> getLabels() { // return labels; // } // // String getPluginName() { // return pluginName; // } // // public void setTimestamps(List<Float> timestamps) { // this.timestamps = timestamps; // } // // public void setValues(List<Float> values) { // this.values = values; // } // // public void setLabels(List<String> labels) { // this.labels = labels; // } // // public void setPluginName(String pluginName) { // this.pluginName = pluginName; // } // }
import org.harmony_analyser.jharmonyanalyser.services.*; import org.harmony_analyser.application.visualizations.VisualizationData; import java.io.IOException; import java.util.ArrayList; import java.util.List;
package org.harmony_analyser.jharmonyanalyser.plugins; /** * Abstract class for plugins that support line chart visualization */ @SuppressWarnings("SameParameterValue") public abstract class LineChartPlugin extends AnalysisPlugin {
// Path: src/main/java/org/harmony_analyser/application/visualizations/VisualizationData.java // public class VisualizationData { // private String pluginName; // private List<Float> timestamps; // private List<Float> values; // private List<String> labels; // // public final static VisualizationData EMPTY_VISUALIZATION_DATA = new VisualizationData(); // // public VisualizationData() { // setTimestamps(new ArrayList<>()); // setValues(new ArrayList<>()); // setLabels(new ArrayList<>()); // } // // List<Float> getTimestamps() { // return timestamps; // } // // public List<Float> getValues() { // return values; // } // // List<String> getLabels() { // return labels; // } // // String getPluginName() { // return pluginName; // } // // public void setTimestamps(List<Float> timestamps) { // this.timestamps = timestamps; // } // // public void setValues(List<Float> values) { // this.values = values; // } // // public void setLabels(List<String> labels) { // this.labels = labels; // } // // public void setPluginName(String pluginName) { // this.pluginName = pluginName; // } // } // Path: src/main/java/org/harmony_analyser/jharmonyanalyser/plugins/LineChartPlugin.java import org.harmony_analyser.jharmonyanalyser.services.*; import org.harmony_analyser.application.visualizations.VisualizationData; import java.io.IOException; import java.util.ArrayList; import java.util.List; package org.harmony_analyser.jharmonyanalyser.plugins; /** * Abstract class for plugins that support line chart visualization */ @SuppressWarnings("SameParameterValue") public abstract class LineChartPlugin extends AnalysisPlugin {
public VisualizationData getDataFromOutput(String inputWavFile) throws IOException, AudioAnalyser.OutputNotReady, AudioAnalyser.ParseOutputError, AudioAnalyser.IncorrectInputException, AudioAnalyser.OutputAlreadyExists {
lacimarsik/harmony-analyser
src/main/java/org/harmony_analyser/jharmonyanalyser/plugins/chordanal_plugins/ChordAnalyserPlugin.java
// Path: src/main/java/org/harmony_analyser/jharmonyanalyser/chroma_analyser/Chroma.java // @SuppressWarnings({"SameParameterValue", "WeakerAccess"}) // // public class Chroma { // public final float[] values; // // public static final Chroma EMPTY_CHROMA = new Chroma(); // // /* Exceptions */ // // public class WrongChromaSize extends Exception { // public WrongChromaSize(String message) { // super(message); // } // } // // public Chroma() { // this.values = new float[0]; // } // // public Chroma(float[] chroma) throws WrongChromaSize { // this.values = new float[Chromanal.CHROMA_LENGTH]; // if (chroma.length != Chromanal.CHROMA_LENGTH) { // throw new WrongChromaSize("Wrong Chroma size"); // } // System.arraycopy(chroma, 0, values, 0, Chromanal.CHROMA_LENGTH - 1); // } // // /* Public / Package methods */ // // /* Private methods */ // } // // Path: src/main/java/org/harmony_analyser/jharmonyanalyser/plugins/LineChartPlugin.java // @SuppressWarnings("SameParameterValue") // // public abstract class LineChartPlugin extends AnalysisPlugin { // public VisualizationData getDataFromOutput(String inputWavFile) throws IOException, AudioAnalyser.OutputNotReady, AudioAnalyser.ParseOutputError, AudioAnalyser.IncorrectInputException, AudioAnalyser.OutputAlreadyExists { // VisualizationData data = super.prepareVisualizationData(); // List<Float> timestamps = new ArrayList<>(); // List<Float> values = new ArrayList<>(); // List<String> linesList = readOutputFile(inputWavFile); // // float timestamp, value; // // /* Plugin-specific parsing of the result */ // try { // for (String line : linesList) { // timestamp = AudioAnalysisHelper.getTimestampFromLine(line); // value = Float.parseFloat(AudioAnalysisHelper.getLabelFromLine(line)); // timestamps.add(timestamp); // values.add(value); // } // } catch (NumberFormatException e) { // throw new AudioAnalyser.ParseOutputError("Output did not have the required fields"); // } // data.setTimestamps(timestamps); // data.setValues(values); // return data; // } // }
import org.harmony_analyser.jharmonyanalyser.services.*; import org.harmony_analyser.jharmonyanalyser.chord_analyser.*; import org.harmony_analyser.jharmonyanalyser.chroma_analyser.Chroma; import org.harmony_analyser.jharmonyanalyser.plugins.LineChartPlugin; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; import java.util.*; import java.util.stream.Collectors;
package org.harmony_analyser.jharmonyanalyser.plugins.chordanal_plugins; /** * Abstract class for chord_analyser plugins */ @SuppressWarnings("SameParameterValue") abstract class ChordAnalyserPlugin extends LineChartPlugin { private static float audibleThreshold = (float) 0.07; // used to filter chroma activations that we consider not audible private static int maximumNumberOfChordTones = 4; // used to limit number of tones we work with in chord private static int maximalComplexity = 7; // used to assign a maximal value for 2 chords that have no common root /** * Analyzes the song: converts chroma + segmentation information to harmony complexity descriptors * * @param inputFile [String] name of the WAV audio file * These additional files are expected in the folder * - chroma file: name of the file containing chroma information (suffix: -chromas.txt) * - segmentation file: name of the file containing segmentation information (suffix: -chordino-labels.txt, historically, since we have used Chordino segments) */
// Path: src/main/java/org/harmony_analyser/jharmonyanalyser/chroma_analyser/Chroma.java // @SuppressWarnings({"SameParameterValue", "WeakerAccess"}) // // public class Chroma { // public final float[] values; // // public static final Chroma EMPTY_CHROMA = new Chroma(); // // /* Exceptions */ // // public class WrongChromaSize extends Exception { // public WrongChromaSize(String message) { // super(message); // } // } // // public Chroma() { // this.values = new float[0]; // } // // public Chroma(float[] chroma) throws WrongChromaSize { // this.values = new float[Chromanal.CHROMA_LENGTH]; // if (chroma.length != Chromanal.CHROMA_LENGTH) { // throw new WrongChromaSize("Wrong Chroma size"); // } // System.arraycopy(chroma, 0, values, 0, Chromanal.CHROMA_LENGTH - 1); // } // // /* Public / Package methods */ // // /* Private methods */ // } // // Path: src/main/java/org/harmony_analyser/jharmonyanalyser/plugins/LineChartPlugin.java // @SuppressWarnings("SameParameterValue") // // public abstract class LineChartPlugin extends AnalysisPlugin { // public VisualizationData getDataFromOutput(String inputWavFile) throws IOException, AudioAnalyser.OutputNotReady, AudioAnalyser.ParseOutputError, AudioAnalyser.IncorrectInputException, AudioAnalyser.OutputAlreadyExists { // VisualizationData data = super.prepareVisualizationData(); // List<Float> timestamps = new ArrayList<>(); // List<Float> values = new ArrayList<>(); // List<String> linesList = readOutputFile(inputWavFile); // // float timestamp, value; // // /* Plugin-specific parsing of the result */ // try { // for (String line : linesList) { // timestamp = AudioAnalysisHelper.getTimestampFromLine(line); // value = Float.parseFloat(AudioAnalysisHelper.getLabelFromLine(line)); // timestamps.add(timestamp); // values.add(value); // } // } catch (NumberFormatException e) { // throw new AudioAnalyser.ParseOutputError("Output did not have the required fields"); // } // data.setTimestamps(timestamps); // data.setValues(values); // return data; // } // } // Path: src/main/java/org/harmony_analyser/jharmonyanalyser/plugins/chordanal_plugins/ChordAnalyserPlugin.java import org.harmony_analyser.jharmonyanalyser.services.*; import org.harmony_analyser.jharmonyanalyser.chord_analyser.*; import org.harmony_analyser.jharmonyanalyser.chroma_analyser.Chroma; import org.harmony_analyser.jharmonyanalyser.plugins.LineChartPlugin; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; import java.util.*; import java.util.stream.Collectors; package org.harmony_analyser.jharmonyanalyser.plugins.chordanal_plugins; /** * Abstract class for chord_analyser plugins */ @SuppressWarnings("SameParameterValue") abstract class ChordAnalyserPlugin extends LineChartPlugin { private static float audibleThreshold = (float) 0.07; // used to filter chroma activations that we consider not audible private static int maximumNumberOfChordTones = 4; // used to limit number of tones we work with in chord private static int maximalComplexity = 7; // used to assign a maximal value for 2 chords that have no common root /** * Analyzes the song: converts chroma + segmentation information to harmony complexity descriptors * * @param inputFile [String] name of the WAV audio file * These additional files are expected in the folder * - chroma file: name of the file containing chroma information (suffix: -chromas.txt) * - segmentation file: name of the file containing segmentation information (suffix: -chordino-labels.txt, historically, since we have used Chordino segments) */
public String analyse(String inputFile, boolean force) throws IOException, AudioAnalyser.IncorrectInputException, AudioAnalyser.OutputAlreadyExists, Chroma.WrongChromaSize {
lacimarsik/harmony-analyser
src/test/java/org/harmony_analyser/jharmonyanalyser/services/AudioAnalyserTest.java
// Path: src/main/java/org/harmony_analyser/application/visualizations/DataChartFactory.java // public class DataChartFactory { // private final String[] ALL_VISUALIZATIONS = new String[] { // "nnls-chroma:chordino-labels", // "qm-vamp-plugins:qm-keydetector", // "chord_analyser:average_chord_complexity_distance", // "chord_analyser:chord_complexity_distance", // "chord_analyser:tps_distance", // "chroma_analyser:simple_difference", // "chroma_analyser:complexity_difference", // }; // // public String[] getAllVisualizations() { // return ALL_VISUALIZATIONS; // } // // public DataChart createDataChart(String analysisKey, VisualizationData visualizationData) { // switch (analysisKey) { // case "nnls-chroma:chordino-labels": // case "qm-vamp-plugins:qm-keydetector": // return new SegmentationDataChart(visualizationData); // case "chord_analyser:average_chord_complexity_distance": // return new AveragesDataChart(visualizationData); // case "chord_analyser:chord_complexity_distance": // case "chroma_analyser:simple_difference": // case "chroma_analyser:complexity_difference": // case "chord_analyser:tps_distance": // return new LineDataChart(visualizationData); // default: // return new EmptyDataChart(VisualizationData.EMPTY_VISUALIZATION_DATA); // } // } // } // // Path: src/main/java/org/harmony_analyser/jharmonyanalyser/chroma_analyser/Chroma.java // @SuppressWarnings({"SameParameterValue", "WeakerAccess"}) // // public class Chroma { // public final float[] values; // // public static final Chroma EMPTY_CHROMA = new Chroma(); // // /* Exceptions */ // // public class WrongChromaSize extends Exception { // public WrongChromaSize(String message) { // super(message); // } // } // // public Chroma() { // this.values = new float[0]; // } // // public Chroma(float[] chroma) throws WrongChromaSize { // this.values = new float[Chromanal.CHROMA_LENGTH]; // if (chroma.length != Chromanal.CHROMA_LENGTH) { // throw new WrongChromaSize("Wrong Chroma size"); // } // System.arraycopy(chroma, 0, values, 0, Chromanal.CHROMA_LENGTH - 1); // } // // /* Public / Package methods */ // // /* Private methods */ // }
import org.harmony_analyser.application.visualizations.DataChartFactory; import org.harmony_analyser.jharmonyanalyser.chroma_analyser.Chroma; import org.harmony_analyser.jharmonyanalyser.plugins.*; import static org.mockito.Mockito.*; import java.io.*; import org.junit.*; import static org.junit.Assert.assertEquals;
package org.harmony_analyser.jharmonyanalyser.services; /** * Unit tests for AudioAnalyser class */ @SuppressWarnings("ConstantConditions") public class AudioAnalyserTest { private AudioAnalyser audioAnalyser;
// Path: src/main/java/org/harmony_analyser/application/visualizations/DataChartFactory.java // public class DataChartFactory { // private final String[] ALL_VISUALIZATIONS = new String[] { // "nnls-chroma:chordino-labels", // "qm-vamp-plugins:qm-keydetector", // "chord_analyser:average_chord_complexity_distance", // "chord_analyser:chord_complexity_distance", // "chord_analyser:tps_distance", // "chroma_analyser:simple_difference", // "chroma_analyser:complexity_difference", // }; // // public String[] getAllVisualizations() { // return ALL_VISUALIZATIONS; // } // // public DataChart createDataChart(String analysisKey, VisualizationData visualizationData) { // switch (analysisKey) { // case "nnls-chroma:chordino-labels": // case "qm-vamp-plugins:qm-keydetector": // return new SegmentationDataChart(visualizationData); // case "chord_analyser:average_chord_complexity_distance": // return new AveragesDataChart(visualizationData); // case "chord_analyser:chord_complexity_distance": // case "chroma_analyser:simple_difference": // case "chroma_analyser:complexity_difference": // case "chord_analyser:tps_distance": // return new LineDataChart(visualizationData); // default: // return new EmptyDataChart(VisualizationData.EMPTY_VISUALIZATION_DATA); // } // } // } // // Path: src/main/java/org/harmony_analyser/jharmonyanalyser/chroma_analyser/Chroma.java // @SuppressWarnings({"SameParameterValue", "WeakerAccess"}) // // public class Chroma { // public final float[] values; // // public static final Chroma EMPTY_CHROMA = new Chroma(); // // /* Exceptions */ // // public class WrongChromaSize extends Exception { // public WrongChromaSize(String message) { // super(message); // } // } // // public Chroma() { // this.values = new float[0]; // } // // public Chroma(float[] chroma) throws WrongChromaSize { // this.values = new float[Chromanal.CHROMA_LENGTH]; // if (chroma.length != Chromanal.CHROMA_LENGTH) { // throw new WrongChromaSize("Wrong Chroma size"); // } // System.arraycopy(chroma, 0, values, 0, Chromanal.CHROMA_LENGTH - 1); // } // // /* Public / Package methods */ // // /* Private methods */ // } // Path: src/test/java/org/harmony_analyser/jharmonyanalyser/services/AudioAnalyserTest.java import org.harmony_analyser.application.visualizations.DataChartFactory; import org.harmony_analyser.jharmonyanalyser.chroma_analyser.Chroma; import org.harmony_analyser.jharmonyanalyser.plugins.*; import static org.mockito.Mockito.*; import java.io.*; import org.junit.*; import static org.junit.Assert.assertEquals; package org.harmony_analyser.jharmonyanalyser.services; /** * Unit tests for AudioAnalyser class */ @SuppressWarnings("ConstantConditions") public class AudioAnalyserTest { private AudioAnalyser audioAnalyser;
private DataChartFactory dataChartFactory;
lacimarsik/harmony-analyser
src/test/java/org/harmony_analyser/jharmonyanalyser/services/AudioAnalyserTest.java
// Path: src/main/java/org/harmony_analyser/application/visualizations/DataChartFactory.java // public class DataChartFactory { // private final String[] ALL_VISUALIZATIONS = new String[] { // "nnls-chroma:chordino-labels", // "qm-vamp-plugins:qm-keydetector", // "chord_analyser:average_chord_complexity_distance", // "chord_analyser:chord_complexity_distance", // "chord_analyser:tps_distance", // "chroma_analyser:simple_difference", // "chroma_analyser:complexity_difference", // }; // // public String[] getAllVisualizations() { // return ALL_VISUALIZATIONS; // } // // public DataChart createDataChart(String analysisKey, VisualizationData visualizationData) { // switch (analysisKey) { // case "nnls-chroma:chordino-labels": // case "qm-vamp-plugins:qm-keydetector": // return new SegmentationDataChart(visualizationData); // case "chord_analyser:average_chord_complexity_distance": // return new AveragesDataChart(visualizationData); // case "chord_analyser:chord_complexity_distance": // case "chroma_analyser:simple_difference": // case "chroma_analyser:complexity_difference": // case "chord_analyser:tps_distance": // return new LineDataChart(visualizationData); // default: // return new EmptyDataChart(VisualizationData.EMPTY_VISUALIZATION_DATA); // } // } // } // // Path: src/main/java/org/harmony_analyser/jharmonyanalyser/chroma_analyser/Chroma.java // @SuppressWarnings({"SameParameterValue", "WeakerAccess"}) // // public class Chroma { // public final float[] values; // // public static final Chroma EMPTY_CHROMA = new Chroma(); // // /* Exceptions */ // // public class WrongChromaSize extends Exception { // public WrongChromaSize(String message) { // super(message); // } // } // // public Chroma() { // this.values = new float[0]; // } // // public Chroma(float[] chroma) throws WrongChromaSize { // this.values = new float[Chromanal.CHROMA_LENGTH]; // if (chroma.length != Chromanal.CHROMA_LENGTH) { // throw new WrongChromaSize("Wrong Chroma size"); // } // System.arraycopy(chroma, 0, values, 0, Chromanal.CHROMA_LENGTH - 1); // } // // /* Public / Package methods */ // // /* Private methods */ // }
import org.harmony_analyser.application.visualizations.DataChartFactory; import org.harmony_analyser.jharmonyanalyser.chroma_analyser.Chroma; import org.harmony_analyser.jharmonyanalyser.plugins.*; import static org.mockito.Mockito.*; import java.io.*; import org.junit.*; import static org.junit.Assert.assertEquals;
package org.harmony_analyser.jharmonyanalyser.services; /** * Unit tests for AudioAnalyser class */ @SuppressWarnings("ConstantConditions") public class AudioAnalyserTest { private AudioAnalyser audioAnalyser; private DataChartFactory dataChartFactory; private String wrongInputFile; private File testWavFile, testReportFixture; private String resultFile; @Before public void setUp() { dataChartFactory = new DataChartFactory(); wrongInputFile = "wrongfile"; ClassLoader classLoader = getClass().getClassLoader(); testWavFile = new File(classLoader.getResource("test.wav").getPath()); testReportFixture = new File(classLoader.getResource("test-printAnalysisFixture.txt").getPath()); } @Test(expected = AudioAnalyser.IncorrectInputException.class)
// Path: src/main/java/org/harmony_analyser/application/visualizations/DataChartFactory.java // public class DataChartFactory { // private final String[] ALL_VISUALIZATIONS = new String[] { // "nnls-chroma:chordino-labels", // "qm-vamp-plugins:qm-keydetector", // "chord_analyser:average_chord_complexity_distance", // "chord_analyser:chord_complexity_distance", // "chord_analyser:tps_distance", // "chroma_analyser:simple_difference", // "chroma_analyser:complexity_difference", // }; // // public String[] getAllVisualizations() { // return ALL_VISUALIZATIONS; // } // // public DataChart createDataChart(String analysisKey, VisualizationData visualizationData) { // switch (analysisKey) { // case "nnls-chroma:chordino-labels": // case "qm-vamp-plugins:qm-keydetector": // return new SegmentationDataChart(visualizationData); // case "chord_analyser:average_chord_complexity_distance": // return new AveragesDataChart(visualizationData); // case "chord_analyser:chord_complexity_distance": // case "chroma_analyser:simple_difference": // case "chroma_analyser:complexity_difference": // case "chord_analyser:tps_distance": // return new LineDataChart(visualizationData); // default: // return new EmptyDataChart(VisualizationData.EMPTY_VISUALIZATION_DATA); // } // } // } // // Path: src/main/java/org/harmony_analyser/jharmonyanalyser/chroma_analyser/Chroma.java // @SuppressWarnings({"SameParameterValue", "WeakerAccess"}) // // public class Chroma { // public final float[] values; // // public static final Chroma EMPTY_CHROMA = new Chroma(); // // /* Exceptions */ // // public class WrongChromaSize extends Exception { // public WrongChromaSize(String message) { // super(message); // } // } // // public Chroma() { // this.values = new float[0]; // } // // public Chroma(float[] chroma) throws WrongChromaSize { // this.values = new float[Chromanal.CHROMA_LENGTH]; // if (chroma.length != Chromanal.CHROMA_LENGTH) { // throw new WrongChromaSize("Wrong Chroma size"); // } // System.arraycopy(chroma, 0, values, 0, Chromanal.CHROMA_LENGTH - 1); // } // // /* Public / Package methods */ // // /* Private methods */ // } // Path: src/test/java/org/harmony_analyser/jharmonyanalyser/services/AudioAnalyserTest.java import org.harmony_analyser.application.visualizations.DataChartFactory; import org.harmony_analyser.jharmonyanalyser.chroma_analyser.Chroma; import org.harmony_analyser.jharmonyanalyser.plugins.*; import static org.mockito.Mockito.*; import java.io.*; import org.junit.*; import static org.junit.Assert.assertEquals; package org.harmony_analyser.jharmonyanalyser.services; /** * Unit tests for AudioAnalyser class */ @SuppressWarnings("ConstantConditions") public class AudioAnalyserTest { private AudioAnalyser audioAnalyser; private DataChartFactory dataChartFactory; private String wrongInputFile; private File testWavFile, testReportFixture; private String resultFile; @Before public void setUp() { dataChartFactory = new DataChartFactory(); wrongInputFile = "wrongfile"; ClassLoader classLoader = getClass().getClassLoader(); testWavFile = new File(classLoader.getResource("test.wav").getPath()); testReportFixture = new File(classLoader.getResource("test-printAnalysisFixture.txt").getPath()); } @Test(expected = AudioAnalyser.IncorrectInputException.class)
public void shouldThrowExceptionOnWrongFile() throws IOException, AudioAnalyser.LoadFailedException, AudioAnalyser.IncorrectInputException, AudioAnalyser.OutputAlreadyExists, Chroma.WrongChromaSize {
lacimarsik/harmony-analyser
src/main/java/org/harmony_analyser/application/AudioAnalysisToolController.java
// Path: src/main/java/org/harmony_analyser/application/visualizations/DataChartFactory.java // public class DataChartFactory { // private final String[] ALL_VISUALIZATIONS = new String[] { // "nnls-chroma:chordino-labels", // "qm-vamp-plugins:qm-keydetector", // "chord_analyser:average_chord_complexity_distance", // "chord_analyser:chord_complexity_distance", // "chord_analyser:tps_distance", // "chroma_analyser:simple_difference", // "chroma_analyser:complexity_difference", // }; // // public String[] getAllVisualizations() { // return ALL_VISUALIZATIONS; // } // // public DataChart createDataChart(String analysisKey, VisualizationData visualizationData) { // switch (analysisKey) { // case "nnls-chroma:chordino-labels": // case "qm-vamp-plugins:qm-keydetector": // return new SegmentationDataChart(visualizationData); // case "chord_analyser:average_chord_complexity_distance": // return new AveragesDataChart(visualizationData); // case "chord_analyser:chord_complexity_distance": // case "chroma_analyser:simple_difference": // case "chroma_analyser:complexity_difference": // case "chord_analyser:tps_distance": // return new LineDataChart(visualizationData); // default: // return new EmptyDataChart(VisualizationData.EMPTY_VISUALIZATION_DATA); // } // } // }
import javafx.collections.*; import javafx.event.ActionEvent; import javafx.fxml.*; import javafx.scene.control.*; import javafx.scene.layout.StackPane; import java.io.*; import java.net.URL; import java.nio.file.*; import java.nio.file.attribute.BasicFileAttributes; import java.util.ResourceBundle; import org.harmony_analyser.application.visualizations.DataChartFactory; import org.harmony_analyser.jharmonyanalyser.services.*;
@FXML private Button chrSettings; @FXML private Button chrAnalyse; @FXML private ListView<String> ppAvailable; @FXML private Label ppTitle; @FXML private Label ppDescription; @FXML private Button ppSettings; @FXML private Button ppAnalyse; @FXML private TextField ppExtension; private AudioAnalyser audioAnalyser; @Override // This method is called by the FXMLLoader when initialization is complete public void initialize(URL fxmlFileLocation, ResourceBundle resources) { //initialize AudioAnalyser AnalysisFactory analysisFactory = new AnalysisFactory();
// Path: src/main/java/org/harmony_analyser/application/visualizations/DataChartFactory.java // public class DataChartFactory { // private final String[] ALL_VISUALIZATIONS = new String[] { // "nnls-chroma:chordino-labels", // "qm-vamp-plugins:qm-keydetector", // "chord_analyser:average_chord_complexity_distance", // "chord_analyser:chord_complexity_distance", // "chord_analyser:tps_distance", // "chroma_analyser:simple_difference", // "chroma_analyser:complexity_difference", // }; // // public String[] getAllVisualizations() { // return ALL_VISUALIZATIONS; // } // // public DataChart createDataChart(String analysisKey, VisualizationData visualizationData) { // switch (analysisKey) { // case "nnls-chroma:chordino-labels": // case "qm-vamp-plugins:qm-keydetector": // return new SegmentationDataChart(visualizationData); // case "chord_analyser:average_chord_complexity_distance": // return new AveragesDataChart(visualizationData); // case "chord_analyser:chord_complexity_distance": // case "chroma_analyser:simple_difference": // case "chroma_analyser:complexity_difference": // case "chord_analyser:tps_distance": // return new LineDataChart(visualizationData); // default: // return new EmptyDataChart(VisualizationData.EMPTY_VISUALIZATION_DATA); // } // } // } // Path: src/main/java/org/harmony_analyser/application/AudioAnalysisToolController.java import javafx.collections.*; import javafx.event.ActionEvent; import javafx.fxml.*; import javafx.scene.control.*; import javafx.scene.layout.StackPane; import java.io.*; import java.net.URL; import java.nio.file.*; import java.nio.file.attribute.BasicFileAttributes; import java.util.ResourceBundle; import org.harmony_analyser.application.visualizations.DataChartFactory; import org.harmony_analyser.jharmonyanalyser.services.*; @FXML private Button chrSettings; @FXML private Button chrAnalyse; @FXML private ListView<String> ppAvailable; @FXML private Label ppTitle; @FXML private Label ppDescription; @FXML private Button ppSettings; @FXML private Button ppAnalyse; @FXML private TextField ppExtension; private AudioAnalyser audioAnalyser; @Override // This method is called by the FXMLLoader when initialization is complete public void initialize(URL fxmlFileLocation, ResourceBundle resources) { //initialize AudioAnalyser AnalysisFactory analysisFactory = new AnalysisFactory();
DataChartFactory dataChartFactory = new DataChartFactory();
lacimarsik/harmony-analyser
src/main/java/org/harmony_analyser/jharmonyanalyser/filters/TimeSeriesFilter.java
// Path: src/main/java/org/harmony_analyser/application/visualizations/VisualizationData.java // public class VisualizationData { // private String pluginName; // private List<Float> timestamps; // private List<Float> values; // private List<String> labels; // // public final static VisualizationData EMPTY_VISUALIZATION_DATA = new VisualizationData(); // // public VisualizationData() { // setTimestamps(new ArrayList<>()); // setValues(new ArrayList<>()); // setLabels(new ArrayList<>()); // } // // List<Float> getTimestamps() { // return timestamps; // } // // public List<Float> getValues() { // return values; // } // // List<String> getLabels() { // return labels; // } // // String getPluginName() { // return pluginName; // } // // public void setTimestamps(List<Float> timestamps) { // this.timestamps = timestamps; // } // // public void setValues(List<Float> values) { // this.values = values; // } // // public void setLabels(List<String> labels) { // this.labels = labels; // } // // public void setPluginName(String pluginName) { // this.pluginName = pluginName; // } // } // // Path: src/main/java/org/harmony_analyser/jharmonyanalyser/chroma_analyser/Chroma.java // @SuppressWarnings({"SameParameterValue", "WeakerAccess"}) // // public class Chroma { // public final float[] values; // // public static final Chroma EMPTY_CHROMA = new Chroma(); // // /* Exceptions */ // // public class WrongChromaSize extends Exception { // public WrongChromaSize(String message) { // super(message); // } // } // // public Chroma() { // this.values = new float[0]; // } // // public Chroma(float[] chroma) throws WrongChromaSize { // this.values = new float[Chromanal.CHROMA_LENGTH]; // if (chroma.length != Chromanal.CHROMA_LENGTH) { // throw new WrongChromaSize("Wrong Chroma size"); // } // System.arraycopy(chroma, 0, values, 0, Chromanal.CHROMA_LENGTH - 1); // } // // /* Public / Package methods */ // // /* Private methods */ // }
import org.harmony_analyser.application.visualizations.VisualizationData; import org.harmony_analyser.jharmonyanalyser.chroma_analyser.Chroma; import org.harmony_analyser.jharmonyanalyser.services.*; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.stream.Collectors;
package org.harmony_analyser.jharmonyanalyser.filters; /** * Filter to convert outputs: create a time series from a timestamp-based text file containting a XY-plot in the way that the plot lines remains the same */ /* * TimeSeriesFilter * * - requires: Time series in the form timestamp: value * - creates a time series with a fixed sampling rate */ @SuppressWarnings("SameParameterValue") public class TimeSeriesFilter extends AnalysisFilter { private float samplingRate; public TimeSeriesFilter() { key = "filters:time_series"; name = "Timestamp to time series filter"; description = "Takes 'timestamp: value' time series, and transforms it into fixed sample-rate time series preserving the lines"; inputFileSuffixes = new ArrayList<>(); inputFileSuffixes.add(""); // no suffix, arbitrary input file is allowed inputFileExtension = ".txt"; outputFileSuffix = "-series"; outputFileExtension = ".txt"; parameters = new HashMap<>(); parameters.put("samplingRate", (float) 100); setParameters(); } /** * Filters the result text file, creating a fixed sampling rate time series */
// Path: src/main/java/org/harmony_analyser/application/visualizations/VisualizationData.java // public class VisualizationData { // private String pluginName; // private List<Float> timestamps; // private List<Float> values; // private List<String> labels; // // public final static VisualizationData EMPTY_VISUALIZATION_DATA = new VisualizationData(); // // public VisualizationData() { // setTimestamps(new ArrayList<>()); // setValues(new ArrayList<>()); // setLabels(new ArrayList<>()); // } // // List<Float> getTimestamps() { // return timestamps; // } // // public List<Float> getValues() { // return values; // } // // List<String> getLabels() { // return labels; // } // // String getPluginName() { // return pluginName; // } // // public void setTimestamps(List<Float> timestamps) { // this.timestamps = timestamps; // } // // public void setValues(List<Float> values) { // this.values = values; // } // // public void setLabels(List<String> labels) { // this.labels = labels; // } // // public void setPluginName(String pluginName) { // this.pluginName = pluginName; // } // } // // Path: src/main/java/org/harmony_analyser/jharmonyanalyser/chroma_analyser/Chroma.java // @SuppressWarnings({"SameParameterValue", "WeakerAccess"}) // // public class Chroma { // public final float[] values; // // public static final Chroma EMPTY_CHROMA = new Chroma(); // // /* Exceptions */ // // public class WrongChromaSize extends Exception { // public WrongChromaSize(String message) { // super(message); // } // } // // public Chroma() { // this.values = new float[0]; // } // // public Chroma(float[] chroma) throws WrongChromaSize { // this.values = new float[Chromanal.CHROMA_LENGTH]; // if (chroma.length != Chromanal.CHROMA_LENGTH) { // throw new WrongChromaSize("Wrong Chroma size"); // } // System.arraycopy(chroma, 0, values, 0, Chromanal.CHROMA_LENGTH - 1); // } // // /* Public / Package methods */ // // /* Private methods */ // } // Path: src/main/java/org/harmony_analyser/jharmonyanalyser/filters/TimeSeriesFilter.java import org.harmony_analyser.application.visualizations.VisualizationData; import org.harmony_analyser.jharmonyanalyser.chroma_analyser.Chroma; import org.harmony_analyser.jharmonyanalyser.services.*; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.stream.Collectors; package org.harmony_analyser.jharmonyanalyser.filters; /** * Filter to convert outputs: create a time series from a timestamp-based text file containting a XY-plot in the way that the plot lines remains the same */ /* * TimeSeriesFilter * * - requires: Time series in the form timestamp: value * - creates a time series with a fixed sampling rate */ @SuppressWarnings("SameParameterValue") public class TimeSeriesFilter extends AnalysisFilter { private float samplingRate; public TimeSeriesFilter() { key = "filters:time_series"; name = "Timestamp to time series filter"; description = "Takes 'timestamp: value' time series, and transforms it into fixed sample-rate time series preserving the lines"; inputFileSuffixes = new ArrayList<>(); inputFileSuffixes.add(""); // no suffix, arbitrary input file is allowed inputFileExtension = ".txt"; outputFileSuffix = "-series"; outputFileExtension = ".txt"; parameters = new HashMap<>(); parameters.put("samplingRate", (float) 100); setParameters(); } /** * Filters the result text file, creating a fixed sampling rate time series */
public String analyse(String inputFile, boolean force) throws IOException, AudioAnalyser.IncorrectInputException, Chroma.WrongChromaSize, AudioAnalyser.OutputAlreadyExists {
lacimarsik/harmony-analyser
src/main/java/org/harmony_analyser/jharmonyanalyser/filters/TimeSeriesFilter.java
// Path: src/main/java/org/harmony_analyser/application/visualizations/VisualizationData.java // public class VisualizationData { // private String pluginName; // private List<Float> timestamps; // private List<Float> values; // private List<String> labels; // // public final static VisualizationData EMPTY_VISUALIZATION_DATA = new VisualizationData(); // // public VisualizationData() { // setTimestamps(new ArrayList<>()); // setValues(new ArrayList<>()); // setLabels(new ArrayList<>()); // } // // List<Float> getTimestamps() { // return timestamps; // } // // public List<Float> getValues() { // return values; // } // // List<String> getLabels() { // return labels; // } // // String getPluginName() { // return pluginName; // } // // public void setTimestamps(List<Float> timestamps) { // this.timestamps = timestamps; // } // // public void setValues(List<Float> values) { // this.values = values; // } // // public void setLabels(List<String> labels) { // this.labels = labels; // } // // public void setPluginName(String pluginName) { // this.pluginName = pluginName; // } // } // // Path: src/main/java/org/harmony_analyser/jharmonyanalyser/chroma_analyser/Chroma.java // @SuppressWarnings({"SameParameterValue", "WeakerAccess"}) // // public class Chroma { // public final float[] values; // // public static final Chroma EMPTY_CHROMA = new Chroma(); // // /* Exceptions */ // // public class WrongChromaSize extends Exception { // public WrongChromaSize(String message) { // super(message); // } // } // // public Chroma() { // this.values = new float[0]; // } // // public Chroma(float[] chroma) throws WrongChromaSize { // this.values = new float[Chromanal.CHROMA_LENGTH]; // if (chroma.length != Chromanal.CHROMA_LENGTH) { // throw new WrongChromaSize("Wrong Chroma size"); // } // System.arraycopy(chroma, 0, values, 0, Chromanal.CHROMA_LENGTH - 1); // } // // /* Public / Package methods */ // // /* Private methods */ // }
import org.harmony_analyser.application.visualizations.VisualizationData; import org.harmony_analyser.jharmonyanalyser.chroma_analyser.Chroma; import org.harmony_analyser.jharmonyanalyser.services.*; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.stream.Collectors;
} // bump previous timestamp-value and continue previousTimestamp = timestamp; previousValue = value; index++; } else { // CASE 2: Timestamp difference lower than sample length // Omit the current timestamp-value pair and continue with the next one, leaving previous timestamp-value pair index++; } } // 4. Rewrite input file using new timestamps and values index = 0; BufferedWriter out = new BufferedWriter(new FileWriter(inputFile)); for (Float value : outputValuesList) { timestamp = outputTimestampList.get(index); out.write(timestamp + ": " + value + "\n"); index++; } out.close(); return result; } protected void setParameters() { samplingRate = parameters.get("samplingRate"); }
// Path: src/main/java/org/harmony_analyser/application/visualizations/VisualizationData.java // public class VisualizationData { // private String pluginName; // private List<Float> timestamps; // private List<Float> values; // private List<String> labels; // // public final static VisualizationData EMPTY_VISUALIZATION_DATA = new VisualizationData(); // // public VisualizationData() { // setTimestamps(new ArrayList<>()); // setValues(new ArrayList<>()); // setLabels(new ArrayList<>()); // } // // List<Float> getTimestamps() { // return timestamps; // } // // public List<Float> getValues() { // return values; // } // // List<String> getLabels() { // return labels; // } // // String getPluginName() { // return pluginName; // } // // public void setTimestamps(List<Float> timestamps) { // this.timestamps = timestamps; // } // // public void setValues(List<Float> values) { // this.values = values; // } // // public void setLabels(List<String> labels) { // this.labels = labels; // } // // public void setPluginName(String pluginName) { // this.pluginName = pluginName; // } // } // // Path: src/main/java/org/harmony_analyser/jharmonyanalyser/chroma_analyser/Chroma.java // @SuppressWarnings({"SameParameterValue", "WeakerAccess"}) // // public class Chroma { // public final float[] values; // // public static final Chroma EMPTY_CHROMA = new Chroma(); // // /* Exceptions */ // // public class WrongChromaSize extends Exception { // public WrongChromaSize(String message) { // super(message); // } // } // // public Chroma() { // this.values = new float[0]; // } // // public Chroma(float[] chroma) throws WrongChromaSize { // this.values = new float[Chromanal.CHROMA_LENGTH]; // if (chroma.length != Chromanal.CHROMA_LENGTH) { // throw new WrongChromaSize("Wrong Chroma size"); // } // System.arraycopy(chroma, 0, values, 0, Chromanal.CHROMA_LENGTH - 1); // } // // /* Public / Package methods */ // // /* Private methods */ // } // Path: src/main/java/org/harmony_analyser/jharmonyanalyser/filters/TimeSeriesFilter.java import org.harmony_analyser.application.visualizations.VisualizationData; import org.harmony_analyser.jharmonyanalyser.chroma_analyser.Chroma; import org.harmony_analyser.jharmonyanalyser.services.*; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.stream.Collectors; } // bump previous timestamp-value and continue previousTimestamp = timestamp; previousValue = value; index++; } else { // CASE 2: Timestamp difference lower than sample length // Omit the current timestamp-value pair and continue with the next one, leaving previous timestamp-value pair index++; } } // 4. Rewrite input file using new timestamps and values index = 0; BufferedWriter out = new BufferedWriter(new FileWriter(inputFile)); for (Float value : outputValuesList) { timestamp = outputTimestampList.get(index); out.write(timestamp + ": " + value + "\n"); index++; } out.close(); return result; } protected void setParameters() { samplingRate = parameters.get("samplingRate"); }
public VisualizationData getDataFromOutput(String inputWavFile) {
lacimarsik/harmony-analyser
src/test/java/org/harmony_analyser/jharmonyanalyser/plugins/vamp_plugins/NNLSPluginTest.java
// Path: src/main/java/org/harmony_analyser/jharmonyanalyser/chroma_analyser/Chroma.java // @SuppressWarnings({"SameParameterValue", "WeakerAccess"}) // // public class Chroma { // public final float[] values; // // public static final Chroma EMPTY_CHROMA = new Chroma(); // // /* Exceptions */ // // public class WrongChromaSize extends Exception { // public WrongChromaSize(String message) { // super(message); // } // } // // public Chroma() { // this.values = new float[0]; // } // // public Chroma(float[] chroma) throws WrongChromaSize { // this.values = new float[Chromanal.CHROMA_LENGTH]; // if (chroma.length != Chromanal.CHROMA_LENGTH) { // throw new WrongChromaSize("Wrong Chroma size"); // } // System.arraycopy(chroma, 0, values, 0, Chromanal.CHROMA_LENGTH - 1); // } // // /* Public / Package methods */ // // /* Private methods */ // }
import org.harmony_analyser.jharmonyanalyser.services.*; import org.harmony_analyser.jharmonyanalyser.chroma_analyser.Chroma; import org.junit.*; import java.io.*; import java.util.*; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals;
package org.harmony_analyser.jharmonyanalyser.plugins.vamp_plugins; /** * Unit tests for NNLSPlugin class */ @SuppressWarnings("ConstantConditions") public class NNLSPluginTest { private NNLSPlugin nnls; private File testWavFile; private List<String> inputFiles; @Before public void setUp() throws Exception { nnls = new NNLSPlugin(); ClassLoader classLoader = getClass().getClassLoader(); testWavFile = new File(classLoader.getResource("test.wav").getPath()); } @Test
// Path: src/main/java/org/harmony_analyser/jharmonyanalyser/chroma_analyser/Chroma.java // @SuppressWarnings({"SameParameterValue", "WeakerAccess"}) // // public class Chroma { // public final float[] values; // // public static final Chroma EMPTY_CHROMA = new Chroma(); // // /* Exceptions */ // // public class WrongChromaSize extends Exception { // public WrongChromaSize(String message) { // super(message); // } // } // // public Chroma() { // this.values = new float[0]; // } // // public Chroma(float[] chroma) throws WrongChromaSize { // this.values = new float[Chromanal.CHROMA_LENGTH]; // if (chroma.length != Chromanal.CHROMA_LENGTH) { // throw new WrongChromaSize("Wrong Chroma size"); // } // System.arraycopy(chroma, 0, values, 0, Chromanal.CHROMA_LENGTH - 1); // } // // /* Public / Package methods */ // // /* Private methods */ // } // Path: src/test/java/org/harmony_analyser/jharmonyanalyser/plugins/vamp_plugins/NNLSPluginTest.java import org.harmony_analyser.jharmonyanalyser.services.*; import org.harmony_analyser.jharmonyanalyser.chroma_analyser.Chroma; import org.junit.*; import java.io.*; import java.util.*; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; package org.harmony_analyser.jharmonyanalyser.plugins.vamp_plugins; /** * Unit tests for NNLSPlugin class */ @SuppressWarnings("ConstantConditions") public class NNLSPluginTest { private NNLSPlugin nnls; private File testWavFile; private List<String> inputFiles; @Before public void setUp() throws Exception { nnls = new NNLSPlugin(); ClassLoader classLoader = getClass().getClassLoader(); testWavFile = new File(classLoader.getResource("test.wav").getPath()); } @Test
public void shouldExtractChromas() throws IOException, AudioAnalyser.IncorrectInputException, AudioAnalyser.OutputAlreadyExists, Chroma.WrongChromaSize {
lacimarsik/harmony-analyser
src/main/java/org/harmony_analyser/cli_scripts/HarmonyAnalyserScript.java
// Path: src/main/java/org/harmony_analyser/application/visualizations/DataChartFactory.java // public class DataChartFactory { // private final String[] ALL_VISUALIZATIONS = new String[] { // "nnls-chroma:chordino-labels", // "qm-vamp-plugins:qm-keydetector", // "chord_analyser:average_chord_complexity_distance", // "chord_analyser:chord_complexity_distance", // "chord_analyser:tps_distance", // "chroma_analyser:simple_difference", // "chroma_analyser:complexity_difference", // }; // // public String[] getAllVisualizations() { // return ALL_VISUALIZATIONS; // } // // public DataChart createDataChart(String analysisKey, VisualizationData visualizationData) { // switch (analysisKey) { // case "nnls-chroma:chordino-labels": // case "qm-vamp-plugins:qm-keydetector": // return new SegmentationDataChart(visualizationData); // case "chord_analyser:average_chord_complexity_distance": // return new AveragesDataChart(visualizationData); // case "chord_analyser:chord_complexity_distance": // case "chroma_analyser:simple_difference": // case "chroma_analyser:complexity_difference": // case "chord_analyser:tps_distance": // return new LineDataChart(visualizationData); // default: // return new EmptyDataChart(VisualizationData.EMPTY_VISUALIZATION_DATA); // } // } // }
import org.apache.commons.cli.*; import org.harmony_analyser.application.visualizations.DataChartFactory; import org.harmony_analyser.jharmonyanalyser.services.*; import java.io.File;
package org.harmony_analyser.cli_scripts; /** * Script to perform arbitrary harmony-analyser analysis in the current directory */ public class HarmonyAnalyserScript { private static String analysisKey; private static String suffixAndExtension; private static float audibleThreshold; private static AudioAnalyser audioAnalyser; public static void main(String[] args) { System.out.println("--- Starting Harmony Analyser 1.2-beta ---"); System.out.println("Author: marsik@ksi.mff.cuni.cz"); System.out.println("harmony-analyser.org"); System.out.println(); AnalysisFactory analysisFactory = new AnalysisFactory();
// Path: src/main/java/org/harmony_analyser/application/visualizations/DataChartFactory.java // public class DataChartFactory { // private final String[] ALL_VISUALIZATIONS = new String[] { // "nnls-chroma:chordino-labels", // "qm-vamp-plugins:qm-keydetector", // "chord_analyser:average_chord_complexity_distance", // "chord_analyser:chord_complexity_distance", // "chord_analyser:tps_distance", // "chroma_analyser:simple_difference", // "chroma_analyser:complexity_difference", // }; // // public String[] getAllVisualizations() { // return ALL_VISUALIZATIONS; // } // // public DataChart createDataChart(String analysisKey, VisualizationData visualizationData) { // switch (analysisKey) { // case "nnls-chroma:chordino-labels": // case "qm-vamp-plugins:qm-keydetector": // return new SegmentationDataChart(visualizationData); // case "chord_analyser:average_chord_complexity_distance": // return new AveragesDataChart(visualizationData); // case "chord_analyser:chord_complexity_distance": // case "chroma_analyser:simple_difference": // case "chroma_analyser:complexity_difference": // case "chord_analyser:tps_distance": // return new LineDataChart(visualizationData); // default: // return new EmptyDataChart(VisualizationData.EMPTY_VISUALIZATION_DATA); // } // } // } // Path: src/main/java/org/harmony_analyser/cli_scripts/HarmonyAnalyserScript.java import org.apache.commons.cli.*; import org.harmony_analyser.application.visualizations.DataChartFactory; import org.harmony_analyser.jharmonyanalyser.services.*; import java.io.File; package org.harmony_analyser.cli_scripts; /** * Script to perform arbitrary harmony-analyser analysis in the current directory */ public class HarmonyAnalyserScript { private static String analysisKey; private static String suffixAndExtension; private static float audibleThreshold; private static AudioAnalyser audioAnalyser; public static void main(String[] args) { System.out.println("--- Starting Harmony Analyser 1.2-beta ---"); System.out.println("Author: marsik@ksi.mff.cuni.cz"); System.out.println("harmony-analyser.org"); System.out.println(); AnalysisFactory analysisFactory = new AnalysisFactory();
DataChartFactory dataChartFactory = new DataChartFactory();
lacimarsik/harmony-analyser
src/test/java/org/harmony_analyser/jharmonyanalyser/plugins/AnalysisFactoryTest.java
// Path: src/main/java/org/harmony_analyser/jharmonyanalyser/plugins/chordanal_plugins/AverageChordComplexityDistancePlugin.java // @SuppressWarnings("SameParameterValue") // // public class AverageChordComplexityDistancePlugin extends ChordAnalyserPlugin { // private final static int NUMBER_OUTPUTS = 3; // // public AverageChordComplexityDistancePlugin() { // key = "chord_analyser:average_chord_complexity_distance"; // name = "Avg Chord Complexity Distance"; // description = "Derives chord complexity distances from the subsequent chords and computes averages"; // // inputFileSuffixes = new ArrayList<>(); // inputFileSuffixes.add("-chromas"); // inputFileSuffixes.add("-chordino-labels"); // inputFileExtension = ".txt"; // // outputFileSuffix = "-average-cc-distance"; // outputFileExtension = ".txt"; // // parameters = new HashMap<>(); // parameters.put("audibleThreshold", (float) 0.07); // parameters.put("maximumNumberOfChordTones", (float) 4.0); // parameters.put("maximalComplexity", (float) 7.0); // // setParameters(); // } // // @Override // public VisualizationData getDataFromOutput(String inputWavFile) throws IOException, AudioAnalyser.OutputNotReady, AudioAnalyser.ParseOutputError, AudioAnalyser.IncorrectInputException, AudioAnalyser.OutputAlreadyExists { // VisualizationData data = super.prepareVisualizationData(); // List<Float> values = new ArrayList<>(); // List<String> labels = new ArrayList<>(); // List<String> linesList = readOutputFile(inputWavFile); // // /* Plugin-specific parsing of the result */ // // get last NUMBER_OUTPUTS lines // List<String> tail = linesList.subList(Math.max(linesList.size() - NUMBER_OUTPUTS, 0), linesList.size()); // for (String line : tail) { // Scanner sc = new Scanner(line).useDelimiter("\\s*:\\s*"); // labels.add(sc.next()); // if (sc.hasNextFloat()) { // values.add(sc.nextFloat()); // } else { // throw new AudioAnalyser.ParseOutputError("Output did not have the required fields"); // } // sc.close(); // } // data.setValues(values); // data.setLabels(labels); // return data; // } // // protected String getTransitionOutput(float timestamp, int transitionComplexity) { // return ""; // This plugin doesn't provide transition output // } // // protected String getFinalResult(float hc, float acc, float rtd) { // return "Average Chord Complexity Distance (ACCD): " + hc + "\n" + // "Average Chord Complexity (ACC): " + acc + "\n" + // "Relative Chord Complexity Distance (RCCD): " + rtd + "\n"; // } // }
import org.harmony_analyser.jharmonyanalyser.plugins.chordanal_plugins.AverageChordComplexityDistancePlugin; import org.harmony_analyser.jharmonyanalyser.services.*; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import static org.mockito.Mockito.mock; import static org.powermock.api.mockito.PowerMockito.verifyNew; import static org.powermock.api.mockito.PowerMockito.whenNew;
package org.harmony_analyser.jharmonyanalyser.plugins; /** * Unit tests for AnalysisFactory class */ @SuppressWarnings("UnusedAssignment") @RunWith(PowerMockRunner.class) @PrepareForTest(AnalysisFactory.class) public class AnalysisFactoryTest { private AnalysisFactory analysisFactory; @Before public void setUp() { analysisFactory = new AnalysisFactory(); } @Test public void shouldCreateAnalysisPlugin() throws Exception {
// Path: src/main/java/org/harmony_analyser/jharmonyanalyser/plugins/chordanal_plugins/AverageChordComplexityDistancePlugin.java // @SuppressWarnings("SameParameterValue") // // public class AverageChordComplexityDistancePlugin extends ChordAnalyserPlugin { // private final static int NUMBER_OUTPUTS = 3; // // public AverageChordComplexityDistancePlugin() { // key = "chord_analyser:average_chord_complexity_distance"; // name = "Avg Chord Complexity Distance"; // description = "Derives chord complexity distances from the subsequent chords and computes averages"; // // inputFileSuffixes = new ArrayList<>(); // inputFileSuffixes.add("-chromas"); // inputFileSuffixes.add("-chordino-labels"); // inputFileExtension = ".txt"; // // outputFileSuffix = "-average-cc-distance"; // outputFileExtension = ".txt"; // // parameters = new HashMap<>(); // parameters.put("audibleThreshold", (float) 0.07); // parameters.put("maximumNumberOfChordTones", (float) 4.0); // parameters.put("maximalComplexity", (float) 7.0); // // setParameters(); // } // // @Override // public VisualizationData getDataFromOutput(String inputWavFile) throws IOException, AudioAnalyser.OutputNotReady, AudioAnalyser.ParseOutputError, AudioAnalyser.IncorrectInputException, AudioAnalyser.OutputAlreadyExists { // VisualizationData data = super.prepareVisualizationData(); // List<Float> values = new ArrayList<>(); // List<String> labels = new ArrayList<>(); // List<String> linesList = readOutputFile(inputWavFile); // // /* Plugin-specific parsing of the result */ // // get last NUMBER_OUTPUTS lines // List<String> tail = linesList.subList(Math.max(linesList.size() - NUMBER_OUTPUTS, 0), linesList.size()); // for (String line : tail) { // Scanner sc = new Scanner(line).useDelimiter("\\s*:\\s*"); // labels.add(sc.next()); // if (sc.hasNextFloat()) { // values.add(sc.nextFloat()); // } else { // throw new AudioAnalyser.ParseOutputError("Output did not have the required fields"); // } // sc.close(); // } // data.setValues(values); // data.setLabels(labels); // return data; // } // // protected String getTransitionOutput(float timestamp, int transitionComplexity) { // return ""; // This plugin doesn't provide transition output // } // // protected String getFinalResult(float hc, float acc, float rtd) { // return "Average Chord Complexity Distance (ACCD): " + hc + "\n" + // "Average Chord Complexity (ACC): " + acc + "\n" + // "Relative Chord Complexity Distance (RCCD): " + rtd + "\n"; // } // } // Path: src/test/java/org/harmony_analyser/jharmonyanalyser/plugins/AnalysisFactoryTest.java import org.harmony_analyser.jharmonyanalyser.plugins.chordanal_plugins.AverageChordComplexityDistancePlugin; import org.harmony_analyser.jharmonyanalyser.services.*; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import static org.mockito.Mockito.mock; import static org.powermock.api.mockito.PowerMockito.verifyNew; import static org.powermock.api.mockito.PowerMockito.whenNew; package org.harmony_analyser.jharmonyanalyser.plugins; /** * Unit tests for AnalysisFactory class */ @SuppressWarnings("UnusedAssignment") @RunWith(PowerMockRunner.class) @PrepareForTest(AnalysisFactory.class) public class AnalysisFactoryTest { private AnalysisFactory analysisFactory; @Before public void setUp() { analysisFactory = new AnalysisFactory(); } @Test public void shouldCreateAnalysisPlugin() throws Exception {
AverageChordComplexityDistancePlugin transitionComplexityPlugin = mock(AverageChordComplexityDistancePlugin.class);
lacimarsik/harmony-analyser
src/main/java/org/harmony_analyser/jharmonyanalyser/plugins/AnalysisPlugin.java
// Path: src/main/java/org/harmony_analyser/application/visualizations/VisualizationData.java // public class VisualizationData { // private String pluginName; // private List<Float> timestamps; // private List<Float> values; // private List<String> labels; // // public final static VisualizationData EMPTY_VISUALIZATION_DATA = new VisualizationData(); // // public VisualizationData() { // setTimestamps(new ArrayList<>()); // setValues(new ArrayList<>()); // setLabels(new ArrayList<>()); // } // // List<Float> getTimestamps() { // return timestamps; // } // // public List<Float> getValues() { // return values; // } // // List<String> getLabels() { // return labels; // } // // String getPluginName() { // return pluginName; // } // // public void setTimestamps(List<Float> timestamps) { // this.timestamps = timestamps; // } // // public void setValues(List<Float> values) { // this.values = values; // } // // public void setLabels(List<String> labels) { // this.labels = labels; // } // // public void setPluginName(String pluginName) { // this.pluginName = pluginName; // } // }
import org.harmony_analyser.jharmonyanalyser.services.*; import org.harmony_analyser.application.visualizations.VisualizationData;
package org.harmony_analyser.jharmonyanalyser.plugins; /** * Abstract class for low and high-level audio analysis plugin */ @SuppressWarnings("SameParameterValue") public abstract class AnalysisPlugin extends Analysis {
// Path: src/main/java/org/harmony_analyser/application/visualizations/VisualizationData.java // public class VisualizationData { // private String pluginName; // private List<Float> timestamps; // private List<Float> values; // private List<String> labels; // // public final static VisualizationData EMPTY_VISUALIZATION_DATA = new VisualizationData(); // // public VisualizationData() { // setTimestamps(new ArrayList<>()); // setValues(new ArrayList<>()); // setLabels(new ArrayList<>()); // } // // List<Float> getTimestamps() { // return timestamps; // } // // public List<Float> getValues() { // return values; // } // // List<String> getLabels() { // return labels; // } // // String getPluginName() { // return pluginName; // } // // public void setTimestamps(List<Float> timestamps) { // this.timestamps = timestamps; // } // // public void setValues(List<Float> values) { // this.values = values; // } // // public void setLabels(List<String> labels) { // this.labels = labels; // } // // public void setPluginName(String pluginName) { // this.pluginName = pluginName; // } // } // Path: src/main/java/org/harmony_analyser/jharmonyanalyser/plugins/AnalysisPlugin.java import org.harmony_analyser.jharmonyanalyser.services.*; import org.harmony_analyser.application.visualizations.VisualizationData; package org.harmony_analyser.jharmonyanalyser.plugins; /** * Abstract class for low and high-level audio analysis plugin */ @SuppressWarnings("SameParameterValue") public abstract class AnalysisPlugin extends Analysis {
protected VisualizationData prepareVisualizationData() {
lacimarsik/harmony-analyser
src/main/java/org/harmony_analyser/jharmonyanalyser/plugins/EmptyPlugin.java
// Path: src/main/java/org/harmony_analyser/application/visualizations/VisualizationData.java // public class VisualizationData { // private String pluginName; // private List<Float> timestamps; // private List<Float> values; // private List<String> labels; // // public final static VisualizationData EMPTY_VISUALIZATION_DATA = new VisualizationData(); // // public VisualizationData() { // setTimestamps(new ArrayList<>()); // setValues(new ArrayList<>()); // setLabels(new ArrayList<>()); // } // // List<Float> getTimestamps() { // return timestamps; // } // // public List<Float> getValues() { // return values; // } // // List<String> getLabels() { // return labels; // } // // String getPluginName() { // return pluginName; // } // // public void setTimestamps(List<Float> timestamps) { // this.timestamps = timestamps; // } // // public void setValues(List<Float> values) { // this.values = values; // } // // public void setLabels(List<String> labels) { // this.labels = labels; // } // // public void setPluginName(String pluginName) { // this.pluginName = pluginName; // } // }
import org.harmony_analyser.application.visualizations.VisualizationData;
package org.harmony_analyser.jharmonyanalyser.plugins; public class EmptyPlugin extends AnalysisPlugin { protected void setParameters() { /* Do nothing */ } @Override public String analyse(String inputFile, boolean force) { return ""; }
// Path: src/main/java/org/harmony_analyser/application/visualizations/VisualizationData.java // public class VisualizationData { // private String pluginName; // private List<Float> timestamps; // private List<Float> values; // private List<String> labels; // // public final static VisualizationData EMPTY_VISUALIZATION_DATA = new VisualizationData(); // // public VisualizationData() { // setTimestamps(new ArrayList<>()); // setValues(new ArrayList<>()); // setLabels(new ArrayList<>()); // } // // List<Float> getTimestamps() { // return timestamps; // } // // public List<Float> getValues() { // return values; // } // // List<String> getLabels() { // return labels; // } // // String getPluginName() { // return pluginName; // } // // public void setTimestamps(List<Float> timestamps) { // this.timestamps = timestamps; // } // // public void setValues(List<Float> values) { // this.values = values; // } // // public void setLabels(List<String> labels) { // this.labels = labels; // } // // public void setPluginName(String pluginName) { // this.pluginName = pluginName; // } // } // Path: src/main/java/org/harmony_analyser/jharmonyanalyser/plugins/EmptyPlugin.java import org.harmony_analyser.application.visualizations.VisualizationData; package org.harmony_analyser.jharmonyanalyser.plugins; public class EmptyPlugin extends AnalysisPlugin { protected void setParameters() { /* Do nothing */ } @Override public String analyse(String inputFile, boolean force) { return ""; }
public VisualizationData getDataFromOutput(String inputWavFile) {
lacimarsik/harmony-analyser
src/main/java/org/harmony_analyser/jharmonyanalyser/plugins/chordanal_plugins/TPSDistancePlugin.java
// Path: src/main/java/org/harmony_analyser/jharmonyanalyser/chroma_analyser/Chroma.java // @SuppressWarnings({"SameParameterValue", "WeakerAccess"}) // // public class Chroma { // public final float[] values; // // public static final Chroma EMPTY_CHROMA = new Chroma(); // // /* Exceptions */ // // public class WrongChromaSize extends Exception { // public WrongChromaSize(String message) { // super(message); // } // } // // public Chroma() { // this.values = new float[0]; // } // // public Chroma(float[] chroma) throws WrongChromaSize { // this.values = new float[Chromanal.CHROMA_LENGTH]; // if (chroma.length != Chromanal.CHROMA_LENGTH) { // throw new WrongChromaSize("Wrong Chroma size"); // } // System.arraycopy(chroma, 0, values, 0, Chromanal.CHROMA_LENGTH - 1); // } // // /* Public / Package methods */ // // /* Private methods */ // } // // Path: src/main/java/org/harmony_analyser/jharmonyanalyser/plugins/LineChartPlugin.java // @SuppressWarnings("SameParameterValue") // // public abstract class LineChartPlugin extends AnalysisPlugin { // public VisualizationData getDataFromOutput(String inputWavFile) throws IOException, AudioAnalyser.OutputNotReady, AudioAnalyser.ParseOutputError, AudioAnalyser.IncorrectInputException, AudioAnalyser.OutputAlreadyExists { // VisualizationData data = super.prepareVisualizationData(); // List<Float> timestamps = new ArrayList<>(); // List<Float> values = new ArrayList<>(); // List<String> linesList = readOutputFile(inputWavFile); // // float timestamp, value; // // /* Plugin-specific parsing of the result */ // try { // for (String line : linesList) { // timestamp = AudioAnalysisHelper.getTimestampFromLine(line); // value = Float.parseFloat(AudioAnalysisHelper.getLabelFromLine(line)); // timestamps.add(timestamp); // values.add(value); // } // } catch (NumberFormatException e) { // throw new AudioAnalyser.ParseOutputError("Output did not have the required fields"); // } // data.setTimestamps(timestamps); // data.setValues(values); // return data; // } // }
import org.harmony_analyser.jharmonyanalyser.services.*; import org.harmony_analyser.jharmonyanalyser.chord_analyser.*; import org.harmony_analyser.jharmonyanalyser.chroma_analyser.Chroma; import org.harmony_analyser.jharmonyanalyser.plugins.LineChartPlugin; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.stream.Collectors;
package org.harmony_analyser.jharmonyanalyser.plugins.chordanal_plugins; /** * Plugin for high-level audio analysis using chroma / chord transcription input, based on Fred Lerdahl's Tonal Pitch Space (TPS) * for more information on TPS: http://www.oupcanada.com/catalog/9780195178296.html */ /* * TPSDistancePlugin * * - requires: chord estimates, key estimates * - calculates TPS distance for each pair of subsequent chords * * parameters * - no parameters present */ @SuppressWarnings("SameParameterValue") public class TPSDistancePlugin extends LineChartPlugin { public TPSDistancePlugin() { key = "chord_analyser:tps_distance"; name = "TPS Distance"; description = "Derives TPS distances from the subsequent chords"; inputFileSuffixes = new ArrayList<>(); inputFileSuffixes.add("-chordino-labels"); inputFileSuffixes.add("-chordino-tones"); inputFileSuffixes.add("-key"); inputFileExtension = ".txt"; outputFileSuffix = "-tps-distance"; outputFileExtension = ".txt"; parameters = new HashMap<>(); setParameters(); }
// Path: src/main/java/org/harmony_analyser/jharmonyanalyser/chroma_analyser/Chroma.java // @SuppressWarnings({"SameParameterValue", "WeakerAccess"}) // // public class Chroma { // public final float[] values; // // public static final Chroma EMPTY_CHROMA = new Chroma(); // // /* Exceptions */ // // public class WrongChromaSize extends Exception { // public WrongChromaSize(String message) { // super(message); // } // } // // public Chroma() { // this.values = new float[0]; // } // // public Chroma(float[] chroma) throws WrongChromaSize { // this.values = new float[Chromanal.CHROMA_LENGTH]; // if (chroma.length != Chromanal.CHROMA_LENGTH) { // throw new WrongChromaSize("Wrong Chroma size"); // } // System.arraycopy(chroma, 0, values, 0, Chromanal.CHROMA_LENGTH - 1); // } // // /* Public / Package methods */ // // /* Private methods */ // } // // Path: src/main/java/org/harmony_analyser/jharmonyanalyser/plugins/LineChartPlugin.java // @SuppressWarnings("SameParameterValue") // // public abstract class LineChartPlugin extends AnalysisPlugin { // public VisualizationData getDataFromOutput(String inputWavFile) throws IOException, AudioAnalyser.OutputNotReady, AudioAnalyser.ParseOutputError, AudioAnalyser.IncorrectInputException, AudioAnalyser.OutputAlreadyExists { // VisualizationData data = super.prepareVisualizationData(); // List<Float> timestamps = new ArrayList<>(); // List<Float> values = new ArrayList<>(); // List<String> linesList = readOutputFile(inputWavFile); // // float timestamp, value; // // /* Plugin-specific parsing of the result */ // try { // for (String line : linesList) { // timestamp = AudioAnalysisHelper.getTimestampFromLine(line); // value = Float.parseFloat(AudioAnalysisHelper.getLabelFromLine(line)); // timestamps.add(timestamp); // values.add(value); // } // } catch (NumberFormatException e) { // throw new AudioAnalyser.ParseOutputError("Output did not have the required fields"); // } // data.setTimestamps(timestamps); // data.setValues(values); // return data; // } // } // Path: src/main/java/org/harmony_analyser/jharmonyanalyser/plugins/chordanal_plugins/TPSDistancePlugin.java import org.harmony_analyser.jharmonyanalyser.services.*; import org.harmony_analyser.jharmonyanalyser.chord_analyser.*; import org.harmony_analyser.jharmonyanalyser.chroma_analyser.Chroma; import org.harmony_analyser.jharmonyanalyser.plugins.LineChartPlugin; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.Files; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.stream.Collectors; package org.harmony_analyser.jharmonyanalyser.plugins.chordanal_plugins; /** * Plugin for high-level audio analysis using chroma / chord transcription input, based on Fred Lerdahl's Tonal Pitch Space (TPS) * for more information on TPS: http://www.oupcanada.com/catalog/9780195178296.html */ /* * TPSDistancePlugin * * - requires: chord estimates, key estimates * - calculates TPS distance for each pair of subsequent chords * * parameters * - no parameters present */ @SuppressWarnings("SameParameterValue") public class TPSDistancePlugin extends LineChartPlugin { public TPSDistancePlugin() { key = "chord_analyser:tps_distance"; name = "TPS Distance"; description = "Derives TPS distances from the subsequent chords"; inputFileSuffixes = new ArrayList<>(); inputFileSuffixes.add("-chordino-labels"); inputFileSuffixes.add("-chordino-tones"); inputFileSuffixes.add("-key"); inputFileExtension = ".txt"; outputFileSuffix = "-tps-distance"; outputFileExtension = ".txt"; parameters = new HashMap<>(); setParameters(); }
public String analyse(String inputFile, boolean force) throws IOException, AudioAnalyser.IncorrectInputException, AudioAnalyser.OutputAlreadyExists, Chroma.WrongChromaSize {
lacimarsik/harmony-analyser
src/main/java/org/harmony_analyser/jharmonyanalyser/services/AudioAnalyser.java
// Path: src/main/java/org/harmony_analyser/jharmonyanalyser/chroma_analyser/Chroma.java // @SuppressWarnings({"SameParameterValue", "WeakerAccess"}) // // public class Chroma { // public final float[] values; // // public static final Chroma EMPTY_CHROMA = new Chroma(); // // /* Exceptions */ // // public class WrongChromaSize extends Exception { // public WrongChromaSize(String message) { // super(message); // } // } // // public Chroma() { // this.values = new float[0]; // } // // public Chroma(float[] chroma) throws WrongChromaSize { // this.values = new float[Chromanal.CHROMA_LENGTH]; // if (chroma.length != Chromanal.CHROMA_LENGTH) { // throw new WrongChromaSize("Wrong Chroma size"); // } // System.arraycopy(chroma, 0, values, 0, Chromanal.CHROMA_LENGTH - 1); // } // // /* Public / Package methods */ // // /* Private methods */ // }
import org.harmony_analyser.application.visualizations.*; import org.harmony_analyser.jharmonyanalyser.chroma_analyser.Chroma; import org.vamp_plugins.PluginLoader; import java.io.*; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.util.*;
List<String> wrappedPlugins = new ArrayList<>(); for (int i = 0; i < plugins.length; ++i) { for (String wrapped_plugin : analysisFactory.getWrappedVampPlugins()) { if (plugins[i].equals(wrapped_plugin)) { wrappedPlugins.add(i + ": " + plugins[i] + "\n"); } } } result += "\n> Implemented VAMP plugins (" + wrappedPlugins.size() + "):\n"; for (String s : wrappedPlugins) { result += s; } } catch(java.lang.UnsatisfiedLinkError e) { return "\nWARNING: jVamp not installed on this machine, Vamp plugins are not available."; } return result; } public String getPluginName(String analysisKey) throws LoadFailedException { return analysisFactory.createAnalysis(analysisKey).name; } public String getPluginDescription(String analysisKey) throws LoadFailedException { return analysisFactory.createAnalysis(analysisKey).description; } public String printParameters(String analysisKey) throws LoadFailedException { return analysisFactory.createAnalysis(analysisKey).printParameters(); }
// Path: src/main/java/org/harmony_analyser/jharmonyanalyser/chroma_analyser/Chroma.java // @SuppressWarnings({"SameParameterValue", "WeakerAccess"}) // // public class Chroma { // public final float[] values; // // public static final Chroma EMPTY_CHROMA = new Chroma(); // // /* Exceptions */ // // public class WrongChromaSize extends Exception { // public WrongChromaSize(String message) { // super(message); // } // } // // public Chroma() { // this.values = new float[0]; // } // // public Chroma(float[] chroma) throws WrongChromaSize { // this.values = new float[Chromanal.CHROMA_LENGTH]; // if (chroma.length != Chromanal.CHROMA_LENGTH) { // throw new WrongChromaSize("Wrong Chroma size"); // } // System.arraycopy(chroma, 0, values, 0, Chromanal.CHROMA_LENGTH - 1); // } // // /* Public / Package methods */ // // /* Private methods */ // } // Path: src/main/java/org/harmony_analyser/jharmonyanalyser/services/AudioAnalyser.java import org.harmony_analyser.application.visualizations.*; import org.harmony_analyser.jharmonyanalyser.chroma_analyser.Chroma; import org.vamp_plugins.PluginLoader; import java.io.*; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.util.*; List<String> wrappedPlugins = new ArrayList<>(); for (int i = 0; i < plugins.length; ++i) { for (String wrapped_plugin : analysisFactory.getWrappedVampPlugins()) { if (plugins[i].equals(wrapped_plugin)) { wrappedPlugins.add(i + ": " + plugins[i] + "\n"); } } } result += "\n> Implemented VAMP plugins (" + wrappedPlugins.size() + "):\n"; for (String s : wrappedPlugins) { result += s; } } catch(java.lang.UnsatisfiedLinkError e) { return "\nWARNING: jVamp not installed on this machine, Vamp plugins are not available."; } return result; } public String getPluginName(String analysisKey) throws LoadFailedException { return analysisFactory.createAnalysis(analysisKey).name; } public String getPluginDescription(String analysisKey) throws LoadFailedException { return analysisFactory.createAnalysis(analysisKey).description; } public String printParameters(String analysisKey) throws LoadFailedException { return analysisFactory.createAnalysis(analysisKey).printParameters(); }
public String runAnalysis(String inputFile, String analysisKey, boolean force, boolean verbose) throws AudioAnalyser.IncorrectInputException, OutputAlreadyExists, IOException, LoadFailedException, Chroma.WrongChromaSize {
ljessendk/easybinder
src/test/java/org/vaadin/easybinder/it/FormBuilderIT.java
// Path: src/test/java/org/vaadin/easybinder/example/BuildAndBindExample.java // public class BuildAndBindExample extends AbstractTest { // private static final long serialVersionUID = 1L; // // @Override // public Component getTestComponent() { // AutoBinder<Flight> binder = new AutoBinder<>(Flight.class); // // FormLayout f = new FormLayout(); // f.addComponents(binder.buildAndBind("flightId")); // // Label statusLabel = new Label(); // binder.setStatusLabel(statusLabel); // f.addComponents(statusLabel); // // binder.setBean(new Flight()); // // return f; // } // }
import org.openqa.selenium.support.ui.WebDriverWait; import org.vaadin.addonhelpers.automated.AbstractWebDriverCase; import org.vaadin.addonhelpers.automated.VaadinConditions; import org.vaadin.easybinder.example.BuildAndBindExample; import org.openqa.selenium.firefox.FirefoxDriver;
package org.vaadin.easybinder.it; //import org.junit.Test; /** * A simple example that uses Selenium to do a browser level test for a * BasicJavaSCriptComponentUsageUI. For more complex tests, consider using page * object pattern. */ public class FormBuilderIT extends AbstractWebDriverCase { //@Test public void testJavaScriptComponentWithBrowser() throws InterruptedException { startBrowser();
// Path: src/test/java/org/vaadin/easybinder/example/BuildAndBindExample.java // public class BuildAndBindExample extends AbstractTest { // private static final long serialVersionUID = 1L; // // @Override // public Component getTestComponent() { // AutoBinder<Flight> binder = new AutoBinder<>(Flight.class); // // FormLayout f = new FormLayout(); // f.addComponents(binder.buildAndBind("flightId")); // // Label statusLabel = new Label(); // binder.setStatusLabel(statusLabel); // f.addComponents(statusLabel); // // binder.setBean(new Flight()); // // return f; // } // } // Path: src/test/java/org/vaadin/easybinder/it/FormBuilderIT.java import org.openqa.selenium.support.ui.WebDriverWait; import org.vaadin.addonhelpers.automated.AbstractWebDriverCase; import org.vaadin.addonhelpers.automated.VaadinConditions; import org.vaadin.easybinder.example.BuildAndBindExample; import org.openqa.selenium.firefox.FirefoxDriver; package org.vaadin.easybinder.it; //import org.junit.Test; /** * A simple example that uses Selenium to do a browser level test for a * BasicJavaSCriptComponentUsageUI. For more complex tests, consider using page * object pattern. */ public class FormBuilderIT extends AbstractWebDriverCase { //@Test public void testJavaScriptComponentWithBrowser() throws InterruptedException { startBrowser();
driver.navigate().to(BASEURL + BuildAndBindExample.class.getName());
ljessendk/easybinder
src/main/java/org/vaadin/easybinder/data/ConverterRegistry.java
// Path: src/main/java/org/vaadin/easybinder/data/converters/NullConverter.java // @SuppressWarnings("serial") // public class NullConverter<T> implements Converter<T, T> { // // protected T nullRepresentation; // // public NullConverter(T nullRepresentation) { // this.nullRepresentation = nullRepresentation; // } // // @Override // public Result<T> convertToModel(T value, ValueContext context) { // return (nullRepresentation == null && value == null) // || (nullRepresentation != null && nullRepresentation.equals(value)) ? Result.ok(null) // : Result.ok(value); // } // // @Override // public T convertToPresentation(T value, ValueContext context) { // return value == null ? nullRepresentation : value; // } // } // // Path: src/main/java/org/vaadin/easybinder/data/converters/StringLengthConverterValidator.java // public class StringLengthConverterValidator implements Converter<String, String> { // // private static final long serialVersionUID = 1L; // // Integer minLength; // Integer maxLength; // String errorMessage; // // public StringLengthConverterValidator(String errorMessage, Integer minLength, Integer maxLength) { // this.errorMessage = errorMessage; // this.minLength = minLength; // this.maxLength = maxLength; // } // // @Override // public Result<String> convertToModel(String value, ValueContext context) { // if (value == null) { // return Result.ok(null); // } // if (minLength != null && value.length() < minLength || maxLength != null && value.length() > maxLength) { // return Result.error(errorMessage); // } // return Result.ok(value); // } // // @Override // public String convertToPresentation(String value, ValueContext context) { // return value; // } // // }
import java.math.BigDecimal; import java.math.BigInteger; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.ZoneId; import java.util.Date; import java.util.EnumSet; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.vaadin.easybinder.data.converters.NullConverter; import org.vaadin.easybinder.data.converters.StringLengthConverterValidator; import com.vaadin.data.Converter; import com.vaadin.data.Result; import com.vaadin.data.converter.LocalDateTimeToDateConverter; import com.vaadin.data.converter.LocalDateToDateConverter; import com.vaadin.data.converter.StringToBigDecimalConverter; import com.vaadin.data.converter.StringToBigIntegerConverter; import com.vaadin.data.converter.StringToBooleanConverter; import com.vaadin.data.converter.StringToDoubleConverter; import com.vaadin.data.converter.StringToFloatConverter; import com.vaadin.data.converter.StringToIntegerConverter; import com.vaadin.data.converter.StringToLongConverter;
/* * Copyright 2017 Lars Sønderby Jessen * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.vaadin.easybinder.data; public class ConverterRegistry { static ConverterRegistry instance; protected Map<Pair<Class<?>, Class<?>>, Converter<?, ?>> converters = new HashMap<>(); public static ConverterRegistry getInstance() { if (instance == null) { instance = new ConverterRegistry(); } return instance; } @SuppressWarnings("unchecked") private ConverterRegistry() {
// Path: src/main/java/org/vaadin/easybinder/data/converters/NullConverter.java // @SuppressWarnings("serial") // public class NullConverter<T> implements Converter<T, T> { // // protected T nullRepresentation; // // public NullConverter(T nullRepresentation) { // this.nullRepresentation = nullRepresentation; // } // // @Override // public Result<T> convertToModel(T value, ValueContext context) { // return (nullRepresentation == null && value == null) // || (nullRepresentation != null && nullRepresentation.equals(value)) ? Result.ok(null) // : Result.ok(value); // } // // @Override // public T convertToPresentation(T value, ValueContext context) { // return value == null ? nullRepresentation : value; // } // } // // Path: src/main/java/org/vaadin/easybinder/data/converters/StringLengthConverterValidator.java // public class StringLengthConverterValidator implements Converter<String, String> { // // private static final long serialVersionUID = 1L; // // Integer minLength; // Integer maxLength; // String errorMessage; // // public StringLengthConverterValidator(String errorMessage, Integer minLength, Integer maxLength) { // this.errorMessage = errorMessage; // this.minLength = minLength; // this.maxLength = maxLength; // } // // @Override // public Result<String> convertToModel(String value, ValueContext context) { // if (value == null) { // return Result.ok(null); // } // if (minLength != null && value.length() < minLength || maxLength != null && value.length() > maxLength) { // return Result.error(errorMessage); // } // return Result.ok(value); // } // // @Override // public String convertToPresentation(String value, ValueContext context) { // return value; // } // // } // Path: src/main/java/org/vaadin/easybinder/data/ConverterRegistry.java import java.math.BigDecimal; import java.math.BigInteger; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.ZoneId; import java.util.Date; import java.util.EnumSet; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.vaadin.easybinder.data.converters.NullConverter; import org.vaadin.easybinder.data.converters.StringLengthConverterValidator; import com.vaadin.data.Converter; import com.vaadin.data.Result; import com.vaadin.data.converter.LocalDateTimeToDateConverter; import com.vaadin.data.converter.LocalDateToDateConverter; import com.vaadin.data.converter.StringToBigDecimalConverter; import com.vaadin.data.converter.StringToBigIntegerConverter; import com.vaadin.data.converter.StringToBooleanConverter; import com.vaadin.data.converter.StringToDoubleConverter; import com.vaadin.data.converter.StringToFloatConverter; import com.vaadin.data.converter.StringToIntegerConverter; import com.vaadin.data.converter.StringToLongConverter; /* * Copyright 2017 Lars Sønderby Jessen * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.vaadin.easybinder.data; public class ConverterRegistry { static ConverterRegistry instance; protected Map<Pair<Class<?>, Class<?>>, Converter<?, ?>> converters = new HashMap<>(); public static ConverterRegistry getInstance() { if (instance == null) { instance = new ConverterRegistry(); } return instance; } @SuppressWarnings("unchecked") private ConverterRegistry() {
registerConverter(String.class, int.class, new StringLengthConverterValidator("Must be a number", 1, null)
ljessendk/easybinder
src/main/java/org/vaadin/easybinder/data/ConverterRegistry.java
// Path: src/main/java/org/vaadin/easybinder/data/converters/NullConverter.java // @SuppressWarnings("serial") // public class NullConverter<T> implements Converter<T, T> { // // protected T nullRepresentation; // // public NullConverter(T nullRepresentation) { // this.nullRepresentation = nullRepresentation; // } // // @Override // public Result<T> convertToModel(T value, ValueContext context) { // return (nullRepresentation == null && value == null) // || (nullRepresentation != null && nullRepresentation.equals(value)) ? Result.ok(null) // : Result.ok(value); // } // // @Override // public T convertToPresentation(T value, ValueContext context) { // return value == null ? nullRepresentation : value; // } // } // // Path: src/main/java/org/vaadin/easybinder/data/converters/StringLengthConverterValidator.java // public class StringLengthConverterValidator implements Converter<String, String> { // // private static final long serialVersionUID = 1L; // // Integer minLength; // Integer maxLength; // String errorMessage; // // public StringLengthConverterValidator(String errorMessage, Integer minLength, Integer maxLength) { // this.errorMessage = errorMessage; // this.minLength = minLength; // this.maxLength = maxLength; // } // // @Override // public Result<String> convertToModel(String value, ValueContext context) { // if (value == null) { // return Result.ok(null); // } // if (minLength != null && value.length() < minLength || maxLength != null && value.length() > maxLength) { // return Result.error(errorMessage); // } // return Result.ok(value); // } // // @Override // public String convertToPresentation(String value, ValueContext context) { // return value; // } // // }
import java.math.BigDecimal; import java.math.BigInteger; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.ZoneId; import java.util.Date; import java.util.EnumSet; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.vaadin.easybinder.data.converters.NullConverter; import org.vaadin.easybinder.data.converters.StringLengthConverterValidator; import com.vaadin.data.Converter; import com.vaadin.data.Result; import com.vaadin.data.converter.LocalDateTimeToDateConverter; import com.vaadin.data.converter.LocalDateToDateConverter; import com.vaadin.data.converter.StringToBigDecimalConverter; import com.vaadin.data.converter.StringToBigIntegerConverter; import com.vaadin.data.converter.StringToBooleanConverter; import com.vaadin.data.converter.StringToDoubleConverter; import com.vaadin.data.converter.StringToFloatConverter; import com.vaadin.data.converter.StringToIntegerConverter; import com.vaadin.data.converter.StringToLongConverter;
/* * Copyright 2017 Lars Sønderby Jessen * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.vaadin.easybinder.data; public class ConverterRegistry { static ConverterRegistry instance; protected Map<Pair<Class<?>, Class<?>>, Converter<?, ?>> converters = new HashMap<>(); public static ConverterRegistry getInstance() { if (instance == null) { instance = new ConverterRegistry(); } return instance; } @SuppressWarnings("unchecked") private ConverterRegistry() { registerConverter(String.class, int.class, new StringLengthConverterValidator("Must be a number", 1, null) .chain(new StringToIntegerConverter("Must be a number"))); registerConverter(String.class, Integer.class,
// Path: src/main/java/org/vaadin/easybinder/data/converters/NullConverter.java // @SuppressWarnings("serial") // public class NullConverter<T> implements Converter<T, T> { // // protected T nullRepresentation; // // public NullConverter(T nullRepresentation) { // this.nullRepresentation = nullRepresentation; // } // // @Override // public Result<T> convertToModel(T value, ValueContext context) { // return (nullRepresentation == null && value == null) // || (nullRepresentation != null && nullRepresentation.equals(value)) ? Result.ok(null) // : Result.ok(value); // } // // @Override // public T convertToPresentation(T value, ValueContext context) { // return value == null ? nullRepresentation : value; // } // } // // Path: src/main/java/org/vaadin/easybinder/data/converters/StringLengthConverterValidator.java // public class StringLengthConverterValidator implements Converter<String, String> { // // private static final long serialVersionUID = 1L; // // Integer minLength; // Integer maxLength; // String errorMessage; // // public StringLengthConverterValidator(String errorMessage, Integer minLength, Integer maxLength) { // this.errorMessage = errorMessage; // this.minLength = minLength; // this.maxLength = maxLength; // } // // @Override // public Result<String> convertToModel(String value, ValueContext context) { // if (value == null) { // return Result.ok(null); // } // if (minLength != null && value.length() < minLength || maxLength != null && value.length() > maxLength) { // return Result.error(errorMessage); // } // return Result.ok(value); // } // // @Override // public String convertToPresentation(String value, ValueContext context) { // return value; // } // // } // Path: src/main/java/org/vaadin/easybinder/data/ConverterRegistry.java import java.math.BigDecimal; import java.math.BigInteger; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.ZoneId; import java.util.Date; import java.util.EnumSet; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.vaadin.easybinder.data.converters.NullConverter; import org.vaadin.easybinder.data.converters.StringLengthConverterValidator; import com.vaadin.data.Converter; import com.vaadin.data.Result; import com.vaadin.data.converter.LocalDateTimeToDateConverter; import com.vaadin.data.converter.LocalDateToDateConverter; import com.vaadin.data.converter.StringToBigDecimalConverter; import com.vaadin.data.converter.StringToBigIntegerConverter; import com.vaadin.data.converter.StringToBooleanConverter; import com.vaadin.data.converter.StringToDoubleConverter; import com.vaadin.data.converter.StringToFloatConverter; import com.vaadin.data.converter.StringToIntegerConverter; import com.vaadin.data.converter.StringToLongConverter; /* * Copyright 2017 Lars Sønderby Jessen * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.vaadin.easybinder.data; public class ConverterRegistry { static ConverterRegistry instance; protected Map<Pair<Class<?>, Class<?>>, Converter<?, ?>> converters = new HashMap<>(); public static ConverterRegistry getInstance() { if (instance == null) { instance = new ConverterRegistry(); } return instance; } @SuppressWarnings("unchecked") private ConverterRegistry() { registerConverter(String.class, int.class, new StringLengthConverterValidator("Must be a number", 1, null) .chain(new StringToIntegerConverter("Must be a number"))); registerConverter(String.class, Integer.class,
new NullConverter<String>("").chain(new StringToIntegerConverter("Must be a number")));
ljessendk/easybinder
src/test/java/org/vaadin/easybinder/example/VaadinBeanBinderExample.java
// Path: src/test/java/org/vaadin/easybinder/testentity/Flight.java // @FlightValid // @GroupSequenceProvider(FlightGroupProvider.class) // public class Flight { // @Valid // FlightId flightId; // // @Temporal(TemporalType.TIMESTAMP) // Date sbt; // // @Temporal(TemporalType.TIMESTAMP) // Date ebt; // // @Temporal(TemporalType.TIMESTAMP) // Date abt; // // @NotNull(groups = FlightGroupProvider.Scheduled.class, message = "Gate should be set when scheduled") // String gate; // // boolean canceled; // // public Flight() { // flightId = new FlightId(); // } // // /** // * @return the flightId // */ // public FlightId getFlightId() { // return flightId; // } // // /** // * @param flightId // * the flightId to set // */ // public void setFlightId(FlightId flightId) { // this.flightId = flightId; // } // // /** // * @return the sbt // */ // public Date getSbt() { // return sbt; // } // // /** // * @return the ebt // */ // public Date getEbt() { // return ebt; // } // // /** // * @return the abt // */ // public Date getAbt() { // return abt; // } // // /** // * @return the gate // */ // public String getGate() { // return gate; // } // // /** // * @param sbt // * the sbt to set // */ // public void setSbt(Date sbt) { // this.sbt = sbt; // } // // /** // * @param ebt // * the ebt to set // */ // public void setEbt(Date ebt) { // this.ebt = ebt; // } // // /** // * @param abt // * the abt to set // */ // public void setAbt(Date abt) { // this.abt = abt; // } // // /** // * @param gate // * the gate to set // */ // public void setGate(String gate) { // this.gate = gate; // } // // public void setCanceled(boolean canceled) { // this.canceled = canceled; // } // // public boolean getCanceled() { // return canceled; // } // // public boolean isCanceled() { // return canceled; // } // // } // // Path: src/test/java/org/vaadin/easybinder/testentity/FlightValidator.java // public class FlightValidator implements ConstraintValidator<FlightValid, Flight> { // // @Override // public void initialize(FlightValid constraintAnnotation) { // } // // @Override // public boolean isValid(Flight flight, ConstraintValidatorContext context) { // return (flight.getAbt() == null || flight.getEbt() != null) // && (flight.getEbt() == null || flight.getSbt() != null); // } // } // // Path: src/test/java/org/vaadin/easybinder/testentity/FlightId.java // public static enum LegType { // DEPARTURE, ARRIVAL // }
import com.vaadin.data.BeanValidationBinder; import com.vaadin.data.Binder; import com.vaadin.data.Converter; import com.vaadin.data.RequiredFieldConfigurator; import com.vaadin.data.Result; import com.vaadin.data.converter.LocalDateTimeToDateConverter; import com.vaadin.data.converter.LocalDateToDateConverter; import com.vaadin.ui.CheckBox; import com.vaadin.ui.Component; import com.vaadin.ui.DateField; import com.vaadin.ui.DateTimeField; import com.vaadin.ui.FormLayout; import com.vaadin.ui.Label; import com.vaadin.ui.RadioButtonGroup; import com.vaadin.ui.TextField; import java.time.ZoneId; import java.util.EnumSet; import javax.validation.constraints.Min; import org.vaadin.addonhelpers.AbstractTest; import org.vaadin.easybinder.testentity.Flight; import org.vaadin.easybinder.testentity.FlightValid; import org.vaadin.easybinder.testentity.FlightValidator; import org.vaadin.easybinder.testentity.FlightId.LegType;
package org.vaadin.easybinder.example; public class VaadinBeanBinderExample extends AbstractTest { private static final long serialVersionUID = 1L; TextField airline = new TextField("Airline"); TextField flightNumber = new TextField("Flight number"); TextField flightSuffix = new TextField("Flight suffix"); DateField date = new DateField("Date");
// Path: src/test/java/org/vaadin/easybinder/testentity/Flight.java // @FlightValid // @GroupSequenceProvider(FlightGroupProvider.class) // public class Flight { // @Valid // FlightId flightId; // // @Temporal(TemporalType.TIMESTAMP) // Date sbt; // // @Temporal(TemporalType.TIMESTAMP) // Date ebt; // // @Temporal(TemporalType.TIMESTAMP) // Date abt; // // @NotNull(groups = FlightGroupProvider.Scheduled.class, message = "Gate should be set when scheduled") // String gate; // // boolean canceled; // // public Flight() { // flightId = new FlightId(); // } // // /** // * @return the flightId // */ // public FlightId getFlightId() { // return flightId; // } // // /** // * @param flightId // * the flightId to set // */ // public void setFlightId(FlightId flightId) { // this.flightId = flightId; // } // // /** // * @return the sbt // */ // public Date getSbt() { // return sbt; // } // // /** // * @return the ebt // */ // public Date getEbt() { // return ebt; // } // // /** // * @return the abt // */ // public Date getAbt() { // return abt; // } // // /** // * @return the gate // */ // public String getGate() { // return gate; // } // // /** // * @param sbt // * the sbt to set // */ // public void setSbt(Date sbt) { // this.sbt = sbt; // } // // /** // * @param ebt // * the ebt to set // */ // public void setEbt(Date ebt) { // this.ebt = ebt; // } // // /** // * @param abt // * the abt to set // */ // public void setAbt(Date abt) { // this.abt = abt; // } // // /** // * @param gate // * the gate to set // */ // public void setGate(String gate) { // this.gate = gate; // } // // public void setCanceled(boolean canceled) { // this.canceled = canceled; // } // // public boolean getCanceled() { // return canceled; // } // // public boolean isCanceled() { // return canceled; // } // // } // // Path: src/test/java/org/vaadin/easybinder/testentity/FlightValidator.java // public class FlightValidator implements ConstraintValidator<FlightValid, Flight> { // // @Override // public void initialize(FlightValid constraintAnnotation) { // } // // @Override // public boolean isValid(Flight flight, ConstraintValidatorContext context) { // return (flight.getAbt() == null || flight.getEbt() != null) // && (flight.getEbt() == null || flight.getSbt() != null); // } // } // // Path: src/test/java/org/vaadin/easybinder/testentity/FlightId.java // public static enum LegType { // DEPARTURE, ARRIVAL // } // Path: src/test/java/org/vaadin/easybinder/example/VaadinBeanBinderExample.java import com.vaadin.data.BeanValidationBinder; import com.vaadin.data.Binder; import com.vaadin.data.Converter; import com.vaadin.data.RequiredFieldConfigurator; import com.vaadin.data.Result; import com.vaadin.data.converter.LocalDateTimeToDateConverter; import com.vaadin.data.converter.LocalDateToDateConverter; import com.vaadin.ui.CheckBox; import com.vaadin.ui.Component; import com.vaadin.ui.DateField; import com.vaadin.ui.DateTimeField; import com.vaadin.ui.FormLayout; import com.vaadin.ui.Label; import com.vaadin.ui.RadioButtonGroup; import com.vaadin.ui.TextField; import java.time.ZoneId; import java.util.EnumSet; import javax.validation.constraints.Min; import org.vaadin.addonhelpers.AbstractTest; import org.vaadin.easybinder.testentity.Flight; import org.vaadin.easybinder.testentity.FlightValid; import org.vaadin.easybinder.testentity.FlightValidator; import org.vaadin.easybinder.testentity.FlightId.LegType; package org.vaadin.easybinder.example; public class VaadinBeanBinderExample extends AbstractTest { private static final long serialVersionUID = 1L; TextField airline = new TextField("Airline"); TextField flightNumber = new TextField("Flight number"); TextField flightSuffix = new TextField("Flight suffix"); DateField date = new DateField("Date");
RadioButtonGroup<LegType> legType = new RadioButtonGroup<>("Leg type", EnumSet.allOf(LegType.class));
ljessendk/easybinder
src/test/java/org/vaadin/easybinder/example/VaadinBeanBinderExample.java
// Path: src/test/java/org/vaadin/easybinder/testentity/Flight.java // @FlightValid // @GroupSequenceProvider(FlightGroupProvider.class) // public class Flight { // @Valid // FlightId flightId; // // @Temporal(TemporalType.TIMESTAMP) // Date sbt; // // @Temporal(TemporalType.TIMESTAMP) // Date ebt; // // @Temporal(TemporalType.TIMESTAMP) // Date abt; // // @NotNull(groups = FlightGroupProvider.Scheduled.class, message = "Gate should be set when scheduled") // String gate; // // boolean canceled; // // public Flight() { // flightId = new FlightId(); // } // // /** // * @return the flightId // */ // public FlightId getFlightId() { // return flightId; // } // // /** // * @param flightId // * the flightId to set // */ // public void setFlightId(FlightId flightId) { // this.flightId = flightId; // } // // /** // * @return the sbt // */ // public Date getSbt() { // return sbt; // } // // /** // * @return the ebt // */ // public Date getEbt() { // return ebt; // } // // /** // * @return the abt // */ // public Date getAbt() { // return abt; // } // // /** // * @return the gate // */ // public String getGate() { // return gate; // } // // /** // * @param sbt // * the sbt to set // */ // public void setSbt(Date sbt) { // this.sbt = sbt; // } // // /** // * @param ebt // * the ebt to set // */ // public void setEbt(Date ebt) { // this.ebt = ebt; // } // // /** // * @param abt // * the abt to set // */ // public void setAbt(Date abt) { // this.abt = abt; // } // // /** // * @param gate // * the gate to set // */ // public void setGate(String gate) { // this.gate = gate; // } // // public void setCanceled(boolean canceled) { // this.canceled = canceled; // } // // public boolean getCanceled() { // return canceled; // } // // public boolean isCanceled() { // return canceled; // } // // } // // Path: src/test/java/org/vaadin/easybinder/testentity/FlightValidator.java // public class FlightValidator implements ConstraintValidator<FlightValid, Flight> { // // @Override // public void initialize(FlightValid constraintAnnotation) { // } // // @Override // public boolean isValid(Flight flight, ConstraintValidatorContext context) { // return (flight.getAbt() == null || flight.getEbt() != null) // && (flight.getEbt() == null || flight.getSbt() != null); // } // } // // Path: src/test/java/org/vaadin/easybinder/testentity/FlightId.java // public static enum LegType { // DEPARTURE, ARRIVAL // }
import com.vaadin.data.BeanValidationBinder; import com.vaadin.data.Binder; import com.vaadin.data.Converter; import com.vaadin.data.RequiredFieldConfigurator; import com.vaadin.data.Result; import com.vaadin.data.converter.LocalDateTimeToDateConverter; import com.vaadin.data.converter.LocalDateToDateConverter; import com.vaadin.ui.CheckBox; import com.vaadin.ui.Component; import com.vaadin.ui.DateField; import com.vaadin.ui.DateTimeField; import com.vaadin.ui.FormLayout; import com.vaadin.ui.Label; import com.vaadin.ui.RadioButtonGroup; import com.vaadin.ui.TextField; import java.time.ZoneId; import java.util.EnumSet; import javax.validation.constraints.Min; import org.vaadin.addonhelpers.AbstractTest; import org.vaadin.easybinder.testentity.Flight; import org.vaadin.easybinder.testentity.FlightValid; import org.vaadin.easybinder.testentity.FlightValidator; import org.vaadin.easybinder.testentity.FlightId.LegType;
package org.vaadin.easybinder.example; public class VaadinBeanBinderExample extends AbstractTest { private static final long serialVersionUID = 1L; TextField airline = new TextField("Airline"); TextField flightNumber = new TextField("Flight number"); TextField flightSuffix = new TextField("Flight suffix"); DateField date = new DateField("Date"); RadioButtonGroup<LegType> legType = new RadioButtonGroup<>("Leg type", EnumSet.allOf(LegType.class)); DateTimeField sbt = new DateTimeField("SBT"); DateTimeField ebt = new DateTimeField("EBT"); DateTimeField abt = new DateTimeField("ABT"); TextField gate = new TextField("Gate"); CheckBox canceled = new CheckBox("Canceled"); @Override public Component getTestComponent() {
// Path: src/test/java/org/vaadin/easybinder/testentity/Flight.java // @FlightValid // @GroupSequenceProvider(FlightGroupProvider.class) // public class Flight { // @Valid // FlightId flightId; // // @Temporal(TemporalType.TIMESTAMP) // Date sbt; // // @Temporal(TemporalType.TIMESTAMP) // Date ebt; // // @Temporal(TemporalType.TIMESTAMP) // Date abt; // // @NotNull(groups = FlightGroupProvider.Scheduled.class, message = "Gate should be set when scheduled") // String gate; // // boolean canceled; // // public Flight() { // flightId = new FlightId(); // } // // /** // * @return the flightId // */ // public FlightId getFlightId() { // return flightId; // } // // /** // * @param flightId // * the flightId to set // */ // public void setFlightId(FlightId flightId) { // this.flightId = flightId; // } // // /** // * @return the sbt // */ // public Date getSbt() { // return sbt; // } // // /** // * @return the ebt // */ // public Date getEbt() { // return ebt; // } // // /** // * @return the abt // */ // public Date getAbt() { // return abt; // } // // /** // * @return the gate // */ // public String getGate() { // return gate; // } // // /** // * @param sbt // * the sbt to set // */ // public void setSbt(Date sbt) { // this.sbt = sbt; // } // // /** // * @param ebt // * the ebt to set // */ // public void setEbt(Date ebt) { // this.ebt = ebt; // } // // /** // * @param abt // * the abt to set // */ // public void setAbt(Date abt) { // this.abt = abt; // } // // /** // * @param gate // * the gate to set // */ // public void setGate(String gate) { // this.gate = gate; // } // // public void setCanceled(boolean canceled) { // this.canceled = canceled; // } // // public boolean getCanceled() { // return canceled; // } // // public boolean isCanceled() { // return canceled; // } // // } // // Path: src/test/java/org/vaadin/easybinder/testentity/FlightValidator.java // public class FlightValidator implements ConstraintValidator<FlightValid, Flight> { // // @Override // public void initialize(FlightValid constraintAnnotation) { // } // // @Override // public boolean isValid(Flight flight, ConstraintValidatorContext context) { // return (flight.getAbt() == null || flight.getEbt() != null) // && (flight.getEbt() == null || flight.getSbt() != null); // } // } // // Path: src/test/java/org/vaadin/easybinder/testentity/FlightId.java // public static enum LegType { // DEPARTURE, ARRIVAL // } // Path: src/test/java/org/vaadin/easybinder/example/VaadinBeanBinderExample.java import com.vaadin.data.BeanValidationBinder; import com.vaadin.data.Binder; import com.vaadin.data.Converter; import com.vaadin.data.RequiredFieldConfigurator; import com.vaadin.data.Result; import com.vaadin.data.converter.LocalDateTimeToDateConverter; import com.vaadin.data.converter.LocalDateToDateConverter; import com.vaadin.ui.CheckBox; import com.vaadin.ui.Component; import com.vaadin.ui.DateField; import com.vaadin.ui.DateTimeField; import com.vaadin.ui.FormLayout; import com.vaadin.ui.Label; import com.vaadin.ui.RadioButtonGroup; import com.vaadin.ui.TextField; import java.time.ZoneId; import java.util.EnumSet; import javax.validation.constraints.Min; import org.vaadin.addonhelpers.AbstractTest; import org.vaadin.easybinder.testentity.Flight; import org.vaadin.easybinder.testentity.FlightValid; import org.vaadin.easybinder.testentity.FlightValidator; import org.vaadin.easybinder.testentity.FlightId.LegType; package org.vaadin.easybinder.example; public class VaadinBeanBinderExample extends AbstractTest { private static final long serialVersionUID = 1L; TextField airline = new TextField("Airline"); TextField flightNumber = new TextField("Flight number"); TextField flightSuffix = new TextField("Flight suffix"); DateField date = new DateField("Date"); RadioButtonGroup<LegType> legType = new RadioButtonGroup<>("Leg type", EnumSet.allOf(LegType.class)); DateTimeField sbt = new DateTimeField("SBT"); DateTimeField ebt = new DateTimeField("EBT"); DateTimeField abt = new DateTimeField("ABT"); TextField gate = new TextField("Gate"); CheckBox canceled = new CheckBox("Canceled"); @Override public Component getTestComponent() {
BeanValidationBinder<Flight> binder = new BeanValidationBinder<>(Flight.class);
ljessendk/easybinder
src/test/java/org/vaadin/easybinder/usagetest/VaadinBeanBinderTest.java
// Path: src/test/java/org/vaadin/easybinder/testentity/Flight.java // @FlightValid // @GroupSequenceProvider(FlightGroupProvider.class) // public class Flight { // @Valid // FlightId flightId; // // @Temporal(TemporalType.TIMESTAMP) // Date sbt; // // @Temporal(TemporalType.TIMESTAMP) // Date ebt; // // @Temporal(TemporalType.TIMESTAMP) // Date abt; // // @NotNull(groups = FlightGroupProvider.Scheduled.class, message = "Gate should be set when scheduled") // String gate; // // boolean canceled; // // public Flight() { // flightId = new FlightId(); // } // // /** // * @return the flightId // */ // public FlightId getFlightId() { // return flightId; // } // // /** // * @param flightId // * the flightId to set // */ // public void setFlightId(FlightId flightId) { // this.flightId = flightId; // } // // /** // * @return the sbt // */ // public Date getSbt() { // return sbt; // } // // /** // * @return the ebt // */ // public Date getEbt() { // return ebt; // } // // /** // * @return the abt // */ // public Date getAbt() { // return abt; // } // // /** // * @return the gate // */ // public String getGate() { // return gate; // } // // /** // * @param sbt // * the sbt to set // */ // public void setSbt(Date sbt) { // this.sbt = sbt; // } // // /** // * @param ebt // * the ebt to set // */ // public void setEbt(Date ebt) { // this.ebt = ebt; // } // // /** // * @param abt // * the abt to set // */ // public void setAbt(Date abt) { // this.abt = abt; // } // // /** // * @param gate // * the gate to set // */ // public void setGate(String gate) { // this.gate = gate; // } // // public void setCanceled(boolean canceled) { // this.canceled = canceled; // } // // public boolean getCanceled() { // return canceled; // } // // public boolean isCanceled() { // return canceled; // } // // } // // Path: src/test/java/org/vaadin/easybinder/testentity/FlightValidator.java // public class FlightValidator implements ConstraintValidator<FlightValid, Flight> { // // @Override // public void initialize(FlightValid constraintAnnotation) { // } // // @Override // public boolean isValid(Flight flight, ConstraintValidatorContext context) { // return (flight.getAbt() == null || flight.getEbt() != null) // && (flight.getEbt() == null || flight.getSbt() != null); // } // }
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import java.time.ZoneId; import java.util.stream.Stream; import javax.validation.constraints.Min; import org.junit.BeforeClass; import org.junit.Test; import org.vaadin.easybinder.testentity.Flight; import org.vaadin.easybinder.testentity.FlightValid; import org.vaadin.easybinder.testentity.FlightValidator; import com.vaadin.data.BeanValidationBinder; import com.vaadin.data.Binder; import com.vaadin.data.Converter; import com.vaadin.data.HasValue; import com.vaadin.data.RequiredFieldConfigurator; import com.vaadin.data.Result; import com.vaadin.data.converter.LocalDateTimeToDateConverter; import com.vaadin.data.converter.LocalDateToDateConverter; import com.vaadin.ui.Label;
if (e.length() == 0) { return Result.error("Must be a number"); } try { return Result.ok(Integer.parseInt(e)); } catch (NumberFormatException ex) { return Result.error("Must be a number"); } }, e -> Integer.toString(e)); binder.forField(form.airline).bind("flightId.airline"); binder.forField(form.flightNumber).withConverter(c).bind("flightId.flightNumber"); binder.forField(form.flightSuffix) .withConverter(Converter.from( e -> e.length() == 0 ? Result.ok(null) : (e.length() == 1 ? Result.ok(e.charAt(0)) : Result.error("Must be 1 character")), f -> f == null ? "" : "" + f)) .bind("flightId.flightSuffix"); binder.forField(form.date).withConverter(new LocalDateToDateConverter()).bind("flightId.date"); binder.forField(form.legType).bind("flightId.legType"); binder.forField(form.sbt).withConverter(new LocalDateTimeToDateConverter(ZoneId.systemDefault())).bind("sbt"); binder.forField(form.ebt).withConverter(new LocalDateTimeToDateConverter(ZoneId.systemDefault())).bind("ebt"); binder.forField(form.abt).withConverter(new LocalDateTimeToDateConverter(ZoneId.systemDefault())).bind("abt"); Binder.Binding<Flight, String> scheduledDependingBinding = binder.forField(form.gate).withNullRepresentation("") .withValidator(e -> form.sbt.getValue() == null ? true : e != null, "Gate should be set when scheduled") .bind(Flight::getGate, Flight::setGate); form.sbt.addValueChangeListener(e -> scheduledDependingBinding.validate()); binder.bindInstanceFields(form);
// Path: src/test/java/org/vaadin/easybinder/testentity/Flight.java // @FlightValid // @GroupSequenceProvider(FlightGroupProvider.class) // public class Flight { // @Valid // FlightId flightId; // // @Temporal(TemporalType.TIMESTAMP) // Date sbt; // // @Temporal(TemporalType.TIMESTAMP) // Date ebt; // // @Temporal(TemporalType.TIMESTAMP) // Date abt; // // @NotNull(groups = FlightGroupProvider.Scheduled.class, message = "Gate should be set when scheduled") // String gate; // // boolean canceled; // // public Flight() { // flightId = new FlightId(); // } // // /** // * @return the flightId // */ // public FlightId getFlightId() { // return flightId; // } // // /** // * @param flightId // * the flightId to set // */ // public void setFlightId(FlightId flightId) { // this.flightId = flightId; // } // // /** // * @return the sbt // */ // public Date getSbt() { // return sbt; // } // // /** // * @return the ebt // */ // public Date getEbt() { // return ebt; // } // // /** // * @return the abt // */ // public Date getAbt() { // return abt; // } // // /** // * @return the gate // */ // public String getGate() { // return gate; // } // // /** // * @param sbt // * the sbt to set // */ // public void setSbt(Date sbt) { // this.sbt = sbt; // } // // /** // * @param ebt // * the ebt to set // */ // public void setEbt(Date ebt) { // this.ebt = ebt; // } // // /** // * @param abt // * the abt to set // */ // public void setAbt(Date abt) { // this.abt = abt; // } // // /** // * @param gate // * the gate to set // */ // public void setGate(String gate) { // this.gate = gate; // } // // public void setCanceled(boolean canceled) { // this.canceled = canceled; // } // // public boolean getCanceled() { // return canceled; // } // // public boolean isCanceled() { // return canceled; // } // // } // // Path: src/test/java/org/vaadin/easybinder/testentity/FlightValidator.java // public class FlightValidator implements ConstraintValidator<FlightValid, Flight> { // // @Override // public void initialize(FlightValid constraintAnnotation) { // } // // @Override // public boolean isValid(Flight flight, ConstraintValidatorContext context) { // return (flight.getAbt() == null || flight.getEbt() != null) // && (flight.getEbt() == null || flight.getSbt() != null); // } // } // Path: src/test/java/org/vaadin/easybinder/usagetest/VaadinBeanBinderTest.java import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import java.time.ZoneId; import java.util.stream.Stream; import javax.validation.constraints.Min; import org.junit.BeforeClass; import org.junit.Test; import org.vaadin.easybinder.testentity.Flight; import org.vaadin.easybinder.testentity.FlightValid; import org.vaadin.easybinder.testentity.FlightValidator; import com.vaadin.data.BeanValidationBinder; import com.vaadin.data.Binder; import com.vaadin.data.Converter; import com.vaadin.data.HasValue; import com.vaadin.data.RequiredFieldConfigurator; import com.vaadin.data.Result; import com.vaadin.data.converter.LocalDateTimeToDateConverter; import com.vaadin.data.converter.LocalDateToDateConverter; import com.vaadin.ui.Label; if (e.length() == 0) { return Result.error("Must be a number"); } try { return Result.ok(Integer.parseInt(e)); } catch (NumberFormatException ex) { return Result.error("Must be a number"); } }, e -> Integer.toString(e)); binder.forField(form.airline).bind("flightId.airline"); binder.forField(form.flightNumber).withConverter(c).bind("flightId.flightNumber"); binder.forField(form.flightSuffix) .withConverter(Converter.from( e -> e.length() == 0 ? Result.ok(null) : (e.length() == 1 ? Result.ok(e.charAt(0)) : Result.error("Must be 1 character")), f -> f == null ? "" : "" + f)) .bind("flightId.flightSuffix"); binder.forField(form.date).withConverter(new LocalDateToDateConverter()).bind("flightId.date"); binder.forField(form.legType).bind("flightId.legType"); binder.forField(form.sbt).withConverter(new LocalDateTimeToDateConverter(ZoneId.systemDefault())).bind("sbt"); binder.forField(form.ebt).withConverter(new LocalDateTimeToDateConverter(ZoneId.systemDefault())).bind("ebt"); binder.forField(form.abt).withConverter(new LocalDateTimeToDateConverter(ZoneId.systemDefault())).bind("abt"); Binder.Binding<Flight, String> scheduledDependingBinding = binder.forField(form.gate).withNullRepresentation("") .withValidator(e -> form.sbt.getValue() == null ? true : e != null, "Gate should be set when scheduled") .bind(Flight::getGate, Flight::setGate); form.sbt.addValueChangeListener(e -> scheduledDependingBinding.validate()); binder.bindInstanceFields(form);
binder.withValidator(e -> new FlightValidator().isValid(e, null), FlightValid.MESSAGE);
ljessendk/easybinder
src/main/java/org/vaadin/easybinder/data/ReflectionBinder.java
// Path: src/main/java/org/vaadin/easybinder/data/converters/NullConverter.java // @SuppressWarnings("serial") // public class NullConverter<T> implements Converter<T, T> { // // protected T nullRepresentation; // // public NullConverter(T nullRepresentation) { // this.nullRepresentation = nullRepresentation; // } // // @Override // public Result<T> convertToModel(T value, ValueContext context) { // return (nullRepresentation == null && value == null) // || (nullRepresentation != null && nullRepresentation.equals(value)) ? Result.ok(null) // : Result.ok(value); // } // // @Override // public T convertToPresentation(T value, ValueContext context) { // return value == null ? nullRepresentation : value; // } // } // // Path: src/main/java/org/vaadin/easybinder/data/converters/NullConverterPrimitiveTarget.java // @SuppressWarnings("serial") // public class NullConverterPrimitiveTarget<T> implements Converter<T, T> { // // @Override // public Result<T> convertToModel(T value, ValueContext context) { // return value == null ? Result.error("Null not allowed") : Result.ok(value); // } // // @Override // public T convertToPresentation(T value, ValueContext context) { // return value; // } // }
import java.lang.reflect.Field; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.logging.Level; import java.util.logging.Logger; import javax.validation.constraints.Min; import org.vaadin.easybinder.data.converters.NullConverter; import org.vaadin.easybinder.data.converters.NullConverterPrimitiveTarget; import com.googlecode.gentyref.GenericTypeReflector; import com.vaadin.data.BeanPropertySet; import com.vaadin.data.BeanPropertySet.NestedBeanPropertyDefinition; import com.vaadin.data.Converter; import com.vaadin.data.HasItems; import com.vaadin.data.HasValue; import com.vaadin.data.PropertyDefinition; import com.vaadin.data.PropertySet; import com.vaadin.data.RequiredFieldConfigurator; import com.vaadin.data.ValueProvider; import com.vaadin.data.provider.DataProvider; import com.vaadin.data.provider.Query; import com.vaadin.server.Setter; import com.vaadin.util.ReflectTools;
"Could not resolve property name " + propertyName + " from " + propertySet)); ValueProvider<BEAN, ?> getter = definition.getGetter(); Setter<BEAN, ?> setter = readOnly ? null : definition.getSetter().orElse(null); EasyBinding<BEAN, PRESENTATION, MODEL> binding = bind(field, (ValueProvider) getter, (Setter) setter, propertyName, (Converter) converter); boundProperties.put(propertyName, binding); Optional<Field> modelField = getDeclaredFieldByName(definition.getPropertyHolderType(), getTopLevelName(definition)); if (Arrays.asList(modelField.get().getAnnotations()).stream().anyMatch(requiredConfigurator)) { field.setRequiredIndicatorVisible(true); } return binding; } @SuppressWarnings("unchecked") protected <PRESENTATION, MODEL> Converter<PRESENTATION, MODEL> createConverter(Class<PRESENTATION> presentationType, Class<MODEL> modelType, PRESENTATION emptyValue) { Objects.requireNonNull(presentationType); Objects.requireNonNull(modelType); Converter<PRESENTATION, MODEL> converter = converterRegistry.getConverter(presentationType, modelType); if (converter != null) { log.log(Level.INFO, "Converter for {0}->{1} found by lookup", new Object[] { presentationType, modelType }); } else if (ReflectTools.convertPrimitiveType(presentationType) .equals(ReflectTools.convertPrimitiveType(modelType))) { if (modelType.isPrimitive()) {
// Path: src/main/java/org/vaadin/easybinder/data/converters/NullConverter.java // @SuppressWarnings("serial") // public class NullConverter<T> implements Converter<T, T> { // // protected T nullRepresentation; // // public NullConverter(T nullRepresentation) { // this.nullRepresentation = nullRepresentation; // } // // @Override // public Result<T> convertToModel(T value, ValueContext context) { // return (nullRepresentation == null && value == null) // || (nullRepresentation != null && nullRepresentation.equals(value)) ? Result.ok(null) // : Result.ok(value); // } // // @Override // public T convertToPresentation(T value, ValueContext context) { // return value == null ? nullRepresentation : value; // } // } // // Path: src/main/java/org/vaadin/easybinder/data/converters/NullConverterPrimitiveTarget.java // @SuppressWarnings("serial") // public class NullConverterPrimitiveTarget<T> implements Converter<T, T> { // // @Override // public Result<T> convertToModel(T value, ValueContext context) { // return value == null ? Result.error("Null not allowed") : Result.ok(value); // } // // @Override // public T convertToPresentation(T value, ValueContext context) { // return value; // } // } // Path: src/main/java/org/vaadin/easybinder/data/ReflectionBinder.java import java.lang.reflect.Field; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.logging.Level; import java.util.logging.Logger; import javax.validation.constraints.Min; import org.vaadin.easybinder.data.converters.NullConverter; import org.vaadin.easybinder.data.converters.NullConverterPrimitiveTarget; import com.googlecode.gentyref.GenericTypeReflector; import com.vaadin.data.BeanPropertySet; import com.vaadin.data.BeanPropertySet.NestedBeanPropertyDefinition; import com.vaadin.data.Converter; import com.vaadin.data.HasItems; import com.vaadin.data.HasValue; import com.vaadin.data.PropertyDefinition; import com.vaadin.data.PropertySet; import com.vaadin.data.RequiredFieldConfigurator; import com.vaadin.data.ValueProvider; import com.vaadin.data.provider.DataProvider; import com.vaadin.data.provider.Query; import com.vaadin.server.Setter; import com.vaadin.util.ReflectTools; "Could not resolve property name " + propertyName + " from " + propertySet)); ValueProvider<BEAN, ?> getter = definition.getGetter(); Setter<BEAN, ?> setter = readOnly ? null : definition.getSetter().orElse(null); EasyBinding<BEAN, PRESENTATION, MODEL> binding = bind(field, (ValueProvider) getter, (Setter) setter, propertyName, (Converter) converter); boundProperties.put(propertyName, binding); Optional<Field> modelField = getDeclaredFieldByName(definition.getPropertyHolderType(), getTopLevelName(definition)); if (Arrays.asList(modelField.get().getAnnotations()).stream().anyMatch(requiredConfigurator)) { field.setRequiredIndicatorVisible(true); } return binding; } @SuppressWarnings("unchecked") protected <PRESENTATION, MODEL> Converter<PRESENTATION, MODEL> createConverter(Class<PRESENTATION> presentationType, Class<MODEL> modelType, PRESENTATION emptyValue) { Objects.requireNonNull(presentationType); Objects.requireNonNull(modelType); Converter<PRESENTATION, MODEL> converter = converterRegistry.getConverter(presentationType, modelType); if (converter != null) { log.log(Level.INFO, "Converter for {0}->{1} found by lookup", new Object[] { presentationType, modelType }); } else if (ReflectTools.convertPrimitiveType(presentationType) .equals(ReflectTools.convertPrimitiveType(modelType))) { if (modelType.isPrimitive()) {
converter = (Converter<PRESENTATION, MODEL>) new NullConverterPrimitiveTarget<PRESENTATION>();
ljessendk/easybinder
src/main/java/org/vaadin/easybinder/data/ReflectionBinder.java
// Path: src/main/java/org/vaadin/easybinder/data/converters/NullConverter.java // @SuppressWarnings("serial") // public class NullConverter<T> implements Converter<T, T> { // // protected T nullRepresentation; // // public NullConverter(T nullRepresentation) { // this.nullRepresentation = nullRepresentation; // } // // @Override // public Result<T> convertToModel(T value, ValueContext context) { // return (nullRepresentation == null && value == null) // || (nullRepresentation != null && nullRepresentation.equals(value)) ? Result.ok(null) // : Result.ok(value); // } // // @Override // public T convertToPresentation(T value, ValueContext context) { // return value == null ? nullRepresentation : value; // } // } // // Path: src/main/java/org/vaadin/easybinder/data/converters/NullConverterPrimitiveTarget.java // @SuppressWarnings("serial") // public class NullConverterPrimitiveTarget<T> implements Converter<T, T> { // // @Override // public Result<T> convertToModel(T value, ValueContext context) { // return value == null ? Result.error("Null not allowed") : Result.ok(value); // } // // @Override // public T convertToPresentation(T value, ValueContext context) { // return value; // } // }
import java.lang.reflect.Field; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.logging.Level; import java.util.logging.Logger; import javax.validation.constraints.Min; import org.vaadin.easybinder.data.converters.NullConverter; import org.vaadin.easybinder.data.converters.NullConverterPrimitiveTarget; import com.googlecode.gentyref.GenericTypeReflector; import com.vaadin.data.BeanPropertySet; import com.vaadin.data.BeanPropertySet.NestedBeanPropertyDefinition; import com.vaadin.data.Converter; import com.vaadin.data.HasItems; import com.vaadin.data.HasValue; import com.vaadin.data.PropertyDefinition; import com.vaadin.data.PropertySet; import com.vaadin.data.RequiredFieldConfigurator; import com.vaadin.data.ValueProvider; import com.vaadin.data.provider.DataProvider; import com.vaadin.data.provider.Query; import com.vaadin.server.Setter; import com.vaadin.util.ReflectTools;
EasyBinding<BEAN, PRESENTATION, MODEL> binding = bind(field, (ValueProvider) getter, (Setter) setter, propertyName, (Converter) converter); boundProperties.put(propertyName, binding); Optional<Field> modelField = getDeclaredFieldByName(definition.getPropertyHolderType(), getTopLevelName(definition)); if (Arrays.asList(modelField.get().getAnnotations()).stream().anyMatch(requiredConfigurator)) { field.setRequiredIndicatorVisible(true); } return binding; } @SuppressWarnings("unchecked") protected <PRESENTATION, MODEL> Converter<PRESENTATION, MODEL> createConverter(Class<PRESENTATION> presentationType, Class<MODEL> modelType, PRESENTATION emptyValue) { Objects.requireNonNull(presentationType); Objects.requireNonNull(modelType); Converter<PRESENTATION, MODEL> converter = converterRegistry.getConverter(presentationType, modelType); if (converter != null) { log.log(Level.INFO, "Converter for {0}->{1} found by lookup", new Object[] { presentationType, modelType }); } else if (ReflectTools.convertPrimitiveType(presentationType) .equals(ReflectTools.convertPrimitiveType(modelType))) { if (modelType.isPrimitive()) { converter = (Converter<PRESENTATION, MODEL>) new NullConverterPrimitiveTarget<PRESENTATION>(); log.log(Level.INFO, "Converter for primitive {0}->{1} found by identity", new Object[] { presentationType, modelType }); } else {
// Path: src/main/java/org/vaadin/easybinder/data/converters/NullConverter.java // @SuppressWarnings("serial") // public class NullConverter<T> implements Converter<T, T> { // // protected T nullRepresentation; // // public NullConverter(T nullRepresentation) { // this.nullRepresentation = nullRepresentation; // } // // @Override // public Result<T> convertToModel(T value, ValueContext context) { // return (nullRepresentation == null && value == null) // || (nullRepresentation != null && nullRepresentation.equals(value)) ? Result.ok(null) // : Result.ok(value); // } // // @Override // public T convertToPresentation(T value, ValueContext context) { // return value == null ? nullRepresentation : value; // } // } // // Path: src/main/java/org/vaadin/easybinder/data/converters/NullConverterPrimitiveTarget.java // @SuppressWarnings("serial") // public class NullConverterPrimitiveTarget<T> implements Converter<T, T> { // // @Override // public Result<T> convertToModel(T value, ValueContext context) { // return value == null ? Result.error("Null not allowed") : Result.ok(value); // } // // @Override // public T convertToPresentation(T value, ValueContext context) { // return value; // } // } // Path: src/main/java/org/vaadin/easybinder/data/ReflectionBinder.java import java.lang.reflect.Field; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.logging.Level; import java.util.logging.Logger; import javax.validation.constraints.Min; import org.vaadin.easybinder.data.converters.NullConverter; import org.vaadin.easybinder.data.converters.NullConverterPrimitiveTarget; import com.googlecode.gentyref.GenericTypeReflector; import com.vaadin.data.BeanPropertySet; import com.vaadin.data.BeanPropertySet.NestedBeanPropertyDefinition; import com.vaadin.data.Converter; import com.vaadin.data.HasItems; import com.vaadin.data.HasValue; import com.vaadin.data.PropertyDefinition; import com.vaadin.data.PropertySet; import com.vaadin.data.RequiredFieldConfigurator; import com.vaadin.data.ValueProvider; import com.vaadin.data.provider.DataProvider; import com.vaadin.data.provider.Query; import com.vaadin.server.Setter; import com.vaadin.util.ReflectTools; EasyBinding<BEAN, PRESENTATION, MODEL> binding = bind(field, (ValueProvider) getter, (Setter) setter, propertyName, (Converter) converter); boundProperties.put(propertyName, binding); Optional<Field> modelField = getDeclaredFieldByName(definition.getPropertyHolderType(), getTopLevelName(definition)); if (Arrays.asList(modelField.get().getAnnotations()).stream().anyMatch(requiredConfigurator)) { field.setRequiredIndicatorVisible(true); } return binding; } @SuppressWarnings("unchecked") protected <PRESENTATION, MODEL> Converter<PRESENTATION, MODEL> createConverter(Class<PRESENTATION> presentationType, Class<MODEL> modelType, PRESENTATION emptyValue) { Objects.requireNonNull(presentationType); Objects.requireNonNull(modelType); Converter<PRESENTATION, MODEL> converter = converterRegistry.getConverter(presentationType, modelType); if (converter != null) { log.log(Level.INFO, "Converter for {0}->{1} found by lookup", new Object[] { presentationType, modelType }); } else if (ReflectTools.convertPrimitiveType(presentationType) .equals(ReflectTools.convertPrimitiveType(modelType))) { if (modelType.isPrimitive()) { converter = (Converter<PRESENTATION, MODEL>) new NullConverterPrimitiveTarget<PRESENTATION>(); log.log(Level.INFO, "Converter for primitive {0}->{1} found by identity", new Object[] { presentationType, modelType }); } else {
converter = (Converter<PRESENTATION, MODEL>) new NullConverter<PRESENTATION>(emptyValue);
ljessendk/easybinder
src/main/java/org/vaadin/easybinder/data/ComponentFactoryRegistry.java
// Path: src/main/java/org/vaadin/easybinder/ui/EComboBox.java // public class EComboBox<T> extends ComboBox<T> implements HasGenericType<T> { // // private static final long serialVersionUID = 1L; // // protected Class<T> type; // // public EComboBox(Class<T> type, String caption) { // super(caption); // this.type = type; // } // // public EComboBox(Class<T> type, String caption, ListDataProvider<T> dataProvider) { // super(caption); // this.type = type; // setDataProvider(dataProvider); // } // // public EComboBox(Class<T> type, String caption, Collection<T> items) { // super(caption, items); // this.type = type; // } // // public EComboBox(Class<T> type) { // super(); // this.type = type; // } // // @Override // public Class<T> getGenericType() { // return type; // } // // }
import java.lang.reflect.Field; import java.math.BigDecimal; import java.math.BigInteger; import java.time.LocalDate; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Date; import java.util.EnumSet; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.function.Function; import java.util.function.Predicate; import java.util.logging.Level; import java.util.logging.Logger; import javax.persistence.Temporal; import javax.persistence.TemporalType; import org.vaadin.easybinder.ui.EComboBox; import com.googlecode.gentyref.GenericTypeReflector; import com.vaadin.shared.util.SharedUtil; import com.vaadin.ui.CheckBox; import com.vaadin.ui.Component; import com.vaadin.ui.DateField; import com.vaadin.ui.DateTimeField; import com.vaadin.ui.Grid; import com.vaadin.ui.TextField; import com.vaadin.ui.TwinColSelect;
addBuildPattern(Float.class, e -> true, e -> new TextField(SharedUtil.camelCaseToHumanFriendly(e.getName()))); addBuildPattern(float.class, e -> true, e -> new TextField(SharedUtil.camelCaseToHumanFriendly(e.getName()))); addBuildPattern(Double.class, e -> true, e -> new TextField(SharedUtil.camelCaseToHumanFriendly(e.getName()))); addBuildPattern(double.class, e -> true, e -> new TextField(SharedUtil.camelCaseToHumanFriendly(e.getName()))); addBuildPattern(BigInteger.class, e -> true, e -> new TextField(SharedUtil.camelCaseToHumanFriendly(e.getName()))); addBuildPattern(BigDecimal.class, e -> true, e -> new TextField(SharedUtil.camelCaseToHumanFriendly(e.getName()))); addBuildPattern(Character.class, e -> true, e -> new TextField(SharedUtil.camelCaseToHumanFriendly(e.getName()))); addBuildPattern(char.class, e -> true, e -> new TextField(SharedUtil.camelCaseToHumanFriendly(e.getName()))); addBuildPattern(Date.class, e -> Arrays.asList(e.getAnnotations()).stream().filter(f -> f instanceof Temporal) .map(f -> (Temporal) f).filter(f -> f.value() == TemporalType.TIMESTAMP).findAny().isPresent(), e -> new DateTimeField(SharedUtil.camelCaseToHumanFriendly(e.getName()))); addBuildPattern(Date.class, e -> !Arrays.asList(e.getAnnotations()).stream().filter(f -> f instanceof Temporal) .map(f -> (Temporal) f).filter(f -> f.value() == TemporalType.TIMESTAMP).findAny().isPresent(), e -> new DateField(SharedUtil.camelCaseToHumanFriendly(e.getName()))); addBuildPattern(LocalDate.class, e -> true, e -> new DateField(SharedUtil.camelCaseToHumanFriendly(e.getName()))); addBuildPattern(LocalDateTime.class, e -> true, e -> new DateTimeField(SharedUtil.camelCaseToHumanFriendly(e.getName()))); addBuildPattern(Boolean.class, e -> true, e -> new CheckBox(SharedUtil.camelCaseToHumanFriendly(e.getName()))); addBuildPattern(boolean.class, e -> true, e -> new CheckBox(SharedUtil.camelCaseToHumanFriendly(e.getName()))); addBuildPattern(Enum.class, e -> true, e -> { Class<?> clazz = e.getGenericType() != null ? (Class<?>) e.getGenericType() : e.getType(); @SuppressWarnings({ "rawtypes", "unchecked" })
// Path: src/main/java/org/vaadin/easybinder/ui/EComboBox.java // public class EComboBox<T> extends ComboBox<T> implements HasGenericType<T> { // // private static final long serialVersionUID = 1L; // // protected Class<T> type; // // public EComboBox(Class<T> type, String caption) { // super(caption); // this.type = type; // } // // public EComboBox(Class<T> type, String caption, ListDataProvider<T> dataProvider) { // super(caption); // this.type = type; // setDataProvider(dataProvider); // } // // public EComboBox(Class<T> type, String caption, Collection<T> items) { // super(caption, items); // this.type = type; // } // // public EComboBox(Class<T> type) { // super(); // this.type = type; // } // // @Override // public Class<T> getGenericType() { // return type; // } // // } // Path: src/main/java/org/vaadin/easybinder/data/ComponentFactoryRegistry.java import java.lang.reflect.Field; import java.math.BigDecimal; import java.math.BigInteger; import java.time.LocalDate; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Date; import java.util.EnumSet; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.function.Function; import java.util.function.Predicate; import java.util.logging.Level; import java.util.logging.Logger; import javax.persistence.Temporal; import javax.persistence.TemporalType; import org.vaadin.easybinder.ui.EComboBox; import com.googlecode.gentyref.GenericTypeReflector; import com.vaadin.shared.util.SharedUtil; import com.vaadin.ui.CheckBox; import com.vaadin.ui.Component; import com.vaadin.ui.DateField; import com.vaadin.ui.DateTimeField; import com.vaadin.ui.Grid; import com.vaadin.ui.TextField; import com.vaadin.ui.TwinColSelect; addBuildPattern(Float.class, e -> true, e -> new TextField(SharedUtil.camelCaseToHumanFriendly(e.getName()))); addBuildPattern(float.class, e -> true, e -> new TextField(SharedUtil.camelCaseToHumanFriendly(e.getName()))); addBuildPattern(Double.class, e -> true, e -> new TextField(SharedUtil.camelCaseToHumanFriendly(e.getName()))); addBuildPattern(double.class, e -> true, e -> new TextField(SharedUtil.camelCaseToHumanFriendly(e.getName()))); addBuildPattern(BigInteger.class, e -> true, e -> new TextField(SharedUtil.camelCaseToHumanFriendly(e.getName()))); addBuildPattern(BigDecimal.class, e -> true, e -> new TextField(SharedUtil.camelCaseToHumanFriendly(e.getName()))); addBuildPattern(Character.class, e -> true, e -> new TextField(SharedUtil.camelCaseToHumanFriendly(e.getName()))); addBuildPattern(char.class, e -> true, e -> new TextField(SharedUtil.camelCaseToHumanFriendly(e.getName()))); addBuildPattern(Date.class, e -> Arrays.asList(e.getAnnotations()).stream().filter(f -> f instanceof Temporal) .map(f -> (Temporal) f).filter(f -> f.value() == TemporalType.TIMESTAMP).findAny().isPresent(), e -> new DateTimeField(SharedUtil.camelCaseToHumanFriendly(e.getName()))); addBuildPattern(Date.class, e -> !Arrays.asList(e.getAnnotations()).stream().filter(f -> f instanceof Temporal) .map(f -> (Temporal) f).filter(f -> f.value() == TemporalType.TIMESTAMP).findAny().isPresent(), e -> new DateField(SharedUtil.camelCaseToHumanFriendly(e.getName()))); addBuildPattern(LocalDate.class, e -> true, e -> new DateField(SharedUtil.camelCaseToHumanFriendly(e.getName()))); addBuildPattern(LocalDateTime.class, e -> true, e -> new DateTimeField(SharedUtil.camelCaseToHumanFriendly(e.getName()))); addBuildPattern(Boolean.class, e -> true, e -> new CheckBox(SharedUtil.camelCaseToHumanFriendly(e.getName()))); addBuildPattern(boolean.class, e -> true, e -> new CheckBox(SharedUtil.camelCaseToHumanFriendly(e.getName()))); addBuildPattern(Enum.class, e -> true, e -> { Class<?> clazz = e.getGenericType() != null ? (Class<?>) e.getGenericType() : e.getType(); @SuppressWarnings({ "rawtypes", "unchecked" })
Component c = new EComboBox(clazz, SharedUtil.camelCaseToHumanFriendly(e.getName()),
ljessendk/easybinder
src/test/java/org/vaadin/easybinder/usagetest/BaseTests.java
// Path: src/test/java/org/vaadin/easybinder/testentity/Flight.java // @FlightValid // @GroupSequenceProvider(FlightGroupProvider.class) // public class Flight { // @Valid // FlightId flightId; // // @Temporal(TemporalType.TIMESTAMP) // Date sbt; // // @Temporal(TemporalType.TIMESTAMP) // Date ebt; // // @Temporal(TemporalType.TIMESTAMP) // Date abt; // // @NotNull(groups = FlightGroupProvider.Scheduled.class, message = "Gate should be set when scheduled") // String gate; // // boolean canceled; // // public Flight() { // flightId = new FlightId(); // } // // /** // * @return the flightId // */ // public FlightId getFlightId() { // return flightId; // } // // /** // * @param flightId // * the flightId to set // */ // public void setFlightId(FlightId flightId) { // this.flightId = flightId; // } // // /** // * @return the sbt // */ // public Date getSbt() { // return sbt; // } // // /** // * @return the ebt // */ // public Date getEbt() { // return ebt; // } // // /** // * @return the abt // */ // public Date getAbt() { // return abt; // } // // /** // * @return the gate // */ // public String getGate() { // return gate; // } // // /** // * @param sbt // * the sbt to set // */ // public void setSbt(Date sbt) { // this.sbt = sbt; // } // // /** // * @param ebt // * the ebt to set // */ // public void setEbt(Date ebt) { // this.ebt = ebt; // } // // /** // * @param abt // * the abt to set // */ // public void setAbt(Date abt) { // this.abt = abt; // } // // /** // * @param gate // * the gate to set // */ // public void setGate(String gate) { // this.gate = gate; // } // // public void setCanceled(boolean canceled) { // this.canceled = canceled; // } // // public boolean getCanceled() { // return canceled; // } // // public boolean isCanceled() { // return canceled; // } // // } // // Path: src/test/java/org/vaadin/easybinder/testentity/FlightId.java // public static enum LegType { // DEPARTURE, ARRIVAL // }
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.time.LocalDate; import java.time.LocalDateTime; import java.util.EnumSet; import java.util.stream.Collectors; import java.util.stream.Stream; import org.junit.Test; import org.vaadin.easybinder.testentity.Flight; import org.vaadin.easybinder.testentity.FlightId.LegType; import com.vaadin.annotations.PropertyId; import com.vaadin.data.HasValue; import com.vaadin.ui.AbstractSingleSelect; import com.vaadin.ui.CheckBox; import com.vaadin.ui.ComboBox; import com.vaadin.ui.DateField; import com.vaadin.ui.DateTimeField; import com.vaadin.ui.Label; import com.vaadin.ui.TextField;
package org.vaadin.easybinder.usagetest; public abstract class BaseTests { static class MyForm { @PropertyId("flightId.airline") TextField airline = new TextField("Airline"); @PropertyId("flightId.flightNumber") TextField flightNumber = new TextField("Flight number"); @PropertyId("flightId.flightSuffix") TextField flightSuffix = new TextField("Flight suffix"); @PropertyId("flightId.date") DateField date = new DateField("Date"); @PropertyId("flightId.legType")
// Path: src/test/java/org/vaadin/easybinder/testentity/Flight.java // @FlightValid // @GroupSequenceProvider(FlightGroupProvider.class) // public class Flight { // @Valid // FlightId flightId; // // @Temporal(TemporalType.TIMESTAMP) // Date sbt; // // @Temporal(TemporalType.TIMESTAMP) // Date ebt; // // @Temporal(TemporalType.TIMESTAMP) // Date abt; // // @NotNull(groups = FlightGroupProvider.Scheduled.class, message = "Gate should be set when scheduled") // String gate; // // boolean canceled; // // public Flight() { // flightId = new FlightId(); // } // // /** // * @return the flightId // */ // public FlightId getFlightId() { // return flightId; // } // // /** // * @param flightId // * the flightId to set // */ // public void setFlightId(FlightId flightId) { // this.flightId = flightId; // } // // /** // * @return the sbt // */ // public Date getSbt() { // return sbt; // } // // /** // * @return the ebt // */ // public Date getEbt() { // return ebt; // } // // /** // * @return the abt // */ // public Date getAbt() { // return abt; // } // // /** // * @return the gate // */ // public String getGate() { // return gate; // } // // /** // * @param sbt // * the sbt to set // */ // public void setSbt(Date sbt) { // this.sbt = sbt; // } // // /** // * @param ebt // * the ebt to set // */ // public void setEbt(Date ebt) { // this.ebt = ebt; // } // // /** // * @param abt // * the abt to set // */ // public void setAbt(Date abt) { // this.abt = abt; // } // // /** // * @param gate // * the gate to set // */ // public void setGate(String gate) { // this.gate = gate; // } // // public void setCanceled(boolean canceled) { // this.canceled = canceled; // } // // public boolean getCanceled() { // return canceled; // } // // public boolean isCanceled() { // return canceled; // } // // } // // Path: src/test/java/org/vaadin/easybinder/testentity/FlightId.java // public static enum LegType { // DEPARTURE, ARRIVAL // } // Path: src/test/java/org/vaadin/easybinder/usagetest/BaseTests.java import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.time.LocalDate; import java.time.LocalDateTime; import java.util.EnumSet; import java.util.stream.Collectors; import java.util.stream.Stream; import org.junit.Test; import org.vaadin.easybinder.testentity.Flight; import org.vaadin.easybinder.testentity.FlightId.LegType; import com.vaadin.annotations.PropertyId; import com.vaadin.data.HasValue; import com.vaadin.ui.AbstractSingleSelect; import com.vaadin.ui.CheckBox; import com.vaadin.ui.ComboBox; import com.vaadin.ui.DateField; import com.vaadin.ui.DateTimeField; import com.vaadin.ui.Label; import com.vaadin.ui.TextField; package org.vaadin.easybinder.usagetest; public abstract class BaseTests { static class MyForm { @PropertyId("flightId.airline") TextField airline = new TextField("Airline"); @PropertyId("flightId.flightNumber") TextField flightNumber = new TextField("Flight number"); @PropertyId("flightId.flightSuffix") TextField flightSuffix = new TextField("Flight suffix"); @PropertyId("flightId.date") DateField date = new DateField("Date"); @PropertyId("flightId.legType")
AbstractSingleSelect<LegType> legType = new ComboBox<>("Leg type", EnumSet.allOf(LegType.class));
ljessendk/easybinder
src/test/java/org/vaadin/easybinder/usagetest/BaseTests.java
// Path: src/test/java/org/vaadin/easybinder/testentity/Flight.java // @FlightValid // @GroupSequenceProvider(FlightGroupProvider.class) // public class Flight { // @Valid // FlightId flightId; // // @Temporal(TemporalType.TIMESTAMP) // Date sbt; // // @Temporal(TemporalType.TIMESTAMP) // Date ebt; // // @Temporal(TemporalType.TIMESTAMP) // Date abt; // // @NotNull(groups = FlightGroupProvider.Scheduled.class, message = "Gate should be set when scheduled") // String gate; // // boolean canceled; // // public Flight() { // flightId = new FlightId(); // } // // /** // * @return the flightId // */ // public FlightId getFlightId() { // return flightId; // } // // /** // * @param flightId // * the flightId to set // */ // public void setFlightId(FlightId flightId) { // this.flightId = flightId; // } // // /** // * @return the sbt // */ // public Date getSbt() { // return sbt; // } // // /** // * @return the ebt // */ // public Date getEbt() { // return ebt; // } // // /** // * @return the abt // */ // public Date getAbt() { // return abt; // } // // /** // * @return the gate // */ // public String getGate() { // return gate; // } // // /** // * @param sbt // * the sbt to set // */ // public void setSbt(Date sbt) { // this.sbt = sbt; // } // // /** // * @param ebt // * the ebt to set // */ // public void setEbt(Date ebt) { // this.ebt = ebt; // } // // /** // * @param abt // * the abt to set // */ // public void setAbt(Date abt) { // this.abt = abt; // } // // /** // * @param gate // * the gate to set // */ // public void setGate(String gate) { // this.gate = gate; // } // // public void setCanceled(boolean canceled) { // this.canceled = canceled; // } // // public boolean getCanceled() { // return canceled; // } // // public boolean isCanceled() { // return canceled; // } // // } // // Path: src/test/java/org/vaadin/easybinder/testentity/FlightId.java // public static enum LegType { // DEPARTURE, ARRIVAL // }
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.time.LocalDate; import java.time.LocalDateTime; import java.util.EnumSet; import java.util.stream.Collectors; import java.util.stream.Stream; import org.junit.Test; import org.vaadin.easybinder.testentity.Flight; import org.vaadin.easybinder.testentity.FlightId.LegType; import com.vaadin.annotations.PropertyId; import com.vaadin.data.HasValue; import com.vaadin.ui.AbstractSingleSelect; import com.vaadin.ui.CheckBox; import com.vaadin.ui.ComboBox; import com.vaadin.ui.DateField; import com.vaadin.ui.DateTimeField; import com.vaadin.ui.Label; import com.vaadin.ui.TextField;
package org.vaadin.easybinder.usagetest; public abstract class BaseTests { static class MyForm { @PropertyId("flightId.airline") TextField airline = new TextField("Airline"); @PropertyId("flightId.flightNumber") TextField flightNumber = new TextField("Flight number"); @PropertyId("flightId.flightSuffix") TextField flightSuffix = new TextField("Flight suffix"); @PropertyId("flightId.date") DateField date = new DateField("Date"); @PropertyId("flightId.legType") AbstractSingleSelect<LegType> legType = new ComboBox<>("Leg type", EnumSet.allOf(LegType.class)); DateTimeField sbt = new DateTimeField("SBT"); DateTimeField ebt = new DateTimeField("EBT"); DateTimeField abt = new DateTimeField("ABT"); TextField gate = new TextField("Gate"); CheckBox canceled = new CheckBox("Canceled"); }
// Path: src/test/java/org/vaadin/easybinder/testentity/Flight.java // @FlightValid // @GroupSequenceProvider(FlightGroupProvider.class) // public class Flight { // @Valid // FlightId flightId; // // @Temporal(TemporalType.TIMESTAMP) // Date sbt; // // @Temporal(TemporalType.TIMESTAMP) // Date ebt; // // @Temporal(TemporalType.TIMESTAMP) // Date abt; // // @NotNull(groups = FlightGroupProvider.Scheduled.class, message = "Gate should be set when scheduled") // String gate; // // boolean canceled; // // public Flight() { // flightId = new FlightId(); // } // // /** // * @return the flightId // */ // public FlightId getFlightId() { // return flightId; // } // // /** // * @param flightId // * the flightId to set // */ // public void setFlightId(FlightId flightId) { // this.flightId = flightId; // } // // /** // * @return the sbt // */ // public Date getSbt() { // return sbt; // } // // /** // * @return the ebt // */ // public Date getEbt() { // return ebt; // } // // /** // * @return the abt // */ // public Date getAbt() { // return abt; // } // // /** // * @return the gate // */ // public String getGate() { // return gate; // } // // /** // * @param sbt // * the sbt to set // */ // public void setSbt(Date sbt) { // this.sbt = sbt; // } // // /** // * @param ebt // * the ebt to set // */ // public void setEbt(Date ebt) { // this.ebt = ebt; // } // // /** // * @param abt // * the abt to set // */ // public void setAbt(Date abt) { // this.abt = abt; // } // // /** // * @param gate // * the gate to set // */ // public void setGate(String gate) { // this.gate = gate; // } // // public void setCanceled(boolean canceled) { // this.canceled = canceled; // } // // public boolean getCanceled() { // return canceled; // } // // public boolean isCanceled() { // return canceled; // } // // } // // Path: src/test/java/org/vaadin/easybinder/testentity/FlightId.java // public static enum LegType { // DEPARTURE, ARRIVAL // } // Path: src/test/java/org/vaadin/easybinder/usagetest/BaseTests.java import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.time.LocalDate; import java.time.LocalDateTime; import java.util.EnumSet; import java.util.stream.Collectors; import java.util.stream.Stream; import org.junit.Test; import org.vaadin.easybinder.testentity.Flight; import org.vaadin.easybinder.testentity.FlightId.LegType; import com.vaadin.annotations.PropertyId; import com.vaadin.data.HasValue; import com.vaadin.ui.AbstractSingleSelect; import com.vaadin.ui.CheckBox; import com.vaadin.ui.ComboBox; import com.vaadin.ui.DateField; import com.vaadin.ui.DateTimeField; import com.vaadin.ui.Label; import com.vaadin.ui.TextField; package org.vaadin.easybinder.usagetest; public abstract class BaseTests { static class MyForm { @PropertyId("flightId.airline") TextField airline = new TextField("Airline"); @PropertyId("flightId.flightNumber") TextField flightNumber = new TextField("Flight number"); @PropertyId("flightId.flightSuffix") TextField flightSuffix = new TextField("Flight suffix"); @PropertyId("flightId.date") DateField date = new DateField("Date"); @PropertyId("flightId.legType") AbstractSingleSelect<LegType> legType = new ComboBox<>("Leg type", EnumSet.allOf(LegType.class)); DateTimeField sbt = new DateTimeField("SBT"); DateTimeField ebt = new DateTimeField("EBT"); DateTimeField abt = new DateTimeField("ABT"); TextField gate = new TextField("Gate"); CheckBox canceled = new CheckBox("Canceled"); }
protected abstract void setBean(Flight flight);
co-ode-owl-plugins/matrix
src/main/java/org/coode/matrix/ui/renderer/OWLObjectListRenderer.java
// Path: src/main/java/org/coode/matrix/model/impl/FillerModel.java // public class FillerModel<R extends OWLPropertyRange, P extends OWLPropertyExpression> { // // private OWLClass cls; // private P p; // private FillerHelper helper; // // private Class<? extends OWLQuantifiedRestriction<R>> restrictionType; // // // public FillerModel(OWLClass cls, RestrictionTreeMatrixModel.PropertyRestrictionPair<R, P> pair, FillerHelper helper) { // this.cls = cls; // this.p = pair.getColumnObject(); // this.helper = helper; // this.restrictionType = pair.getFilterObject(); // } // // // public Set<R> getAssertedFillersFromSupers(){ // return helper.getAssertedFillers(cls, p, restrictionType); // } // // public Set<R> getInheritedFillers(){ // return helper.getInheritedNamedFillers(cls, p, restrictionType); // } // // public Set<R> getAssertedFillersFromEquiv(){ // return helper.getAssertedNamedFillersFromEquivs(cls, p, restrictionType); // } // // // @Override // public String toString() { // StringBuilder sb = new StringBuilder(); // for(R descr : getAssertedFillersFromSupers()){ // if (sb.length() != 0){ // sb.append(", "); // } // sb.append(descr.toString()); // } // return sb.toString(); // } // }
import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Font; import java.util.Collection; import java.util.Set; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTable; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.TableCellRenderer; import org.coode.matrix.model.impl.FillerModel; import org.protege.editor.owl.ui.renderer.OWLRendererPreferences; import org.semanticweb.owlapi.model.OWLObject;
package org.coode.matrix.ui.renderer; /* * Copyright (C) 2007, University of Manchester * * Modifications to the initial code base are copyright of their * respective authors, or their employers as appropriate. Authorship * of the modifications may be determined from the ChangeLog placed at * the end of this file. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ /** * Author: Nick Drummond<br> * http://www.cs.man.ac.uk/~drummond/<br><br> * <p/> * The University Of Manchester<br> * Bio Health Informatics Group<br> * Date: Jul 3, 2007<br><br> */ public class OWLObjectListRenderer implements TableCellRenderer { private static final Color NOT_EDITABLE_COLOUR = new Color(50, 50, 50); private static final Color EDITABLE_COLOUR = new Color(0, 0, 0); private OWLObjectsRenderer ren; private JPanel p; private Component delegate; private DefaultTableCellRenderer defaultCellRenderer = new DefaultTableCellRenderer(); public OWLObjectListRenderer(OWLObjectsRenderer ren) { this.ren = ren; p = new JPanel(){ private static final long serialVersionUID = 1L; // for some reason the BoxLayout reports a prefSize of 0, 0 so do this by hand @Override public Dimension getPreferredSize() { int prefWidth = 0; int prefHeight = 0; for (Component c : getComponents()){ final Dimension pref = c.getPreferredSize(); prefWidth += pref.width; prefHeight = Math.max(prefHeight, pref.height); } return new Dimension(prefWidth, prefHeight); } }; p.setLayout(new BoxLayout(p, BoxLayout.LINE_AXIS)); } public Component getTableCellRendererComponent(JTable jTable, Object value, boolean isSelected, boolean hasFocus, int row, int col) {
// Path: src/main/java/org/coode/matrix/model/impl/FillerModel.java // public class FillerModel<R extends OWLPropertyRange, P extends OWLPropertyExpression> { // // private OWLClass cls; // private P p; // private FillerHelper helper; // // private Class<? extends OWLQuantifiedRestriction<R>> restrictionType; // // // public FillerModel(OWLClass cls, RestrictionTreeMatrixModel.PropertyRestrictionPair<R, P> pair, FillerHelper helper) { // this.cls = cls; // this.p = pair.getColumnObject(); // this.helper = helper; // this.restrictionType = pair.getFilterObject(); // } // // // public Set<R> getAssertedFillersFromSupers(){ // return helper.getAssertedFillers(cls, p, restrictionType); // } // // public Set<R> getInheritedFillers(){ // return helper.getInheritedNamedFillers(cls, p, restrictionType); // } // // public Set<R> getAssertedFillersFromEquiv(){ // return helper.getAssertedNamedFillersFromEquivs(cls, p, restrictionType); // } // // // @Override // public String toString() { // StringBuilder sb = new StringBuilder(); // for(R descr : getAssertedFillersFromSupers()){ // if (sb.length() != 0){ // sb.append(", "); // } // sb.append(descr.toString()); // } // return sb.toString(); // } // } // Path: src/main/java/org/coode/matrix/ui/renderer/OWLObjectListRenderer.java import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Font; import java.util.Collection; import java.util.Set; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTable; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.TableCellRenderer; import org.coode.matrix.model.impl.FillerModel; import org.protege.editor.owl.ui.renderer.OWLRendererPreferences; import org.semanticweb.owlapi.model.OWLObject; package org.coode.matrix.ui.renderer; /* * Copyright (C) 2007, University of Manchester * * Modifications to the initial code base are copyright of their * respective authors, or their employers as appropriate. Authorship * of the modifications may be determined from the ChangeLog placed at * the end of this file. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ /** * Author: Nick Drummond<br> * http://www.cs.man.ac.uk/~drummond/<br><br> * <p/> * The University Of Manchester<br> * Bio Health Informatics Group<br> * Date: Jul 3, 2007<br><br> */ public class OWLObjectListRenderer implements TableCellRenderer { private static final Color NOT_EDITABLE_COLOUR = new Color(50, 50, 50); private static final Color EDITABLE_COLOUR = new Color(0, 0, 0); private OWLObjectsRenderer ren; private JPanel p; private Component delegate; private DefaultTableCellRenderer defaultCellRenderer = new DefaultTableCellRenderer(); public OWLObjectListRenderer(OWLObjectsRenderer ren) { this.ren = ren; p = new JPanel(){ private static final long serialVersionUID = 1L; // for some reason the BoxLayout reports a prefSize of 0, 0 so do this by hand @Override public Dimension getPreferredSize() { int prefWidth = 0; int prefHeight = 0; for (Component c : getComponents()){ final Dimension pref = c.getPreferredSize(); prefWidth += pref.width; prefHeight = Math.max(prefHeight, pref.height); } return new Dimension(prefWidth, prefHeight); } }; p.setLayout(new BoxLayout(p, BoxLayout.LINE_AXIS)); } public Component getTableCellRendererComponent(JTable jTable, Object value, boolean isSelected, boolean hasFocus, int row, int col) {
if (value instanceof FillerModel){
co-ode-owl-plugins/matrix
src/main/java/org/coode/matrix/ui/component/MatrixTreeTable.java
// Path: src/main/java/org/coode/matrix/model/api/MatrixModel.java // public interface MatrixModel<R extends OWLObject> extends TreeTableModel<R> { // // String getTreeColumnLabel(); // // Object getMatrixValue(R rowObject, Object columnObject); // // List<OWLOntologyChange> setMatrixValue(R rowObj, Object columnObj, Object value); // // List<OWLOntologyChange> addMatrixValue(R rowObj, Object columnObj, Object value); // // boolean isSuitableCellValue(Object value, int row, int col); // // Object getSuitableColumnObject(Object columnObject); // // boolean isValueRestricted(R rowObject, Object columnObject); // // Set getSuggestedFillers(R rowObject, Object columnObject, int threshold); // // // void setFilterForColumn(Object columnObject, Object filter); // // // // Object getFilterForColumn(Object obj); // // void dispose(); // } // // Path: src/main/java/org/coode/matrix/ui/renderer/MatrixHeaderCellRenderer.java // public class MatrixHeaderCellRenderer extends DefaultTableCellRenderer { // private static final long serialVersionUID = 1L; // @Override // public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int col) { // // use getColumnName from the model // col = table.convertColumnIndexToModel(col); // value = table.getModel().getColumnName(col); // super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col); // // Inherit the colors and font from the header component // JTableHeader header = table.getTableHeader(); // if (header != null) { // setForeground(header.getForeground()); // setBackground(header.getBackground()); // setFont(header.getFont()); // } // // setBorder(UIManager.getBorder("TableHeader.cellBorder")); // setHorizontalAlignment(SwingConstants.CENTER); // return this; // } // }
import java.awt.Color; import java.awt.Container; import java.awt.Cursor; import java.awt.Point; import java.awt.Rectangle; import java.awt.datatransfer.Transferable; import java.awt.dnd.DropTarget; import java.awt.dnd.DropTargetDragEvent; import java.awt.dnd.DropTargetEvent; import java.util.List; import javax.swing.JComponent; import javax.swing.table.TableCellRenderer; import javax.swing.table.TableColumn; import javax.swing.table.TableColumnModel; import javax.swing.tree.TreeSelectionModel; import org.coode.matrix.model.api.MatrixModel; import org.coode.matrix.ui.renderer.MatrixHeaderCellRenderer; import org.protege.editor.owl.model.OWLModelManager; import org.protege.editor.owl.model.event.EventType; import org.protege.editor.owl.model.event.OWLModelManagerChangeEvent; import org.protege.editor.owl.model.event.OWLModelManagerListener; import org.protege.editor.owl.ui.renderer.LinkedObjectComponent; import org.protege.editor.owl.ui.renderer.OWLRendererPreferences; import org.protege.editor.owl.ui.table.OWLObjectDropTargetListener; import org.protege.editor.owl.ui.transfer.OWLObjectDropTarget; import org.protege.editor.owl.ui.tree.OWLObjectTree; import org.semanticweb.owlapi.model.OWLEntity; import org.semanticweb.owlapi.model.OWLObject; import org.semanticweb.owlapi.model.OWLOntologyChange; import uk.ac.manchester.cs.bhig.jtreetable.JTreeTable;
/* * Copyright (C) 2007, University of Manchester */ package org.coode.matrix.ui.component; /** * Author: Nick Drummond<br> * http://www.cs.man.ac.uk/~drummond/<br><br> * <p/> * The University Of Manchester<br> * Bio Health Informatics Group<br> * Date: Jan 3, 2008<br><br> */ public class MatrixTreeTable<R extends OWLObject> extends JTreeTable<R> implements OWLObjectDropTarget, LinkedObjectComponent { private static final long serialVersionUID = 1L; private OWLModelManager mngr;
// Path: src/main/java/org/coode/matrix/model/api/MatrixModel.java // public interface MatrixModel<R extends OWLObject> extends TreeTableModel<R> { // // String getTreeColumnLabel(); // // Object getMatrixValue(R rowObject, Object columnObject); // // List<OWLOntologyChange> setMatrixValue(R rowObj, Object columnObj, Object value); // // List<OWLOntologyChange> addMatrixValue(R rowObj, Object columnObj, Object value); // // boolean isSuitableCellValue(Object value, int row, int col); // // Object getSuitableColumnObject(Object columnObject); // // boolean isValueRestricted(R rowObject, Object columnObject); // // Set getSuggestedFillers(R rowObject, Object columnObject, int threshold); // // // void setFilterForColumn(Object columnObject, Object filter); // // // // Object getFilterForColumn(Object obj); // // void dispose(); // } // // Path: src/main/java/org/coode/matrix/ui/renderer/MatrixHeaderCellRenderer.java // public class MatrixHeaderCellRenderer extends DefaultTableCellRenderer { // private static final long serialVersionUID = 1L; // @Override // public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int col) { // // use getColumnName from the model // col = table.convertColumnIndexToModel(col); // value = table.getModel().getColumnName(col); // super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col); // // Inherit the colors and font from the header component // JTableHeader header = table.getTableHeader(); // if (header != null) { // setForeground(header.getForeground()); // setBackground(header.getBackground()); // setFont(header.getFont()); // } // // setBorder(UIManager.getBorder("TableHeader.cellBorder")); // setHorizontalAlignment(SwingConstants.CENTER); // return this; // } // } // Path: src/main/java/org/coode/matrix/ui/component/MatrixTreeTable.java import java.awt.Color; import java.awt.Container; import java.awt.Cursor; import java.awt.Point; import java.awt.Rectangle; import java.awt.datatransfer.Transferable; import java.awt.dnd.DropTarget; import java.awt.dnd.DropTargetDragEvent; import java.awt.dnd.DropTargetEvent; import java.util.List; import javax.swing.JComponent; import javax.swing.table.TableCellRenderer; import javax.swing.table.TableColumn; import javax.swing.table.TableColumnModel; import javax.swing.tree.TreeSelectionModel; import org.coode.matrix.model.api.MatrixModel; import org.coode.matrix.ui.renderer.MatrixHeaderCellRenderer; import org.protege.editor.owl.model.OWLModelManager; import org.protege.editor.owl.model.event.EventType; import org.protege.editor.owl.model.event.OWLModelManagerChangeEvent; import org.protege.editor.owl.model.event.OWLModelManagerListener; import org.protege.editor.owl.ui.renderer.LinkedObjectComponent; import org.protege.editor.owl.ui.renderer.OWLRendererPreferences; import org.protege.editor.owl.ui.table.OWLObjectDropTargetListener; import org.protege.editor.owl.ui.transfer.OWLObjectDropTarget; import org.protege.editor.owl.ui.tree.OWLObjectTree; import org.semanticweb.owlapi.model.OWLEntity; import org.semanticweb.owlapi.model.OWLObject; import org.semanticweb.owlapi.model.OWLOntologyChange; import uk.ac.manchester.cs.bhig.jtreetable.JTreeTable; /* * Copyright (C) 2007, University of Manchester */ package org.coode.matrix.ui.component; /** * Author: Nick Drummond<br> * http://www.cs.man.ac.uk/~drummond/<br><br> * <p/> * The University Of Manchester<br> * Bio Health Informatics Group<br> * Date: Jan 3, 2008<br><br> */ public class MatrixTreeTable<R extends OWLObject> extends JTreeTable<R> implements OWLObjectDropTarget, LinkedObjectComponent { private static final long serialVersionUID = 1L; private OWLModelManager mngr;
protected MatrixModel<R> model;
co-ode-owl-plugins/matrix
src/main/java/org/coode/matrix/ui/component/MatrixTreeTable.java
// Path: src/main/java/org/coode/matrix/model/api/MatrixModel.java // public interface MatrixModel<R extends OWLObject> extends TreeTableModel<R> { // // String getTreeColumnLabel(); // // Object getMatrixValue(R rowObject, Object columnObject); // // List<OWLOntologyChange> setMatrixValue(R rowObj, Object columnObj, Object value); // // List<OWLOntologyChange> addMatrixValue(R rowObj, Object columnObj, Object value); // // boolean isSuitableCellValue(Object value, int row, int col); // // Object getSuitableColumnObject(Object columnObject); // // boolean isValueRestricted(R rowObject, Object columnObject); // // Set getSuggestedFillers(R rowObject, Object columnObject, int threshold); // // // void setFilterForColumn(Object columnObject, Object filter); // // // // Object getFilterForColumn(Object obj); // // void dispose(); // } // // Path: src/main/java/org/coode/matrix/ui/renderer/MatrixHeaderCellRenderer.java // public class MatrixHeaderCellRenderer extends DefaultTableCellRenderer { // private static final long serialVersionUID = 1L; // @Override // public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int col) { // // use getColumnName from the model // col = table.convertColumnIndexToModel(col); // value = table.getModel().getColumnName(col); // super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col); // // Inherit the colors and font from the header component // JTableHeader header = table.getTableHeader(); // if (header != null) { // setForeground(header.getForeground()); // setBackground(header.getBackground()); // setFont(header.getFont()); // } // // setBorder(UIManager.getBorder("TableHeader.cellBorder")); // setHorizontalAlignment(SwingConstants.CENTER); // return this; // } // }
import java.awt.Color; import java.awt.Container; import java.awt.Cursor; import java.awt.Point; import java.awt.Rectangle; import java.awt.datatransfer.Transferable; import java.awt.dnd.DropTarget; import java.awt.dnd.DropTargetDragEvent; import java.awt.dnd.DropTargetEvent; import java.util.List; import javax.swing.JComponent; import javax.swing.table.TableCellRenderer; import javax.swing.table.TableColumn; import javax.swing.table.TableColumnModel; import javax.swing.tree.TreeSelectionModel; import org.coode.matrix.model.api.MatrixModel; import org.coode.matrix.ui.renderer.MatrixHeaderCellRenderer; import org.protege.editor.owl.model.OWLModelManager; import org.protege.editor.owl.model.event.EventType; import org.protege.editor.owl.model.event.OWLModelManagerChangeEvent; import org.protege.editor.owl.model.event.OWLModelManagerListener; import org.protege.editor.owl.ui.renderer.LinkedObjectComponent; import org.protege.editor.owl.ui.renderer.OWLRendererPreferences; import org.protege.editor.owl.ui.table.OWLObjectDropTargetListener; import org.protege.editor.owl.ui.transfer.OWLObjectDropTarget; import org.protege.editor.owl.ui.tree.OWLObjectTree; import org.semanticweb.owlapi.model.OWLEntity; import org.semanticweb.owlapi.model.OWLObject; import org.semanticweb.owlapi.model.OWLOntologyChange; import uk.ac.manchester.cs.bhig.jtreetable.JTreeTable;
/* * Copyright (C) 2007, University of Manchester */ package org.coode.matrix.ui.component; /** * Author: Nick Drummond<br> * http://www.cs.man.ac.uk/~drummond/<br><br> * <p/> * The University Of Manchester<br> * Bio Health Informatics Group<br> * Date: Jan 3, 2008<br><br> */ public class MatrixTreeTable<R extends OWLObject> extends JTreeTable<R> implements OWLObjectDropTarget, LinkedObjectComponent { private static final long serialVersionUID = 1L; private OWLModelManager mngr; protected MatrixModel<R> model; protected Cursor defaultCursor; private TableCellRenderer headerRenderer; private OWLModelManagerListener l = new OWLModelManagerListener(){ public void handleChange(OWLModelManagerChangeEvent event) { if (event.getType().equals(EventType.ENTITY_RENDERER_CHANGED)){ handleRendererChanged(); } } }; public MatrixTreeTable(OWLObjectTree<R> tree, MatrixModel<R> model, OWLModelManager mngr) { // constructor ensures createColsFromModel disabled otherwise JTable redraws all columns // on a tableChanged() losing any width info columns are added manually in tableChanged() super(tree, model); this.model = model; this.mngr = mngr;
// Path: src/main/java/org/coode/matrix/model/api/MatrixModel.java // public interface MatrixModel<R extends OWLObject> extends TreeTableModel<R> { // // String getTreeColumnLabel(); // // Object getMatrixValue(R rowObject, Object columnObject); // // List<OWLOntologyChange> setMatrixValue(R rowObj, Object columnObj, Object value); // // List<OWLOntologyChange> addMatrixValue(R rowObj, Object columnObj, Object value); // // boolean isSuitableCellValue(Object value, int row, int col); // // Object getSuitableColumnObject(Object columnObject); // // boolean isValueRestricted(R rowObject, Object columnObject); // // Set getSuggestedFillers(R rowObject, Object columnObject, int threshold); // // // void setFilterForColumn(Object columnObject, Object filter); // // // // Object getFilterForColumn(Object obj); // // void dispose(); // } // // Path: src/main/java/org/coode/matrix/ui/renderer/MatrixHeaderCellRenderer.java // public class MatrixHeaderCellRenderer extends DefaultTableCellRenderer { // private static final long serialVersionUID = 1L; // @Override // public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int col) { // // use getColumnName from the model // col = table.convertColumnIndexToModel(col); // value = table.getModel().getColumnName(col); // super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col); // // Inherit the colors and font from the header component // JTableHeader header = table.getTableHeader(); // if (header != null) { // setForeground(header.getForeground()); // setBackground(header.getBackground()); // setFont(header.getFont()); // } // // setBorder(UIManager.getBorder("TableHeader.cellBorder")); // setHorizontalAlignment(SwingConstants.CENTER); // return this; // } // } // Path: src/main/java/org/coode/matrix/ui/component/MatrixTreeTable.java import java.awt.Color; import java.awt.Container; import java.awt.Cursor; import java.awt.Point; import java.awt.Rectangle; import java.awt.datatransfer.Transferable; import java.awt.dnd.DropTarget; import java.awt.dnd.DropTargetDragEvent; import java.awt.dnd.DropTargetEvent; import java.util.List; import javax.swing.JComponent; import javax.swing.table.TableCellRenderer; import javax.swing.table.TableColumn; import javax.swing.table.TableColumnModel; import javax.swing.tree.TreeSelectionModel; import org.coode.matrix.model.api.MatrixModel; import org.coode.matrix.ui.renderer.MatrixHeaderCellRenderer; import org.protege.editor.owl.model.OWLModelManager; import org.protege.editor.owl.model.event.EventType; import org.protege.editor.owl.model.event.OWLModelManagerChangeEvent; import org.protege.editor.owl.model.event.OWLModelManagerListener; import org.protege.editor.owl.ui.renderer.LinkedObjectComponent; import org.protege.editor.owl.ui.renderer.OWLRendererPreferences; import org.protege.editor.owl.ui.table.OWLObjectDropTargetListener; import org.protege.editor.owl.ui.transfer.OWLObjectDropTarget; import org.protege.editor.owl.ui.tree.OWLObjectTree; import org.semanticweb.owlapi.model.OWLEntity; import org.semanticweb.owlapi.model.OWLObject; import org.semanticweb.owlapi.model.OWLOntologyChange; import uk.ac.manchester.cs.bhig.jtreetable.JTreeTable; /* * Copyright (C) 2007, University of Manchester */ package org.coode.matrix.ui.component; /** * Author: Nick Drummond<br> * http://www.cs.man.ac.uk/~drummond/<br><br> * <p/> * The University Of Manchester<br> * Bio Health Informatics Group<br> * Date: Jan 3, 2008<br><br> */ public class MatrixTreeTable<R extends OWLObject> extends JTreeTable<R> implements OWLObjectDropTarget, LinkedObjectComponent { private static final long serialVersionUID = 1L; private OWLModelManager mngr; protected MatrixModel<R> model; protected Cursor defaultCursor; private TableCellRenderer headerRenderer; private OWLModelManagerListener l = new OWLModelManagerListener(){ public void handleChange(OWLModelManagerChangeEvent event) { if (event.getType().equals(EventType.ENTITY_RENDERER_CHANGED)){ handleRendererChanged(); } } }; public MatrixTreeTable(OWLObjectTree<R> tree, MatrixModel<R> model, OWLModelManager mngr) { // constructor ensures createColsFromModel disabled otherwise JTable redraws all columns // on a tableChanged() losing any width info columns are added manually in tableChanged() super(tree, model); this.model = model; this.mngr = mngr;
headerRenderer = new MatrixHeaderCellRenderer();
jrimum/texgit
src/main/java/org/jrimum/texgit/type/component/Record.java
// Path: src/main/java/org/jrimum/texgit/type/Field.java // public interface Field<G> extends TextStream, Cloneable{ // // public abstract String getName(); // // public abstract void setName(String name); // // public abstract G getValue(); // // public abstract void setValue(G value); // // public abstract Format getFormatter(); // // public abstract void setFormatter(Format formatter); // // public abstract boolean isBlankAccepted(); // // public abstract void setBlankAccepted(boolean blankAccepted); // // public abstract Field<G> clone() throws CloneNotSupportedException; // }
import static org.apache.commons.lang.StringUtils.isNotBlank; import static org.jrimum.utilix.Objects.isNotNull; import static org.jrimum.utilix.Objects.isNull; import java.util.ArrayList; import java.util.List; import java.util.Set; import org.jrimum.texgit.type.Field; import org.jrimum.utilix.Objects; import static java.lang.String.format; import static org.apache.commons.lang.StringUtils.EMPTY;
} catch (CloneNotSupportedException e) { throw new UnsupportedOperationException(format("Quebra de contrato [%s] não suporta clonagem!",Objects.whenNull(ffID, "FixedField", ffID.getClass())), e); } getIdType().read(lineRecord.substring(getIdPosition(), getIdPosition() + getIdType().getFixedLength())); return ffID; } public org.jrimum.texgit.type.FixedField<?> getField(String fieldName) { org.jrimum.texgit.type.FixedField<?> field = null; if (isNotBlank(fieldName)) if (!getFields().isEmpty()) for (FixedField<?> ff : this.getFields()) if (ff.getName().equals(fieldName)) { field = ff; break; } return field; } public boolean isMyField(String idName){ boolean is = false; if (isNotBlank(idName)) { if(!getFields().isEmpty())
// Path: src/main/java/org/jrimum/texgit/type/Field.java // public interface Field<G> extends TextStream, Cloneable{ // // public abstract String getName(); // // public abstract void setName(String name); // // public abstract G getValue(); // // public abstract void setValue(G value); // // public abstract Format getFormatter(); // // public abstract void setFormatter(Format formatter); // // public abstract boolean isBlankAccepted(); // // public abstract void setBlankAccepted(boolean blankAccepted); // // public abstract Field<G> clone() throws CloneNotSupportedException; // } // Path: src/main/java/org/jrimum/texgit/type/component/Record.java import static org.apache.commons.lang.StringUtils.isNotBlank; import static org.jrimum.utilix.Objects.isNotNull; import static org.jrimum.utilix.Objects.isNull; import java.util.ArrayList; import java.util.List; import java.util.Set; import org.jrimum.texgit.type.Field; import org.jrimum.utilix.Objects; import static java.lang.String.format; import static org.apache.commons.lang.StringUtils.EMPTY; } catch (CloneNotSupportedException e) { throw new UnsupportedOperationException(format("Quebra de contrato [%s] não suporta clonagem!",Objects.whenNull(ffID, "FixedField", ffID.getClass())), e); } getIdType().read(lineRecord.substring(getIdPosition(), getIdPosition() + getIdType().getFixedLength())); return ffID; } public org.jrimum.texgit.type.FixedField<?> getField(String fieldName) { org.jrimum.texgit.type.FixedField<?> field = null; if (isNotBlank(fieldName)) if (!getFields().isEmpty()) for (FixedField<?> ff : this.getFields()) if (ff.getName().equals(fieldName)) { field = ff; break; } return field; } public boolean isMyField(String idName){ boolean is = false; if (isNotBlank(idName)) { if(!getFields().isEmpty())
for(org.jrimum.texgit.type.Field<?> f : getFields())
jrimum/texgit
src/main/java/org/jrimum/texgit/type/Filler.java
// Path: src/main/java/org/jrimum/texgit/TextStream.java // public interface TextStream extends ReadWriteStream<String> { // // }
import java.io.Serializable; import org.jrimum.texgit.TextStream;
package org.jrimum.texgit.type; public interface Filler extends Serializable{ /** * Preenche o campo com o caracter especificado e no lado especificado. * * <p> * Exemplo: * <br/> * Se <code>sideToFill == SideToFill.LEFT</code>, o caracter especificado será adicionado à String * no lado esquerdo até que o campo fique com o tamanho que foi definido. * </p> * * @param toFill * @param length * @return String preenchida * * @since 0.2 */ String fill(String toFill, int length); /** * Executa o método <code>fill(String, int)</code> passando o parâmetro * <code>toFill</code> como <code>String.valueOf(toFill)</code>. * * @param tofill * @param length * @return String preenchida * * @see Filler#fill(String, int) * * @since 0.2 */ String fill(long tofill, int length); /** * Executa o método <code>fill(String, int)</code> passando o parâmetro * <code>toFill</code> como <code>String.valueOf(toFill)</code>. * * @param tofill * @param length * @return String preenchida * * @see Filler#fill(String, int) * * @since 0.2 */ String fill(int tofill, int length); /** * Executa o método <code>fill(String, int)</code> passando o parâmetro * <code>toFill</code> como <code>String.valueOf(toFill)</code>. * * @param tofill * @param length * @return String preenchida * * @see Filler#fill(String, int) * * @since 0.2 */ String fill(short tofill, int length); /** * Executa o método <code>fill(String, int)</code> passando o parâmetro * <code>toFill</code> como <code>String.valueOf(toFill)</code>. * * @param tofill * @param length * @return String preenchida * * @see Filler#fill(String, int) * * @since 0.2 */ String fill(byte tofill, int length); /** * Executa o método <code>fill(String, int)</code> passando o parâmetro * <code>toFill</code> como <code>String.valueOf(toFill)</code>. * * @param tofill * @param length * @return String preenchida * * @see Filler#fill(String, int) * * @since 0.2 */ String fill(char tofill, int length); /** * Executa o método <code>fill(String, int)</code> passando o parâmetro * <code>toFill</code> como <code>String.valueOf(toFill)</code>. * * @param tofill * @param length * @return String preenchida * * @see Filler#fill(String, int) * * @since 0.2 */ String fill(double tofill, int length); /** * Executa o método <code>fill(String, int)</code> passando o parâmetro * <code>toFill</code> como <code>String.valueOf(toFill)</code>. * * @param tofill * @param length * @return String preenchida * * @see Filler#fill(String, int) * * @since */ String fill(float tofill, int length); /** * Executa o método <code>fill(String, int)</code> passando o parâmetro * <code>toFill</code> como <code>toFill.toString()</code>. * * <p> * Caso <code>toFill</code> seja <code>null</code>, o método * <code>fill(String, int)</code> receberá uma String nula como parâmetro. * </p> * * @param tofill * @param length * @return String preenchida * * @see Filler#fill(String, int) * * @since 0.2 */ String fill(Object tofill, int length); /** * Executa o método <code>fill(String, int)</code> passando o parâmetro * <code>toFill</code> como <code>toFill.write()</code>. * * <p> * Caso <code>toFill</code> seja <code>null</code>, o método * <code>fill(String, int)</code> receberá uma String nula como parâmetro. * </p> * * @param tofill * @param length * @return String preenchida * * @see Filler#fill(String, int) * * @since 0.2 */
// Path: src/main/java/org/jrimum/texgit/TextStream.java // public interface TextStream extends ReadWriteStream<String> { // // } // Path: src/main/java/org/jrimum/texgit/type/Filler.java import java.io.Serializable; import org.jrimum.texgit.TextStream; package org.jrimum.texgit.type; public interface Filler extends Serializable{ /** * Preenche o campo com o caracter especificado e no lado especificado. * * <p> * Exemplo: * <br/> * Se <code>sideToFill == SideToFill.LEFT</code>, o caracter especificado será adicionado à String * no lado esquerdo até que o campo fique com o tamanho que foi definido. * </p> * * @param toFill * @param length * @return String preenchida * * @since 0.2 */ String fill(String toFill, int length); /** * Executa o método <code>fill(String, int)</code> passando o parâmetro * <code>toFill</code> como <code>String.valueOf(toFill)</code>. * * @param tofill * @param length * @return String preenchida * * @see Filler#fill(String, int) * * @since 0.2 */ String fill(long tofill, int length); /** * Executa o método <code>fill(String, int)</code> passando o parâmetro * <code>toFill</code> como <code>String.valueOf(toFill)</code>. * * @param tofill * @param length * @return String preenchida * * @see Filler#fill(String, int) * * @since 0.2 */ String fill(int tofill, int length); /** * Executa o método <code>fill(String, int)</code> passando o parâmetro * <code>toFill</code> como <code>String.valueOf(toFill)</code>. * * @param tofill * @param length * @return String preenchida * * @see Filler#fill(String, int) * * @since 0.2 */ String fill(short tofill, int length); /** * Executa o método <code>fill(String, int)</code> passando o parâmetro * <code>toFill</code> como <code>String.valueOf(toFill)</code>. * * @param tofill * @param length * @return String preenchida * * @see Filler#fill(String, int) * * @since 0.2 */ String fill(byte tofill, int length); /** * Executa o método <code>fill(String, int)</code> passando o parâmetro * <code>toFill</code> como <code>String.valueOf(toFill)</code>. * * @param tofill * @param length * @return String preenchida * * @see Filler#fill(String, int) * * @since 0.2 */ String fill(char tofill, int length); /** * Executa o método <code>fill(String, int)</code> passando o parâmetro * <code>toFill</code> como <code>String.valueOf(toFill)</code>. * * @param tofill * @param length * @return String preenchida * * @see Filler#fill(String, int) * * @since 0.2 */ String fill(double tofill, int length); /** * Executa o método <code>fill(String, int)</code> passando o parâmetro * <code>toFill</code> como <code>String.valueOf(toFill)</code>. * * @param tofill * @param length * @return String preenchida * * @see Filler#fill(String, int) * * @since */ String fill(float tofill, int length); /** * Executa o método <code>fill(String, int)</code> passando o parâmetro * <code>toFill</code> como <code>toFill.toString()</code>. * * <p> * Caso <code>toFill</code> seja <code>null</code>, o método * <code>fill(String, int)</code> receberá uma String nula como parâmetro. * </p> * * @param tofill * @param length * @return String preenchida * * @see Filler#fill(String, int) * * @since 0.2 */ String fill(Object tofill, int length); /** * Executa o método <code>fill(String, int)</code> passando o parâmetro * <code>toFill</code> como <code>toFill.write()</code>. * * <p> * Caso <code>toFill</code> seja <code>null</code>, o método * <code>fill(String, int)</code> receberá uma String nula como parâmetro. * </p> * * @param tofill * @param length * @return String preenchida * * @see Filler#fill(String, int) * * @since 0.2 */
String fill(TextStream tofill, int length);
jrimum/texgit
src/main/java/org/jrimum/texgit/type/component/Field.java
// Path: src/main/java/org/jrimum/texgit/TextStream.java // public interface TextStream extends ReadWriteStream<String> { // // }
import static org.apache.commons.lang.StringUtils.isBlank; import static org.apache.commons.lang.StringUtils.isNumeric; import static org.jrimum.utilix.Objects.isNotNull; import java.lang.reflect.Constructor; import java.math.BigDecimal; import java.text.DecimalFormat; import java.text.Format; import java.text.ParseException; import java.util.Date; import org.jrimum.texgit.TextStream; import org.jrimum.utilix.Dates; import org.jrimum.utilix.Objects; import static java.lang.String.format; import static org.apache.commons.lang.StringUtils.EMPTY;
* <p> * Cria um <code>Field</code> com nome para identificação, valor e um formatador. * </p> * * @param name * @param value * @param formatter * * @see #Field(Object, Format) */ public Field(String name, G value, Format formatter){ setName(name); setValue(value); setFormatter(formatter); } @SuppressWarnings("unchecked") @Override public Field<G> clone() throws CloneNotSupportedException { return (Field<G>) super.clone(); } public void read(String str) { Objects.checkNotNull(str, "String inválida [null]!"); try{
// Path: src/main/java/org/jrimum/texgit/TextStream.java // public interface TextStream extends ReadWriteStream<String> { // // } // Path: src/main/java/org/jrimum/texgit/type/component/Field.java import static org.apache.commons.lang.StringUtils.isBlank; import static org.apache.commons.lang.StringUtils.isNumeric; import static org.jrimum.utilix.Objects.isNotNull; import java.lang.reflect.Constructor; import java.math.BigDecimal; import java.text.DecimalFormat; import java.text.Format; import java.text.ParseException; import java.util.Date; import org.jrimum.texgit.TextStream; import org.jrimum.utilix.Dates; import org.jrimum.utilix.Objects; import static java.lang.String.format; import static org.apache.commons.lang.StringUtils.EMPTY; * <p> * Cria um <code>Field</code> com nome para identificação, valor e um formatador. * </p> * * @param name * @param value * @param formatter * * @see #Field(Object, Format) */ public Field(String name, G value, Format formatter){ setName(name); setValue(value); setFormatter(formatter); } @SuppressWarnings("unchecked") @Override public Field<G> clone() throws CloneNotSupportedException { return (Field<G>) super.clone(); } public void read(String str) { Objects.checkNotNull(str, "String inválida [null]!"); try{
if (this.value instanceof TextStream) {
jrimum/texgit
src/main/java/org/jrimum/texgit/Texgit.java
// Path: src/main/java/org/jrimum/texgit/engine/TexgitManager.java // public class TexgitManager { // // public static FlatFile<org.jrimum.texgit.Record> buildFlatFile(InputStream xmlDefStream) { // // FlatFile<Record> iFlatFile = null; // // try { // // MetaTexgit tgMeta = TexgitXmlReader.parse(xmlDefStream); // // iFlatFile = FlatFileBuilder.build(tgMeta.getFlatFile()); // // } catch (Exception e) { // throw new TexgitException(e); // } // // return iFlatFile; // } // }
import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.net.URL; import org.jrimum.texgit.engine.TexgitManager; import static org.apache.commons.lang.StringUtils.isNotBlank; import static org.jrimum.utilix.Objects.isNotNull;
/* * Copyright 2008 JRimum Project * * 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. * * Created at: 26/07/2008 - 12:44:41 * * ================================================================================ * * Direitos autorais 2008 JRimum Project * * Licenciado sob a Licença Apache, Versão 2.0 ("LICENÇA"); você não pode usar * esse arquivo exceto em conformidade com a esta LICENÇA. Você pode obter uma * cópia desta LICENÇA em http://www.apache.org/licenses/LICENSE-2.0 A menos que * haja exigência legal ou acordo por escrito, a distribuição de software sob * esta LICENÇA se dará “COMO ESTÁ”, SEM GARANTIAS OU CONDIÇÕES DE QUALQUER * TIPO, sejam expressas ou tácitas. Veja a LICENÇA para a redação específica a * reger permissões e limitações sob esta LICENÇA. * * Criado em: 26/07/2008 - 12:44:41 * */ package org.jrimum.texgit; /** * @author <a href="http://gilmatryx.googlepages.com/">Gilmar P.S.L.</a> * */ public final class Texgit { public static final FlatFile<Record> createFlatFile(String xmlDefFilePath) throws TexgitException { try { if (isNotBlank(xmlDefFilePath)) return createFlatFile(new File(xmlDefFilePath)); } catch (Exception e) { throw new TexgitException(e); } return null; } public static final FlatFile<Record> createFlatFile(File xmlDefFile) throws TexgitException { try { if (isNotNull(xmlDefFile)) { return createFlatFile(new FileInputStream(xmlDefFile)); } } catch (Exception e) { throw new TexgitException(e); } return null; } public static final FlatFile<Record> createFlatFile(URL xmlDefUrl) throws TexgitException { try { if (isNotNull(xmlDefUrl)) {
// Path: src/main/java/org/jrimum/texgit/engine/TexgitManager.java // public class TexgitManager { // // public static FlatFile<org.jrimum.texgit.Record> buildFlatFile(InputStream xmlDefStream) { // // FlatFile<Record> iFlatFile = null; // // try { // // MetaTexgit tgMeta = TexgitXmlReader.parse(xmlDefStream); // // iFlatFile = FlatFileBuilder.build(tgMeta.getFlatFile()); // // } catch (Exception e) { // throw new TexgitException(e); // } // // return iFlatFile; // } // } // Path: src/main/java/org/jrimum/texgit/Texgit.java import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.net.URL; import org.jrimum.texgit.engine.TexgitManager; import static org.apache.commons.lang.StringUtils.isNotBlank; import static org.jrimum.utilix.Objects.isNotNull; /* * Copyright 2008 JRimum Project * * 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. * * Created at: 26/07/2008 - 12:44:41 * * ================================================================================ * * Direitos autorais 2008 JRimum Project * * Licenciado sob a Licença Apache, Versão 2.0 ("LICENÇA"); você não pode usar * esse arquivo exceto em conformidade com a esta LICENÇA. Você pode obter uma * cópia desta LICENÇA em http://www.apache.org/licenses/LICENSE-2.0 A menos que * haja exigência legal ou acordo por escrito, a distribuição de software sob * esta LICENÇA se dará “COMO ESTÁ”, SEM GARANTIAS OU CONDIÇÕES DE QUALQUER * TIPO, sejam expressas ou tácitas. Veja a LICENÇA para a redação específica a * reger permissões e limitações sob esta LICENÇA. * * Criado em: 26/07/2008 - 12:44:41 * */ package org.jrimum.texgit; /** * @author <a href="http://gilmatryx.googlepages.com/">Gilmar P.S.L.</a> * */ public final class Texgit { public static final FlatFile<Record> createFlatFile(String xmlDefFilePath) throws TexgitException { try { if (isNotBlank(xmlDefFilePath)) return createFlatFile(new File(xmlDefFilePath)); } catch (Exception e) { throw new TexgitException(e); } return null; } public static final FlatFile<Record> createFlatFile(File xmlDefFile) throws TexgitException { try { if (isNotNull(xmlDefFile)) { return createFlatFile(new FileInputStream(xmlDefFile)); } } catch (Exception e) { throw new TexgitException(e); } return null; } public static final FlatFile<Record> createFlatFile(URL xmlDefUrl) throws TexgitException { try { if (isNotNull(xmlDefUrl)) {
return TexgitManager.buildFlatFile(xmlDefUrl.openStream());
jrimum/texgit
src/main/java/org/jrimum/texgit/type/component/Fillers.java
// Path: src/main/java/org/jrimum/texgit/TextStream.java // public interface TextStream extends ReadWriteStream<String> { // // }
import org.jrimum.texgit.TextStream; import org.jrimum.utilix.text.Strings;
public String fill(double tofill, int length) { return filler.fill(tofill, length); } /** * @param tofill * @param length * @return String preenchida * @see org.jrimum.texgit.type.component.Filler#fill(float, int) */ public String fill(float tofill, int length) { return filler.fill(tofill, length); } /** * @param tofill * @param length * @return String preenchida * @see org.jrimum.texgit.type.component.Filler#fill(java.lang.Object, int) */ public String fill(Object tofill, int length) { return filler.fill(tofill, length); } /** * @param tofill * @param length * @return String preenchida * @see org.jrimum.texgit.type.component.Filler#fill(org.jrimum.texgit.TextStream, int) */
// Path: src/main/java/org/jrimum/texgit/TextStream.java // public interface TextStream extends ReadWriteStream<String> { // // } // Path: src/main/java/org/jrimum/texgit/type/component/Fillers.java import org.jrimum.texgit.TextStream; import org.jrimum.utilix.text.Strings; public String fill(double tofill, int length) { return filler.fill(tofill, length); } /** * @param tofill * @param length * @return String preenchida * @see org.jrimum.texgit.type.component.Filler#fill(float, int) */ public String fill(float tofill, int length) { return filler.fill(tofill, length); } /** * @param tofill * @param length * @return String preenchida * @see org.jrimum.texgit.type.component.Filler#fill(java.lang.Object, int) */ public String fill(Object tofill, int length) { return filler.fill(tofill, length); } /** * @param tofill * @param length * @return String preenchida * @see org.jrimum.texgit.type.component.Filler#fill(org.jrimum.texgit.TextStream, int) */
public String fill(TextStream tofill, int length) {
jrimum/texgit
src/main/java/org/jrimum/texgit/type/component/Filler.java
// Path: src/main/java/org/jrimum/texgit/TextStream.java // public interface TextStream extends ReadWriteStream<String> { // // }
import static org.jrimum.utilix.Objects.isNotNull; import org.apache.commons.lang.StringUtils; import org.jrimum.texgit.TextStream; import org.jrimum.utilix.Objects; import static java.lang.String.format; import static org.apache.commons.lang.StringUtils.EMPTY;
* @see org.jrimum.texgit.type#fill(double, int) */ public String fill(double tofill, int length){ return fill(String.valueOf(tofill), length); } /** * @see org.jrimum.texgit.type#fill(float, int) */ public String fill(float tofill, int length){ return fill(String.valueOf(tofill), length); } /** * @see org.jrimum.texgit.type#fill(java.lang.Object, int) */ public String fill(Object tofill, int length){ String toFillTemp = null; if(isNotNull(tofill)){ toFillTemp = tofill.toString(); } return fill(toFillTemp, length); } /** * @see org.jrimum.texgit.type#fill(org.jrimum.texgit.TextStream, int) */
// Path: src/main/java/org/jrimum/texgit/TextStream.java // public interface TextStream extends ReadWriteStream<String> { // // } // Path: src/main/java/org/jrimum/texgit/type/component/Filler.java import static org.jrimum.utilix.Objects.isNotNull; import org.apache.commons.lang.StringUtils; import org.jrimum.texgit.TextStream; import org.jrimum.utilix.Objects; import static java.lang.String.format; import static org.apache.commons.lang.StringUtils.EMPTY; * @see org.jrimum.texgit.type#fill(double, int) */ public String fill(double tofill, int length){ return fill(String.valueOf(tofill), length); } /** * @see org.jrimum.texgit.type#fill(float, int) */ public String fill(float tofill, int length){ return fill(String.valueOf(tofill), length); } /** * @see org.jrimum.texgit.type#fill(java.lang.Object, int) */ public String fill(Object tofill, int length){ String toFillTemp = null; if(isNotNull(tofill)){ toFillTemp = tofill.toString(); } return fill(toFillTemp, length); } /** * @see org.jrimum.texgit.type#fill(org.jrimum.texgit.TextStream, int) */
public String fill(TextStream tofill, int length){
HestiaPi/hestia-engine-stable
src/opt/boilercontrol/uk/co/jaynne/ConfigBoostMonitor.java
// Path: src/opt/boilercontrol/uk/co/jaynne/datasource/interfaces/ConfigSource.java // public interface ConfigSource { // // public ConfigObject get(String key); // // public int set(String key, String value); // // public int set(String key, int value); // // public int set(String key, boolean value); // // public int set(String key, long value); // // public int set(String key, float value); // }
import uk.co.jaynne.datasource.ConfigSqlSource; import uk.co.jaynne.datasource.interfaces.ConfigSource;
package uk.co.jaynne; public class ConfigBoostMonitor extends Thread{ private String key; private boolean heating; private boolean water; private int sleepTime = 20000; /** * Monitors a pin for presses and activates boost * @param pin the pin to monitor * @param water whether this pin controls water * @param heating whether this pin controls heating */ public ConfigBoostMonitor(String key, boolean water, boolean heating) { this.key = key; this.heating = heating; this.water = water; } public void run() {
// Path: src/opt/boilercontrol/uk/co/jaynne/datasource/interfaces/ConfigSource.java // public interface ConfigSource { // // public ConfigObject get(String key); // // public int set(String key, String value); // // public int set(String key, int value); // // public int set(String key, boolean value); // // public int set(String key, long value); // // public int set(String key, float value); // } // Path: src/opt/boilercontrol/uk/co/jaynne/ConfigBoostMonitor.java import uk.co.jaynne.datasource.ConfigSqlSource; import uk.co.jaynne.datasource.interfaces.ConfigSource; package uk.co.jaynne; public class ConfigBoostMonitor extends Thread{ private String key; private boolean heating; private boolean water; private int sleepTime = 20000; /** * Monitors a pin for presses and activates boost * @param pin the pin to monitor * @param water whether this pin controls water * @param heating whether this pin controls heating */ public ConfigBoostMonitor(String key, boolean water, boolean heating) { this.key = key; this.heating = heating; this.water = water; } public void run() {
ConfigSource config = new ConfigSqlSource();
HestiaPi/hestia-engine-stable
src/opt/boilercontrol/uk/co/jaynne/datasource/ScheduleSqlSource.java
// Path: src/opt/boilercontrol/uk/co/jaynne/dataobjects/ScheduleObject.java // public class ScheduleObject{ // private int id = 0; // private int group = 0; // private int day = 0; // private int hourOn = 0; // private int minuteOn = 0; // private int hourOff = 0; // private int minuteOff = 0; // private boolean heatingOn = false; // private float TempSet = 22.00f; // private boolean waterOn = false; // private boolean enabled = false; // private String sday = ""; // // // public ScheduleObject(int id, int group, int day, int hourOn, int minuteOn, // int hourOff, int minuteOff, boolean heatingOn, float TempSet, boolean waterOn, // boolean enabled) { // this.id = id; // this.group = group; // this.day = day; // this.hourOn = hourOn; // this.minuteOn = minuteOn; // this.hourOff = hourOff; // this.minuteOff = minuteOff; // this.heatingOn = heatingOn; // this.TempSet = TempSet; // this.waterOn = waterOn; // this.enabled = enabled; // } // // // /** // * @return the id // */ // public int getId() { // return id; // } // // // /** // * @return the day // */ // public int getDay() { // return day; // } // // // /** // * @return the hourOn // */ // public int getHourOn() { // return hourOn; // } // // // /** // * @return the hourOff // */ // public int getHourOff() { // return hourOff; // } // // // /** // * @return the minuteOn // */ // public int getMinuteOn() { // return minuteOn; // } // // // /** // * @return the minuteOff // */ // public int getMinuteOff() { // return minuteOff; // } // // /** // * @return the heatingOn // */ // public boolean getHeatingOn() { // return heatingOn; // } // // /** // * @return the TempSet // */ // public float getTempSet() { // return TempSet; // } // // /** // * @return the waterOn // */ // public boolean getWaterOn() { // return waterOn; // } // // /** // * @return the group // */ // public int getGroup() { // return group; // } // // // /** // * @return the enabled // */ // public boolean getEnabled() { // return enabled; // } // /** // public String toString() { // return "Day:" + day + " Time On:" + hourOn + ":" + minuteOn + " Time Off:" + // hourOff + ":" + minuteOff + " Heating On:" + heatingOn + " Water On:" + // waterOn + " Group:" + group + " Enabled:" + enabled; // } // **/ // public String toString() { // switch (day) // { // case 1: // sday = "Sunday"; // break; // case 2: // sday = "Monday"; // break; // case 3: // sday = "Tuesday"; // break; // case 4: // sday = "Wednesday"; // break; // case 5: // sday = "Thursday"; // break; // case 6: // sday = "Friday"; // break; // case 7: // sday = "Saturday"; // break; // } // return sday + ": Period:" + hourOn + ":" + minuteOn + " - " + // hourOff + ":" + minuteOff + ", H: " + heatingOn + ", Set to: " + TempSet+ "C, W: " + // waterOn + ", Group:" + group + ", Enabled:" + enabled; // } // } // // Path: src/opt/boilercontrol/uk/co/jaynne/datasource/interfaces/ScheduleSource.java // public interface ScheduleSource { // public ScheduleObject getById(int id); // /** // * Returns an ordered set of SheduleObjects containing all the schedules for the day // * @param day // * @return // */ // public Set<ScheduleObject> getByDay(int day); // public int update(ScheduleObject schedule); // public int add(ScheduleObject schedule); // public int delete(int key); // // }
import java.sql.ResultSet; import java.sql.SQLException; import java.util.HashSet; import java.util.Set; import uk.co.jaynne.dataobjects.ScheduleObject; import uk.co.jaynne.datasource.interfaces.ScheduleSource;
package uk.co.jaynne.datasource; /** * Class to retrieve, update add and delte schedule items * @author James Cooke */ public class ScheduleSqlSource implements ScheduleSource{ private static String TABLE = "schedule"; private static String ID = "id"; private static String GROUP = "group"; private static String DAY = "day"; private static String HOURON = "hourOn"; private static String MINUTEON = "minuteOn"; private static String HOUROFF = "hourOff"; private static String MINUTEOFF = "minuteOff"; private static String TEMPERATURE = "temperature"; private static String HEATINGON = "heatingOn"; private static String WATERON = "waterOn"; private static String ENABLED = "enabled"; private static int MINUTES_IN_HOUR = 60;
// Path: src/opt/boilercontrol/uk/co/jaynne/dataobjects/ScheduleObject.java // public class ScheduleObject{ // private int id = 0; // private int group = 0; // private int day = 0; // private int hourOn = 0; // private int minuteOn = 0; // private int hourOff = 0; // private int minuteOff = 0; // private boolean heatingOn = false; // private float TempSet = 22.00f; // private boolean waterOn = false; // private boolean enabled = false; // private String sday = ""; // // // public ScheduleObject(int id, int group, int day, int hourOn, int minuteOn, // int hourOff, int minuteOff, boolean heatingOn, float TempSet, boolean waterOn, // boolean enabled) { // this.id = id; // this.group = group; // this.day = day; // this.hourOn = hourOn; // this.minuteOn = minuteOn; // this.hourOff = hourOff; // this.minuteOff = minuteOff; // this.heatingOn = heatingOn; // this.TempSet = TempSet; // this.waterOn = waterOn; // this.enabled = enabled; // } // // // /** // * @return the id // */ // public int getId() { // return id; // } // // // /** // * @return the day // */ // public int getDay() { // return day; // } // // // /** // * @return the hourOn // */ // public int getHourOn() { // return hourOn; // } // // // /** // * @return the hourOff // */ // public int getHourOff() { // return hourOff; // } // // // /** // * @return the minuteOn // */ // public int getMinuteOn() { // return minuteOn; // } // // // /** // * @return the minuteOff // */ // public int getMinuteOff() { // return minuteOff; // } // // /** // * @return the heatingOn // */ // public boolean getHeatingOn() { // return heatingOn; // } // // /** // * @return the TempSet // */ // public float getTempSet() { // return TempSet; // } // // /** // * @return the waterOn // */ // public boolean getWaterOn() { // return waterOn; // } // // /** // * @return the group // */ // public int getGroup() { // return group; // } // // // /** // * @return the enabled // */ // public boolean getEnabled() { // return enabled; // } // /** // public String toString() { // return "Day:" + day + " Time On:" + hourOn + ":" + minuteOn + " Time Off:" + // hourOff + ":" + minuteOff + " Heating On:" + heatingOn + " Water On:" + // waterOn + " Group:" + group + " Enabled:" + enabled; // } // **/ // public String toString() { // switch (day) // { // case 1: // sday = "Sunday"; // break; // case 2: // sday = "Monday"; // break; // case 3: // sday = "Tuesday"; // break; // case 4: // sday = "Wednesday"; // break; // case 5: // sday = "Thursday"; // break; // case 6: // sday = "Friday"; // break; // case 7: // sday = "Saturday"; // break; // } // return sday + ": Period:" + hourOn + ":" + minuteOn + " - " + // hourOff + ":" + minuteOff + ", H: " + heatingOn + ", Set to: " + TempSet+ "C, W: " + // waterOn + ", Group:" + group + ", Enabled:" + enabled; // } // } // // Path: src/opt/boilercontrol/uk/co/jaynne/datasource/interfaces/ScheduleSource.java // public interface ScheduleSource { // public ScheduleObject getById(int id); // /** // * Returns an ordered set of SheduleObjects containing all the schedules for the day // * @param day // * @return // */ // public Set<ScheduleObject> getByDay(int day); // public int update(ScheduleObject schedule); // public int add(ScheduleObject schedule); // public int delete(int key); // // } // Path: src/opt/boilercontrol/uk/co/jaynne/datasource/ScheduleSqlSource.java import java.sql.ResultSet; import java.sql.SQLException; import java.util.HashSet; import java.util.Set; import uk.co.jaynne.dataobjects.ScheduleObject; import uk.co.jaynne.datasource.interfaces.ScheduleSource; package uk.co.jaynne.datasource; /** * Class to retrieve, update add and delte schedule items * @author James Cooke */ public class ScheduleSqlSource implements ScheduleSource{ private static String TABLE = "schedule"; private static String ID = "id"; private static String GROUP = "group"; private static String DAY = "day"; private static String HOURON = "hourOn"; private static String MINUTEON = "minuteOn"; private static String HOUROFF = "hourOff"; private static String MINUTEOFF = "minuteOff"; private static String TEMPERATURE = "temperature"; private static String HEATINGON = "heatingOn"; private static String WATERON = "waterOn"; private static String ENABLED = "enabled"; private static int MINUTES_IN_HOUR = 60;
public ScheduleObject getById(int id) {
HestiaPi/hestia-engine-stable
src/opt/boilercontrol/uk/co/jaynne/BoilerControl.java
// Path: src/opt/boilercontrol/uk/co/jaynne/datasource/interfaces/ConfigSource.java // public interface ConfigSource { // // public ConfigObject get(String key); // // public int set(String key, String value); // // public int set(String key, int value); // // public int set(String key, boolean value); // // public int set(String key, long value); // // public int set(String key, float value); // }
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import uk.co.jaynne.datasource.ConfigSqlSource; import uk.co.jaynne.datasource.interfaces.ConfigSource;
package uk.co.jaynne; /** * Program to control a boiler with two channels - heating and water. * Schedules are set in a database with the option to override them via * "boost" buttons * @author James Cooke * @version 1.1 * */ public class BoilerControl { public static void main(String[] args) {
// Path: src/opt/boilercontrol/uk/co/jaynne/datasource/interfaces/ConfigSource.java // public interface ConfigSource { // // public ConfigObject get(String key); // // public int set(String key, String value); // // public int set(String key, int value); // // public int set(String key, boolean value); // // public int set(String key, long value); // // public int set(String key, float value); // } // Path: src/opt/boilercontrol/uk/co/jaynne/BoilerControl.java import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import uk.co.jaynne.datasource.ConfigSqlSource; import uk.co.jaynne.datasource.interfaces.ConfigSource; package uk.co.jaynne; /** * Program to control a boiler with two channels - heating and water. * Schedules are set in a database with the option to override them via * "boost" buttons * @author James Cooke * @version 1.1 * */ public class BoilerControl { public static void main(String[] args) {
ConfigSource config = new ConfigSqlSource();
Hippoom/wechat-mp-starter
examples/oauth2/src/main/java/com/github/hippoom/wechat/mp/examples/oauth2/http/HttpSecurityConfig.java
// Path: wechat-mp-autoconfigure/src/main/java/com/github/hippoom/wechat/mp/autoconfigure/security/web/WeChatMpWebSecurityConfigurerAdapter.java // @RequiredArgsConstructor // public class WeChatMpWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter { // // @Getter // @Autowired // private WxMpService wxMpService; // // @Override // protected void configure(AuthenticationManagerBuilder auth) // throws Exception { // } // // @Override // protected void configure(HttpSecurity http) throws Exception { // // configureAuthorizeRequests(defaultHttp(http)); // } // // /** // * subclass should override this to customize protected resources. // * // * @param httpSecurity see {@link HttpSecurity} // * @throws Exception just throw // */ // protected void configureAuthorizeRequests(HttpSecurity httpSecurity) throws Exception { // // @formatter:off // httpSecurity // .antMatcher("/**").authorizeRequests() // .antMatchers("/rel/**/me").authenticated() // .anyRequest().permitAll(); // // @formatter:on // } // // protected HttpSecurity defaultHttp(HttpSecurity http) throws Exception { // // @formatter:off // return http.sessionManagement().sessionCreationPolicy(IF_REQUIRED) // .and() // .csrf().requireCsrfProtectionMatcher(requireCsrfProtectionMatcher()) // .csrfTokenRepository(csrfTokenRepository()) // .and() // .addFilterAfter(weChatMpOAuth2AuthenticationProcessingFilter(wxMpService), // CsrfFilter.class) // .exceptionHandling() // .authenticationEntryPoint(restAuthenticationEntryPoint()) // .and(); // // @formatter:on // } // // /** // * subclass should override this to // * customize {@link CsrfConfigurer#requireCsrfProtectionMatcher(RequestMatcher)}. // * // * @return see {@link RequestMatcher} // */ // protected RequestMatcher requireCsrfProtectionMatcher() { // return new AntPathRequestMatcher("/rel/**/me"); // } // // @Bean // protected CsrfTokenRepository csrfTokenRepository() { // return CookieCsrfTokenRepository.withHttpOnlyFalse(); // } // // @Bean // protected CsrfAuthenticationStrategy sessionAuthenticationStrategy() { // return new CsrfAuthenticationStrategy(csrfTokenRepository()); // } // // // @Bean // protected RestAuthenticationEntryPoint restAuthenticationEntryPoint() { // return new RestAuthenticationEntryPoint(); // } // // protected WeChatMpOAuth2AuthenticationProcessingFilter // // @formatter:off // weChatMpOAuth2AuthenticationProcessingFilter(WxMpService wxMpService) { // // WeChatMpOAuth2AuthenticationProcessingFilter filter = // new WeChatMpOAuth2AuthenticationProcessingFilter("/wechat/oauth/token"); // filter.setWxMpService(wxMpService); // filter // .setAuthenticationSuccessHandler(new WeChatMpOAuth2AuthenticationSuccessHandler()); // filter.setSessionAuthenticationStrategy(sessionAuthenticationStrategy()); // // return filter; // } // // @formatter:on // // }
import com.github.hippoom.wechat.mp.autoconfigure.security.web.WeChatMpWebSecurityConfigurerAdapter; import lombok.RequiredArgsConstructor; import org.springframework.context.annotation.Configuration;
package com.github.hippoom.wechat.mp.examples.oauth2.http; @Configuration @RequiredArgsConstructor
// Path: wechat-mp-autoconfigure/src/main/java/com/github/hippoom/wechat/mp/autoconfigure/security/web/WeChatMpWebSecurityConfigurerAdapter.java // @RequiredArgsConstructor // public class WeChatMpWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter { // // @Getter // @Autowired // private WxMpService wxMpService; // // @Override // protected void configure(AuthenticationManagerBuilder auth) // throws Exception { // } // // @Override // protected void configure(HttpSecurity http) throws Exception { // // configureAuthorizeRequests(defaultHttp(http)); // } // // /** // * subclass should override this to customize protected resources. // * // * @param httpSecurity see {@link HttpSecurity} // * @throws Exception just throw // */ // protected void configureAuthorizeRequests(HttpSecurity httpSecurity) throws Exception { // // @formatter:off // httpSecurity // .antMatcher("/**").authorizeRequests() // .antMatchers("/rel/**/me").authenticated() // .anyRequest().permitAll(); // // @formatter:on // } // // protected HttpSecurity defaultHttp(HttpSecurity http) throws Exception { // // @formatter:off // return http.sessionManagement().sessionCreationPolicy(IF_REQUIRED) // .and() // .csrf().requireCsrfProtectionMatcher(requireCsrfProtectionMatcher()) // .csrfTokenRepository(csrfTokenRepository()) // .and() // .addFilterAfter(weChatMpOAuth2AuthenticationProcessingFilter(wxMpService), // CsrfFilter.class) // .exceptionHandling() // .authenticationEntryPoint(restAuthenticationEntryPoint()) // .and(); // // @formatter:on // } // // /** // * subclass should override this to // * customize {@link CsrfConfigurer#requireCsrfProtectionMatcher(RequestMatcher)}. // * // * @return see {@link RequestMatcher} // */ // protected RequestMatcher requireCsrfProtectionMatcher() { // return new AntPathRequestMatcher("/rel/**/me"); // } // // @Bean // protected CsrfTokenRepository csrfTokenRepository() { // return CookieCsrfTokenRepository.withHttpOnlyFalse(); // } // // @Bean // protected CsrfAuthenticationStrategy sessionAuthenticationStrategy() { // return new CsrfAuthenticationStrategy(csrfTokenRepository()); // } // // // @Bean // protected RestAuthenticationEntryPoint restAuthenticationEntryPoint() { // return new RestAuthenticationEntryPoint(); // } // // protected WeChatMpOAuth2AuthenticationProcessingFilter // // @formatter:off // weChatMpOAuth2AuthenticationProcessingFilter(WxMpService wxMpService) { // // WeChatMpOAuth2AuthenticationProcessingFilter filter = // new WeChatMpOAuth2AuthenticationProcessingFilter("/wechat/oauth/token"); // filter.setWxMpService(wxMpService); // filter // .setAuthenticationSuccessHandler(new WeChatMpOAuth2AuthenticationSuccessHandler()); // filter.setSessionAuthenticationStrategy(sessionAuthenticationStrategy()); // // return filter; // } // // @formatter:on // // } // Path: examples/oauth2/src/main/java/com/github/hippoom/wechat/mp/examples/oauth2/http/HttpSecurityConfig.java import com.github.hippoom.wechat.mp.autoconfigure.security.web.WeChatMpWebSecurityConfigurerAdapter; import lombok.RequiredArgsConstructor; import org.springframework.context.annotation.Configuration; package com.github.hippoom.wechat.mp.examples.oauth2.http; @Configuration @RequiredArgsConstructor
public class HttpSecurityConfig extends WeChatMpWebSecurityConfigurerAdapter {
Hippoom/wechat-mp-starter
wechat-mp-autoconfigure/src/main/java/com/github/hippoom/wechat/mp/autoconfigure/WeChatMpConfiguration.java
// Path: wechat-mp-autoconfigure/src/main/java/com/github/hippoom/wechat/mp/autoconfigure/web/WeChatMpWebConfiguration.java // @Configuration // @ComponentScan(value = "com.github.hippoom.wechat.mp.web", // includeFilters = { // @ComponentScan.Filter(type = FilterType.ANNOTATION, classes = Controller.class) // } // ) // public class WeChatMpWebConfiguration { // // } // // Path: wechat-mp-autoconfigure/src/main/java/com/github/hippoom/wechat/mp/autoconfigure/web/WeChatMpWebMethodConfiguration.java // @Configuration // @RequiredArgsConstructor // public class WeChatMpWebMethodConfiguration extends WebMvcConfigurerAdapter { // // // @Override // public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) { // argumentResolvers.add(new OpenIdHandlerMethodArgumentResolver()); // } // // }
import com.github.hippoom.wechat.mp.autoconfigure.web.WeChatMpWebConfiguration; import com.github.hippoom.wechat.mp.autoconfigure.web.WeChatMpWebMethodConfiguration; import me.chanjar.weixin.mp.api.WxMpCardService; import me.chanjar.weixin.mp.api.WxMpConfigStorage; import me.chanjar.weixin.mp.api.WxMpDataCubeService; import me.chanjar.weixin.mp.api.WxMpDeviceService; import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage; import me.chanjar.weixin.mp.api.WxMpKefuService; import me.chanjar.weixin.mp.api.WxMpMaterialService; import me.chanjar.weixin.mp.api.WxMpMenuService; import me.chanjar.weixin.mp.api.WxMpQrcodeService; import me.chanjar.weixin.mp.api.WxMpService; import me.chanjar.weixin.mp.api.WxMpStoreService; import me.chanjar.weixin.mp.api.WxMpTemplateMsgService; import me.chanjar.weixin.mp.api.WxMpUserBlacklistService; import me.chanjar.weixin.mp.api.WxMpUserService; import me.chanjar.weixin.mp.api.WxMpUserTagService; import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import;
package com.github.hippoom.wechat.mp.autoconfigure; /** * Provide default {@link WxMpService}. * * @see WeChatMpProperties * @see WeChatMpWebConfiguration * @see WeChatMpWebMethodConfiguration * @since 0.1.0 */ @Configuration @EnableConfigurationProperties(WeChatMpProperties.class) @Import( {
// Path: wechat-mp-autoconfigure/src/main/java/com/github/hippoom/wechat/mp/autoconfigure/web/WeChatMpWebConfiguration.java // @Configuration // @ComponentScan(value = "com.github.hippoom.wechat.mp.web", // includeFilters = { // @ComponentScan.Filter(type = FilterType.ANNOTATION, classes = Controller.class) // } // ) // public class WeChatMpWebConfiguration { // // } // // Path: wechat-mp-autoconfigure/src/main/java/com/github/hippoom/wechat/mp/autoconfigure/web/WeChatMpWebMethodConfiguration.java // @Configuration // @RequiredArgsConstructor // public class WeChatMpWebMethodConfiguration extends WebMvcConfigurerAdapter { // // // @Override // public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) { // argumentResolvers.add(new OpenIdHandlerMethodArgumentResolver()); // } // // } // Path: wechat-mp-autoconfigure/src/main/java/com/github/hippoom/wechat/mp/autoconfigure/WeChatMpConfiguration.java import com.github.hippoom.wechat.mp.autoconfigure.web.WeChatMpWebConfiguration; import com.github.hippoom.wechat.mp.autoconfigure.web.WeChatMpWebMethodConfiguration; import me.chanjar.weixin.mp.api.WxMpCardService; import me.chanjar.weixin.mp.api.WxMpConfigStorage; import me.chanjar.weixin.mp.api.WxMpDataCubeService; import me.chanjar.weixin.mp.api.WxMpDeviceService; import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage; import me.chanjar.weixin.mp.api.WxMpKefuService; import me.chanjar.weixin.mp.api.WxMpMaterialService; import me.chanjar.weixin.mp.api.WxMpMenuService; import me.chanjar.weixin.mp.api.WxMpQrcodeService; import me.chanjar.weixin.mp.api.WxMpService; import me.chanjar.weixin.mp.api.WxMpStoreService; import me.chanjar.weixin.mp.api.WxMpTemplateMsgService; import me.chanjar.weixin.mp.api.WxMpUserBlacklistService; import me.chanjar.weixin.mp.api.WxMpUserService; import me.chanjar.weixin.mp.api.WxMpUserTagService; import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; package com.github.hippoom.wechat.mp.autoconfigure; /** * Provide default {@link WxMpService}. * * @see WeChatMpProperties * @see WeChatMpWebConfiguration * @see WeChatMpWebMethodConfiguration * @since 0.1.0 */ @Configuration @EnableConfigurationProperties(WeChatMpProperties.class) @Import( {
WeChatMpWebConfiguration.class,
Hippoom/wechat-mp-starter
wechat-mp-autoconfigure/src/main/java/com/github/hippoom/wechat/mp/autoconfigure/WeChatMpConfiguration.java
// Path: wechat-mp-autoconfigure/src/main/java/com/github/hippoom/wechat/mp/autoconfigure/web/WeChatMpWebConfiguration.java // @Configuration // @ComponentScan(value = "com.github.hippoom.wechat.mp.web", // includeFilters = { // @ComponentScan.Filter(type = FilterType.ANNOTATION, classes = Controller.class) // } // ) // public class WeChatMpWebConfiguration { // // } // // Path: wechat-mp-autoconfigure/src/main/java/com/github/hippoom/wechat/mp/autoconfigure/web/WeChatMpWebMethodConfiguration.java // @Configuration // @RequiredArgsConstructor // public class WeChatMpWebMethodConfiguration extends WebMvcConfigurerAdapter { // // // @Override // public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) { // argumentResolvers.add(new OpenIdHandlerMethodArgumentResolver()); // } // // }
import com.github.hippoom.wechat.mp.autoconfigure.web.WeChatMpWebConfiguration; import com.github.hippoom.wechat.mp.autoconfigure.web.WeChatMpWebMethodConfiguration; import me.chanjar.weixin.mp.api.WxMpCardService; import me.chanjar.weixin.mp.api.WxMpConfigStorage; import me.chanjar.weixin.mp.api.WxMpDataCubeService; import me.chanjar.weixin.mp.api.WxMpDeviceService; import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage; import me.chanjar.weixin.mp.api.WxMpKefuService; import me.chanjar.weixin.mp.api.WxMpMaterialService; import me.chanjar.weixin.mp.api.WxMpMenuService; import me.chanjar.weixin.mp.api.WxMpQrcodeService; import me.chanjar.weixin.mp.api.WxMpService; import me.chanjar.weixin.mp.api.WxMpStoreService; import me.chanjar.weixin.mp.api.WxMpTemplateMsgService; import me.chanjar.weixin.mp.api.WxMpUserBlacklistService; import me.chanjar.weixin.mp.api.WxMpUserService; import me.chanjar.weixin.mp.api.WxMpUserTagService; import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import;
package com.github.hippoom.wechat.mp.autoconfigure; /** * Provide default {@link WxMpService}. * * @see WeChatMpProperties * @see WeChatMpWebConfiguration * @see WeChatMpWebMethodConfiguration * @since 0.1.0 */ @Configuration @EnableConfigurationProperties(WeChatMpProperties.class) @Import( { WeChatMpWebConfiguration.class,
// Path: wechat-mp-autoconfigure/src/main/java/com/github/hippoom/wechat/mp/autoconfigure/web/WeChatMpWebConfiguration.java // @Configuration // @ComponentScan(value = "com.github.hippoom.wechat.mp.web", // includeFilters = { // @ComponentScan.Filter(type = FilterType.ANNOTATION, classes = Controller.class) // } // ) // public class WeChatMpWebConfiguration { // // } // // Path: wechat-mp-autoconfigure/src/main/java/com/github/hippoom/wechat/mp/autoconfigure/web/WeChatMpWebMethodConfiguration.java // @Configuration // @RequiredArgsConstructor // public class WeChatMpWebMethodConfiguration extends WebMvcConfigurerAdapter { // // // @Override // public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) { // argumentResolvers.add(new OpenIdHandlerMethodArgumentResolver()); // } // // } // Path: wechat-mp-autoconfigure/src/main/java/com/github/hippoom/wechat/mp/autoconfigure/WeChatMpConfiguration.java import com.github.hippoom.wechat.mp.autoconfigure.web.WeChatMpWebConfiguration; import com.github.hippoom.wechat.mp.autoconfigure.web.WeChatMpWebMethodConfiguration; import me.chanjar.weixin.mp.api.WxMpCardService; import me.chanjar.weixin.mp.api.WxMpConfigStorage; import me.chanjar.weixin.mp.api.WxMpDataCubeService; import me.chanjar.weixin.mp.api.WxMpDeviceService; import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage; import me.chanjar.weixin.mp.api.WxMpKefuService; import me.chanjar.weixin.mp.api.WxMpMaterialService; import me.chanjar.weixin.mp.api.WxMpMenuService; import me.chanjar.weixin.mp.api.WxMpQrcodeService; import me.chanjar.weixin.mp.api.WxMpService; import me.chanjar.weixin.mp.api.WxMpStoreService; import me.chanjar.weixin.mp.api.WxMpTemplateMsgService; import me.chanjar.weixin.mp.api.WxMpUserBlacklistService; import me.chanjar.weixin.mp.api.WxMpUserService; import me.chanjar.weixin.mp.api.WxMpUserTagService; import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; package com.github.hippoom.wechat.mp.autoconfigure; /** * Provide default {@link WxMpService}. * * @see WeChatMpProperties * @see WeChatMpWebConfiguration * @see WeChatMpWebMethodConfiguration * @since 0.1.0 */ @Configuration @EnableConfigurationProperties(WeChatMpProperties.class) @Import( { WeChatMpWebConfiguration.class,
WeChatMpWebMethodConfiguration.class
Hippoom/wechat-mp-starter
wechat-mp-test/src/main/java/com/github/hippoom/wechat/mp/test/fixture/WxMpUserFixture.java
// Path: wechat-mp-autoconfigure/src/main/java/com/github/hippoom/wechat/oauth/OpenId.java // @Value // public class OpenId { // // private String value; // // private OpenId(String value) { // this.value = value; // } // // public static OpenId valueOf(String value) { // return new OpenId(value); // } // }
import com.github.hippoom.wechat.oauth.OpenId; import java.util.UUID; import me.chanjar.weixin.mp.bean.result.WxMpUser;
package com.github.hippoom.wechat.mp.test.fixture; /** * Test fixture for {@link WxMpUser}. * * <pre class="code"> * * import static com.github.hippoom.wechat.mp.test.fixture.WxMpUserFixture.aWxMpUser; * * //Declare OpenId openId = ... * * WxMpUser wxMpUser = aWxMpUser().with(openId).build(); * * </pre> * * @see WxMpUser * @since 0.3.0 */ public class WxMpUserFixture { private WxMpUser target = new WxMpUser(); private WxMpUserFixture() {
// Path: wechat-mp-autoconfigure/src/main/java/com/github/hippoom/wechat/oauth/OpenId.java // @Value // public class OpenId { // // private String value; // // private OpenId(String value) { // this.value = value; // } // // public static OpenId valueOf(String value) { // return new OpenId(value); // } // } // Path: wechat-mp-test/src/main/java/com/github/hippoom/wechat/mp/test/fixture/WxMpUserFixture.java import com.github.hippoom.wechat.oauth.OpenId; import java.util.UUID; import me.chanjar.weixin.mp.bean.result.WxMpUser; package com.github.hippoom.wechat.mp.test.fixture; /** * Test fixture for {@link WxMpUser}. * * <pre class="code"> * * import static com.github.hippoom.wechat.mp.test.fixture.WxMpUserFixture.aWxMpUser; * * //Declare OpenId openId = ... * * WxMpUser wxMpUser = aWxMpUser().with(openId).build(); * * </pre> * * @see WxMpUser * @since 0.3.0 */ public class WxMpUserFixture { private WxMpUser target = new WxMpUser(); private WxMpUserFixture() {
target.setOpenId(OpenId.valueOf(UUID.randomUUID().toString()).getValue());
Hippoom/wechat-mp-starter
examples/oauth2/src/main/java/com/github/hippoom/wechat/mp/examples/oauth2/http/assembler/WeChatUserProfileResourceAssembler.java
// Path: examples/oauth2/src/main/java/com/github/hippoom/wechat/mp/examples/oauth2/http/WeChatUserRestController.java // @Slf4j // @RestController // @RequiredArgsConstructor // public class WeChatUserRestController { // // @NonNull // private final WeChatUserProfileResourceAssembler userResourceAssembler; // // @NonNull // private final WxMpUserService wxMpUserService; // // @SneakyThrows // @RequestMapping(value = "/rel/wechat/user/profile/me", method = GET) // public WeChatUserProfileResource me(@CurrentWeChatMpUser OpenId openId) { // WxMpUser userProfile = wxMpUserService.userInfo(openId.getValue()); // return userResourceAssembler.toResource(userProfile); // } // // // } // // Path: examples/oauth2/src/main/java/com/github/hippoom/wechat/mp/examples/oauth2/http/resource/WeChatUserProfileResource.java // @Data // @EqualsAndHashCode(callSuper = false) // public class WeChatUserProfileResource extends ResourceSupport { // // private String nickname; // private String avatar; // } // // Path: wechat-mp-autoconfigure/src/main/java/com/github/hippoom/wechat/oauth/OpenId.java // @Value // public class OpenId { // // private String value; // // private OpenId(String value) { // this.value = value; // } // // public static OpenId valueOf(String value) { // return new OpenId(value); // } // }
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn; import com.github.hippoom.wechat.mp.examples.oauth2.http.WeChatUserRestController; import com.github.hippoom.wechat.mp.examples.oauth2.http.resource.WeChatUserProfileResource; import com.github.hippoom.wechat.oauth.OpenId; import me.chanjar.weixin.mp.bean.result.WxMpUser; import org.springframework.hateoas.mvc.ResourceAssemblerSupport; import org.springframework.stereotype.Component;
package com.github.hippoom.wechat.mp.examples.oauth2.http.assembler; @Component public class WeChatUserProfileResourceAssembler extends
// Path: examples/oauth2/src/main/java/com/github/hippoom/wechat/mp/examples/oauth2/http/WeChatUserRestController.java // @Slf4j // @RestController // @RequiredArgsConstructor // public class WeChatUserRestController { // // @NonNull // private final WeChatUserProfileResourceAssembler userResourceAssembler; // // @NonNull // private final WxMpUserService wxMpUserService; // // @SneakyThrows // @RequestMapping(value = "/rel/wechat/user/profile/me", method = GET) // public WeChatUserProfileResource me(@CurrentWeChatMpUser OpenId openId) { // WxMpUser userProfile = wxMpUserService.userInfo(openId.getValue()); // return userResourceAssembler.toResource(userProfile); // } // // // } // // Path: examples/oauth2/src/main/java/com/github/hippoom/wechat/mp/examples/oauth2/http/resource/WeChatUserProfileResource.java // @Data // @EqualsAndHashCode(callSuper = false) // public class WeChatUserProfileResource extends ResourceSupport { // // private String nickname; // private String avatar; // } // // Path: wechat-mp-autoconfigure/src/main/java/com/github/hippoom/wechat/oauth/OpenId.java // @Value // public class OpenId { // // private String value; // // private OpenId(String value) { // this.value = value; // } // // public static OpenId valueOf(String value) { // return new OpenId(value); // } // } // Path: examples/oauth2/src/main/java/com/github/hippoom/wechat/mp/examples/oauth2/http/assembler/WeChatUserProfileResourceAssembler.java import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn; import com.github.hippoom.wechat.mp.examples.oauth2.http.WeChatUserRestController; import com.github.hippoom.wechat.mp.examples.oauth2.http.resource.WeChatUserProfileResource; import com.github.hippoom.wechat.oauth.OpenId; import me.chanjar.weixin.mp.bean.result.WxMpUser; import org.springframework.hateoas.mvc.ResourceAssemblerSupport; import org.springframework.stereotype.Component; package com.github.hippoom.wechat.mp.examples.oauth2.http.assembler; @Component public class WeChatUserProfileResourceAssembler extends
ResourceAssemblerSupport<WxMpUser, WeChatUserProfileResource> {
Hippoom/wechat-mp-starter
examples/oauth2/src/main/java/com/github/hippoom/wechat/mp/examples/oauth2/http/assembler/WeChatUserProfileResourceAssembler.java
// Path: examples/oauth2/src/main/java/com/github/hippoom/wechat/mp/examples/oauth2/http/WeChatUserRestController.java // @Slf4j // @RestController // @RequiredArgsConstructor // public class WeChatUserRestController { // // @NonNull // private final WeChatUserProfileResourceAssembler userResourceAssembler; // // @NonNull // private final WxMpUserService wxMpUserService; // // @SneakyThrows // @RequestMapping(value = "/rel/wechat/user/profile/me", method = GET) // public WeChatUserProfileResource me(@CurrentWeChatMpUser OpenId openId) { // WxMpUser userProfile = wxMpUserService.userInfo(openId.getValue()); // return userResourceAssembler.toResource(userProfile); // } // // // } // // Path: examples/oauth2/src/main/java/com/github/hippoom/wechat/mp/examples/oauth2/http/resource/WeChatUserProfileResource.java // @Data // @EqualsAndHashCode(callSuper = false) // public class WeChatUserProfileResource extends ResourceSupport { // // private String nickname; // private String avatar; // } // // Path: wechat-mp-autoconfigure/src/main/java/com/github/hippoom/wechat/oauth/OpenId.java // @Value // public class OpenId { // // private String value; // // private OpenId(String value) { // this.value = value; // } // // public static OpenId valueOf(String value) { // return new OpenId(value); // } // }
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn; import com.github.hippoom.wechat.mp.examples.oauth2.http.WeChatUserRestController; import com.github.hippoom.wechat.mp.examples.oauth2.http.resource.WeChatUserProfileResource; import com.github.hippoom.wechat.oauth.OpenId; import me.chanjar.weixin.mp.bean.result.WxMpUser; import org.springframework.hateoas.mvc.ResourceAssemblerSupport; import org.springframework.stereotype.Component;
package com.github.hippoom.wechat.mp.examples.oauth2.http.assembler; @Component public class WeChatUserProfileResourceAssembler extends ResourceAssemblerSupport<WxMpUser, WeChatUserProfileResource> { public WeChatUserProfileResourceAssembler() {
// Path: examples/oauth2/src/main/java/com/github/hippoom/wechat/mp/examples/oauth2/http/WeChatUserRestController.java // @Slf4j // @RestController // @RequiredArgsConstructor // public class WeChatUserRestController { // // @NonNull // private final WeChatUserProfileResourceAssembler userResourceAssembler; // // @NonNull // private final WxMpUserService wxMpUserService; // // @SneakyThrows // @RequestMapping(value = "/rel/wechat/user/profile/me", method = GET) // public WeChatUserProfileResource me(@CurrentWeChatMpUser OpenId openId) { // WxMpUser userProfile = wxMpUserService.userInfo(openId.getValue()); // return userResourceAssembler.toResource(userProfile); // } // // // } // // Path: examples/oauth2/src/main/java/com/github/hippoom/wechat/mp/examples/oauth2/http/resource/WeChatUserProfileResource.java // @Data // @EqualsAndHashCode(callSuper = false) // public class WeChatUserProfileResource extends ResourceSupport { // // private String nickname; // private String avatar; // } // // Path: wechat-mp-autoconfigure/src/main/java/com/github/hippoom/wechat/oauth/OpenId.java // @Value // public class OpenId { // // private String value; // // private OpenId(String value) { // this.value = value; // } // // public static OpenId valueOf(String value) { // return new OpenId(value); // } // } // Path: examples/oauth2/src/main/java/com/github/hippoom/wechat/mp/examples/oauth2/http/assembler/WeChatUserProfileResourceAssembler.java import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn; import com.github.hippoom.wechat.mp.examples.oauth2.http.WeChatUserRestController; import com.github.hippoom.wechat.mp.examples.oauth2.http.resource.WeChatUserProfileResource; import com.github.hippoom.wechat.oauth.OpenId; import me.chanjar.weixin.mp.bean.result.WxMpUser; import org.springframework.hateoas.mvc.ResourceAssemblerSupport; import org.springframework.stereotype.Component; package com.github.hippoom.wechat.mp.examples.oauth2.http.assembler; @Component public class WeChatUserProfileResourceAssembler extends ResourceAssemblerSupport<WxMpUser, WeChatUserProfileResource> { public WeChatUserProfileResourceAssembler() {
super(WeChatUserRestController.class, WeChatUserProfileResource.class);
Hippoom/wechat-mp-starter
examples/oauth2/src/main/java/com/github/hippoom/wechat/mp/examples/oauth2/http/assembler/WeChatUserProfileResourceAssembler.java
// Path: examples/oauth2/src/main/java/com/github/hippoom/wechat/mp/examples/oauth2/http/WeChatUserRestController.java // @Slf4j // @RestController // @RequiredArgsConstructor // public class WeChatUserRestController { // // @NonNull // private final WeChatUserProfileResourceAssembler userResourceAssembler; // // @NonNull // private final WxMpUserService wxMpUserService; // // @SneakyThrows // @RequestMapping(value = "/rel/wechat/user/profile/me", method = GET) // public WeChatUserProfileResource me(@CurrentWeChatMpUser OpenId openId) { // WxMpUser userProfile = wxMpUserService.userInfo(openId.getValue()); // return userResourceAssembler.toResource(userProfile); // } // // // } // // Path: examples/oauth2/src/main/java/com/github/hippoom/wechat/mp/examples/oauth2/http/resource/WeChatUserProfileResource.java // @Data // @EqualsAndHashCode(callSuper = false) // public class WeChatUserProfileResource extends ResourceSupport { // // private String nickname; // private String avatar; // } // // Path: wechat-mp-autoconfigure/src/main/java/com/github/hippoom/wechat/oauth/OpenId.java // @Value // public class OpenId { // // private String value; // // private OpenId(String value) { // this.value = value; // } // // public static OpenId valueOf(String value) { // return new OpenId(value); // } // }
import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn; import com.github.hippoom.wechat.mp.examples.oauth2.http.WeChatUserRestController; import com.github.hippoom.wechat.mp.examples.oauth2.http.resource.WeChatUserProfileResource; import com.github.hippoom.wechat.oauth.OpenId; import me.chanjar.weixin.mp.bean.result.WxMpUser; import org.springframework.hateoas.mvc.ResourceAssemblerSupport; import org.springframework.stereotype.Component;
package com.github.hippoom.wechat.mp.examples.oauth2.http.assembler; @Component public class WeChatUserProfileResourceAssembler extends ResourceAssemblerSupport<WxMpUser, WeChatUserProfileResource> { public WeChatUserProfileResourceAssembler() { super(WeChatUserRestController.class, WeChatUserProfileResource.class); } @Override public WeChatUserProfileResource toResource(WxMpUser entity) { WeChatUserProfileResource resource = new WeChatUserProfileResource(); resource.setAvatar(entity.getHeadImgUrl()); resource.setNickname(entity.getNickname()); resource .add( linkTo(methodOn(WeChatUserRestController.class)
// Path: examples/oauth2/src/main/java/com/github/hippoom/wechat/mp/examples/oauth2/http/WeChatUserRestController.java // @Slf4j // @RestController // @RequiredArgsConstructor // public class WeChatUserRestController { // // @NonNull // private final WeChatUserProfileResourceAssembler userResourceAssembler; // // @NonNull // private final WxMpUserService wxMpUserService; // // @SneakyThrows // @RequestMapping(value = "/rel/wechat/user/profile/me", method = GET) // public WeChatUserProfileResource me(@CurrentWeChatMpUser OpenId openId) { // WxMpUser userProfile = wxMpUserService.userInfo(openId.getValue()); // return userResourceAssembler.toResource(userProfile); // } // // // } // // Path: examples/oauth2/src/main/java/com/github/hippoom/wechat/mp/examples/oauth2/http/resource/WeChatUserProfileResource.java // @Data // @EqualsAndHashCode(callSuper = false) // public class WeChatUserProfileResource extends ResourceSupport { // // private String nickname; // private String avatar; // } // // Path: wechat-mp-autoconfigure/src/main/java/com/github/hippoom/wechat/oauth/OpenId.java // @Value // public class OpenId { // // private String value; // // private OpenId(String value) { // this.value = value; // } // // public static OpenId valueOf(String value) { // return new OpenId(value); // } // } // Path: examples/oauth2/src/main/java/com/github/hippoom/wechat/mp/examples/oauth2/http/assembler/WeChatUserProfileResourceAssembler.java import static org.springframework.hateoas.mvc.ControllerLinkBuilder.linkTo; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.methodOn; import com.github.hippoom.wechat.mp.examples.oauth2.http.WeChatUserRestController; import com.github.hippoom.wechat.mp.examples.oauth2.http.resource.WeChatUserProfileResource; import com.github.hippoom.wechat.oauth.OpenId; import me.chanjar.weixin.mp.bean.result.WxMpUser; import org.springframework.hateoas.mvc.ResourceAssemblerSupport; import org.springframework.stereotype.Component; package com.github.hippoom.wechat.mp.examples.oauth2.http.assembler; @Component public class WeChatUserProfileResourceAssembler extends ResourceAssemblerSupport<WxMpUser, WeChatUserProfileResource> { public WeChatUserProfileResourceAssembler() { super(WeChatUserRestController.class, WeChatUserProfileResource.class); } @Override public WeChatUserProfileResource toResource(WxMpUser entity) { WeChatUserProfileResource resource = new WeChatUserProfileResource(); resource.setAvatar(entity.getHeadImgUrl()); resource.setNickname(entity.getNickname()); resource .add( linkTo(methodOn(WeChatUserRestController.class)
.me(OpenId.valueOf(entity.getOpenId()))).withSelfRel());
Hippoom/wechat-mp-starter
wechat-mp-test/src/main/java/com/github/hippoom/wechat/mp/test/fixture/WxMpOAuth2AccessTokenFixture.java
// Path: wechat-mp-autoconfigure/src/main/java/com/github/hippoom/wechat/oauth/OpenId.java // @Value // public class OpenId { // // private String value; // // private OpenId(String value) { // this.value = value; // } // // public static OpenId valueOf(String value) { // return new OpenId(value); // } // }
import com.github.hippoom.wechat.oauth.OpenId; import java.util.UUID; import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
package com.github.hippoom.wechat.mp.test.fixture; /** * Test fixture for {@link WxMpOAuth2AccessTokenFixture}. * * <pre class="code"> * * import static com.github.hippoom.wechat.mp.test.fixture * .WxMpOAuth2AccessTokenFixture.aWxMpOAuth2AccessToken; * * //Declare OpenId openId = ... * * WxMpOAuth2AccessToken accessToken = aWxMpOAuth2AccessToken().with(openId).build(); * * </pre> * * @see WxMpOAuth2AccessTokenFixture * @since 0.3.0 */ public class WxMpOAuth2AccessTokenFixture { private WxMpOAuth2AccessToken target = new WxMpOAuth2AccessToken(); private WxMpOAuth2AccessTokenFixture() {
// Path: wechat-mp-autoconfigure/src/main/java/com/github/hippoom/wechat/oauth/OpenId.java // @Value // public class OpenId { // // private String value; // // private OpenId(String value) { // this.value = value; // } // // public static OpenId valueOf(String value) { // return new OpenId(value); // } // } // Path: wechat-mp-test/src/main/java/com/github/hippoom/wechat/mp/test/fixture/WxMpOAuth2AccessTokenFixture.java import com.github.hippoom.wechat.oauth.OpenId; import java.util.UUID; import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken; package com.github.hippoom.wechat.mp.test.fixture; /** * Test fixture for {@link WxMpOAuth2AccessTokenFixture}. * * <pre class="code"> * * import static com.github.hippoom.wechat.mp.test.fixture * .WxMpOAuth2AccessTokenFixture.aWxMpOAuth2AccessToken; * * //Declare OpenId openId = ... * * WxMpOAuth2AccessToken accessToken = aWxMpOAuth2AccessToken().with(openId).build(); * * </pre> * * @see WxMpOAuth2AccessTokenFixture * @since 0.3.0 */ public class WxMpOAuth2AccessTokenFixture { private WxMpOAuth2AccessToken target = new WxMpOAuth2AccessToken(); private WxMpOAuth2AccessTokenFixture() {
target.setOpenId(OpenId.valueOf(UUID.randomUUID().toString()).getValue());
Hippoom/wechat-mp-starter
wechat-mp-test/src/main/java/com/github/hippoom/wechat/mp/test/web/servlet/request/WxMpOAuth2AccessTokenRequestPostProcessor.java
// Path: wechat-mp-autoconfigure/src/main/java/com/github/hippoom/wechat/mp/security/authentication/WeChatMpOAuth2AccessTokenAuthentication.java // public class WeChatMpOAuth2AccessTokenAuthentication implements Authentication { // // private final WxMpOAuth2AccessToken accessToken; // // public WeChatMpOAuth2AccessTokenAuthentication(WxMpOAuth2AccessToken accessToken) { // this.accessToken = accessToken; // } // // @Override // public Collection<? extends GrantedAuthority> getAuthorities() { // return Collections.emptyList(); // } // // @Override // public Object getCredentials() { // return null; // } // // @Override // public Object getDetails() { // return getOpenId(); // } // // @Override // public Object getPrincipal() { // return getOpenId(); // } // // @Override // public boolean isAuthenticated() { // return true; // } // // @Override // public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException { // // } // // @Override // public String getName() { // return accessToken.getOpenId(); // } // // public OpenId getOpenId() { // return OpenId.valueOf(accessToken.getOpenId()); // } // } // // Path: wechat-mp-test/src/main/java/com/github/hippoom/wechat/mp/test/fixture/WxMpOAuth2AccessTokenFixture.java // public class WxMpOAuth2AccessTokenFixture { // // private WxMpOAuth2AccessToken target = new WxMpOAuth2AccessToken(); // // private WxMpOAuth2AccessTokenFixture() { // target.setOpenId(OpenId.valueOf(UUID.randomUUID().toString()).getValue()); // target.setAccessToken("accessToken"); // target.setRefreshToken("refreshToken"); // target.setExpiresIn(3600); // target.setScope("snsapi_base"); // } // // /** // * Customize the {@link OpenId}. // * // * @param openId a custom {@link OpenId} // * @return this {@link WxMpOAuth2AccessTokenFixture} // */ // public WxMpOAuth2AccessTokenFixture with(OpenId openId) { // target.setOpenId(openId.getValue()); // return this; // } // // /** // * Build the {@link WxMpOAuth2AccessToken}. // * // * @return this {@link WxMpOAuth2AccessToken} // */ // public WxMpOAuth2AccessToken build() { // return target; // } // // /** // * Static factory method for {@link WxMpOAuth2AccessTokenFixture}. // * // * @return a {@link WxMpOAuth2AccessTokenFixture} with default values // */ // public static WxMpOAuth2AccessTokenFixture aWxMpOAuth2AccessToken() { // return new WxMpOAuth2AccessTokenFixture(); // } // } // // Path: wechat-mp-autoconfigure/src/main/java/com/github/hippoom/wechat/oauth/OpenId.java // @Value // public class OpenId { // // private String value; // // private OpenId(String value) { // this.value = value; // } // // public static OpenId valueOf(String value) { // return new OpenId(value); // } // }
import com.github.hippoom.wechat.mp.security.authentication.WeChatMpOAuth2AccessTokenAuthentication; import com.github.hippoom.wechat.mp.test.fixture.WxMpOAuth2AccessTokenFixture; import com.github.hippoom.wechat.oauth.OpenId; import java.util.UUID; import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors; import org.springframework.test.web.servlet.request.RequestPostProcessor;
package com.github.hippoom.wechat.mp.test.web.servlet.request; // @formatter:off /** * Test fixture for {@link WxMpOAuth2AccessTokenFixture}. * <pre class="code"> * * import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; * import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; * import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; * import static com.github.hippoom.wechat.mp.test.web.servlet.request * .WxMpOAuth2AccessTokenRequestPostProcessor.aWeChatMpUser; * * &#064;Test public void returns_wechat_user_profile() { * this.mockMvc.perform( * get("/rel/wechat/user/profile/me").with(aWeChatMpUser().withOpenId(userProfile.openId)) * ).andDo(print()).andExpect(status().isOk()); * } * * </pre> * * @see RequestPostProcessor * @since 0.3.0 */ //@formatter:on public class WxMpOAuth2AccessTokenRequestPostProcessor implements RequestPostProcessor { private OpenId openId = OpenId.valueOf(UUID.randomUUID().toString()); /** * Customize the {@link OpenId}. * * @param openId a custom {@link OpenId} * @return this {@link WxMpOAuth2AccessTokenRequestPostProcessor} */ public WxMpOAuth2AccessTokenRequestPostProcessor with(OpenId openId) { this.openId = openId; return this; } /** * Customize the {@link OpenId}. * * @param openId a custom {@link OpenId} value * @return this {@link WxMpOAuth2AccessTokenRequestPostProcessor} */ public WxMpOAuth2AccessTokenRequestPostProcessor withOpenId(String openId) { return with(OpenId.valueOf(openId)); } @Override public MockHttpServletRequest postProcessRequest( MockHttpServletRequest mockHttpServletRequest) {
// Path: wechat-mp-autoconfigure/src/main/java/com/github/hippoom/wechat/mp/security/authentication/WeChatMpOAuth2AccessTokenAuthentication.java // public class WeChatMpOAuth2AccessTokenAuthentication implements Authentication { // // private final WxMpOAuth2AccessToken accessToken; // // public WeChatMpOAuth2AccessTokenAuthentication(WxMpOAuth2AccessToken accessToken) { // this.accessToken = accessToken; // } // // @Override // public Collection<? extends GrantedAuthority> getAuthorities() { // return Collections.emptyList(); // } // // @Override // public Object getCredentials() { // return null; // } // // @Override // public Object getDetails() { // return getOpenId(); // } // // @Override // public Object getPrincipal() { // return getOpenId(); // } // // @Override // public boolean isAuthenticated() { // return true; // } // // @Override // public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException { // // } // // @Override // public String getName() { // return accessToken.getOpenId(); // } // // public OpenId getOpenId() { // return OpenId.valueOf(accessToken.getOpenId()); // } // } // // Path: wechat-mp-test/src/main/java/com/github/hippoom/wechat/mp/test/fixture/WxMpOAuth2AccessTokenFixture.java // public class WxMpOAuth2AccessTokenFixture { // // private WxMpOAuth2AccessToken target = new WxMpOAuth2AccessToken(); // // private WxMpOAuth2AccessTokenFixture() { // target.setOpenId(OpenId.valueOf(UUID.randomUUID().toString()).getValue()); // target.setAccessToken("accessToken"); // target.setRefreshToken("refreshToken"); // target.setExpiresIn(3600); // target.setScope("snsapi_base"); // } // // /** // * Customize the {@link OpenId}. // * // * @param openId a custom {@link OpenId} // * @return this {@link WxMpOAuth2AccessTokenFixture} // */ // public WxMpOAuth2AccessTokenFixture with(OpenId openId) { // target.setOpenId(openId.getValue()); // return this; // } // // /** // * Build the {@link WxMpOAuth2AccessToken}. // * // * @return this {@link WxMpOAuth2AccessToken} // */ // public WxMpOAuth2AccessToken build() { // return target; // } // // /** // * Static factory method for {@link WxMpOAuth2AccessTokenFixture}. // * // * @return a {@link WxMpOAuth2AccessTokenFixture} with default values // */ // public static WxMpOAuth2AccessTokenFixture aWxMpOAuth2AccessToken() { // return new WxMpOAuth2AccessTokenFixture(); // } // } // // Path: wechat-mp-autoconfigure/src/main/java/com/github/hippoom/wechat/oauth/OpenId.java // @Value // public class OpenId { // // private String value; // // private OpenId(String value) { // this.value = value; // } // // public static OpenId valueOf(String value) { // return new OpenId(value); // } // } // Path: wechat-mp-test/src/main/java/com/github/hippoom/wechat/mp/test/web/servlet/request/WxMpOAuth2AccessTokenRequestPostProcessor.java import com.github.hippoom.wechat.mp.security.authentication.WeChatMpOAuth2AccessTokenAuthentication; import com.github.hippoom.wechat.mp.test.fixture.WxMpOAuth2AccessTokenFixture; import com.github.hippoom.wechat.oauth.OpenId; import java.util.UUID; import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors; import org.springframework.test.web.servlet.request.RequestPostProcessor; package com.github.hippoom.wechat.mp.test.web.servlet.request; // @formatter:off /** * Test fixture for {@link WxMpOAuth2AccessTokenFixture}. * <pre class="code"> * * import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; * import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; * import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; * import static com.github.hippoom.wechat.mp.test.web.servlet.request * .WxMpOAuth2AccessTokenRequestPostProcessor.aWeChatMpUser; * * &#064;Test public void returns_wechat_user_profile() { * this.mockMvc.perform( * get("/rel/wechat/user/profile/me").with(aWeChatMpUser().withOpenId(userProfile.openId)) * ).andDo(print()).andExpect(status().isOk()); * } * * </pre> * * @see RequestPostProcessor * @since 0.3.0 */ //@formatter:on public class WxMpOAuth2AccessTokenRequestPostProcessor implements RequestPostProcessor { private OpenId openId = OpenId.valueOf(UUID.randomUUID().toString()); /** * Customize the {@link OpenId}. * * @param openId a custom {@link OpenId} * @return this {@link WxMpOAuth2AccessTokenRequestPostProcessor} */ public WxMpOAuth2AccessTokenRequestPostProcessor with(OpenId openId) { this.openId = openId; return this; } /** * Customize the {@link OpenId}. * * @param openId a custom {@link OpenId} value * @return this {@link WxMpOAuth2AccessTokenRequestPostProcessor} */ public WxMpOAuth2AccessTokenRequestPostProcessor withOpenId(String openId) { return with(OpenId.valueOf(openId)); } @Override public MockHttpServletRequest postProcessRequest( MockHttpServletRequest mockHttpServletRequest) {
WxMpOAuth2AccessToken accessToken = WxMpOAuth2AccessTokenFixture.aWxMpOAuth2AccessToken()
Hippoom/wechat-mp-starter
wechat-mp-test/src/main/java/com/github/hippoom/wechat/mp/test/web/servlet/request/WxMpOAuth2AccessTokenRequestPostProcessor.java
// Path: wechat-mp-autoconfigure/src/main/java/com/github/hippoom/wechat/mp/security/authentication/WeChatMpOAuth2AccessTokenAuthentication.java // public class WeChatMpOAuth2AccessTokenAuthentication implements Authentication { // // private final WxMpOAuth2AccessToken accessToken; // // public WeChatMpOAuth2AccessTokenAuthentication(WxMpOAuth2AccessToken accessToken) { // this.accessToken = accessToken; // } // // @Override // public Collection<? extends GrantedAuthority> getAuthorities() { // return Collections.emptyList(); // } // // @Override // public Object getCredentials() { // return null; // } // // @Override // public Object getDetails() { // return getOpenId(); // } // // @Override // public Object getPrincipal() { // return getOpenId(); // } // // @Override // public boolean isAuthenticated() { // return true; // } // // @Override // public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException { // // } // // @Override // public String getName() { // return accessToken.getOpenId(); // } // // public OpenId getOpenId() { // return OpenId.valueOf(accessToken.getOpenId()); // } // } // // Path: wechat-mp-test/src/main/java/com/github/hippoom/wechat/mp/test/fixture/WxMpOAuth2AccessTokenFixture.java // public class WxMpOAuth2AccessTokenFixture { // // private WxMpOAuth2AccessToken target = new WxMpOAuth2AccessToken(); // // private WxMpOAuth2AccessTokenFixture() { // target.setOpenId(OpenId.valueOf(UUID.randomUUID().toString()).getValue()); // target.setAccessToken("accessToken"); // target.setRefreshToken("refreshToken"); // target.setExpiresIn(3600); // target.setScope("snsapi_base"); // } // // /** // * Customize the {@link OpenId}. // * // * @param openId a custom {@link OpenId} // * @return this {@link WxMpOAuth2AccessTokenFixture} // */ // public WxMpOAuth2AccessTokenFixture with(OpenId openId) { // target.setOpenId(openId.getValue()); // return this; // } // // /** // * Build the {@link WxMpOAuth2AccessToken}. // * // * @return this {@link WxMpOAuth2AccessToken} // */ // public WxMpOAuth2AccessToken build() { // return target; // } // // /** // * Static factory method for {@link WxMpOAuth2AccessTokenFixture}. // * // * @return a {@link WxMpOAuth2AccessTokenFixture} with default values // */ // public static WxMpOAuth2AccessTokenFixture aWxMpOAuth2AccessToken() { // return new WxMpOAuth2AccessTokenFixture(); // } // } // // Path: wechat-mp-autoconfigure/src/main/java/com/github/hippoom/wechat/oauth/OpenId.java // @Value // public class OpenId { // // private String value; // // private OpenId(String value) { // this.value = value; // } // // public static OpenId valueOf(String value) { // return new OpenId(value); // } // }
import com.github.hippoom.wechat.mp.security.authentication.WeChatMpOAuth2AccessTokenAuthentication; import com.github.hippoom.wechat.mp.test.fixture.WxMpOAuth2AccessTokenFixture; import com.github.hippoom.wechat.oauth.OpenId; import java.util.UUID; import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors; import org.springframework.test.web.servlet.request.RequestPostProcessor;
package com.github.hippoom.wechat.mp.test.web.servlet.request; // @formatter:off /** * Test fixture for {@link WxMpOAuth2AccessTokenFixture}. * <pre class="code"> * * import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; * import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; * import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; * import static com.github.hippoom.wechat.mp.test.web.servlet.request * .WxMpOAuth2AccessTokenRequestPostProcessor.aWeChatMpUser; * * &#064;Test public void returns_wechat_user_profile() { * this.mockMvc.perform( * get("/rel/wechat/user/profile/me").with(aWeChatMpUser().withOpenId(userProfile.openId)) * ).andDo(print()).andExpect(status().isOk()); * } * * </pre> * * @see RequestPostProcessor * @since 0.3.0 */ //@formatter:on public class WxMpOAuth2AccessTokenRequestPostProcessor implements RequestPostProcessor { private OpenId openId = OpenId.valueOf(UUID.randomUUID().toString()); /** * Customize the {@link OpenId}. * * @param openId a custom {@link OpenId} * @return this {@link WxMpOAuth2AccessTokenRequestPostProcessor} */ public WxMpOAuth2AccessTokenRequestPostProcessor with(OpenId openId) { this.openId = openId; return this; } /** * Customize the {@link OpenId}. * * @param openId a custom {@link OpenId} value * @return this {@link WxMpOAuth2AccessTokenRequestPostProcessor} */ public WxMpOAuth2AccessTokenRequestPostProcessor withOpenId(String openId) { return with(OpenId.valueOf(openId)); } @Override public MockHttpServletRequest postProcessRequest( MockHttpServletRequest mockHttpServletRequest) { WxMpOAuth2AccessToken accessToken = WxMpOAuth2AccessTokenFixture.aWxMpOAuth2AccessToken() .with(openId).build(); RequestPostProcessor delegate = SecurityMockMvcRequestPostProcessors
// Path: wechat-mp-autoconfigure/src/main/java/com/github/hippoom/wechat/mp/security/authentication/WeChatMpOAuth2AccessTokenAuthentication.java // public class WeChatMpOAuth2AccessTokenAuthentication implements Authentication { // // private final WxMpOAuth2AccessToken accessToken; // // public WeChatMpOAuth2AccessTokenAuthentication(WxMpOAuth2AccessToken accessToken) { // this.accessToken = accessToken; // } // // @Override // public Collection<? extends GrantedAuthority> getAuthorities() { // return Collections.emptyList(); // } // // @Override // public Object getCredentials() { // return null; // } // // @Override // public Object getDetails() { // return getOpenId(); // } // // @Override // public Object getPrincipal() { // return getOpenId(); // } // // @Override // public boolean isAuthenticated() { // return true; // } // // @Override // public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException { // // } // // @Override // public String getName() { // return accessToken.getOpenId(); // } // // public OpenId getOpenId() { // return OpenId.valueOf(accessToken.getOpenId()); // } // } // // Path: wechat-mp-test/src/main/java/com/github/hippoom/wechat/mp/test/fixture/WxMpOAuth2AccessTokenFixture.java // public class WxMpOAuth2AccessTokenFixture { // // private WxMpOAuth2AccessToken target = new WxMpOAuth2AccessToken(); // // private WxMpOAuth2AccessTokenFixture() { // target.setOpenId(OpenId.valueOf(UUID.randomUUID().toString()).getValue()); // target.setAccessToken("accessToken"); // target.setRefreshToken("refreshToken"); // target.setExpiresIn(3600); // target.setScope("snsapi_base"); // } // // /** // * Customize the {@link OpenId}. // * // * @param openId a custom {@link OpenId} // * @return this {@link WxMpOAuth2AccessTokenFixture} // */ // public WxMpOAuth2AccessTokenFixture with(OpenId openId) { // target.setOpenId(openId.getValue()); // return this; // } // // /** // * Build the {@link WxMpOAuth2AccessToken}. // * // * @return this {@link WxMpOAuth2AccessToken} // */ // public WxMpOAuth2AccessToken build() { // return target; // } // // /** // * Static factory method for {@link WxMpOAuth2AccessTokenFixture}. // * // * @return a {@link WxMpOAuth2AccessTokenFixture} with default values // */ // public static WxMpOAuth2AccessTokenFixture aWxMpOAuth2AccessToken() { // return new WxMpOAuth2AccessTokenFixture(); // } // } // // Path: wechat-mp-autoconfigure/src/main/java/com/github/hippoom/wechat/oauth/OpenId.java // @Value // public class OpenId { // // private String value; // // private OpenId(String value) { // this.value = value; // } // // public static OpenId valueOf(String value) { // return new OpenId(value); // } // } // Path: wechat-mp-test/src/main/java/com/github/hippoom/wechat/mp/test/web/servlet/request/WxMpOAuth2AccessTokenRequestPostProcessor.java import com.github.hippoom.wechat.mp.security.authentication.WeChatMpOAuth2AccessTokenAuthentication; import com.github.hippoom.wechat.mp.test.fixture.WxMpOAuth2AccessTokenFixture; import com.github.hippoom.wechat.oauth.OpenId; import java.util.UUID; import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors; import org.springframework.test.web.servlet.request.RequestPostProcessor; package com.github.hippoom.wechat.mp.test.web.servlet.request; // @formatter:off /** * Test fixture for {@link WxMpOAuth2AccessTokenFixture}. * <pre class="code"> * * import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; * import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; * import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; * import static com.github.hippoom.wechat.mp.test.web.servlet.request * .WxMpOAuth2AccessTokenRequestPostProcessor.aWeChatMpUser; * * &#064;Test public void returns_wechat_user_profile() { * this.mockMvc.perform( * get("/rel/wechat/user/profile/me").with(aWeChatMpUser().withOpenId(userProfile.openId)) * ).andDo(print()).andExpect(status().isOk()); * } * * </pre> * * @see RequestPostProcessor * @since 0.3.0 */ //@formatter:on public class WxMpOAuth2AccessTokenRequestPostProcessor implements RequestPostProcessor { private OpenId openId = OpenId.valueOf(UUID.randomUUID().toString()); /** * Customize the {@link OpenId}. * * @param openId a custom {@link OpenId} * @return this {@link WxMpOAuth2AccessTokenRequestPostProcessor} */ public WxMpOAuth2AccessTokenRequestPostProcessor with(OpenId openId) { this.openId = openId; return this; } /** * Customize the {@link OpenId}. * * @param openId a custom {@link OpenId} value * @return this {@link WxMpOAuth2AccessTokenRequestPostProcessor} */ public WxMpOAuth2AccessTokenRequestPostProcessor withOpenId(String openId) { return with(OpenId.valueOf(openId)); } @Override public MockHttpServletRequest postProcessRequest( MockHttpServletRequest mockHttpServletRequest) { WxMpOAuth2AccessToken accessToken = WxMpOAuth2AccessTokenFixture.aWxMpOAuth2AccessToken() .with(openId).build(); RequestPostProcessor delegate = SecurityMockMvcRequestPostProcessors
.authentication(new WeChatMpOAuth2AccessTokenAuthentication(accessToken));
Hippoom/wechat-mp-starter
wechat-mp-autoconfigure/src/main/java/com/github/hippoom/wechat/mp/autoconfigure/security/web/WeChatMpWebSecurityConfigurerAdapter.java
// Path: wechat-mp-autoconfigure/src/main/java/com/github/hippoom/wechat/mp/security/web/RestAuthenticationEntryPoint.java // public class RestAuthenticationEntryPoint // implements AuthenticationEntryPoint { // // @Override // public void commence( // HttpServletRequest request, // HttpServletResponse response, // AuthenticationException authException) throws IOException { // // This is invoked when user tries to access a secured REST resource // // without supplying any credentials // // We should just send a 401 Unauthorized response // // because there is no 'login page' to redirect to // response.sendError(SC_UNAUTHORIZED, "Unauthorized"); // } // } // // Path: wechat-mp-autoconfigure/src/main/java/com/github/hippoom/wechat/mp/security/web/authentication/WeChatMpOAuth2AuthenticationProcessingFilter.java // public class WeChatMpOAuth2AuthenticationProcessingFilter // extends AbstractAuthenticationProcessingFilter { // // @Setter // private WxMpService wxMpService; // // public WeChatMpOAuth2AuthenticationProcessingFilter(String defaultFilterProcessesUrl) { // super(defaultFilterProcessesUrl); // } // // public WeChatMpOAuth2AuthenticationProcessingFilter( // RequestMatcher requiresAuthenticationRequestMatcher) { // super(requiresAuthenticationRequestMatcher); // } // // @SneakyThrows // @Override // public Authentication attemptAuthentication(HttpServletRequest request, // HttpServletResponse response) // throws AuthenticationException, IOException, ServletException { // // final String code = request.getParameter("code"); // // WxMpOAuth2AccessToken accessToken = wxMpService.oauth2getAccessToken(code); // // return new WeChatMpOAuth2AccessTokenAuthentication(accessToken); // } // } // // Path: wechat-mp-autoconfigure/src/main/java/com/github/hippoom/wechat/mp/security/web/authentication/WeChatMpOAuth2AuthenticationSuccessHandler.java // public class WeChatMpOAuth2AuthenticationSuccessHandler implements AuthenticationSuccessHandler { // // public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, // Authentication authentication) throws IOException, ServletException { // // String origin = request.getParameter("state"); // // URL raw = new URL( // new String(Base64.getUrlDecoder().decode(origin.getBytes(Charset.forName("UTF-8"))), // Charset.forName("UTF-8"))); // response.sendRedirect(raw.toString()); // } // }
import static org.springframework.security.config.http.SessionCreationPolicy.IF_REQUIRED; import com.github.hippoom.wechat.mp.security.web.RestAuthenticationEntryPoint; import com.github.hippoom.wechat.mp.security.web.authentication.WeChatMpOAuth2AuthenticationProcessingFilter; import com.github.hippoom.wechat.mp.security.web.authentication.WeChatMpOAuth2AuthenticationSuccessHandler; import lombok.Getter; import lombok.RequiredArgsConstructor; import me.chanjar.weixin.mp.api.WxMpService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.annotation.web.configurers.CsrfConfigurer; import org.springframework.security.web.csrf.CookieCsrfTokenRepository; import org.springframework.security.web.csrf.CsrfAuthenticationStrategy; import org.springframework.security.web.csrf.CsrfFilter; import org.springframework.security.web.csrf.CsrfTokenRepository; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import org.springframework.security.web.util.matcher.RequestMatcher;
.addFilterAfter(weChatMpOAuth2AuthenticationProcessingFilter(wxMpService), CsrfFilter.class) .exceptionHandling() .authenticationEntryPoint(restAuthenticationEntryPoint()) .and(); // @formatter:on } /** * subclass should override this to * customize {@link CsrfConfigurer#requireCsrfProtectionMatcher(RequestMatcher)}. * * @return see {@link RequestMatcher} */ protected RequestMatcher requireCsrfProtectionMatcher() { return new AntPathRequestMatcher("/rel/**/me"); } @Bean protected CsrfTokenRepository csrfTokenRepository() { return CookieCsrfTokenRepository.withHttpOnlyFalse(); } @Bean protected CsrfAuthenticationStrategy sessionAuthenticationStrategy() { return new CsrfAuthenticationStrategy(csrfTokenRepository()); } @Bean
// Path: wechat-mp-autoconfigure/src/main/java/com/github/hippoom/wechat/mp/security/web/RestAuthenticationEntryPoint.java // public class RestAuthenticationEntryPoint // implements AuthenticationEntryPoint { // // @Override // public void commence( // HttpServletRequest request, // HttpServletResponse response, // AuthenticationException authException) throws IOException { // // This is invoked when user tries to access a secured REST resource // // without supplying any credentials // // We should just send a 401 Unauthorized response // // because there is no 'login page' to redirect to // response.sendError(SC_UNAUTHORIZED, "Unauthorized"); // } // } // // Path: wechat-mp-autoconfigure/src/main/java/com/github/hippoom/wechat/mp/security/web/authentication/WeChatMpOAuth2AuthenticationProcessingFilter.java // public class WeChatMpOAuth2AuthenticationProcessingFilter // extends AbstractAuthenticationProcessingFilter { // // @Setter // private WxMpService wxMpService; // // public WeChatMpOAuth2AuthenticationProcessingFilter(String defaultFilterProcessesUrl) { // super(defaultFilterProcessesUrl); // } // // public WeChatMpOAuth2AuthenticationProcessingFilter( // RequestMatcher requiresAuthenticationRequestMatcher) { // super(requiresAuthenticationRequestMatcher); // } // // @SneakyThrows // @Override // public Authentication attemptAuthentication(HttpServletRequest request, // HttpServletResponse response) // throws AuthenticationException, IOException, ServletException { // // final String code = request.getParameter("code"); // // WxMpOAuth2AccessToken accessToken = wxMpService.oauth2getAccessToken(code); // // return new WeChatMpOAuth2AccessTokenAuthentication(accessToken); // } // } // // Path: wechat-mp-autoconfigure/src/main/java/com/github/hippoom/wechat/mp/security/web/authentication/WeChatMpOAuth2AuthenticationSuccessHandler.java // public class WeChatMpOAuth2AuthenticationSuccessHandler implements AuthenticationSuccessHandler { // // public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, // Authentication authentication) throws IOException, ServletException { // // String origin = request.getParameter("state"); // // URL raw = new URL( // new String(Base64.getUrlDecoder().decode(origin.getBytes(Charset.forName("UTF-8"))), // Charset.forName("UTF-8"))); // response.sendRedirect(raw.toString()); // } // } // Path: wechat-mp-autoconfigure/src/main/java/com/github/hippoom/wechat/mp/autoconfigure/security/web/WeChatMpWebSecurityConfigurerAdapter.java import static org.springframework.security.config.http.SessionCreationPolicy.IF_REQUIRED; import com.github.hippoom.wechat.mp.security.web.RestAuthenticationEntryPoint; import com.github.hippoom.wechat.mp.security.web.authentication.WeChatMpOAuth2AuthenticationProcessingFilter; import com.github.hippoom.wechat.mp.security.web.authentication.WeChatMpOAuth2AuthenticationSuccessHandler; import lombok.Getter; import lombok.RequiredArgsConstructor; import me.chanjar.weixin.mp.api.WxMpService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.annotation.web.configurers.CsrfConfigurer; import org.springframework.security.web.csrf.CookieCsrfTokenRepository; import org.springframework.security.web.csrf.CsrfAuthenticationStrategy; import org.springframework.security.web.csrf.CsrfFilter; import org.springframework.security.web.csrf.CsrfTokenRepository; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import org.springframework.security.web.util.matcher.RequestMatcher; .addFilterAfter(weChatMpOAuth2AuthenticationProcessingFilter(wxMpService), CsrfFilter.class) .exceptionHandling() .authenticationEntryPoint(restAuthenticationEntryPoint()) .and(); // @formatter:on } /** * subclass should override this to * customize {@link CsrfConfigurer#requireCsrfProtectionMatcher(RequestMatcher)}. * * @return see {@link RequestMatcher} */ protected RequestMatcher requireCsrfProtectionMatcher() { return new AntPathRequestMatcher("/rel/**/me"); } @Bean protected CsrfTokenRepository csrfTokenRepository() { return CookieCsrfTokenRepository.withHttpOnlyFalse(); } @Bean protected CsrfAuthenticationStrategy sessionAuthenticationStrategy() { return new CsrfAuthenticationStrategy(csrfTokenRepository()); } @Bean
protected RestAuthenticationEntryPoint restAuthenticationEntryPoint() {
Hippoom/wechat-mp-starter
wechat-mp-autoconfigure/src/main/java/com/github/hippoom/wechat/mp/autoconfigure/security/web/WeChatMpWebSecurityConfigurerAdapter.java
// Path: wechat-mp-autoconfigure/src/main/java/com/github/hippoom/wechat/mp/security/web/RestAuthenticationEntryPoint.java // public class RestAuthenticationEntryPoint // implements AuthenticationEntryPoint { // // @Override // public void commence( // HttpServletRequest request, // HttpServletResponse response, // AuthenticationException authException) throws IOException { // // This is invoked when user tries to access a secured REST resource // // without supplying any credentials // // We should just send a 401 Unauthorized response // // because there is no 'login page' to redirect to // response.sendError(SC_UNAUTHORIZED, "Unauthorized"); // } // } // // Path: wechat-mp-autoconfigure/src/main/java/com/github/hippoom/wechat/mp/security/web/authentication/WeChatMpOAuth2AuthenticationProcessingFilter.java // public class WeChatMpOAuth2AuthenticationProcessingFilter // extends AbstractAuthenticationProcessingFilter { // // @Setter // private WxMpService wxMpService; // // public WeChatMpOAuth2AuthenticationProcessingFilter(String defaultFilterProcessesUrl) { // super(defaultFilterProcessesUrl); // } // // public WeChatMpOAuth2AuthenticationProcessingFilter( // RequestMatcher requiresAuthenticationRequestMatcher) { // super(requiresAuthenticationRequestMatcher); // } // // @SneakyThrows // @Override // public Authentication attemptAuthentication(HttpServletRequest request, // HttpServletResponse response) // throws AuthenticationException, IOException, ServletException { // // final String code = request.getParameter("code"); // // WxMpOAuth2AccessToken accessToken = wxMpService.oauth2getAccessToken(code); // // return new WeChatMpOAuth2AccessTokenAuthentication(accessToken); // } // } // // Path: wechat-mp-autoconfigure/src/main/java/com/github/hippoom/wechat/mp/security/web/authentication/WeChatMpOAuth2AuthenticationSuccessHandler.java // public class WeChatMpOAuth2AuthenticationSuccessHandler implements AuthenticationSuccessHandler { // // public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, // Authentication authentication) throws IOException, ServletException { // // String origin = request.getParameter("state"); // // URL raw = new URL( // new String(Base64.getUrlDecoder().decode(origin.getBytes(Charset.forName("UTF-8"))), // Charset.forName("UTF-8"))); // response.sendRedirect(raw.toString()); // } // }
import static org.springframework.security.config.http.SessionCreationPolicy.IF_REQUIRED; import com.github.hippoom.wechat.mp.security.web.RestAuthenticationEntryPoint; import com.github.hippoom.wechat.mp.security.web.authentication.WeChatMpOAuth2AuthenticationProcessingFilter; import com.github.hippoom.wechat.mp.security.web.authentication.WeChatMpOAuth2AuthenticationSuccessHandler; import lombok.Getter; import lombok.RequiredArgsConstructor; import me.chanjar.weixin.mp.api.WxMpService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.annotation.web.configurers.CsrfConfigurer; import org.springframework.security.web.csrf.CookieCsrfTokenRepository; import org.springframework.security.web.csrf.CsrfAuthenticationStrategy; import org.springframework.security.web.csrf.CsrfFilter; import org.springframework.security.web.csrf.CsrfTokenRepository; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import org.springframework.security.web.util.matcher.RequestMatcher;
.and(); // @formatter:on } /** * subclass should override this to * customize {@link CsrfConfigurer#requireCsrfProtectionMatcher(RequestMatcher)}. * * @return see {@link RequestMatcher} */ protected RequestMatcher requireCsrfProtectionMatcher() { return new AntPathRequestMatcher("/rel/**/me"); } @Bean protected CsrfTokenRepository csrfTokenRepository() { return CookieCsrfTokenRepository.withHttpOnlyFalse(); } @Bean protected CsrfAuthenticationStrategy sessionAuthenticationStrategy() { return new CsrfAuthenticationStrategy(csrfTokenRepository()); } @Bean protected RestAuthenticationEntryPoint restAuthenticationEntryPoint() { return new RestAuthenticationEntryPoint(); }
// Path: wechat-mp-autoconfigure/src/main/java/com/github/hippoom/wechat/mp/security/web/RestAuthenticationEntryPoint.java // public class RestAuthenticationEntryPoint // implements AuthenticationEntryPoint { // // @Override // public void commence( // HttpServletRequest request, // HttpServletResponse response, // AuthenticationException authException) throws IOException { // // This is invoked when user tries to access a secured REST resource // // without supplying any credentials // // We should just send a 401 Unauthorized response // // because there is no 'login page' to redirect to // response.sendError(SC_UNAUTHORIZED, "Unauthorized"); // } // } // // Path: wechat-mp-autoconfigure/src/main/java/com/github/hippoom/wechat/mp/security/web/authentication/WeChatMpOAuth2AuthenticationProcessingFilter.java // public class WeChatMpOAuth2AuthenticationProcessingFilter // extends AbstractAuthenticationProcessingFilter { // // @Setter // private WxMpService wxMpService; // // public WeChatMpOAuth2AuthenticationProcessingFilter(String defaultFilterProcessesUrl) { // super(defaultFilterProcessesUrl); // } // // public WeChatMpOAuth2AuthenticationProcessingFilter( // RequestMatcher requiresAuthenticationRequestMatcher) { // super(requiresAuthenticationRequestMatcher); // } // // @SneakyThrows // @Override // public Authentication attemptAuthentication(HttpServletRequest request, // HttpServletResponse response) // throws AuthenticationException, IOException, ServletException { // // final String code = request.getParameter("code"); // // WxMpOAuth2AccessToken accessToken = wxMpService.oauth2getAccessToken(code); // // return new WeChatMpOAuth2AccessTokenAuthentication(accessToken); // } // } // // Path: wechat-mp-autoconfigure/src/main/java/com/github/hippoom/wechat/mp/security/web/authentication/WeChatMpOAuth2AuthenticationSuccessHandler.java // public class WeChatMpOAuth2AuthenticationSuccessHandler implements AuthenticationSuccessHandler { // // public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, // Authentication authentication) throws IOException, ServletException { // // String origin = request.getParameter("state"); // // URL raw = new URL( // new String(Base64.getUrlDecoder().decode(origin.getBytes(Charset.forName("UTF-8"))), // Charset.forName("UTF-8"))); // response.sendRedirect(raw.toString()); // } // } // Path: wechat-mp-autoconfigure/src/main/java/com/github/hippoom/wechat/mp/autoconfigure/security/web/WeChatMpWebSecurityConfigurerAdapter.java import static org.springframework.security.config.http.SessionCreationPolicy.IF_REQUIRED; import com.github.hippoom.wechat.mp.security.web.RestAuthenticationEntryPoint; import com.github.hippoom.wechat.mp.security.web.authentication.WeChatMpOAuth2AuthenticationProcessingFilter; import com.github.hippoom.wechat.mp.security.web.authentication.WeChatMpOAuth2AuthenticationSuccessHandler; import lombok.Getter; import lombok.RequiredArgsConstructor; import me.chanjar.weixin.mp.api.WxMpService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.annotation.web.configurers.CsrfConfigurer; import org.springframework.security.web.csrf.CookieCsrfTokenRepository; import org.springframework.security.web.csrf.CsrfAuthenticationStrategy; import org.springframework.security.web.csrf.CsrfFilter; import org.springframework.security.web.csrf.CsrfTokenRepository; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import org.springframework.security.web.util.matcher.RequestMatcher; .and(); // @formatter:on } /** * subclass should override this to * customize {@link CsrfConfigurer#requireCsrfProtectionMatcher(RequestMatcher)}. * * @return see {@link RequestMatcher} */ protected RequestMatcher requireCsrfProtectionMatcher() { return new AntPathRequestMatcher("/rel/**/me"); } @Bean protected CsrfTokenRepository csrfTokenRepository() { return CookieCsrfTokenRepository.withHttpOnlyFalse(); } @Bean protected CsrfAuthenticationStrategy sessionAuthenticationStrategy() { return new CsrfAuthenticationStrategy(csrfTokenRepository()); } @Bean protected RestAuthenticationEntryPoint restAuthenticationEntryPoint() { return new RestAuthenticationEntryPoint(); }
protected WeChatMpOAuth2AuthenticationProcessingFilter
Hippoom/wechat-mp-starter
wechat-mp-autoconfigure/src/main/java/com/github/hippoom/wechat/mp/autoconfigure/security/web/WeChatMpWebSecurityConfigurerAdapter.java
// Path: wechat-mp-autoconfigure/src/main/java/com/github/hippoom/wechat/mp/security/web/RestAuthenticationEntryPoint.java // public class RestAuthenticationEntryPoint // implements AuthenticationEntryPoint { // // @Override // public void commence( // HttpServletRequest request, // HttpServletResponse response, // AuthenticationException authException) throws IOException { // // This is invoked when user tries to access a secured REST resource // // without supplying any credentials // // We should just send a 401 Unauthorized response // // because there is no 'login page' to redirect to // response.sendError(SC_UNAUTHORIZED, "Unauthorized"); // } // } // // Path: wechat-mp-autoconfigure/src/main/java/com/github/hippoom/wechat/mp/security/web/authentication/WeChatMpOAuth2AuthenticationProcessingFilter.java // public class WeChatMpOAuth2AuthenticationProcessingFilter // extends AbstractAuthenticationProcessingFilter { // // @Setter // private WxMpService wxMpService; // // public WeChatMpOAuth2AuthenticationProcessingFilter(String defaultFilterProcessesUrl) { // super(defaultFilterProcessesUrl); // } // // public WeChatMpOAuth2AuthenticationProcessingFilter( // RequestMatcher requiresAuthenticationRequestMatcher) { // super(requiresAuthenticationRequestMatcher); // } // // @SneakyThrows // @Override // public Authentication attemptAuthentication(HttpServletRequest request, // HttpServletResponse response) // throws AuthenticationException, IOException, ServletException { // // final String code = request.getParameter("code"); // // WxMpOAuth2AccessToken accessToken = wxMpService.oauth2getAccessToken(code); // // return new WeChatMpOAuth2AccessTokenAuthentication(accessToken); // } // } // // Path: wechat-mp-autoconfigure/src/main/java/com/github/hippoom/wechat/mp/security/web/authentication/WeChatMpOAuth2AuthenticationSuccessHandler.java // public class WeChatMpOAuth2AuthenticationSuccessHandler implements AuthenticationSuccessHandler { // // public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, // Authentication authentication) throws IOException, ServletException { // // String origin = request.getParameter("state"); // // URL raw = new URL( // new String(Base64.getUrlDecoder().decode(origin.getBytes(Charset.forName("UTF-8"))), // Charset.forName("UTF-8"))); // response.sendRedirect(raw.toString()); // } // }
import static org.springframework.security.config.http.SessionCreationPolicy.IF_REQUIRED; import com.github.hippoom.wechat.mp.security.web.RestAuthenticationEntryPoint; import com.github.hippoom.wechat.mp.security.web.authentication.WeChatMpOAuth2AuthenticationProcessingFilter; import com.github.hippoom.wechat.mp.security.web.authentication.WeChatMpOAuth2AuthenticationSuccessHandler; import lombok.Getter; import lombok.RequiredArgsConstructor; import me.chanjar.weixin.mp.api.WxMpService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.annotation.web.configurers.CsrfConfigurer; import org.springframework.security.web.csrf.CookieCsrfTokenRepository; import org.springframework.security.web.csrf.CsrfAuthenticationStrategy; import org.springframework.security.web.csrf.CsrfFilter; import org.springframework.security.web.csrf.CsrfTokenRepository; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import org.springframework.security.web.util.matcher.RequestMatcher;
* @return see {@link RequestMatcher} */ protected RequestMatcher requireCsrfProtectionMatcher() { return new AntPathRequestMatcher("/rel/**/me"); } @Bean protected CsrfTokenRepository csrfTokenRepository() { return CookieCsrfTokenRepository.withHttpOnlyFalse(); } @Bean protected CsrfAuthenticationStrategy sessionAuthenticationStrategy() { return new CsrfAuthenticationStrategy(csrfTokenRepository()); } @Bean protected RestAuthenticationEntryPoint restAuthenticationEntryPoint() { return new RestAuthenticationEntryPoint(); } protected WeChatMpOAuth2AuthenticationProcessingFilter // @formatter:off weChatMpOAuth2AuthenticationProcessingFilter(WxMpService wxMpService) { WeChatMpOAuth2AuthenticationProcessingFilter filter = new WeChatMpOAuth2AuthenticationProcessingFilter("/wechat/oauth/token"); filter.setWxMpService(wxMpService); filter
// Path: wechat-mp-autoconfigure/src/main/java/com/github/hippoom/wechat/mp/security/web/RestAuthenticationEntryPoint.java // public class RestAuthenticationEntryPoint // implements AuthenticationEntryPoint { // // @Override // public void commence( // HttpServletRequest request, // HttpServletResponse response, // AuthenticationException authException) throws IOException { // // This is invoked when user tries to access a secured REST resource // // without supplying any credentials // // We should just send a 401 Unauthorized response // // because there is no 'login page' to redirect to // response.sendError(SC_UNAUTHORIZED, "Unauthorized"); // } // } // // Path: wechat-mp-autoconfigure/src/main/java/com/github/hippoom/wechat/mp/security/web/authentication/WeChatMpOAuth2AuthenticationProcessingFilter.java // public class WeChatMpOAuth2AuthenticationProcessingFilter // extends AbstractAuthenticationProcessingFilter { // // @Setter // private WxMpService wxMpService; // // public WeChatMpOAuth2AuthenticationProcessingFilter(String defaultFilterProcessesUrl) { // super(defaultFilterProcessesUrl); // } // // public WeChatMpOAuth2AuthenticationProcessingFilter( // RequestMatcher requiresAuthenticationRequestMatcher) { // super(requiresAuthenticationRequestMatcher); // } // // @SneakyThrows // @Override // public Authentication attemptAuthentication(HttpServletRequest request, // HttpServletResponse response) // throws AuthenticationException, IOException, ServletException { // // final String code = request.getParameter("code"); // // WxMpOAuth2AccessToken accessToken = wxMpService.oauth2getAccessToken(code); // // return new WeChatMpOAuth2AccessTokenAuthentication(accessToken); // } // } // // Path: wechat-mp-autoconfigure/src/main/java/com/github/hippoom/wechat/mp/security/web/authentication/WeChatMpOAuth2AuthenticationSuccessHandler.java // public class WeChatMpOAuth2AuthenticationSuccessHandler implements AuthenticationSuccessHandler { // // public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, // Authentication authentication) throws IOException, ServletException { // // String origin = request.getParameter("state"); // // URL raw = new URL( // new String(Base64.getUrlDecoder().decode(origin.getBytes(Charset.forName("UTF-8"))), // Charset.forName("UTF-8"))); // response.sendRedirect(raw.toString()); // } // } // Path: wechat-mp-autoconfigure/src/main/java/com/github/hippoom/wechat/mp/autoconfigure/security/web/WeChatMpWebSecurityConfigurerAdapter.java import static org.springframework.security.config.http.SessionCreationPolicy.IF_REQUIRED; import com.github.hippoom.wechat.mp.security.web.RestAuthenticationEntryPoint; import com.github.hippoom.wechat.mp.security.web.authentication.WeChatMpOAuth2AuthenticationProcessingFilter; import com.github.hippoom.wechat.mp.security.web.authentication.WeChatMpOAuth2AuthenticationSuccessHandler; import lombok.Getter; import lombok.RequiredArgsConstructor; import me.chanjar.weixin.mp.api.WxMpService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.annotation.web.configurers.CsrfConfigurer; import org.springframework.security.web.csrf.CookieCsrfTokenRepository; import org.springframework.security.web.csrf.CsrfAuthenticationStrategy; import org.springframework.security.web.csrf.CsrfFilter; import org.springframework.security.web.csrf.CsrfTokenRepository; import org.springframework.security.web.util.matcher.AntPathRequestMatcher; import org.springframework.security.web.util.matcher.RequestMatcher; * @return see {@link RequestMatcher} */ protected RequestMatcher requireCsrfProtectionMatcher() { return new AntPathRequestMatcher("/rel/**/me"); } @Bean protected CsrfTokenRepository csrfTokenRepository() { return CookieCsrfTokenRepository.withHttpOnlyFalse(); } @Bean protected CsrfAuthenticationStrategy sessionAuthenticationStrategy() { return new CsrfAuthenticationStrategy(csrfTokenRepository()); } @Bean protected RestAuthenticationEntryPoint restAuthenticationEntryPoint() { return new RestAuthenticationEntryPoint(); } protected WeChatMpOAuth2AuthenticationProcessingFilter // @formatter:off weChatMpOAuth2AuthenticationProcessingFilter(WxMpService wxMpService) { WeChatMpOAuth2AuthenticationProcessingFilter filter = new WeChatMpOAuth2AuthenticationProcessingFilter("/wechat/oauth/token"); filter.setWxMpService(wxMpService); filter
.setAuthenticationSuccessHandler(new WeChatMpOAuth2AuthenticationSuccessHandler());
Hippoom/wechat-mp-starter
examples/oauth2/src/main/java/com/github/hippoom/wechat/mp/examples/oauth2/http/WeChatUserRestController.java
// Path: examples/oauth2/src/main/java/com/github/hippoom/wechat/mp/examples/oauth2/http/assembler/WeChatUserProfileResourceAssembler.java // @Component // public class WeChatUserProfileResourceAssembler extends // ResourceAssemblerSupport<WxMpUser, WeChatUserProfileResource> { // // // public WeChatUserProfileResourceAssembler() { // super(WeChatUserRestController.class, WeChatUserProfileResource.class); // } // // @Override // public WeChatUserProfileResource toResource(WxMpUser entity) { // WeChatUserProfileResource resource = new WeChatUserProfileResource(); // resource.setAvatar(entity.getHeadImgUrl()); // resource.setNickname(entity.getNickname()); // resource // .add( // linkTo(methodOn(WeChatUserRestController.class) // .me(OpenId.valueOf(entity.getOpenId()))).withSelfRel()); // return resource; // } // } // // Path: examples/oauth2/src/main/java/com/github/hippoom/wechat/mp/examples/oauth2/http/resource/WeChatUserProfileResource.java // @Data // @EqualsAndHashCode(callSuper = false) // public class WeChatUserProfileResource extends ResourceSupport { // // private String nickname; // private String avatar; // } // // Path: wechat-mp-autoconfigure/src/main/java/com/github/hippoom/wechat/oauth/OpenId.java // @Value // public class OpenId { // // private String value; // // private OpenId(String value) { // this.value = value; // } // // public static OpenId valueOf(String value) { // return new OpenId(value); // } // }
import static org.springframework.web.bind.annotation.RequestMethod.GET; import com.github.hippoom.wechat.mp.examples.oauth2.http.assembler.WeChatUserProfileResourceAssembler; import com.github.hippoom.wechat.mp.examples.oauth2.http.resource.WeChatUserProfileResource; import com.github.hippoom.wechat.mp.web.bind.annotation.CurrentWeChatMpUser; import com.github.hippoom.wechat.oauth.OpenId; import lombok.NonNull; import lombok.RequiredArgsConstructor; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; import me.chanjar.weixin.mp.api.WxMpUserService; import me.chanjar.weixin.mp.bean.result.WxMpUser; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController;
package com.github.hippoom.wechat.mp.examples.oauth2.http; @Slf4j @RestController @RequiredArgsConstructor public class WeChatUserRestController { @NonNull
// Path: examples/oauth2/src/main/java/com/github/hippoom/wechat/mp/examples/oauth2/http/assembler/WeChatUserProfileResourceAssembler.java // @Component // public class WeChatUserProfileResourceAssembler extends // ResourceAssemblerSupport<WxMpUser, WeChatUserProfileResource> { // // // public WeChatUserProfileResourceAssembler() { // super(WeChatUserRestController.class, WeChatUserProfileResource.class); // } // // @Override // public WeChatUserProfileResource toResource(WxMpUser entity) { // WeChatUserProfileResource resource = new WeChatUserProfileResource(); // resource.setAvatar(entity.getHeadImgUrl()); // resource.setNickname(entity.getNickname()); // resource // .add( // linkTo(methodOn(WeChatUserRestController.class) // .me(OpenId.valueOf(entity.getOpenId()))).withSelfRel()); // return resource; // } // } // // Path: examples/oauth2/src/main/java/com/github/hippoom/wechat/mp/examples/oauth2/http/resource/WeChatUserProfileResource.java // @Data // @EqualsAndHashCode(callSuper = false) // public class WeChatUserProfileResource extends ResourceSupport { // // private String nickname; // private String avatar; // } // // Path: wechat-mp-autoconfigure/src/main/java/com/github/hippoom/wechat/oauth/OpenId.java // @Value // public class OpenId { // // private String value; // // private OpenId(String value) { // this.value = value; // } // // public static OpenId valueOf(String value) { // return new OpenId(value); // } // } // Path: examples/oauth2/src/main/java/com/github/hippoom/wechat/mp/examples/oauth2/http/WeChatUserRestController.java import static org.springframework.web.bind.annotation.RequestMethod.GET; import com.github.hippoom.wechat.mp.examples.oauth2.http.assembler.WeChatUserProfileResourceAssembler; import com.github.hippoom.wechat.mp.examples.oauth2.http.resource.WeChatUserProfileResource; import com.github.hippoom.wechat.mp.web.bind.annotation.CurrentWeChatMpUser; import com.github.hippoom.wechat.oauth.OpenId; import lombok.NonNull; import lombok.RequiredArgsConstructor; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; import me.chanjar.weixin.mp.api.WxMpUserService; import me.chanjar.weixin.mp.bean.result.WxMpUser; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; package com.github.hippoom.wechat.mp.examples.oauth2.http; @Slf4j @RestController @RequiredArgsConstructor public class WeChatUserRestController { @NonNull
private final WeChatUserProfileResourceAssembler userResourceAssembler;
Hippoom/wechat-mp-starter
examples/oauth2/src/main/java/com/github/hippoom/wechat/mp/examples/oauth2/http/WeChatUserRestController.java
// Path: examples/oauth2/src/main/java/com/github/hippoom/wechat/mp/examples/oauth2/http/assembler/WeChatUserProfileResourceAssembler.java // @Component // public class WeChatUserProfileResourceAssembler extends // ResourceAssemblerSupport<WxMpUser, WeChatUserProfileResource> { // // // public WeChatUserProfileResourceAssembler() { // super(WeChatUserRestController.class, WeChatUserProfileResource.class); // } // // @Override // public WeChatUserProfileResource toResource(WxMpUser entity) { // WeChatUserProfileResource resource = new WeChatUserProfileResource(); // resource.setAvatar(entity.getHeadImgUrl()); // resource.setNickname(entity.getNickname()); // resource // .add( // linkTo(methodOn(WeChatUserRestController.class) // .me(OpenId.valueOf(entity.getOpenId()))).withSelfRel()); // return resource; // } // } // // Path: examples/oauth2/src/main/java/com/github/hippoom/wechat/mp/examples/oauth2/http/resource/WeChatUserProfileResource.java // @Data // @EqualsAndHashCode(callSuper = false) // public class WeChatUserProfileResource extends ResourceSupport { // // private String nickname; // private String avatar; // } // // Path: wechat-mp-autoconfigure/src/main/java/com/github/hippoom/wechat/oauth/OpenId.java // @Value // public class OpenId { // // private String value; // // private OpenId(String value) { // this.value = value; // } // // public static OpenId valueOf(String value) { // return new OpenId(value); // } // }
import static org.springframework.web.bind.annotation.RequestMethod.GET; import com.github.hippoom.wechat.mp.examples.oauth2.http.assembler.WeChatUserProfileResourceAssembler; import com.github.hippoom.wechat.mp.examples.oauth2.http.resource.WeChatUserProfileResource; import com.github.hippoom.wechat.mp.web.bind.annotation.CurrentWeChatMpUser; import com.github.hippoom.wechat.oauth.OpenId; import lombok.NonNull; import lombok.RequiredArgsConstructor; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; import me.chanjar.weixin.mp.api.WxMpUserService; import me.chanjar.weixin.mp.bean.result.WxMpUser; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController;
package com.github.hippoom.wechat.mp.examples.oauth2.http; @Slf4j @RestController @RequiredArgsConstructor public class WeChatUserRestController { @NonNull private final WeChatUserProfileResourceAssembler userResourceAssembler; @NonNull private final WxMpUserService wxMpUserService; @SneakyThrows @RequestMapping(value = "/rel/wechat/user/profile/me", method = GET)
// Path: examples/oauth2/src/main/java/com/github/hippoom/wechat/mp/examples/oauth2/http/assembler/WeChatUserProfileResourceAssembler.java // @Component // public class WeChatUserProfileResourceAssembler extends // ResourceAssemblerSupport<WxMpUser, WeChatUserProfileResource> { // // // public WeChatUserProfileResourceAssembler() { // super(WeChatUserRestController.class, WeChatUserProfileResource.class); // } // // @Override // public WeChatUserProfileResource toResource(WxMpUser entity) { // WeChatUserProfileResource resource = new WeChatUserProfileResource(); // resource.setAvatar(entity.getHeadImgUrl()); // resource.setNickname(entity.getNickname()); // resource // .add( // linkTo(methodOn(WeChatUserRestController.class) // .me(OpenId.valueOf(entity.getOpenId()))).withSelfRel()); // return resource; // } // } // // Path: examples/oauth2/src/main/java/com/github/hippoom/wechat/mp/examples/oauth2/http/resource/WeChatUserProfileResource.java // @Data // @EqualsAndHashCode(callSuper = false) // public class WeChatUserProfileResource extends ResourceSupport { // // private String nickname; // private String avatar; // } // // Path: wechat-mp-autoconfigure/src/main/java/com/github/hippoom/wechat/oauth/OpenId.java // @Value // public class OpenId { // // private String value; // // private OpenId(String value) { // this.value = value; // } // // public static OpenId valueOf(String value) { // return new OpenId(value); // } // } // Path: examples/oauth2/src/main/java/com/github/hippoom/wechat/mp/examples/oauth2/http/WeChatUserRestController.java import static org.springframework.web.bind.annotation.RequestMethod.GET; import com.github.hippoom.wechat.mp.examples.oauth2.http.assembler.WeChatUserProfileResourceAssembler; import com.github.hippoom.wechat.mp.examples.oauth2.http.resource.WeChatUserProfileResource; import com.github.hippoom.wechat.mp.web.bind.annotation.CurrentWeChatMpUser; import com.github.hippoom.wechat.oauth.OpenId; import lombok.NonNull; import lombok.RequiredArgsConstructor; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; import me.chanjar.weixin.mp.api.WxMpUserService; import me.chanjar.weixin.mp.bean.result.WxMpUser; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; package com.github.hippoom.wechat.mp.examples.oauth2.http; @Slf4j @RestController @RequiredArgsConstructor public class WeChatUserRestController { @NonNull private final WeChatUserProfileResourceAssembler userResourceAssembler; @NonNull private final WxMpUserService wxMpUserService; @SneakyThrows @RequestMapping(value = "/rel/wechat/user/profile/me", method = GET)
public WeChatUserProfileResource me(@CurrentWeChatMpUser OpenId openId) {
Hippoom/wechat-mp-starter
examples/oauth2/src/main/java/com/github/hippoom/wechat/mp/examples/oauth2/http/WeChatUserRestController.java
// Path: examples/oauth2/src/main/java/com/github/hippoom/wechat/mp/examples/oauth2/http/assembler/WeChatUserProfileResourceAssembler.java // @Component // public class WeChatUserProfileResourceAssembler extends // ResourceAssemblerSupport<WxMpUser, WeChatUserProfileResource> { // // // public WeChatUserProfileResourceAssembler() { // super(WeChatUserRestController.class, WeChatUserProfileResource.class); // } // // @Override // public WeChatUserProfileResource toResource(WxMpUser entity) { // WeChatUserProfileResource resource = new WeChatUserProfileResource(); // resource.setAvatar(entity.getHeadImgUrl()); // resource.setNickname(entity.getNickname()); // resource // .add( // linkTo(methodOn(WeChatUserRestController.class) // .me(OpenId.valueOf(entity.getOpenId()))).withSelfRel()); // return resource; // } // } // // Path: examples/oauth2/src/main/java/com/github/hippoom/wechat/mp/examples/oauth2/http/resource/WeChatUserProfileResource.java // @Data // @EqualsAndHashCode(callSuper = false) // public class WeChatUserProfileResource extends ResourceSupport { // // private String nickname; // private String avatar; // } // // Path: wechat-mp-autoconfigure/src/main/java/com/github/hippoom/wechat/oauth/OpenId.java // @Value // public class OpenId { // // private String value; // // private OpenId(String value) { // this.value = value; // } // // public static OpenId valueOf(String value) { // return new OpenId(value); // } // }
import static org.springframework.web.bind.annotation.RequestMethod.GET; import com.github.hippoom.wechat.mp.examples.oauth2.http.assembler.WeChatUserProfileResourceAssembler; import com.github.hippoom.wechat.mp.examples.oauth2.http.resource.WeChatUserProfileResource; import com.github.hippoom.wechat.mp.web.bind.annotation.CurrentWeChatMpUser; import com.github.hippoom.wechat.oauth.OpenId; import lombok.NonNull; import lombok.RequiredArgsConstructor; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; import me.chanjar.weixin.mp.api.WxMpUserService; import me.chanjar.weixin.mp.bean.result.WxMpUser; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController;
package com.github.hippoom.wechat.mp.examples.oauth2.http; @Slf4j @RestController @RequiredArgsConstructor public class WeChatUserRestController { @NonNull private final WeChatUserProfileResourceAssembler userResourceAssembler; @NonNull private final WxMpUserService wxMpUserService; @SneakyThrows @RequestMapping(value = "/rel/wechat/user/profile/me", method = GET)
// Path: examples/oauth2/src/main/java/com/github/hippoom/wechat/mp/examples/oauth2/http/assembler/WeChatUserProfileResourceAssembler.java // @Component // public class WeChatUserProfileResourceAssembler extends // ResourceAssemblerSupport<WxMpUser, WeChatUserProfileResource> { // // // public WeChatUserProfileResourceAssembler() { // super(WeChatUserRestController.class, WeChatUserProfileResource.class); // } // // @Override // public WeChatUserProfileResource toResource(WxMpUser entity) { // WeChatUserProfileResource resource = new WeChatUserProfileResource(); // resource.setAvatar(entity.getHeadImgUrl()); // resource.setNickname(entity.getNickname()); // resource // .add( // linkTo(methodOn(WeChatUserRestController.class) // .me(OpenId.valueOf(entity.getOpenId()))).withSelfRel()); // return resource; // } // } // // Path: examples/oauth2/src/main/java/com/github/hippoom/wechat/mp/examples/oauth2/http/resource/WeChatUserProfileResource.java // @Data // @EqualsAndHashCode(callSuper = false) // public class WeChatUserProfileResource extends ResourceSupport { // // private String nickname; // private String avatar; // } // // Path: wechat-mp-autoconfigure/src/main/java/com/github/hippoom/wechat/oauth/OpenId.java // @Value // public class OpenId { // // private String value; // // private OpenId(String value) { // this.value = value; // } // // public static OpenId valueOf(String value) { // return new OpenId(value); // } // } // Path: examples/oauth2/src/main/java/com/github/hippoom/wechat/mp/examples/oauth2/http/WeChatUserRestController.java import static org.springframework.web.bind.annotation.RequestMethod.GET; import com.github.hippoom.wechat.mp.examples.oauth2.http.assembler.WeChatUserProfileResourceAssembler; import com.github.hippoom.wechat.mp.examples.oauth2.http.resource.WeChatUserProfileResource; import com.github.hippoom.wechat.mp.web.bind.annotation.CurrentWeChatMpUser; import com.github.hippoom.wechat.oauth.OpenId; import lombok.NonNull; import lombok.RequiredArgsConstructor; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; import me.chanjar.weixin.mp.api.WxMpUserService; import me.chanjar.weixin.mp.bean.result.WxMpUser; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; package com.github.hippoom.wechat.mp.examples.oauth2.http; @Slf4j @RestController @RequiredArgsConstructor public class WeChatUserRestController { @NonNull private final WeChatUserProfileResourceAssembler userResourceAssembler; @NonNull private final WxMpUserService wxMpUserService; @SneakyThrows @RequestMapping(value = "/rel/wechat/user/profile/me", method = GET)
public WeChatUserProfileResource me(@CurrentWeChatMpUser OpenId openId) {
Hippoom/wechat-mp-starter
wechat-mp-autoconfigure/src/main/java/com/github/hippoom/wechat/mp/security/authentication/WeChatMpOAuth2AccessTokenAuthentication.java
// Path: wechat-mp-autoconfigure/src/main/java/com/github/hippoom/wechat/oauth/OpenId.java // @Value // public class OpenId { // // private String value; // // private OpenId(String value) { // this.value = value; // } // // public static OpenId valueOf(String value) { // return new OpenId(value); // } // }
import com.github.hippoom.wechat.oauth.OpenId; import java.util.Collection; import java.util.Collections; import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority;
@Override public Object getCredentials() { return null; } @Override public Object getDetails() { return getOpenId(); } @Override public Object getPrincipal() { return getOpenId(); } @Override public boolean isAuthenticated() { return true; } @Override public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException { } @Override public String getName() { return accessToken.getOpenId(); }
// Path: wechat-mp-autoconfigure/src/main/java/com/github/hippoom/wechat/oauth/OpenId.java // @Value // public class OpenId { // // private String value; // // private OpenId(String value) { // this.value = value; // } // // public static OpenId valueOf(String value) { // return new OpenId(value); // } // } // Path: wechat-mp-autoconfigure/src/main/java/com/github/hippoom/wechat/mp/security/authentication/WeChatMpOAuth2AccessTokenAuthentication.java import com.github.hippoom.wechat.oauth.OpenId; import java.util.Collection; import java.util.Collections; import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; @Override public Object getCredentials() { return null; } @Override public Object getDetails() { return getOpenId(); } @Override public Object getPrincipal() { return getOpenId(); } @Override public boolean isAuthenticated() { return true; } @Override public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException { } @Override public String getName() { return accessToken.getOpenId(); }
public OpenId getOpenId() {
Hippoom/wechat-mp-starter
examples/core/src/main/java/com/github/hippoom/wechat/mp/examples/core/http/WeChatMpInboundMessageConfiguration.java
// Path: wechat-mp-autoconfigure/src/main/java/com/github/hippoom/wechat/mp/autoconfigure/messaging/WeChatMpInboundMessagingConfigurerAdapter.java // public abstract class WeChatMpInboundMessagingConfigurerAdapter { // // @Bean // protected WxMpMessageRouter wxMpMessageRouter(WxMpService wxMpService) { // WxMpMessageRouter router = new WxMpMessageRouter(wxMpService); // configure(router); // return router; // } // // protected void configure(WxMpMessageRouter router) { // } // }
import com.github.hippoom.wechat.mp.autoconfigure.messaging.WeChatMpInboundMessagingConfigurerAdapter; import lombok.RequiredArgsConstructor; import me.chanjar.weixin.common.api.WxConsts; import me.chanjar.weixin.mp.api.WxMpMessageRouter; import org.springframework.context.annotation.Configuration;
package com.github.hippoom.wechat.mp.examples.core.http; @Configuration @RequiredArgsConstructor
// Path: wechat-mp-autoconfigure/src/main/java/com/github/hippoom/wechat/mp/autoconfigure/messaging/WeChatMpInboundMessagingConfigurerAdapter.java // public abstract class WeChatMpInboundMessagingConfigurerAdapter { // // @Bean // protected WxMpMessageRouter wxMpMessageRouter(WxMpService wxMpService) { // WxMpMessageRouter router = new WxMpMessageRouter(wxMpService); // configure(router); // return router; // } // // protected void configure(WxMpMessageRouter router) { // } // } // Path: examples/core/src/main/java/com/github/hippoom/wechat/mp/examples/core/http/WeChatMpInboundMessageConfiguration.java import com.github.hippoom.wechat.mp.autoconfigure.messaging.WeChatMpInboundMessagingConfigurerAdapter; import lombok.RequiredArgsConstructor; import me.chanjar.weixin.common.api.WxConsts; import me.chanjar.weixin.mp.api.WxMpMessageRouter; import org.springframework.context.annotation.Configuration; package com.github.hippoom.wechat.mp.examples.core.http; @Configuration @RequiredArgsConstructor
public class WeChatMpInboundMessageConfiguration extends WeChatMpInboundMessagingConfigurerAdapter {
Hippoom/wechat-mp-starter
wechat-mp-autoconfigure/src/main/java/com/github/hippoom/wechat/mp/web/method/support/OpenIdHandlerMethodArgumentResolver.java
// Path: wechat-mp-autoconfigure/src/main/java/com/github/hippoom/wechat/mp/security/authentication/WeChatMpOAuth2AccessTokenAuthentication.java // public class WeChatMpOAuth2AccessTokenAuthentication implements Authentication { // // private final WxMpOAuth2AccessToken accessToken; // // public WeChatMpOAuth2AccessTokenAuthentication(WxMpOAuth2AccessToken accessToken) { // this.accessToken = accessToken; // } // // @Override // public Collection<? extends GrantedAuthority> getAuthorities() { // return Collections.emptyList(); // } // // @Override // public Object getCredentials() { // return null; // } // // @Override // public Object getDetails() { // return getOpenId(); // } // // @Override // public Object getPrincipal() { // return getOpenId(); // } // // @Override // public boolean isAuthenticated() { // return true; // } // // @Override // public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException { // // } // // @Override // public String getName() { // return accessToken.getOpenId(); // } // // public OpenId getOpenId() { // return OpenId.valueOf(accessToken.getOpenId()); // } // } // // Path: wechat-mp-autoconfigure/src/main/java/com/github/hippoom/wechat/oauth/OpenId.java // @Value // public class OpenId { // // private String value; // // private OpenId(String value) { // this.value = value; // } // // public static OpenId valueOf(String value) { // return new OpenId(value); // } // }
import com.github.hippoom.wechat.mp.security.authentication.WeChatMpOAuth2AccessTokenAuthentication; import com.github.hippoom.wechat.mp.web.bind.annotation.CurrentWeChatMpUser; import com.github.hippoom.wechat.oauth.OpenId; import org.springframework.core.MethodParameter; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.web.bind.support.WebDataBinderFactory; import org.springframework.web.context.request.NativeWebRequest; import org.springframework.web.method.support.HandlerMethodArgumentResolver; import org.springframework.web.method.support.ModelAndViewContainer;
package com.github.hippoom.wechat.mp.web.method.support; public class OpenIdHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver { @Override public boolean supportsParameter(MethodParameter methodParameter) {
// Path: wechat-mp-autoconfigure/src/main/java/com/github/hippoom/wechat/mp/security/authentication/WeChatMpOAuth2AccessTokenAuthentication.java // public class WeChatMpOAuth2AccessTokenAuthentication implements Authentication { // // private final WxMpOAuth2AccessToken accessToken; // // public WeChatMpOAuth2AccessTokenAuthentication(WxMpOAuth2AccessToken accessToken) { // this.accessToken = accessToken; // } // // @Override // public Collection<? extends GrantedAuthority> getAuthorities() { // return Collections.emptyList(); // } // // @Override // public Object getCredentials() { // return null; // } // // @Override // public Object getDetails() { // return getOpenId(); // } // // @Override // public Object getPrincipal() { // return getOpenId(); // } // // @Override // public boolean isAuthenticated() { // return true; // } // // @Override // public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException { // // } // // @Override // public String getName() { // return accessToken.getOpenId(); // } // // public OpenId getOpenId() { // return OpenId.valueOf(accessToken.getOpenId()); // } // } // // Path: wechat-mp-autoconfigure/src/main/java/com/github/hippoom/wechat/oauth/OpenId.java // @Value // public class OpenId { // // private String value; // // private OpenId(String value) { // this.value = value; // } // // public static OpenId valueOf(String value) { // return new OpenId(value); // } // } // Path: wechat-mp-autoconfigure/src/main/java/com/github/hippoom/wechat/mp/web/method/support/OpenIdHandlerMethodArgumentResolver.java import com.github.hippoom.wechat.mp.security.authentication.WeChatMpOAuth2AccessTokenAuthentication; import com.github.hippoom.wechat.mp.web.bind.annotation.CurrentWeChatMpUser; import com.github.hippoom.wechat.oauth.OpenId; import org.springframework.core.MethodParameter; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.web.bind.support.WebDataBinderFactory; import org.springframework.web.context.request.NativeWebRequest; import org.springframework.web.method.support.HandlerMethodArgumentResolver; import org.springframework.web.method.support.ModelAndViewContainer; package com.github.hippoom.wechat.mp.web.method.support; public class OpenIdHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver { @Override public boolean supportsParameter(MethodParameter methodParameter) {
return methodParameter.getParameterType().equals(OpenId.class);
Hippoom/wechat-mp-starter
wechat-mp-autoconfigure/src/main/java/com/github/hippoom/wechat/mp/web/method/support/OpenIdHandlerMethodArgumentResolver.java
// Path: wechat-mp-autoconfigure/src/main/java/com/github/hippoom/wechat/mp/security/authentication/WeChatMpOAuth2AccessTokenAuthentication.java // public class WeChatMpOAuth2AccessTokenAuthentication implements Authentication { // // private final WxMpOAuth2AccessToken accessToken; // // public WeChatMpOAuth2AccessTokenAuthentication(WxMpOAuth2AccessToken accessToken) { // this.accessToken = accessToken; // } // // @Override // public Collection<? extends GrantedAuthority> getAuthorities() { // return Collections.emptyList(); // } // // @Override // public Object getCredentials() { // return null; // } // // @Override // public Object getDetails() { // return getOpenId(); // } // // @Override // public Object getPrincipal() { // return getOpenId(); // } // // @Override // public boolean isAuthenticated() { // return true; // } // // @Override // public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException { // // } // // @Override // public String getName() { // return accessToken.getOpenId(); // } // // public OpenId getOpenId() { // return OpenId.valueOf(accessToken.getOpenId()); // } // } // // Path: wechat-mp-autoconfigure/src/main/java/com/github/hippoom/wechat/oauth/OpenId.java // @Value // public class OpenId { // // private String value; // // private OpenId(String value) { // this.value = value; // } // // public static OpenId valueOf(String value) { // return new OpenId(value); // } // }
import com.github.hippoom.wechat.mp.security.authentication.WeChatMpOAuth2AccessTokenAuthentication; import com.github.hippoom.wechat.mp.web.bind.annotation.CurrentWeChatMpUser; import com.github.hippoom.wechat.oauth.OpenId; import org.springframework.core.MethodParameter; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.web.bind.support.WebDataBinderFactory; import org.springframework.web.context.request.NativeWebRequest; import org.springframework.web.method.support.HandlerMethodArgumentResolver; import org.springframework.web.method.support.ModelAndViewContainer;
package com.github.hippoom.wechat.mp.web.method.support; public class OpenIdHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver { @Override public boolean supportsParameter(MethodParameter methodParameter) { return methodParameter.getParameterType().equals(OpenId.class); } @Override public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
// Path: wechat-mp-autoconfigure/src/main/java/com/github/hippoom/wechat/mp/security/authentication/WeChatMpOAuth2AccessTokenAuthentication.java // public class WeChatMpOAuth2AccessTokenAuthentication implements Authentication { // // private final WxMpOAuth2AccessToken accessToken; // // public WeChatMpOAuth2AccessTokenAuthentication(WxMpOAuth2AccessToken accessToken) { // this.accessToken = accessToken; // } // // @Override // public Collection<? extends GrantedAuthority> getAuthorities() { // return Collections.emptyList(); // } // // @Override // public Object getCredentials() { // return null; // } // // @Override // public Object getDetails() { // return getOpenId(); // } // // @Override // public Object getPrincipal() { // return getOpenId(); // } // // @Override // public boolean isAuthenticated() { // return true; // } // // @Override // public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException { // // } // // @Override // public String getName() { // return accessToken.getOpenId(); // } // // public OpenId getOpenId() { // return OpenId.valueOf(accessToken.getOpenId()); // } // } // // Path: wechat-mp-autoconfigure/src/main/java/com/github/hippoom/wechat/oauth/OpenId.java // @Value // public class OpenId { // // private String value; // // private OpenId(String value) { // this.value = value; // } // // public static OpenId valueOf(String value) { // return new OpenId(value); // } // } // Path: wechat-mp-autoconfigure/src/main/java/com/github/hippoom/wechat/mp/web/method/support/OpenIdHandlerMethodArgumentResolver.java import com.github.hippoom.wechat.mp.security.authentication.WeChatMpOAuth2AccessTokenAuthentication; import com.github.hippoom.wechat.mp.web.bind.annotation.CurrentWeChatMpUser; import com.github.hippoom.wechat.oauth.OpenId; import org.springframework.core.MethodParameter; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.web.bind.support.WebDataBinderFactory; import org.springframework.web.context.request.NativeWebRequest; import org.springframework.web.method.support.HandlerMethodArgumentResolver; import org.springframework.web.method.support.ModelAndViewContainer; package com.github.hippoom.wechat.mp.web.method.support; public class OpenIdHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver { @Override public boolean supportsParameter(MethodParameter methodParameter) { return methodParameter.getParameterType().equals(OpenId.class); } @Override public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
WeChatMpOAuth2AccessTokenAuthentication user = (WeChatMpOAuth2AccessTokenAuthentication)
Hippoom/wechat-mp-starter
wechat-mp-autoconfigure/src/main/java/com/github/hippoom/wechat/mp/security/web/authentication/WeChatMpOAuth2AuthenticationProcessingFilter.java
// Path: wechat-mp-autoconfigure/src/main/java/com/github/hippoom/wechat/mp/security/authentication/WeChatMpOAuth2AccessTokenAuthentication.java // public class WeChatMpOAuth2AccessTokenAuthentication implements Authentication { // // private final WxMpOAuth2AccessToken accessToken; // // public WeChatMpOAuth2AccessTokenAuthentication(WxMpOAuth2AccessToken accessToken) { // this.accessToken = accessToken; // } // // @Override // public Collection<? extends GrantedAuthority> getAuthorities() { // return Collections.emptyList(); // } // // @Override // public Object getCredentials() { // return null; // } // // @Override // public Object getDetails() { // return getOpenId(); // } // // @Override // public Object getPrincipal() { // return getOpenId(); // } // // @Override // public boolean isAuthenticated() { // return true; // } // // @Override // public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException { // // } // // @Override // public String getName() { // return accessToken.getOpenId(); // } // // public OpenId getOpenId() { // return OpenId.valueOf(accessToken.getOpenId()); // } // }
import com.github.hippoom.wechat.mp.security.authentication.WeChatMpOAuth2AccessTokenAuthentication; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import lombok.Setter; import lombok.SneakyThrows; import me.chanjar.weixin.mp.api.WxMpService; import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter; import org.springframework.security.web.util.matcher.RequestMatcher;
package com.github.hippoom.wechat.mp.security.web.authentication; public class WeChatMpOAuth2AuthenticationProcessingFilter extends AbstractAuthenticationProcessingFilter { @Setter private WxMpService wxMpService; public WeChatMpOAuth2AuthenticationProcessingFilter(String defaultFilterProcessesUrl) { super(defaultFilterProcessesUrl); } public WeChatMpOAuth2AuthenticationProcessingFilter( RequestMatcher requiresAuthenticationRequestMatcher) { super(requiresAuthenticationRequestMatcher); } @SneakyThrows @Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException { final String code = request.getParameter("code"); WxMpOAuth2AccessToken accessToken = wxMpService.oauth2getAccessToken(code);
// Path: wechat-mp-autoconfigure/src/main/java/com/github/hippoom/wechat/mp/security/authentication/WeChatMpOAuth2AccessTokenAuthentication.java // public class WeChatMpOAuth2AccessTokenAuthentication implements Authentication { // // private final WxMpOAuth2AccessToken accessToken; // // public WeChatMpOAuth2AccessTokenAuthentication(WxMpOAuth2AccessToken accessToken) { // this.accessToken = accessToken; // } // // @Override // public Collection<? extends GrantedAuthority> getAuthorities() { // return Collections.emptyList(); // } // // @Override // public Object getCredentials() { // return null; // } // // @Override // public Object getDetails() { // return getOpenId(); // } // // @Override // public Object getPrincipal() { // return getOpenId(); // } // // @Override // public boolean isAuthenticated() { // return true; // } // // @Override // public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException { // // } // // @Override // public String getName() { // return accessToken.getOpenId(); // } // // public OpenId getOpenId() { // return OpenId.valueOf(accessToken.getOpenId()); // } // } // Path: wechat-mp-autoconfigure/src/main/java/com/github/hippoom/wechat/mp/security/web/authentication/WeChatMpOAuth2AuthenticationProcessingFilter.java import com.github.hippoom.wechat.mp.security.authentication.WeChatMpOAuth2AccessTokenAuthentication; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import lombok.Setter; import lombok.SneakyThrows; import me.chanjar.weixin.mp.api.WxMpService; import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter; import org.springframework.security.web.util.matcher.RequestMatcher; package com.github.hippoom.wechat.mp.security.web.authentication; public class WeChatMpOAuth2AuthenticationProcessingFilter extends AbstractAuthenticationProcessingFilter { @Setter private WxMpService wxMpService; public WeChatMpOAuth2AuthenticationProcessingFilter(String defaultFilterProcessesUrl) { super(defaultFilterProcessesUrl); } public WeChatMpOAuth2AuthenticationProcessingFilter( RequestMatcher requiresAuthenticationRequestMatcher) { super(requiresAuthenticationRequestMatcher); } @SneakyThrows @Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException { final String code = request.getParameter("code"); WxMpOAuth2AccessToken accessToken = wxMpService.oauth2getAccessToken(code);
return new WeChatMpOAuth2AccessTokenAuthentication(accessToken);
Hippoom/wechat-mp-starter
wechat-mp-autoconfigure/src/main/java/com/github/hippoom/wechat/mp/autoconfigure/web/WeChatMpWebMethodConfiguration.java
// Path: wechat-mp-autoconfigure/src/main/java/com/github/hippoom/wechat/mp/web/method/support/OpenIdHandlerMethodArgumentResolver.java // public class OpenIdHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver { // // @Override // public boolean supportsParameter(MethodParameter methodParameter) { // return methodParameter.getParameterType().equals(OpenId.class); // } // // @Override // public Object resolveArgument(MethodParameter methodParameter, // ModelAndViewContainer modelAndViewContainer, // NativeWebRequest nativeWebRequest, // WebDataBinderFactory webDataBinderFactory) throws Exception { // // WeChatMpOAuth2AccessTokenAuthentication user = (WeChatMpOAuth2AccessTokenAuthentication) // SecurityContextHolder.getContext().getAuthentication(); // // CurrentWeChatMpUser weChatUser = methodParameter // .getParameterAnnotation(CurrentWeChatMpUser.class); // if (weChatUser == null) { // return null; // } // // return user.getPrincipal(); // } // }
import com.github.hippoom.wechat.mp.web.method.support.OpenIdHandlerMethodArgumentResolver; import java.util.List; import lombok.RequiredArgsConstructor; import org.springframework.context.annotation.Configuration; import org.springframework.web.method.support.HandlerMethodArgumentResolver; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
package com.github.hippoom.wechat.mp.autoconfigure.web; @Configuration @RequiredArgsConstructor public class WeChatMpWebMethodConfiguration extends WebMvcConfigurerAdapter { @Override public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
// Path: wechat-mp-autoconfigure/src/main/java/com/github/hippoom/wechat/mp/web/method/support/OpenIdHandlerMethodArgumentResolver.java // public class OpenIdHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver { // // @Override // public boolean supportsParameter(MethodParameter methodParameter) { // return methodParameter.getParameterType().equals(OpenId.class); // } // // @Override // public Object resolveArgument(MethodParameter methodParameter, // ModelAndViewContainer modelAndViewContainer, // NativeWebRequest nativeWebRequest, // WebDataBinderFactory webDataBinderFactory) throws Exception { // // WeChatMpOAuth2AccessTokenAuthentication user = (WeChatMpOAuth2AccessTokenAuthentication) // SecurityContextHolder.getContext().getAuthentication(); // // CurrentWeChatMpUser weChatUser = methodParameter // .getParameterAnnotation(CurrentWeChatMpUser.class); // if (weChatUser == null) { // return null; // } // // return user.getPrincipal(); // } // } // Path: wechat-mp-autoconfigure/src/main/java/com/github/hippoom/wechat/mp/autoconfigure/web/WeChatMpWebMethodConfiguration.java import com.github.hippoom.wechat.mp.web.method.support.OpenIdHandlerMethodArgumentResolver; import java.util.List; import lombok.RequiredArgsConstructor; import org.springframework.context.annotation.Configuration; import org.springframework.web.method.support.HandlerMethodArgumentResolver; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; package com.github.hippoom.wechat.mp.autoconfigure.web; @Configuration @RequiredArgsConstructor public class WeChatMpWebMethodConfiguration extends WebMvcConfigurerAdapter { @Override public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
argumentResolvers.add(new OpenIdHandlerMethodArgumentResolver());
Hippoom/wechat-mp-starter
examples/oauth2/src/main/java/com/github/hippoom/wechat/mp/examples/oauth2/http/WeChatMpInboundMessageConfiguration.java
// Path: wechat-mp-autoconfigure/src/main/java/com/github/hippoom/wechat/mp/autoconfigure/messaging/WeChatMpInboundMessagingConfigurerAdapter.java // public abstract class WeChatMpInboundMessagingConfigurerAdapter { // // @Bean // protected WxMpMessageRouter wxMpMessageRouter(WxMpService wxMpService) { // WxMpMessageRouter router = new WxMpMessageRouter(wxMpService); // configure(router); // return router; // } // // protected void configure(WxMpMessageRouter router) { // } // }
import com.github.hippoom.wechat.mp.autoconfigure.messaging.WeChatMpInboundMessagingConfigurerAdapter; import lombok.RequiredArgsConstructor; import me.chanjar.weixin.mp.api.WxMpMessageRouter; import org.springframework.context.annotation.Configuration;
package com.github.hippoom.wechat.mp.examples.oauth2.http; @Configuration @RequiredArgsConstructor
// Path: wechat-mp-autoconfigure/src/main/java/com/github/hippoom/wechat/mp/autoconfigure/messaging/WeChatMpInboundMessagingConfigurerAdapter.java // public abstract class WeChatMpInboundMessagingConfigurerAdapter { // // @Bean // protected WxMpMessageRouter wxMpMessageRouter(WxMpService wxMpService) { // WxMpMessageRouter router = new WxMpMessageRouter(wxMpService); // configure(router); // return router; // } // // protected void configure(WxMpMessageRouter router) { // } // } // Path: examples/oauth2/src/main/java/com/github/hippoom/wechat/mp/examples/oauth2/http/WeChatMpInboundMessageConfiguration.java import com.github.hippoom.wechat.mp.autoconfigure.messaging.WeChatMpInboundMessagingConfigurerAdapter; import lombok.RequiredArgsConstructor; import me.chanjar.weixin.mp.api.WxMpMessageRouter; import org.springframework.context.annotation.Configuration; package com.github.hippoom.wechat.mp.examples.oauth2.http; @Configuration @RequiredArgsConstructor
public class WeChatMpInboundMessageConfiguration extends WeChatMpInboundMessagingConfigurerAdapter {
programingjd/okserver
src/main/java/info/jdavid/ok/server/Response.java
// Path: src/main/java/info/jdavid/ok/server/header/CacheControl.java // @SuppressWarnings({ "WeakerAccess" }) // public final class CacheControl { // // private CacheControl() {} // // /** // * Cache-Control header field name. // */ // public static final String HEADER = "Cache-Control"; // /** // * Expires header field name. // */ // public static final String EXPIRES = "Expires"; // // // /** // * Cache-Control directive. // */ // @SuppressWarnings("unused") // public static class Directive { // // private Directive() {} // // /** // * The response should not be stored in the cache. // */ // public static final String NO_STORE = "no-store"; // /** // * The response should be stored as-is in the cache. No transformation (usually by a proxy) is allowed. // */ // public static final String NO_TRANSFORM = "no-transform"; // /** // * The response can be cached publicly, including in shared caches (at the proxy level). // */ // public static final String PUBLIC = "public"; // /** // * The response can only be cached for the current user, but not in shared caches (at the proxy level). // */ // public static final String PRIVATE = "private"; // // /** // * A client should revalidate the response with the server before returning the cached response. // */ // public static final String NO_CACHE = "no-cache"; // /** // * A client should revalidate a stale cached response (max-age expired) with the server // * before returning it. // */ // public static final String MUST_REVALIDATE = "must-revalidate"; // /** // * Same as must-revalidate, but only for public (shared) caches. It does not apply to private cache. // */ // public static final String PROXY_REVALIDATE = "proxy-revalidate"; // /** // * A client should response with a cached response, or with a 504 (gateway timeout). // */ // public static final String ONLY_IF_CACHED = "only-if-cached"; // /** // * A client should consider the response stale once the max-age is expired. // */ // public static final String MAX_AGE_EQUALS = "max-age="; // /** // * s-maxage overrides max-age and the Expires header value for public (shared) caches. // */ // public static final String S_MAX_AGE_EQUALS = "s-maxage="; // /** // * A clients should revalidate a stale cached response (max-age expired) with the server, but it can // * return the cached response if its max-age is lower than the specified limit. // */ // public static final String STALE_WHILE_REVALIDATE_EQUALS = "stale-while-revalidate="; // /** // * A client should revalidate a stale cached response (max-age expired) with the server, but it can // * return the cached response if thevalidation call fails and the cached response max-age is lower than // * the specified limit. // */ // public static final String STALE_IF_ERROR_EQUALS = "stale-if-error="; // /** // * A client should consider that a cached response that is not stale has not changed and should not // * revalidate it with the server. // */ // public static final String IMMUTABLE = "immutable"; // // } // // } // // Path: src/main/java/info/jdavid/ok/server/header/Cors.java // @SuppressWarnings({ "WeakerAccess", "unused" }) // public final class Cors { // // private Cors() {} // // public static final String ALLOW_ORIGIN = "Access-Control-Allow-Origin"; // public static final String ALLOW_METHODS = "Access-Control-Allow-Methods"; // public static final String ALLOW_HEADERS = "Access-Control-Allow-Headers"; // public static final String MAX_AGE = "Access-Control-Max-Age"; // public static final String EXPOSE_HEADERS = "Access-Control-Expose-Headers"; // // } // // Path: src/main/java/info/jdavid/ok/server/header/ETag.java // @SuppressWarnings({ "WeakerAccess" }) // public final class ETag { // // private ETag() {} // // public static final String HEADER = "ETag"; // // public static final String IF_MATCH = "If-Match"; // public static final String IF_NONE_MATCH = "If-None-Match"; // // }
import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import javax.annotation.Nullable; import info.jdavid.ok.server.header.CacheControl; import info.jdavid.ok.server.header.Cors; import info.jdavid.ok.server.header.ETag; import okhttp3.Headers; import okhttp3.HttpUrl; import okhttp3.MediaType; import okhttp3.Protocol; import okhttp3.ResponseBody; import okhttp3.internal.http.StatusLine; import okio.Buffer; import okio.BufferedSink; import okio.BufferedSource;
*/ public Builder() {} /** * Sets the status line. * @param statusLine the status line. * @return this */ public Builder statusLine(final StatusLine statusLine) { protocol = statusLine.protocol; code = statusLine.code; message = statusLine.message; return this; } /** * Gets the http response status code. * @return the status code. */ public int code() { if (code == -1) throw new IllegalStateException("The status line has not been set."); return code; } /** * Sets the etag (optional) and the cache control header to no-cache. * @param etag the etag (optional). * @return this */ public Builder noCache(@Nullable final String etag) {
// Path: src/main/java/info/jdavid/ok/server/header/CacheControl.java // @SuppressWarnings({ "WeakerAccess" }) // public final class CacheControl { // // private CacheControl() {} // // /** // * Cache-Control header field name. // */ // public static final String HEADER = "Cache-Control"; // /** // * Expires header field name. // */ // public static final String EXPIRES = "Expires"; // // // /** // * Cache-Control directive. // */ // @SuppressWarnings("unused") // public static class Directive { // // private Directive() {} // // /** // * The response should not be stored in the cache. // */ // public static final String NO_STORE = "no-store"; // /** // * The response should be stored as-is in the cache. No transformation (usually by a proxy) is allowed. // */ // public static final String NO_TRANSFORM = "no-transform"; // /** // * The response can be cached publicly, including in shared caches (at the proxy level). // */ // public static final String PUBLIC = "public"; // /** // * The response can only be cached for the current user, but not in shared caches (at the proxy level). // */ // public static final String PRIVATE = "private"; // // /** // * A client should revalidate the response with the server before returning the cached response. // */ // public static final String NO_CACHE = "no-cache"; // /** // * A client should revalidate a stale cached response (max-age expired) with the server // * before returning it. // */ // public static final String MUST_REVALIDATE = "must-revalidate"; // /** // * Same as must-revalidate, but only for public (shared) caches. It does not apply to private cache. // */ // public static final String PROXY_REVALIDATE = "proxy-revalidate"; // /** // * A client should response with a cached response, or with a 504 (gateway timeout). // */ // public static final String ONLY_IF_CACHED = "only-if-cached"; // /** // * A client should consider the response stale once the max-age is expired. // */ // public static final String MAX_AGE_EQUALS = "max-age="; // /** // * s-maxage overrides max-age and the Expires header value for public (shared) caches. // */ // public static final String S_MAX_AGE_EQUALS = "s-maxage="; // /** // * A clients should revalidate a stale cached response (max-age expired) with the server, but it can // * return the cached response if its max-age is lower than the specified limit. // */ // public static final String STALE_WHILE_REVALIDATE_EQUALS = "stale-while-revalidate="; // /** // * A client should revalidate a stale cached response (max-age expired) with the server, but it can // * return the cached response if thevalidation call fails and the cached response max-age is lower than // * the specified limit. // */ // public static final String STALE_IF_ERROR_EQUALS = "stale-if-error="; // /** // * A client should consider that a cached response that is not stale has not changed and should not // * revalidate it with the server. // */ // public static final String IMMUTABLE = "immutable"; // // } // // } // // Path: src/main/java/info/jdavid/ok/server/header/Cors.java // @SuppressWarnings({ "WeakerAccess", "unused" }) // public final class Cors { // // private Cors() {} // // public static final String ALLOW_ORIGIN = "Access-Control-Allow-Origin"; // public static final String ALLOW_METHODS = "Access-Control-Allow-Methods"; // public static final String ALLOW_HEADERS = "Access-Control-Allow-Headers"; // public static final String MAX_AGE = "Access-Control-Max-Age"; // public static final String EXPOSE_HEADERS = "Access-Control-Expose-Headers"; // // } // // Path: src/main/java/info/jdavid/ok/server/header/ETag.java // @SuppressWarnings({ "WeakerAccess" }) // public final class ETag { // // private ETag() {} // // public static final String HEADER = "ETag"; // // public static final String IF_MATCH = "If-Match"; // public static final String IF_NONE_MATCH = "If-None-Match"; // // } // Path: src/main/java/info/jdavid/ok/server/Response.java import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import javax.annotation.Nullable; import info.jdavid.ok.server.header.CacheControl; import info.jdavid.ok.server.header.Cors; import info.jdavid.ok.server.header.ETag; import okhttp3.Headers; import okhttp3.HttpUrl; import okhttp3.MediaType; import okhttp3.Protocol; import okhttp3.ResponseBody; import okhttp3.internal.http.StatusLine; import okio.Buffer; import okio.BufferedSink; import okio.BufferedSource; */ public Builder() {} /** * Sets the status line. * @param statusLine the status line. * @return this */ public Builder statusLine(final StatusLine statusLine) { protocol = statusLine.protocol; code = statusLine.code; message = statusLine.message; return this; } /** * Gets the http response status code. * @return the status code. */ public int code() { if (code == -1) throw new IllegalStateException("The status line has not been set."); return code; } /** * Sets the etag (optional) and the cache control header to no-cache. * @param etag the etag (optional). * @return this */ public Builder noCache(@Nullable final String etag) {
if (etag != null) headers.set(ETag.HEADER, etag);
programingjd/okserver
src/main/java/info/jdavid/ok/server/Response.java
// Path: src/main/java/info/jdavid/ok/server/header/CacheControl.java // @SuppressWarnings({ "WeakerAccess" }) // public final class CacheControl { // // private CacheControl() {} // // /** // * Cache-Control header field name. // */ // public static final String HEADER = "Cache-Control"; // /** // * Expires header field name. // */ // public static final String EXPIRES = "Expires"; // // // /** // * Cache-Control directive. // */ // @SuppressWarnings("unused") // public static class Directive { // // private Directive() {} // // /** // * The response should not be stored in the cache. // */ // public static final String NO_STORE = "no-store"; // /** // * The response should be stored as-is in the cache. No transformation (usually by a proxy) is allowed. // */ // public static final String NO_TRANSFORM = "no-transform"; // /** // * The response can be cached publicly, including in shared caches (at the proxy level). // */ // public static final String PUBLIC = "public"; // /** // * The response can only be cached for the current user, but not in shared caches (at the proxy level). // */ // public static final String PRIVATE = "private"; // // /** // * A client should revalidate the response with the server before returning the cached response. // */ // public static final String NO_CACHE = "no-cache"; // /** // * A client should revalidate a stale cached response (max-age expired) with the server // * before returning it. // */ // public static final String MUST_REVALIDATE = "must-revalidate"; // /** // * Same as must-revalidate, but only for public (shared) caches. It does not apply to private cache. // */ // public static final String PROXY_REVALIDATE = "proxy-revalidate"; // /** // * A client should response with a cached response, or with a 504 (gateway timeout). // */ // public static final String ONLY_IF_CACHED = "only-if-cached"; // /** // * A client should consider the response stale once the max-age is expired. // */ // public static final String MAX_AGE_EQUALS = "max-age="; // /** // * s-maxage overrides max-age and the Expires header value for public (shared) caches. // */ // public static final String S_MAX_AGE_EQUALS = "s-maxage="; // /** // * A clients should revalidate a stale cached response (max-age expired) with the server, but it can // * return the cached response if its max-age is lower than the specified limit. // */ // public static final String STALE_WHILE_REVALIDATE_EQUALS = "stale-while-revalidate="; // /** // * A client should revalidate a stale cached response (max-age expired) with the server, but it can // * return the cached response if thevalidation call fails and the cached response max-age is lower than // * the specified limit. // */ // public static final String STALE_IF_ERROR_EQUALS = "stale-if-error="; // /** // * A client should consider that a cached response that is not stale has not changed and should not // * revalidate it with the server. // */ // public static final String IMMUTABLE = "immutable"; // // } // // } // // Path: src/main/java/info/jdavid/ok/server/header/Cors.java // @SuppressWarnings({ "WeakerAccess", "unused" }) // public final class Cors { // // private Cors() {} // // public static final String ALLOW_ORIGIN = "Access-Control-Allow-Origin"; // public static final String ALLOW_METHODS = "Access-Control-Allow-Methods"; // public static final String ALLOW_HEADERS = "Access-Control-Allow-Headers"; // public static final String MAX_AGE = "Access-Control-Max-Age"; // public static final String EXPOSE_HEADERS = "Access-Control-Expose-Headers"; // // } // // Path: src/main/java/info/jdavid/ok/server/header/ETag.java // @SuppressWarnings({ "WeakerAccess" }) // public final class ETag { // // private ETag() {} // // public static final String HEADER = "ETag"; // // public static final String IF_MATCH = "If-Match"; // public static final String IF_NONE_MATCH = "If-None-Match"; // // }
import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import javax.annotation.Nullable; import info.jdavid.ok.server.header.CacheControl; import info.jdavid.ok.server.header.Cors; import info.jdavid.ok.server.header.ETag; import okhttp3.Headers; import okhttp3.HttpUrl; import okhttp3.MediaType; import okhttp3.Protocol; import okhttp3.ResponseBody; import okhttp3.internal.http.StatusLine; import okio.Buffer; import okio.BufferedSink; import okio.BufferedSource;
public Builder() {} /** * Sets the status line. * @param statusLine the status line. * @return this */ public Builder statusLine(final StatusLine statusLine) { protocol = statusLine.protocol; code = statusLine.code; message = statusLine.message; return this; } /** * Gets the http response status code. * @return the status code. */ public int code() { if (code == -1) throw new IllegalStateException("The status line has not been set."); return code; } /** * Sets the etag (optional) and the cache control header to no-cache. * @param etag the etag (optional). * @return this */ public Builder noCache(@Nullable final String etag) { if (etag != null) headers.set(ETag.HEADER, etag);
// Path: src/main/java/info/jdavid/ok/server/header/CacheControl.java // @SuppressWarnings({ "WeakerAccess" }) // public final class CacheControl { // // private CacheControl() {} // // /** // * Cache-Control header field name. // */ // public static final String HEADER = "Cache-Control"; // /** // * Expires header field name. // */ // public static final String EXPIRES = "Expires"; // // // /** // * Cache-Control directive. // */ // @SuppressWarnings("unused") // public static class Directive { // // private Directive() {} // // /** // * The response should not be stored in the cache. // */ // public static final String NO_STORE = "no-store"; // /** // * The response should be stored as-is in the cache. No transformation (usually by a proxy) is allowed. // */ // public static final String NO_TRANSFORM = "no-transform"; // /** // * The response can be cached publicly, including in shared caches (at the proxy level). // */ // public static final String PUBLIC = "public"; // /** // * The response can only be cached for the current user, but not in shared caches (at the proxy level). // */ // public static final String PRIVATE = "private"; // // /** // * A client should revalidate the response with the server before returning the cached response. // */ // public static final String NO_CACHE = "no-cache"; // /** // * A client should revalidate a stale cached response (max-age expired) with the server // * before returning it. // */ // public static final String MUST_REVALIDATE = "must-revalidate"; // /** // * Same as must-revalidate, but only for public (shared) caches. It does not apply to private cache. // */ // public static final String PROXY_REVALIDATE = "proxy-revalidate"; // /** // * A client should response with a cached response, or with a 504 (gateway timeout). // */ // public static final String ONLY_IF_CACHED = "only-if-cached"; // /** // * A client should consider the response stale once the max-age is expired. // */ // public static final String MAX_AGE_EQUALS = "max-age="; // /** // * s-maxage overrides max-age and the Expires header value for public (shared) caches. // */ // public static final String S_MAX_AGE_EQUALS = "s-maxage="; // /** // * A clients should revalidate a stale cached response (max-age expired) with the server, but it can // * return the cached response if its max-age is lower than the specified limit. // */ // public static final String STALE_WHILE_REVALIDATE_EQUALS = "stale-while-revalidate="; // /** // * A client should revalidate a stale cached response (max-age expired) with the server, but it can // * return the cached response if thevalidation call fails and the cached response max-age is lower than // * the specified limit. // */ // public static final String STALE_IF_ERROR_EQUALS = "stale-if-error="; // /** // * A client should consider that a cached response that is not stale has not changed and should not // * revalidate it with the server. // */ // public static final String IMMUTABLE = "immutable"; // // } // // } // // Path: src/main/java/info/jdavid/ok/server/header/Cors.java // @SuppressWarnings({ "WeakerAccess", "unused" }) // public final class Cors { // // private Cors() {} // // public static final String ALLOW_ORIGIN = "Access-Control-Allow-Origin"; // public static final String ALLOW_METHODS = "Access-Control-Allow-Methods"; // public static final String ALLOW_HEADERS = "Access-Control-Allow-Headers"; // public static final String MAX_AGE = "Access-Control-Max-Age"; // public static final String EXPOSE_HEADERS = "Access-Control-Expose-Headers"; // // } // // Path: src/main/java/info/jdavid/ok/server/header/ETag.java // @SuppressWarnings({ "WeakerAccess" }) // public final class ETag { // // private ETag() {} // // public static final String HEADER = "ETag"; // // public static final String IF_MATCH = "If-Match"; // public static final String IF_NONE_MATCH = "If-None-Match"; // // } // Path: src/main/java/info/jdavid/ok/server/Response.java import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import javax.annotation.Nullable; import info.jdavid.ok.server.header.CacheControl; import info.jdavid.ok.server.header.Cors; import info.jdavid.ok.server.header.ETag; import okhttp3.Headers; import okhttp3.HttpUrl; import okhttp3.MediaType; import okhttp3.Protocol; import okhttp3.ResponseBody; import okhttp3.internal.http.StatusLine; import okio.Buffer; import okio.BufferedSink; import okio.BufferedSource; public Builder() {} /** * Sets the status line. * @param statusLine the status line. * @return this */ public Builder statusLine(final StatusLine statusLine) { protocol = statusLine.protocol; code = statusLine.code; message = statusLine.message; return this; } /** * Gets the http response status code. * @return the status code. */ public int code() { if (code == -1) throw new IllegalStateException("The status line has not been set."); return code; } /** * Sets the etag (optional) and the cache control header to no-cache. * @param etag the etag (optional). * @return this */ public Builder noCache(@Nullable final String etag) { if (etag != null) headers.set(ETag.HEADER, etag);
headers.set(CacheControl.HEADER, "no-cache");
programingjd/okserver
src/main/java/info/jdavid/ok/server/Response.java
// Path: src/main/java/info/jdavid/ok/server/header/CacheControl.java // @SuppressWarnings({ "WeakerAccess" }) // public final class CacheControl { // // private CacheControl() {} // // /** // * Cache-Control header field name. // */ // public static final String HEADER = "Cache-Control"; // /** // * Expires header field name. // */ // public static final String EXPIRES = "Expires"; // // // /** // * Cache-Control directive. // */ // @SuppressWarnings("unused") // public static class Directive { // // private Directive() {} // // /** // * The response should not be stored in the cache. // */ // public static final String NO_STORE = "no-store"; // /** // * The response should be stored as-is in the cache. No transformation (usually by a proxy) is allowed. // */ // public static final String NO_TRANSFORM = "no-transform"; // /** // * The response can be cached publicly, including in shared caches (at the proxy level). // */ // public static final String PUBLIC = "public"; // /** // * The response can only be cached for the current user, but not in shared caches (at the proxy level). // */ // public static final String PRIVATE = "private"; // // /** // * A client should revalidate the response with the server before returning the cached response. // */ // public static final String NO_CACHE = "no-cache"; // /** // * A client should revalidate a stale cached response (max-age expired) with the server // * before returning it. // */ // public static final String MUST_REVALIDATE = "must-revalidate"; // /** // * Same as must-revalidate, but only for public (shared) caches. It does not apply to private cache. // */ // public static final String PROXY_REVALIDATE = "proxy-revalidate"; // /** // * A client should response with a cached response, or with a 504 (gateway timeout). // */ // public static final String ONLY_IF_CACHED = "only-if-cached"; // /** // * A client should consider the response stale once the max-age is expired. // */ // public static final String MAX_AGE_EQUALS = "max-age="; // /** // * s-maxage overrides max-age and the Expires header value for public (shared) caches. // */ // public static final String S_MAX_AGE_EQUALS = "s-maxage="; // /** // * A clients should revalidate a stale cached response (max-age expired) with the server, but it can // * return the cached response if its max-age is lower than the specified limit. // */ // public static final String STALE_WHILE_REVALIDATE_EQUALS = "stale-while-revalidate="; // /** // * A client should revalidate a stale cached response (max-age expired) with the server, but it can // * return the cached response if thevalidation call fails and the cached response max-age is lower than // * the specified limit. // */ // public static final String STALE_IF_ERROR_EQUALS = "stale-if-error="; // /** // * A client should consider that a cached response that is not stale has not changed and should not // * revalidate it with the server. // */ // public static final String IMMUTABLE = "immutable"; // // } // // } // // Path: src/main/java/info/jdavid/ok/server/header/Cors.java // @SuppressWarnings({ "WeakerAccess", "unused" }) // public final class Cors { // // private Cors() {} // // public static final String ALLOW_ORIGIN = "Access-Control-Allow-Origin"; // public static final String ALLOW_METHODS = "Access-Control-Allow-Methods"; // public static final String ALLOW_HEADERS = "Access-Control-Allow-Headers"; // public static final String MAX_AGE = "Access-Control-Max-Age"; // public static final String EXPOSE_HEADERS = "Access-Control-Expose-Headers"; // // } // // Path: src/main/java/info/jdavid/ok/server/header/ETag.java // @SuppressWarnings({ "WeakerAccess" }) // public final class ETag { // // private ETag() {} // // public static final String HEADER = "ETag"; // // public static final String IF_MATCH = "If-Match"; // public static final String IF_NONE_MATCH = "If-None-Match"; // // }
import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import javax.annotation.Nullable; import info.jdavid.ok.server.header.CacheControl; import info.jdavid.ok.server.header.Cors; import info.jdavid.ok.server.header.ETag; import okhttp3.Headers; import okhttp3.HttpUrl; import okhttp3.MediaType; import okhttp3.Protocol; import okhttp3.ResponseBody; import okhttp3.internal.http.StatusLine; import okio.Buffer; import okio.BufferedSink; import okio.BufferedSource;
*/ public Builder priv() { headers.add(CacheControl.HEADER, "private"); return this; } /** * Sets the cache control max-age value. * @param secs the max-age value in seconds. * @param immutable the immutable attribute. * @return this */ public Builder maxAge(final long secs, final boolean immutable) { headers.add(CacheControl.HEADER, "max-age=" + secs + (immutable ? ", immutable" : ", must-revalidate")); return this; } /** * Sets the CORS headers for allowing cross domain requests. * @param origin the origin. * @param methods the methods. * @param headers the headers. * @param secs the max-age for the cors headers. * @return this */ public Builder cors(@Nullable final String origin, @Nullable final List<String> methods, @Nullable final List<String> headers, final long secs) {
// Path: src/main/java/info/jdavid/ok/server/header/CacheControl.java // @SuppressWarnings({ "WeakerAccess" }) // public final class CacheControl { // // private CacheControl() {} // // /** // * Cache-Control header field name. // */ // public static final String HEADER = "Cache-Control"; // /** // * Expires header field name. // */ // public static final String EXPIRES = "Expires"; // // // /** // * Cache-Control directive. // */ // @SuppressWarnings("unused") // public static class Directive { // // private Directive() {} // // /** // * The response should not be stored in the cache. // */ // public static final String NO_STORE = "no-store"; // /** // * The response should be stored as-is in the cache. No transformation (usually by a proxy) is allowed. // */ // public static final String NO_TRANSFORM = "no-transform"; // /** // * The response can be cached publicly, including in shared caches (at the proxy level). // */ // public static final String PUBLIC = "public"; // /** // * The response can only be cached for the current user, but not in shared caches (at the proxy level). // */ // public static final String PRIVATE = "private"; // // /** // * A client should revalidate the response with the server before returning the cached response. // */ // public static final String NO_CACHE = "no-cache"; // /** // * A client should revalidate a stale cached response (max-age expired) with the server // * before returning it. // */ // public static final String MUST_REVALIDATE = "must-revalidate"; // /** // * Same as must-revalidate, but only for public (shared) caches. It does not apply to private cache. // */ // public static final String PROXY_REVALIDATE = "proxy-revalidate"; // /** // * A client should response with a cached response, or with a 504 (gateway timeout). // */ // public static final String ONLY_IF_CACHED = "only-if-cached"; // /** // * A client should consider the response stale once the max-age is expired. // */ // public static final String MAX_AGE_EQUALS = "max-age="; // /** // * s-maxage overrides max-age and the Expires header value for public (shared) caches. // */ // public static final String S_MAX_AGE_EQUALS = "s-maxage="; // /** // * A clients should revalidate a stale cached response (max-age expired) with the server, but it can // * return the cached response if its max-age is lower than the specified limit. // */ // public static final String STALE_WHILE_REVALIDATE_EQUALS = "stale-while-revalidate="; // /** // * A client should revalidate a stale cached response (max-age expired) with the server, but it can // * return the cached response if thevalidation call fails and the cached response max-age is lower than // * the specified limit. // */ // public static final String STALE_IF_ERROR_EQUALS = "stale-if-error="; // /** // * A client should consider that a cached response that is not stale has not changed and should not // * revalidate it with the server. // */ // public static final String IMMUTABLE = "immutable"; // // } // // } // // Path: src/main/java/info/jdavid/ok/server/header/Cors.java // @SuppressWarnings({ "WeakerAccess", "unused" }) // public final class Cors { // // private Cors() {} // // public static final String ALLOW_ORIGIN = "Access-Control-Allow-Origin"; // public static final String ALLOW_METHODS = "Access-Control-Allow-Methods"; // public static final String ALLOW_HEADERS = "Access-Control-Allow-Headers"; // public static final String MAX_AGE = "Access-Control-Max-Age"; // public static final String EXPOSE_HEADERS = "Access-Control-Expose-Headers"; // // } // // Path: src/main/java/info/jdavid/ok/server/header/ETag.java // @SuppressWarnings({ "WeakerAccess" }) // public final class ETag { // // private ETag() {} // // public static final String HEADER = "ETag"; // // public static final String IF_MATCH = "If-Match"; // public static final String IF_NONE_MATCH = "If-None-Match"; // // } // Path: src/main/java/info/jdavid/ok/server/Response.java import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import javax.annotation.Nullable; import info.jdavid.ok.server.header.CacheControl; import info.jdavid.ok.server.header.Cors; import info.jdavid.ok.server.header.ETag; import okhttp3.Headers; import okhttp3.HttpUrl; import okhttp3.MediaType; import okhttp3.Protocol; import okhttp3.ResponseBody; import okhttp3.internal.http.StatusLine; import okio.Buffer; import okio.BufferedSink; import okio.BufferedSource; */ public Builder priv() { headers.add(CacheControl.HEADER, "private"); return this; } /** * Sets the cache control max-age value. * @param secs the max-age value in seconds. * @param immutable the immutable attribute. * @return this */ public Builder maxAge(final long secs, final boolean immutable) { headers.add(CacheControl.HEADER, "max-age=" + secs + (immutable ? ", immutable" : ", must-revalidate")); return this; } /** * Sets the CORS headers for allowing cross domain requests. * @param origin the origin. * @param methods the methods. * @param headers the headers. * @param secs the max-age for the cors headers. * @return this */ public Builder cors(@Nullable final String origin, @Nullable final List<String> methods, @Nullable final List<String> headers, final long secs) {
this.headers.set(Cors.ALLOW_ORIGIN, origin == null ? "null" : origin);
programingjd/okserver
src/test/java/info/jdavid/ok/server/RegexHandlerTest.java
// Path: src/main/java/info/jdavid/ok/server/handler/RegexHandler.java // @SuppressWarnings({ "WeakerAccess", "unused" }) // public abstract class RegexHandler implements Handler { // // final Pattern pattern; // final List<String> methods; // // /** // * Creates an handler that will accept a request with the specified methods, // * whose path matches the specified regular expression. // * @param methods the request methods. // * @param regex the regular expression. // */ // protected RegexHandler(final Collection<String> methods, final String regex) { // if (methods.isEmpty()) { // throw new NullPointerException("The accepted request method cannot be null."); // } // final List<String> list = this.methods = new ArrayList<>(methods.size()); // for (final String method: methods) { // list.add(method.toUpperCase()); // } // pattern = Pattern.compile(regex); // } // // /** // * Creates an handler that will accept a request with the specified method, whose path matches the specified // * regular expression. // * @param method the request method. // * @param regex the regular expression. // */ // protected RegexHandler(final String method, final String regex) { // methods = Collections.singletonList(method.toUpperCase()); // pattern = Pattern.compile(regex); // } // // @Override public Handler setup() { return this; } // // @Override // public @Nullable String[] matches(final String method, final HttpUrl url) { // if (methods.contains(method)) { // final String encodedPath = url.encodedPath(); // final Matcher matcher = pattern.matcher(url.encodedPath()); // if (matcher.find()) { // if (matcher.start() > 0) return null; // if (matcher.end() < encodedPath.length()) return null; // final int n = matcher.groupCount(); // final String[] params = new String[n]; // for (int i=0; i<n; ++i) { // params[i] = matcher.group(i + 1); // } // return params; // } // } // return null; // } // // /** // * Adds a check on the request methods and path to the specified handler. // * @param methods the accepted methods. // * @param regex the regular expression that the the url path should match. // * @param delegate the delegate handler. // * @return the handler with the additional requirements. // */ // public static Handler create(final Collection<String> methods, final String regex, final Handler delegate) { // return new RegexHandlerWrapper(methods, regex, delegate); // } // // /** // * Adds a check on the request method and path to the specified handler. // * @param method the accepted method. // * @param regex the regular expression that the the url path should match. // * @param delegate the delegate handler. // * @return the handler with the additional requirements. // */ // public static Handler create(final String method, final String regex, final Handler delegate) { // //noinspection Duplicates // return new RegexHandlerWrapper(method, regex, delegate); // } // // static class RegexHandlerWrapper extends RegexHandler { // // final Handler delegate; // // protected RegexHandlerWrapper(final Collection<String> methods, final String regex, final Handler delegate) { // super(methods, regex); // this.delegate = delegate; // } // // protected RegexHandlerWrapper(final String method, final String regex, final Handler delegate) { // super(method, regex); // this.delegate = delegate; // } // // @Override public Handler setup() { // delegate.setup(); // return this; // } // // @Override public String[] matches(final String method, final HttpUrl url) { // return super.matches(method, url) == null ? null : delegate.matches(method, url); // } // // @Override public Response.Builder handle(final Request request, final String[] params) { // return delegate.handle(request, params); // } // // } // // } // // Path: src/main/java/info/jdavid/ok/server/handler/Request.java // public final class Request { // // /** // * The client ip. // */ // public final String clientIp; // /** // * true when the request is being served with the HTTP 2 protocol rather than HTTP 1.1. // */ // public final boolean http2; // /** // * The request method. // */ // public final String method; // /** // * The request url. // */ // public final HttpUrl url; // /** // * The request headers. // */ // public final Headers headers; // /** // * The request body. // */ // public @Nullable final Buffer body; // // public Request(final String clientIp, final boolean http2, // final String method, final HttpUrl url, // final Headers headers, @Nullable final Buffer body) { // this.clientIp = clientIp; // this.method = method; // this.http2 = http2; // this.url = url; // this.headers = headers; // this.body = body; // } // // }
import java.io.IOException; import java.util.concurrent.TimeUnit; import info.jdavid.ok.server.handler.RegexHandler; import info.jdavid.ok.server.handler.Request; import okhttp3.ConnectionPool; import okhttp3.MediaType; import okhttp3.OkHttpClient; import okhttp3.RequestBody; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*;
package info.jdavid.ok.server; @SuppressWarnings("ConstantConditions") public class RegexHandlerTest { private static final HttpServer SERVER = new HttpServer(); //.dispatcher(new Dispatcher.Logged()); private static final OkHttpClient client = new OkHttpClient(); private static OkHttpClient client() { return client.newBuilder(). readTimeout(0, TimeUnit.SECONDS). retryOnConnectionFailure(false). connectTimeout(60, TimeUnit.SECONDS). connectionPool(new ConnectionPool(0, 1L, TimeUnit.SECONDS)). build(); } @BeforeClass public static void startServer() throws IOException { SERVER. port(8080). maxRequestSize(512). requestHandler(new RequestHandlerChain().
// Path: src/main/java/info/jdavid/ok/server/handler/RegexHandler.java // @SuppressWarnings({ "WeakerAccess", "unused" }) // public abstract class RegexHandler implements Handler { // // final Pattern pattern; // final List<String> methods; // // /** // * Creates an handler that will accept a request with the specified methods, // * whose path matches the specified regular expression. // * @param methods the request methods. // * @param regex the regular expression. // */ // protected RegexHandler(final Collection<String> methods, final String regex) { // if (methods.isEmpty()) { // throw new NullPointerException("The accepted request method cannot be null."); // } // final List<String> list = this.methods = new ArrayList<>(methods.size()); // for (final String method: methods) { // list.add(method.toUpperCase()); // } // pattern = Pattern.compile(regex); // } // // /** // * Creates an handler that will accept a request with the specified method, whose path matches the specified // * regular expression. // * @param method the request method. // * @param regex the regular expression. // */ // protected RegexHandler(final String method, final String regex) { // methods = Collections.singletonList(method.toUpperCase()); // pattern = Pattern.compile(regex); // } // // @Override public Handler setup() { return this; } // // @Override // public @Nullable String[] matches(final String method, final HttpUrl url) { // if (methods.contains(method)) { // final String encodedPath = url.encodedPath(); // final Matcher matcher = pattern.matcher(url.encodedPath()); // if (matcher.find()) { // if (matcher.start() > 0) return null; // if (matcher.end() < encodedPath.length()) return null; // final int n = matcher.groupCount(); // final String[] params = new String[n]; // for (int i=0; i<n; ++i) { // params[i] = matcher.group(i + 1); // } // return params; // } // } // return null; // } // // /** // * Adds a check on the request methods and path to the specified handler. // * @param methods the accepted methods. // * @param regex the regular expression that the the url path should match. // * @param delegate the delegate handler. // * @return the handler with the additional requirements. // */ // public static Handler create(final Collection<String> methods, final String regex, final Handler delegate) { // return new RegexHandlerWrapper(methods, regex, delegate); // } // // /** // * Adds a check on the request method and path to the specified handler. // * @param method the accepted method. // * @param regex the regular expression that the the url path should match. // * @param delegate the delegate handler. // * @return the handler with the additional requirements. // */ // public static Handler create(final String method, final String regex, final Handler delegate) { // //noinspection Duplicates // return new RegexHandlerWrapper(method, regex, delegate); // } // // static class RegexHandlerWrapper extends RegexHandler { // // final Handler delegate; // // protected RegexHandlerWrapper(final Collection<String> methods, final String regex, final Handler delegate) { // super(methods, regex); // this.delegate = delegate; // } // // protected RegexHandlerWrapper(final String method, final String regex, final Handler delegate) { // super(method, regex); // this.delegate = delegate; // } // // @Override public Handler setup() { // delegate.setup(); // return this; // } // // @Override public String[] matches(final String method, final HttpUrl url) { // return super.matches(method, url) == null ? null : delegate.matches(method, url); // } // // @Override public Response.Builder handle(final Request request, final String[] params) { // return delegate.handle(request, params); // } // // } // // } // // Path: src/main/java/info/jdavid/ok/server/handler/Request.java // public final class Request { // // /** // * The client ip. // */ // public final String clientIp; // /** // * true when the request is being served with the HTTP 2 protocol rather than HTTP 1.1. // */ // public final boolean http2; // /** // * The request method. // */ // public final String method; // /** // * The request url. // */ // public final HttpUrl url; // /** // * The request headers. // */ // public final Headers headers; // /** // * The request body. // */ // public @Nullable final Buffer body; // // public Request(final String clientIp, final boolean http2, // final String method, final HttpUrl url, // final Headers headers, @Nullable final Buffer body) { // this.clientIp = clientIp; // this.method = method; // this.http2 = http2; // this.url = url; // this.headers = headers; // this.body = body; // } // // } // Path: src/test/java/info/jdavid/ok/server/RegexHandlerTest.java import java.io.IOException; import java.util.concurrent.TimeUnit; import info.jdavid.ok.server.handler.RegexHandler; import info.jdavid.ok.server.handler.Request; import okhttp3.ConnectionPool; import okhttp3.MediaType; import okhttp3.OkHttpClient; import okhttp3.RequestBody; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; package info.jdavid.ok.server; @SuppressWarnings("ConstantConditions") public class RegexHandlerTest { private static final HttpServer SERVER = new HttpServer(); //.dispatcher(new Dispatcher.Logged()); private static final OkHttpClient client = new OkHttpClient(); private static OkHttpClient client() { return client.newBuilder(). readTimeout(0, TimeUnit.SECONDS). retryOnConnectionFailure(false). connectTimeout(60, TimeUnit.SECONDS). connectionPool(new ConnectionPool(0, 1L, TimeUnit.SECONDS)). build(); } @BeforeClass public static void startServer() throws IOException { SERVER. port(8080). maxRequestSize(512). requestHandler(new RequestHandlerChain().
add(new RegexHandler("GET", "/r1") {
programingjd/okserver
src/test/java/info/jdavid/ok/server/RegexHandlerTest.java
// Path: src/main/java/info/jdavid/ok/server/handler/RegexHandler.java // @SuppressWarnings({ "WeakerAccess", "unused" }) // public abstract class RegexHandler implements Handler { // // final Pattern pattern; // final List<String> methods; // // /** // * Creates an handler that will accept a request with the specified methods, // * whose path matches the specified regular expression. // * @param methods the request methods. // * @param regex the regular expression. // */ // protected RegexHandler(final Collection<String> methods, final String regex) { // if (methods.isEmpty()) { // throw new NullPointerException("The accepted request method cannot be null."); // } // final List<String> list = this.methods = new ArrayList<>(methods.size()); // for (final String method: methods) { // list.add(method.toUpperCase()); // } // pattern = Pattern.compile(regex); // } // // /** // * Creates an handler that will accept a request with the specified method, whose path matches the specified // * regular expression. // * @param method the request method. // * @param regex the regular expression. // */ // protected RegexHandler(final String method, final String regex) { // methods = Collections.singletonList(method.toUpperCase()); // pattern = Pattern.compile(regex); // } // // @Override public Handler setup() { return this; } // // @Override // public @Nullable String[] matches(final String method, final HttpUrl url) { // if (methods.contains(method)) { // final String encodedPath = url.encodedPath(); // final Matcher matcher = pattern.matcher(url.encodedPath()); // if (matcher.find()) { // if (matcher.start() > 0) return null; // if (matcher.end() < encodedPath.length()) return null; // final int n = matcher.groupCount(); // final String[] params = new String[n]; // for (int i=0; i<n; ++i) { // params[i] = matcher.group(i + 1); // } // return params; // } // } // return null; // } // // /** // * Adds a check on the request methods and path to the specified handler. // * @param methods the accepted methods. // * @param regex the regular expression that the the url path should match. // * @param delegate the delegate handler. // * @return the handler with the additional requirements. // */ // public static Handler create(final Collection<String> methods, final String regex, final Handler delegate) { // return new RegexHandlerWrapper(methods, regex, delegate); // } // // /** // * Adds a check on the request method and path to the specified handler. // * @param method the accepted method. // * @param regex the regular expression that the the url path should match. // * @param delegate the delegate handler. // * @return the handler with the additional requirements. // */ // public static Handler create(final String method, final String regex, final Handler delegate) { // //noinspection Duplicates // return new RegexHandlerWrapper(method, regex, delegate); // } // // static class RegexHandlerWrapper extends RegexHandler { // // final Handler delegate; // // protected RegexHandlerWrapper(final Collection<String> methods, final String regex, final Handler delegate) { // super(methods, regex); // this.delegate = delegate; // } // // protected RegexHandlerWrapper(final String method, final String regex, final Handler delegate) { // super(method, regex); // this.delegate = delegate; // } // // @Override public Handler setup() { // delegate.setup(); // return this; // } // // @Override public String[] matches(final String method, final HttpUrl url) { // return super.matches(method, url) == null ? null : delegate.matches(method, url); // } // // @Override public Response.Builder handle(final Request request, final String[] params) { // return delegate.handle(request, params); // } // // } // // } // // Path: src/main/java/info/jdavid/ok/server/handler/Request.java // public final class Request { // // /** // * The client ip. // */ // public final String clientIp; // /** // * true when the request is being served with the HTTP 2 protocol rather than HTTP 1.1. // */ // public final boolean http2; // /** // * The request method. // */ // public final String method; // /** // * The request url. // */ // public final HttpUrl url; // /** // * The request headers. // */ // public final Headers headers; // /** // * The request body. // */ // public @Nullable final Buffer body; // // public Request(final String clientIp, final boolean http2, // final String method, final HttpUrl url, // final Headers headers, @Nullable final Buffer body) { // this.clientIp = clientIp; // this.method = method; // this.http2 = http2; // this.url = url; // this.headers = headers; // this.body = body; // } // // }
import java.io.IOException; import java.util.concurrent.TimeUnit; import info.jdavid.ok.server.handler.RegexHandler; import info.jdavid.ok.server.handler.Request; import okhttp3.ConnectionPool; import okhttp3.MediaType; import okhttp3.OkHttpClient; import okhttp3.RequestBody; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*;
package info.jdavid.ok.server; @SuppressWarnings("ConstantConditions") public class RegexHandlerTest { private static final HttpServer SERVER = new HttpServer(); //.dispatcher(new Dispatcher.Logged()); private static final OkHttpClient client = new OkHttpClient(); private static OkHttpClient client() { return client.newBuilder(). readTimeout(0, TimeUnit.SECONDS). retryOnConnectionFailure(false). connectTimeout(60, TimeUnit.SECONDS). connectionPool(new ConnectionPool(0, 1L, TimeUnit.SECONDS)). build(); } @BeforeClass public static void startServer() throws IOException { SERVER. port(8080). maxRequestSize(512). requestHandler(new RequestHandlerChain(). add(new RegexHandler("GET", "/r1") {
// Path: src/main/java/info/jdavid/ok/server/handler/RegexHandler.java // @SuppressWarnings({ "WeakerAccess", "unused" }) // public abstract class RegexHandler implements Handler { // // final Pattern pattern; // final List<String> methods; // // /** // * Creates an handler that will accept a request with the specified methods, // * whose path matches the specified regular expression. // * @param methods the request methods. // * @param regex the regular expression. // */ // protected RegexHandler(final Collection<String> methods, final String regex) { // if (methods.isEmpty()) { // throw new NullPointerException("The accepted request method cannot be null."); // } // final List<String> list = this.methods = new ArrayList<>(methods.size()); // for (final String method: methods) { // list.add(method.toUpperCase()); // } // pattern = Pattern.compile(regex); // } // // /** // * Creates an handler that will accept a request with the specified method, whose path matches the specified // * regular expression. // * @param method the request method. // * @param regex the regular expression. // */ // protected RegexHandler(final String method, final String regex) { // methods = Collections.singletonList(method.toUpperCase()); // pattern = Pattern.compile(regex); // } // // @Override public Handler setup() { return this; } // // @Override // public @Nullable String[] matches(final String method, final HttpUrl url) { // if (methods.contains(method)) { // final String encodedPath = url.encodedPath(); // final Matcher matcher = pattern.matcher(url.encodedPath()); // if (matcher.find()) { // if (matcher.start() > 0) return null; // if (matcher.end() < encodedPath.length()) return null; // final int n = matcher.groupCount(); // final String[] params = new String[n]; // for (int i=0; i<n; ++i) { // params[i] = matcher.group(i + 1); // } // return params; // } // } // return null; // } // // /** // * Adds a check on the request methods and path to the specified handler. // * @param methods the accepted methods. // * @param regex the regular expression that the the url path should match. // * @param delegate the delegate handler. // * @return the handler with the additional requirements. // */ // public static Handler create(final Collection<String> methods, final String regex, final Handler delegate) { // return new RegexHandlerWrapper(methods, regex, delegate); // } // // /** // * Adds a check on the request method and path to the specified handler. // * @param method the accepted method. // * @param regex the regular expression that the the url path should match. // * @param delegate the delegate handler. // * @return the handler with the additional requirements. // */ // public static Handler create(final String method, final String regex, final Handler delegate) { // //noinspection Duplicates // return new RegexHandlerWrapper(method, regex, delegate); // } // // static class RegexHandlerWrapper extends RegexHandler { // // final Handler delegate; // // protected RegexHandlerWrapper(final Collection<String> methods, final String regex, final Handler delegate) { // super(methods, regex); // this.delegate = delegate; // } // // protected RegexHandlerWrapper(final String method, final String regex, final Handler delegate) { // super(method, regex); // this.delegate = delegate; // } // // @Override public Handler setup() { // delegate.setup(); // return this; // } // // @Override public String[] matches(final String method, final HttpUrl url) { // return super.matches(method, url) == null ? null : delegate.matches(method, url); // } // // @Override public Response.Builder handle(final Request request, final String[] params) { // return delegate.handle(request, params); // } // // } // // } // // Path: src/main/java/info/jdavid/ok/server/handler/Request.java // public final class Request { // // /** // * The client ip. // */ // public final String clientIp; // /** // * true when the request is being served with the HTTP 2 protocol rather than HTTP 1.1. // */ // public final boolean http2; // /** // * The request method. // */ // public final String method; // /** // * The request url. // */ // public final HttpUrl url; // /** // * The request headers. // */ // public final Headers headers; // /** // * The request body. // */ // public @Nullable final Buffer body; // // public Request(final String clientIp, final boolean http2, // final String method, final HttpUrl url, // final Headers headers, @Nullable final Buffer body) { // this.clientIp = clientIp; // this.method = method; // this.http2 = http2; // this.url = url; // this.headers = headers; // this.body = body; // } // // } // Path: src/test/java/info/jdavid/ok/server/RegexHandlerTest.java import java.io.IOException; import java.util.concurrent.TimeUnit; import info.jdavid.ok.server.handler.RegexHandler; import info.jdavid.ok.server.handler.Request; import okhttp3.ConnectionPool; import okhttp3.MediaType; import okhttp3.OkHttpClient; import okhttp3.RequestBody; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; package info.jdavid.ok.server; @SuppressWarnings("ConstantConditions") public class RegexHandlerTest { private static final HttpServer SERVER = new HttpServer(); //.dispatcher(new Dispatcher.Logged()); private static final OkHttpClient client = new OkHttpClient(); private static OkHttpClient client() { return client.newBuilder(). readTimeout(0, TimeUnit.SECONDS). retryOnConnectionFailure(false). connectTimeout(60, TimeUnit.SECONDS). connectionPool(new ConnectionPool(0, 1L, TimeUnit.SECONDS)). build(); } @BeforeClass public static void startServer() throws IOException { SERVER. port(8080). maxRequestSize(512). requestHandler(new RequestHandlerChain(). add(new RegexHandler("GET", "/r1") {
@Override public Response.Builder handle(final Request request, final String[] params) {
programingjd/okserver
src/main/java/info/jdavid/ok/server/Http2.java
// Path: src/main/java/info/jdavid/ok/server/header/ETag.java // @SuppressWarnings({ "WeakerAccess" }) // public final class ETag { // // private ETag() {} // // public static final String HEADER = "ETag"; // // public static final String IF_MATCH = "If-Match"; // public static final String IF_NONE_MATCH = "If-None-Match"; // // }
import java.io.IOException; import java.net.SocketException; import java.net.SocketTimeoutException; import java.util.ArrayList; import java.util.List; import java.util.Locale; import java.util.concurrent.TimeUnit; import javax.annotation.Nullable; import javax.net.ssl.SSLSocket; import info.jdavid.ok.server.header.ETag; import okhttp3.*; import okhttp3.internal.Util; import okhttp3.internal.http2.Http2Connection; import okhttp3.internal.http2.Http2Stream; import okhttp3.internal.http2.Header; import okhttp3.internal.http.HttpMethod; import okhttp3.internal.http.RequestLine; import okio.Buffer; import okio.BufferedSink; import okio.BufferedSource; import okio.ByteString; import okio.Okio; import okio.Timeout; import static okhttp3.internal.http2.Header.TARGET_AUTHORITY; import static okhttp3.internal.http2.Header.TARGET_METHOD; import static okhttp3.internal.http2.Header.TARGET_PATH; import static okhttp3.internal.http2.Header.TARGET_SCHEME;
if (useBody) { response = new Response.Builder().statusLine(StatusLines.BAD_REQUEST).noBody().build(); } else { response = handler.handle(clientIp, true, false,true, method, requestUrl, requestHeaders.build(), null); } } else { if (useBody) { final Buffer body = new Buffer(); if (stream.isOpen()) source.readFully(body, length); body.flush(); response = handler.handle(clientIp, true, false,true, method, requestUrl, requestHeaders.build(), body); } else { response = handler.handle(clientIp, true, false,true, method, requestUrl, requestHeaders.build(), null); } } } } final List<Header> responseHeaders = responseHeaders(response); source.close(); stream.writeHeaders(responseHeaders, true,true); final BufferedSink sink = Okio.buffer(stream.getSink()); try { response.writeBody(source, sink);
// Path: src/main/java/info/jdavid/ok/server/header/ETag.java // @SuppressWarnings({ "WeakerAccess" }) // public final class ETag { // // private ETag() {} // // public static final String HEADER = "ETag"; // // public static final String IF_MATCH = "If-Match"; // public static final String IF_NONE_MATCH = "If-None-Match"; // // } // Path: src/main/java/info/jdavid/ok/server/Http2.java import java.io.IOException; import java.net.SocketException; import java.net.SocketTimeoutException; import java.util.ArrayList; import java.util.List; import java.util.Locale; import java.util.concurrent.TimeUnit; import javax.annotation.Nullable; import javax.net.ssl.SSLSocket; import info.jdavid.ok.server.header.ETag; import okhttp3.*; import okhttp3.internal.Util; import okhttp3.internal.http2.Http2Connection; import okhttp3.internal.http2.Http2Stream; import okhttp3.internal.http2.Header; import okhttp3.internal.http.HttpMethod; import okhttp3.internal.http.RequestLine; import okio.Buffer; import okio.BufferedSink; import okio.BufferedSource; import okio.ByteString; import okio.Okio; import okio.Timeout; import static okhttp3.internal.http2.Header.TARGET_AUTHORITY; import static okhttp3.internal.http2.Header.TARGET_METHOD; import static okhttp3.internal.http2.Header.TARGET_PATH; import static okhttp3.internal.http2.Header.TARGET_SCHEME; if (useBody) { response = new Response.Builder().statusLine(StatusLines.BAD_REQUEST).noBody().build(); } else { response = handler.handle(clientIp, true, false,true, method, requestUrl, requestHeaders.build(), null); } } else { if (useBody) { final Buffer body = new Buffer(); if (stream.isOpen()) source.readFully(body, length); body.flush(); response = handler.handle(clientIp, true, false,true, method, requestUrl, requestHeaders.build(), body); } else { response = handler.handle(clientIp, true, false,true, method, requestUrl, requestHeaders.build(), null); } } } } final List<Header> responseHeaders = responseHeaders(response); source.close(); stream.writeHeaders(responseHeaders, true,true); final BufferedSink sink = Okio.buffer(stream.getSink()); try { response.writeBody(source, sink);
requestHeaders.removeAll(ETag.IF_NONE_MATCH);
programingjd/okserver
src/main/java/info/jdavid/ok/server/RequestHandler.java
// Path: src/main/java/info/jdavid/ok/server/header/Connection.java // @SuppressWarnings({ "WeakerAccess", "unused" }) // public final class Connection { // // private Connection() {} // // public static final String HEADER = "Connection"; // // public static final String CLOSE = "Close"; // public static final String KEEP_ALIVE = "Keep-Alive"; // // }
import javax.annotation.Nullable; import info.jdavid.ok.server.header.Connection; import okhttp3.Headers; import okhttp3.HttpUrl; import okio.Buffer;
package info.jdavid.ok.server; /** * The server request handler. */ @SuppressWarnings("WeakerAccess") public interface RequestHandler { /** * Creates the server response for a given request. * @param clientIp the client ip. * @param secure whether the request is secure (over https) or not. * @param insecureOnly whether the server accepts only insecure connections or whether https is enabled. * @param http2 whether the request protocol is HTTP 2 (h2) rather than an HTTP 1.1. * @param method the request method (get, post, ...). * @param url the request url. * @param requestHeaders the request headers. * @param requestBody the request body. * @return the response for the request. */ public Response handle(final String clientIp, final boolean secure, final boolean insecureOnly, final boolean http2, final String method, final HttpUrl url, final Headers requestHeaders, @Nullable final Buffer requestBody); static class Helper { static Response handle(final RequestHandler handler, final String clientIp, final boolean secure, final boolean insecureOnly, final boolean http2, final String method, final String path, final Headers requestHeaders, @Nullable final Buffer requestBody) { final String h = requestHeaders.get("Host"); if (h == null) { return new Response.Builder(). statusLine(StatusLines.BAD_REQUEST).
// Path: src/main/java/info/jdavid/ok/server/header/Connection.java // @SuppressWarnings({ "WeakerAccess", "unused" }) // public final class Connection { // // private Connection() {} // // public static final String HEADER = "Connection"; // // public static final String CLOSE = "Close"; // public static final String KEEP_ALIVE = "Keep-Alive"; // // } // Path: src/main/java/info/jdavid/ok/server/RequestHandler.java import javax.annotation.Nullable; import info.jdavid.ok.server.header.Connection; import okhttp3.Headers; import okhttp3.HttpUrl; import okio.Buffer; package info.jdavid.ok.server; /** * The server request handler. */ @SuppressWarnings("WeakerAccess") public interface RequestHandler { /** * Creates the server response for a given request. * @param clientIp the client ip. * @param secure whether the request is secure (over https) or not. * @param insecureOnly whether the server accepts only insecure connections or whether https is enabled. * @param http2 whether the request protocol is HTTP 2 (h2) rather than an HTTP 1.1. * @param method the request method (get, post, ...). * @param url the request url. * @param requestHeaders the request headers. * @param requestBody the request body. * @return the response for the request. */ public Response handle(final String clientIp, final boolean secure, final boolean insecureOnly, final boolean http2, final String method, final HttpUrl url, final Headers requestHeaders, @Nullable final Buffer requestBody); static class Helper { static Response handle(final RequestHandler handler, final String clientIp, final boolean secure, final boolean insecureOnly, final boolean http2, final String method, final String path, final Headers requestHeaders, @Nullable final Buffer requestBody) { final String h = requestHeaders.get("Host"); if (h == null) { return new Response.Builder(). statusLine(StatusLines.BAD_REQUEST).
header(Connection.HEADER, Connection.CLOSE).
programingjd/okserver
src/main/java/info/jdavid/ok/server/Https.java
// Path: src/main/java/info/jdavid/ok/server/Logger.java // static final org.slf4j.Logger logger = LoggerFactory.getLogger(HttpServer.class);
import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.net.Socket; import java.security.GeneralSecurityException; import java.security.KeyStore; import java.security.SecureRandom; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Nullable; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocket; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManagerFactory; import static info.jdavid.ok.server.Logger.logger;
@Nullable final String hostname, final boolean http2) throws IOException { final SSLSocketFactory sslFactory = getContext(hostname).getSocketFactory(); final SSLSocket sslSocket = (SSLSocket)sslFactory.createSocket(socket, null, socket.getPort(), true); platform.setupSSLSocket(sslSocket, http2); sslSocket.setUseClientMode(false); sslSocket.setEnabledProtocols(protocols); sslSocket.setEnabledCipherSuites(cipherSuites); sslSocket.startHandshake(); return sslSocket; } private static SSLContext createSSLContext(@Nullable final byte[] certificate) { if (certificate == null) return null; final InputStream cert = new ByteArrayInputStream(certificate); try { final KeyStore keyStore = KeyStore.getInstance("PKCS12"); keyStore.load(cert, new char[0]); final KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(keyStore, new char[0]); final KeyStore trustStore = KeyStore.getInstance("JKS"); trustStore.load(null, null); final TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(trustStore); final SSLContext context = SSLContext.getInstance("TLS"); context.init(kmf.getKeyManagers(), tmf.getTrustManagers(), new SecureRandom()); return context; } catch (final GeneralSecurityException e) {
// Path: src/main/java/info/jdavid/ok/server/Logger.java // static final org.slf4j.Logger logger = LoggerFactory.getLogger(HttpServer.class); // Path: src/main/java/info/jdavid/ok/server/Https.java import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.net.Socket; import java.security.GeneralSecurityException; import java.security.KeyStore; import java.security.SecureRandom; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Nullable; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocket; import javax.net.ssl.SSLSocketFactory; import javax.net.ssl.TrustManagerFactory; import static info.jdavid.ok.server.Logger.logger; @Nullable final String hostname, final boolean http2) throws IOException { final SSLSocketFactory sslFactory = getContext(hostname).getSocketFactory(); final SSLSocket sslSocket = (SSLSocket)sslFactory.createSocket(socket, null, socket.getPort(), true); platform.setupSSLSocket(sslSocket, http2); sslSocket.setUseClientMode(false); sslSocket.setEnabledProtocols(protocols); sslSocket.setEnabledCipherSuites(cipherSuites); sslSocket.startHandshake(); return sslSocket; } private static SSLContext createSSLContext(@Nullable final byte[] certificate) { if (certificate == null) return null; final InputStream cert = new ByteArrayInputStream(certificate); try { final KeyStore keyStore = KeyStore.getInstance("PKCS12"); keyStore.load(cert, new char[0]); final KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(keyStore, new char[0]); final KeyStore trustStore = KeyStore.getInstance("JKS"); trustStore.load(null, null); final TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(trustStore); final SSLContext context = SSLContext.getInstance("TLS"); context.init(kmf.getKeyManagers(), tmf.getTrustManagers(), new SecureRandom()); return context; } catch (final GeneralSecurityException e) {
logger.warn("Failed to create SSL context.", e);
programingjd/okserver
src/main/java/info/jdavid/ok/server/AbstractRequestHandler.java
// Path: src/main/java/info/jdavid/ok/server/header/Connection.java // @SuppressWarnings({ "WeakerAccess", "unused" }) // public final class Connection { // // private Connection() {} // // public static final String HEADER = "Connection"; // // public static final String CLOSE = "Close"; // public static final String KEEP_ALIVE = "Keep-Alive"; // // }
import javax.annotation.Nullable; import info.jdavid.ok.server.header.Connection; import okhttp3.Headers; import okhttp3.HttpUrl; import okio.Buffer;
* @param url the challenge request url. * @param requestHeaders the challenge request headers. * @param requestBody the challenge request body. * @return the challenge response. */ protected abstract Response handleAcmeChallenge(final String clientIp, final String method, final HttpUrl url, final Headers requestHeaders, @Nullable final Buffer requestBody); /** * Handles a request once the request validation has been performed. * @param clientIp the request client ip. * @param http2 true if the request is using http 2 (h2). * @param method the request method. * @param url the request url. * @param requestHeaders the request headers. * @param requestBody the request body. * @return the response. */ protected abstract Response handle(final String clientIp, final boolean http2, final String method, final HttpUrl url, final Headers requestHeaders, @Nullable final Buffer requestBody); private static final Response FORBIDDEN = new Response.Builder(). statusLine(StatusLines.FORBIDDEN).
// Path: src/main/java/info/jdavid/ok/server/header/Connection.java // @SuppressWarnings({ "WeakerAccess", "unused" }) // public final class Connection { // // private Connection() {} // // public static final String HEADER = "Connection"; // // public static final String CLOSE = "Close"; // public static final String KEEP_ALIVE = "Keep-Alive"; // // } // Path: src/main/java/info/jdavid/ok/server/AbstractRequestHandler.java import javax.annotation.Nullable; import info.jdavid.ok.server.header.Connection; import okhttp3.Headers; import okhttp3.HttpUrl; import okio.Buffer; * @param url the challenge request url. * @param requestHeaders the challenge request headers. * @param requestBody the challenge request body. * @return the challenge response. */ protected abstract Response handleAcmeChallenge(final String clientIp, final String method, final HttpUrl url, final Headers requestHeaders, @Nullable final Buffer requestBody); /** * Handles a request once the request validation has been performed. * @param clientIp the request client ip. * @param http2 true if the request is using http 2 (h2). * @param method the request method. * @param url the request url. * @param requestHeaders the request headers. * @param requestBody the request body. * @return the response. */ protected abstract Response handle(final String clientIp, final boolean http2, final String method, final HttpUrl url, final Headers requestHeaders, @Nullable final Buffer requestBody); private static final Response FORBIDDEN = new Response.Builder(). statusLine(StatusLines.FORBIDDEN).
header(Connection.HEADER, Connection.CLOSE).
programingjd/okserver
src/main/java/info/jdavid/ok/server/Http11.java
// Path: src/main/java/info/jdavid/ok/server/header/Connection.java // @SuppressWarnings({ "WeakerAccess", "unused" }) // public final class Connection { // // private Connection() {} // // public static final String HEADER = "Connection"; // // public static final String CLOSE = "Close"; // public static final String KEEP_ALIVE = "Keep-Alive"; // // } // // Path: src/main/java/info/jdavid/ok/server/header/Expect.java // @SuppressWarnings({ "WeakerAccess" }) // public final class Expect { // // private Expect() {} // // public static final String HEADER = "Expect"; // // public static final String CONTINUE = "100-Continue"; // // }
import java.io.IOException; import java.net.Socket; import java.net.SocketException; import java.net.SocketTimeoutException; import java.nio.charset.Charset; import java.util.Locale; import java.util.concurrent.TimeUnit; import info.jdavid.ok.server.header.Connection; import info.jdavid.ok.server.header.Expect; import okhttp3.Headers; import okhttp3.internal.http.HttpMethod; import okio.Buffer; import okio.BufferedSink; import okio.BufferedSource; import okio.ByteString; import okio.Okio;
} private static boolean useSocket(final BufferedSource in, final int reuse, final KeepAliveStrategy strategy) { final int timeout = strategy.timeout(reuse); if (timeout <= 0) { return reuse == 0; } else { in.timeout().timeout(timeout, TimeUnit.SECONDS); return true; } } static void serve(final Socket socket, final boolean secure, final boolean insecureOnly, final long maxRequestSize, final KeepAliveStrategy keepAliveStrategy, final RequestHandler requestHandler) throws IOException { final BufferedSource in = Okio.buffer(Okio.source(socket)); final BufferedSink out = Okio.buffer(Okio.sink(socket)); try { final String clientIp = socket.getInetAddress().getHostAddress(); int reuseCounter = 0; while (useSocket(in, reuseCounter++, keepAliveStrategy)) { long availableRequestSize = maxRequestSize; final ByteString requestByteString = readRequestLine(in); final Response response; if (requestByteString == null || requestByteString.size() < 3) { response = new Response.Builder(). statusLine(StatusLines.BAD_REQUEST).
// Path: src/main/java/info/jdavid/ok/server/header/Connection.java // @SuppressWarnings({ "WeakerAccess", "unused" }) // public final class Connection { // // private Connection() {} // // public static final String HEADER = "Connection"; // // public static final String CLOSE = "Close"; // public static final String KEEP_ALIVE = "Keep-Alive"; // // } // // Path: src/main/java/info/jdavid/ok/server/header/Expect.java // @SuppressWarnings({ "WeakerAccess" }) // public final class Expect { // // private Expect() {} // // public static final String HEADER = "Expect"; // // public static final String CONTINUE = "100-Continue"; // // } // Path: src/main/java/info/jdavid/ok/server/Http11.java import java.io.IOException; import java.net.Socket; import java.net.SocketException; import java.net.SocketTimeoutException; import java.nio.charset.Charset; import java.util.Locale; import java.util.concurrent.TimeUnit; import info.jdavid.ok.server.header.Connection; import info.jdavid.ok.server.header.Expect; import okhttp3.Headers; import okhttp3.internal.http.HttpMethod; import okio.Buffer; import okio.BufferedSink; import okio.BufferedSource; import okio.ByteString; import okio.Okio; } private static boolean useSocket(final BufferedSource in, final int reuse, final KeepAliveStrategy strategy) { final int timeout = strategy.timeout(reuse); if (timeout <= 0) { return reuse == 0; } else { in.timeout().timeout(timeout, TimeUnit.SECONDS); return true; } } static void serve(final Socket socket, final boolean secure, final boolean insecureOnly, final long maxRequestSize, final KeepAliveStrategy keepAliveStrategy, final RequestHandler requestHandler) throws IOException { final BufferedSource in = Okio.buffer(Okio.source(socket)); final BufferedSink out = Okio.buffer(Okio.sink(socket)); try { final String clientIp = socket.getInetAddress().getHostAddress(); int reuseCounter = 0; while (useSocket(in, reuseCounter++, keepAliveStrategy)) { long availableRequestSize = maxRequestSize; final ByteString requestByteString = readRequestLine(in); final Response response; if (requestByteString == null || requestByteString.size() < 3) { response = new Response.Builder(). statusLine(StatusLines.BAD_REQUEST).
header(Connection.HEADER, Connection.CLOSE).
programingjd/okserver
src/main/java/info/jdavid/ok/server/Http11.java
// Path: src/main/java/info/jdavid/ok/server/header/Connection.java // @SuppressWarnings({ "WeakerAccess", "unused" }) // public final class Connection { // // private Connection() {} // // public static final String HEADER = "Connection"; // // public static final String CLOSE = "Close"; // public static final String KEEP_ALIVE = "Keep-Alive"; // // } // // Path: src/main/java/info/jdavid/ok/server/header/Expect.java // @SuppressWarnings({ "WeakerAccess" }) // public final class Expect { // // private Expect() {} // // public static final String HEADER = "Expect"; // // public static final String CONTINUE = "100-Continue"; // // }
import java.io.IOException; import java.net.Socket; import java.net.SocketException; import java.net.SocketTimeoutException; import java.nio.charset.Charset; import java.util.Locale; import java.util.concurrent.TimeUnit; import info.jdavid.ok.server.header.Connection; import info.jdavid.ok.server.header.Expect; import okhttp3.Headers; import okhttp3.internal.http.HttpMethod; import okio.Buffer; import okio.BufferedSink; import okio.BufferedSource; import okio.ByteString; import okio.Okio;
if (method == null || path == null) { response = new Response.Builder(). statusLine(StatusLines.BAD_REQUEST). header(Connection.HEADER, Connection.CLOSE). noBody(). build(); } else { final Headers.Builder headersBuilder = new Headers.Builder(); boolean noHeaders = true; while (true) { final long index = crlf(in, availableRequestSize); if (index == -1) { break; } if (noHeaders) noHeaders = false; final ByteString headerByteString = in.readByteString(index); in.skip(2L); availableRequestSize -= (index + 2); if (index == 0) break; headersBuilder.add(headerByteString.string(ASCII)); } if (noHeaders) { response = new Response.Builder(). statusLine(StatusLines.BAD_REQUEST). header(Connection.HEADER, Connection.CLOSE). noBody(). build(); } else {
// Path: src/main/java/info/jdavid/ok/server/header/Connection.java // @SuppressWarnings({ "WeakerAccess", "unused" }) // public final class Connection { // // private Connection() {} // // public static final String HEADER = "Connection"; // // public static final String CLOSE = "Close"; // public static final String KEEP_ALIVE = "Keep-Alive"; // // } // // Path: src/main/java/info/jdavid/ok/server/header/Expect.java // @SuppressWarnings({ "WeakerAccess" }) // public final class Expect { // // private Expect() {} // // public static final String HEADER = "Expect"; // // public static final String CONTINUE = "100-Continue"; // // } // Path: src/main/java/info/jdavid/ok/server/Http11.java import java.io.IOException; import java.net.Socket; import java.net.SocketException; import java.net.SocketTimeoutException; import java.nio.charset.Charset; import java.util.Locale; import java.util.concurrent.TimeUnit; import info.jdavid.ok.server.header.Connection; import info.jdavid.ok.server.header.Expect; import okhttp3.Headers; import okhttp3.internal.http.HttpMethod; import okio.Buffer; import okio.BufferedSink; import okio.BufferedSource; import okio.ByteString; import okio.Okio; if (method == null || path == null) { response = new Response.Builder(). statusLine(StatusLines.BAD_REQUEST). header(Connection.HEADER, Connection.CLOSE). noBody(). build(); } else { final Headers.Builder headersBuilder = new Headers.Builder(); boolean noHeaders = true; while (true) { final long index = crlf(in, availableRequestSize); if (index == -1) { break; } if (noHeaders) noHeaders = false; final ByteString headerByteString = in.readByteString(index); in.skip(2L); availableRequestSize -= (index + 2); if (index == 0) break; headersBuilder.add(headerByteString.string(ASCII)); } if (noHeaders) { response = new Response.Builder(). statusLine(StatusLines.BAD_REQUEST). header(Connection.HEADER, Connection.CLOSE). noBody(). build(); } else {
if (Expect.CONTINUE.equalsIgnoreCase(headersBuilder.get(Expect.HEADER))) {
programingjd/okserver
src/main/java/info/jdavid/ok/server/Platform.java
// Path: src/main/java/info/jdavid/ok/server/Logger.java // static final org.slf4j.Logger logger = LoggerFactory.getLogger(HttpServer.class);
import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Arrays; import java.util.Collections; import java.util.List; import javax.net.ssl.SSLParameters; import javax.net.ssl.SSLSocket; import static info.jdavid.ok.server.Logger.logger;
} catch (final IllegalAccessException e) { throw new RuntimeException(e); } } private static void setHttp2Protocol(final SSLSocket socket, final Method method) { final SSLParameters parameters = socket.getSSLParameters(); try { method.invoke(parameters, new Object[] { protocols }); socket.setSSLParameters(parameters); } catch (final IllegalAccessException e1) { throw new RuntimeException(e1); } catch (final InvocationTargetException e2) { throw new RuntimeException(e2); } } static class Jdk9Platform extends Platform { static Platform buildIfSupported() { return Float.parseFloat(JAVA_SPEC_VERSION) >= 9 ? new Jdk9Platform() : null; } private final Method applicationProtocols; private Jdk9Platform() { super();
// Path: src/main/java/info/jdavid/ok/server/Logger.java // static final org.slf4j.Logger logger = LoggerFactory.getLogger(HttpServer.class); // Path: src/main/java/info/jdavid/ok/server/Platform.java import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Arrays; import java.util.Collections; import java.util.List; import javax.net.ssl.SSLParameters; import javax.net.ssl.SSLSocket; import static info.jdavid.ok.server.Logger.logger; } catch (final IllegalAccessException e) { throw new RuntimeException(e); } } private static void setHttp2Protocol(final SSLSocket socket, final Method method) { final SSLParameters parameters = socket.getSSLParameters(); try { method.invoke(parameters, new Object[] { protocols }); socket.setSSLParameters(parameters); } catch (final IllegalAccessException e1) { throw new RuntimeException(e1); } catch (final InvocationTargetException e2) { throw new RuntimeException(e2); } } static class Jdk9Platform extends Platform { static Platform buildIfSupported() { return Float.parseFloat(JAVA_SPEC_VERSION) >= 9 ? new Jdk9Platform() : null; } private final Method applicationProtocols; private Jdk9Platform() { super();
logger.info("JDK9 Platform");
programingjd/okserver
src/test/java/info/jdavid/ok/server/SSEServerTest.java
// Path: src/samples/java/info/jdavid/ok/server/samples/SSEServer.java // @SuppressWarnings("WeakerAccess") // public class SSEServer { // // protected final HttpServer mServer; // // public SSEServer(final int port, final int retrySecs, final int periodSecs, final int initialDelaySecs) { // //noinspection Duplicates // mServer = new HttpServer(). // requestHandler( // new RequestHandlerChain(). // add(new SSEHandler(retrySecs, periodSecs, initialDelaySecs)) // ). // port(port); // } // // public void start() { // mServer.start(); // } // // @SuppressWarnings("unused") // public void stop() { // mServer.shutdown(); // } // // // public static void main(final String[] args) { // new SSEServer(8080, 15, 10, 5).start(); // } // // @SuppressWarnings("AnonymousHasLambdaAlternative") // private static class SSEHandler extends RegexHandler { // // private final int mRetrySecs; // private final int mPeriodSecs; // private final int mInitialDelaySecs; // // protected SSEHandler(final int retrySecs, final int periodSecs, final int initialDelaySecs) { // super("GET", "/sse"); // mRetrySecs = retrySecs; // mPeriodSecs = periodSecs; // mInitialDelaySecs = initialDelaySecs; // } // // @Override // public Response.Builder handle(final Request request, final String[] params) { // final Response.EventSource eventSource = new Response.EventSource(); // new Thread() { // // Sends 5 "OK" message. // public void run() { // if (mInitialDelaySecs > 0) { // try { Thread.sleep(mInitialDelaySecs * 1000L); } // catch (final InterruptedException ignore) {} // } // for (int i=0; i<4; ++i) { // eventSource.send("OK"); // try { Thread.sleep(mPeriodSecs * 1000L); } // catch (final InterruptedException ignore) {} // } // eventSource.send("OK"); // eventSource.close(); // } // }.start(); // return new Response.Builder().sse(eventSource, mRetrySecs); // } // // } // // }
import okhttp3.HttpUrl; import okhttp3.OkHttpClient; import okhttp3.Protocol; import okhttp3.Request; import okhttp3.Response; import info.jdavid.ok.server.samples.SSEServer; import okio.Buffer; import okio.BufferedSource; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; import java.io.IOException; import java.util.concurrent.TimeUnit; import javax.annotation.Nullable;
package info.jdavid.ok.server; //@FixMethodOrder(MethodSorters.NAME_ASCENDING) @SuppressWarnings("ConstantConditions") public class SSEServerTest { private static Request.Builder request(@Nullable final String... segments) { HttpUrl.Builder url = new HttpUrl.Builder().scheme("http").host("localhost").port(8082); if (segments != null) { for (final String segment: segments) { url.addPathSegment(segment); } } return new Request.Builder().url(url.build()); } private static final OkHttpClient client = new OkHttpClient(); private static OkHttpClient client() { return client.newBuilder().readTimeout(10, TimeUnit.SECONDS).build(); }
// Path: src/samples/java/info/jdavid/ok/server/samples/SSEServer.java // @SuppressWarnings("WeakerAccess") // public class SSEServer { // // protected final HttpServer mServer; // // public SSEServer(final int port, final int retrySecs, final int periodSecs, final int initialDelaySecs) { // //noinspection Duplicates // mServer = new HttpServer(). // requestHandler( // new RequestHandlerChain(). // add(new SSEHandler(retrySecs, periodSecs, initialDelaySecs)) // ). // port(port); // } // // public void start() { // mServer.start(); // } // // @SuppressWarnings("unused") // public void stop() { // mServer.shutdown(); // } // // // public static void main(final String[] args) { // new SSEServer(8080, 15, 10, 5).start(); // } // // @SuppressWarnings("AnonymousHasLambdaAlternative") // private static class SSEHandler extends RegexHandler { // // private final int mRetrySecs; // private final int mPeriodSecs; // private final int mInitialDelaySecs; // // protected SSEHandler(final int retrySecs, final int periodSecs, final int initialDelaySecs) { // super("GET", "/sse"); // mRetrySecs = retrySecs; // mPeriodSecs = periodSecs; // mInitialDelaySecs = initialDelaySecs; // } // // @Override // public Response.Builder handle(final Request request, final String[] params) { // final Response.EventSource eventSource = new Response.EventSource(); // new Thread() { // // Sends 5 "OK" message. // public void run() { // if (mInitialDelaySecs > 0) { // try { Thread.sleep(mInitialDelaySecs * 1000L); } // catch (final InterruptedException ignore) {} // } // for (int i=0; i<4; ++i) { // eventSource.send("OK"); // try { Thread.sleep(mPeriodSecs * 1000L); } // catch (final InterruptedException ignore) {} // } // eventSource.send("OK"); // eventSource.close(); // } // }.start(); // return new Response.Builder().sse(eventSource, mRetrySecs); // } // // } // // } // Path: src/test/java/info/jdavid/ok/server/SSEServerTest.java import okhttp3.HttpUrl; import okhttp3.OkHttpClient; import okhttp3.Protocol; import okhttp3.Request; import okhttp3.Response; import info.jdavid.ok.server.samples.SSEServer; import okio.Buffer; import okio.BufferedSource; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; import java.io.IOException; import java.util.concurrent.TimeUnit; import javax.annotation.Nullable; package info.jdavid.ok.server; //@FixMethodOrder(MethodSorters.NAME_ASCENDING) @SuppressWarnings("ConstantConditions") public class SSEServerTest { private static Request.Builder request(@Nullable final String... segments) { HttpUrl.Builder url = new HttpUrl.Builder().scheme("http").host("localhost").port(8082); if (segments != null) { for (final String segment: segments) { url.addPathSegment(segment); } } return new Request.Builder().url(url.build()); } private static final OkHttpClient client = new OkHttpClient(); private static OkHttpClient client() { return client.newBuilder().readTimeout(10, TimeUnit.SECONDS).build(); }
private static final SSEServer SERVER = new SSEServer(8082, 5, 3, 3);
programingjd/okserver
src/main/java/info/jdavid/ok/server/SocketDispatcher.java
// Path: src/main/java/info/jdavid/ok/server/Logger.java // static final org.slf4j.Logger logger = LoggerFactory.getLogger(HttpServer.class);
import java.io.Closeable; import java.io.IOException; import java.net.BindException; import java.net.InetAddress; import java.net.Socket; import java.net.SocketException; import java.net.SocketTimeoutException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import javax.annotation.Nullable; import javax.net.ssl.SSLHandshakeException; import javax.net.ssl.SSLSocket; import static info.jdavid.ok.server.Logger.logger;
@Override public void run() { try { dispatchLoop(socket, secure, insecureOnly, https, hostname, maxRequestSize, keepAliveStrategy, requestHandler); } finally { close(socket); } } }).start(); } private void dispatchLoop(final ServerSocket socket, final boolean secure, final boolean insecureOnly, final @Nullable Https https, final @Nullable String hostname, final long maxRequestSize, final KeepAliveStrategy keepAliveStrategy, final RequestHandler requestHandler) { while (true) { try { if (!Thread.currentThread().isInterrupted()) { dispatch(new Request(socket.accept(), secure, insecureOnly, https, hostname, maxRequestSize, keepAliveStrategy, requestHandler)); } } catch (final IOException e) { if (socket.isClosed()) { break; }
// Path: src/main/java/info/jdavid/ok/server/Logger.java // static final org.slf4j.Logger logger = LoggerFactory.getLogger(HttpServer.class); // Path: src/main/java/info/jdavid/ok/server/SocketDispatcher.java import java.io.Closeable; import java.io.IOException; import java.net.BindException; import java.net.InetAddress; import java.net.Socket; import java.net.SocketException; import java.net.SocketTimeoutException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import javax.annotation.Nullable; import javax.net.ssl.SSLHandshakeException; import javax.net.ssl.SSLSocket; import static info.jdavid.ok.server.Logger.logger; @Override public void run() { try { dispatchLoop(socket, secure, insecureOnly, https, hostname, maxRequestSize, keepAliveStrategy, requestHandler); } finally { close(socket); } } }).start(); } private void dispatchLoop(final ServerSocket socket, final boolean secure, final boolean insecureOnly, final @Nullable Https https, final @Nullable String hostname, final long maxRequestSize, final KeepAliveStrategy keepAliveStrategy, final RequestHandler requestHandler) { while (true) { try { if (!Thread.currentThread().isInterrupted()) { dispatch(new Request(socket.accept(), secure, insecureOnly, https, hostname, maxRequestSize, keepAliveStrategy, requestHandler)); } } catch (final IOException e) { if (socket.isClosed()) { break; }
logger.warn(secure ? "HTTPS" : "HTTP", e);
programingjd/okserver
src/main/java/info/jdavid/ok/server/HttpServer.java
// Path: src/main/java/info/jdavid/ok/server/Logger.java // static final org.slf4j.Logger logger = LoggerFactory.getLogger(HttpServer.class);
import java.io.IOException; import java.net.BindException; import java.net.InetAddress; import java.util.concurrent.atomic.AtomicBoolean; import javax.annotation.Nullable; import static info.jdavid.ok.server.Logger.logger;
/** * Starts the server. */ public final void start() { if (started.getAndSet(true)) { throw new IllegalStateException("The server has already been started."); } try { if (!setup.getAndSet(true)) setup(); final RequestHandler handler = requestHandler(); if (handler instanceof AbstractRequestHandler) { ((AbstractRequestHandler)handler).init(); } final Dispatcher dispatcher = dispatcher(); dispatcher.start(); final InetAddress address; if (hostname == null) { address = null; //new InetSocketAddress(0).getAddress(); } else { address = InetAddress.getByName(hostname); } dispatcher.loop(port, securePort, https, address, hostname, maxRequestSize, keepAliveStrategy, handler); } catch (final BindException e) { throw new RuntimeException(e); } catch (final IOException e) {
// Path: src/main/java/info/jdavid/ok/server/Logger.java // static final org.slf4j.Logger logger = LoggerFactory.getLogger(HttpServer.class); // Path: src/main/java/info/jdavid/ok/server/HttpServer.java import java.io.IOException; import java.net.BindException; import java.net.InetAddress; import java.util.concurrent.atomic.AtomicBoolean; import javax.annotation.Nullable; import static info.jdavid.ok.server.Logger.logger; /** * Starts the server. */ public final void start() { if (started.getAndSet(true)) { throw new IllegalStateException("The server has already been started."); } try { if (!setup.getAndSet(true)) setup(); final RequestHandler handler = requestHandler(); if (handler instanceof AbstractRequestHandler) { ((AbstractRequestHandler)handler).init(); } final Dispatcher dispatcher = dispatcher(); dispatcher.start(); final InetAddress address; if (hostname == null) { address = null; //new InetSocketAddress(0).getAddress(); } else { address = InetAddress.getByName(hostname); } dispatcher.loop(port, securePort, https, address, hostname, maxRequestSize, keepAliveStrategy, handler); } catch (final BindException e) { throw new RuntimeException(e); } catch (final IOException e) {
logger.error(e.getMessage(), e);
dain/memcached
src/main/java/org/iq80/memcached/ItemLru.java
// Path: src/main/java/org/iq80/memcached/Item.java // public static class PrevChain implements Iterable<Item> // { // private final Allocator allocator; // private final long start; // // public PrevChain(Allocator allocator, long start) // { // this.allocator = allocator; // this.start = start; // } // // public Iterator<Item> iterator() // { // return new Iterator<Item>() // { // private Item next = cast(allocator, start); // // public boolean hasNext() // { // return next.getAddress() != 0; // } // // public Item next() // { // if (!hasNext()) { // throw new NoSuchElementException(); // } // // next.setAddress(allocator, next.getPrev()); // return next; // } // // public void remove() // { // throw new UnsupportedOperationException(); // } // }; // } // }
import org.iq80.memcached.Item.PrevChain;
/* * Copyright 2010 Proofpoint, Inc. * Copyright (C) 2012, FuseSource Corp. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.iq80.memcached; public class ItemLru { /** * We only reposition items in the LRU queue if they haven't been * repositioned in this many seconds. That saves us from churning on * frequently-accessed items. */ private static final int ITEM_UPDATE_INTERVAL = 60; /** * How long an object can reasonably be assumed to be locked before * harvesting it on a low memory condition? 3 Hours. */ private static final long TAIL_REPAIR_TIME = 3 * 3600; private final SlabManager slabManager; private final boolean evictToFree; private final Monitor monitor; private final ItemStats stats; private long head; private long tail; private long size; public ItemLru(SlabManager slabManager, boolean evictToFree, Monitor monitor, ItemStats stats) { this.slabManager = slabManager; this.evictToFree = evictToFree; this.monitor = monitor; this.stats = stats; } public long size() { return size; } /** * Check if there are any expired items on the tail. */ public Item findExpired(int tries, int currentTime) { // do a quick check if we have any expired items in the tail..
// Path: src/main/java/org/iq80/memcached/Item.java // public static class PrevChain implements Iterable<Item> // { // private final Allocator allocator; // private final long start; // // public PrevChain(Allocator allocator, long start) // { // this.allocator = allocator; // this.start = start; // } // // public Iterator<Item> iterator() // { // return new Iterator<Item>() // { // private Item next = cast(allocator, start); // // public boolean hasNext() // { // return next.getAddress() != 0; // } // // public Item next() // { // if (!hasNext()) { // throw new NoSuchElementException(); // } // // next.setAddress(allocator, next.getPrev()); // return next; // } // // public void remove() // { // throw new UnsupportedOperationException(); // } // }; // } // } // Path: src/main/java/org/iq80/memcached/ItemLru.java import org.iq80.memcached.Item.PrevChain; /* * Copyright 2010 Proofpoint, Inc. * Copyright (C) 2012, FuseSource Corp. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.iq80.memcached; public class ItemLru { /** * We only reposition items in the LRU queue if they haven't been * repositioned in this many seconds. That saves us from churning on * frequently-accessed items. */ private static final int ITEM_UPDATE_INTERVAL = 60; /** * How long an object can reasonably be assumed to be locked before * harvesting it on a low memory condition? 3 Hours. */ private static final long TAIL_REPAIR_TIME = 3 * 3600; private final SlabManager slabManager; private final boolean evictToFree; private final Monitor monitor; private final ItemStats stats; private long head; private long tail; private long size; public ItemLru(SlabManager slabManager, boolean evictToFree, Monitor monitor, ItemStats stats) { this.slabManager = slabManager; this.evictToFree = evictToFree; this.monitor = monitor; this.stats = stats; } public long size() { return size; } /** * Check if there are any expired items on the tail. */ public Item findExpired(int tries, int currentTime) { // do a quick check if we have any expired items in the tail..
for (Item search : new PrevChain(slabManager.getAllocator(), tail)) {
dain/memcached
src/main/java/org/iq80/memory/UnsafeAllocation.java
// Path: src/main/java/org/iq80/memory/UnsafeAllocator.java // public class UnsafeAllocator implements Allocator // { // public static final Unsafe unsafe; // public static final BlockCopy blockCopy; // public static final boolean checkBounds = System.getProperty("org.iq80.memory.CHECK_BOUNDS", "true").equals("true"); // // private static final ReferenceQueue<UnsafeAllocation> REFERENCE_QUEUE; // // static { // try { // Field field = Unsafe.class.getDeclaredField("theUnsafe"); // field.setAccessible(true); // unsafe = (Unsafe) field.get(null); // // int byteArrayIndexScale = unsafe.arrayIndexScale(byte[].class); // if (byteArrayIndexScale != 1) { // throw new IllegalStateException("Byte array index scale must be 1, but is " + byteArrayIndexScale); // } // } // catch (Exception e) { // throw new RuntimeException(e); // } // // blockCopy = new BlockCopy(unsafe); // // REFERENCE_QUEUE = new ReferenceQueue<UnsafeAllocation>(); // Thread thread = new Thread(new UnsafeMemoryFinalizer(REFERENCE_QUEUE), "UnsafeMemoryFinalizer"); // thread.setDaemon(true); // // thread.start(); // todo think about automatic collection... should we only use automatic collection? // } // // public static final int ADDRESS_SIZE = unsafe.addressSize(); // public static final int PAGE_SIZE = unsafe.pageSize(); // // public final static UnsafeAllocator INSTANCE = new UnsafeAllocator(); // // private UnsafeAllocator() {} // // public Region region(long address, long length) // throws IndexOutOfBoundsException // { // return new UnsafeAllocation(address, length); // } // // public Region region(long address) // throws IndexOutOfBoundsException // { // return new UnsafeAllocation(address, Long.MAX_VALUE-address); // } // // public Allocation allocate(long size) // throws IllegalArgumentException, OutOfMemoryError // { // if (size < 0) { // throw new IllegalArgumentException("Size is negative: " + size); // } // // // Allocating zero bytes, results in a pointer to null // if (size == 0) { // return NULL_POINTER; // } // // long address = unsafe.allocateMemory(size); // UnsafeAllocation memory = new UnsafeAllocation(address, size); // // new UnsafeMemoryPhantomReference(memory, referenceQueue); todo // return memory; // } // // private static class UnsafeMemoryFinalizer implements Runnable // { // private final ReferenceQueue<UnsafeAllocation> referenceQueue; // // private UnsafeMemoryFinalizer(ReferenceQueue<UnsafeAllocation> referenceQueue) // { // this.referenceQueue = referenceQueue; // } // // @SuppressWarnings({"InfiniteLoopStatement"}) // public void run() // { // while (true) { // try { // Reference<? extends UnsafeAllocation> reference = referenceQueue.remove(); // if (reference instanceof UnsafeMemoryPhantomReference) { // UnsafeMemoryPhantomReference phantomReference = (UnsafeMemoryPhantomReference) reference; // phantomReference.free(); // } // } // catch (InterruptedException ignored) { // // this is a daemon thread that can't die // Thread.interrupted(); // } // } // } // } // // private static class UnsafeMemoryPhantomReference extends PhantomReference<UnsafeAllocation> // { // private final long address; // // public UnsafeMemoryPhantomReference(UnsafeAllocation referent, ReferenceQueue<UnsafeAllocation> q) // { // super(referent, q); // if (referent == null) { // throw new NullPointerException("referent is null"); // } // address = referent.address; // if (address <= 0) { // throw new IllegalArgumentException("Invalid address " + address); // } // } // // public void free() // { // unsafe.freeMemory(address); // } // } // }
import java.nio.ByteBuffer; import static org.iq80.memory.Allocator.CHAR_SIZE; import static org.iq80.memory.Allocator.DOUBLE_SIZE; import static org.iq80.memory.Allocator.FLOAT_SIZE; import static org.iq80.memory.Allocator.INT_SIZE; import static org.iq80.memory.Allocator.LONG_SIZE; import static org.iq80.memory.Allocator.NULL_POINTER; import static org.iq80.memory.Allocator.SHORT_SIZE; import static org.iq80.memory.UnsafeAllocator.*;
/* * Copyright 2010 Proofpoint, Inc. * Copyright (C) 2012, FuseSource Corp. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.iq80.memory; public class UnsafeAllocation implements Allocation { public final long address; public final long size; private boolean released; static { if( unsafe == null || blockCopy ==null ) { throw new RuntimeException("Unsafe access not available"); } } UnsafeAllocation(long address, long size) { if (address <= 0) { throw new IllegalArgumentException("Invalid address: " + address); } if (size <= 0) { throw new IllegalArgumentException("Invalid size: " + size); } if (address + size < size) { throw new IllegalArgumentException("Address + size is greater than 64 bits"); } this.address = address; this.size = size; } public Allocator getAllocator() {
// Path: src/main/java/org/iq80/memory/UnsafeAllocator.java // public class UnsafeAllocator implements Allocator // { // public static final Unsafe unsafe; // public static final BlockCopy blockCopy; // public static final boolean checkBounds = System.getProperty("org.iq80.memory.CHECK_BOUNDS", "true").equals("true"); // // private static final ReferenceQueue<UnsafeAllocation> REFERENCE_QUEUE; // // static { // try { // Field field = Unsafe.class.getDeclaredField("theUnsafe"); // field.setAccessible(true); // unsafe = (Unsafe) field.get(null); // // int byteArrayIndexScale = unsafe.arrayIndexScale(byte[].class); // if (byteArrayIndexScale != 1) { // throw new IllegalStateException("Byte array index scale must be 1, but is " + byteArrayIndexScale); // } // } // catch (Exception e) { // throw new RuntimeException(e); // } // // blockCopy = new BlockCopy(unsafe); // // REFERENCE_QUEUE = new ReferenceQueue<UnsafeAllocation>(); // Thread thread = new Thread(new UnsafeMemoryFinalizer(REFERENCE_QUEUE), "UnsafeMemoryFinalizer"); // thread.setDaemon(true); // // thread.start(); // todo think about automatic collection... should we only use automatic collection? // } // // public static final int ADDRESS_SIZE = unsafe.addressSize(); // public static final int PAGE_SIZE = unsafe.pageSize(); // // public final static UnsafeAllocator INSTANCE = new UnsafeAllocator(); // // private UnsafeAllocator() {} // // public Region region(long address, long length) // throws IndexOutOfBoundsException // { // return new UnsafeAllocation(address, length); // } // // public Region region(long address) // throws IndexOutOfBoundsException // { // return new UnsafeAllocation(address, Long.MAX_VALUE-address); // } // // public Allocation allocate(long size) // throws IllegalArgumentException, OutOfMemoryError // { // if (size < 0) { // throw new IllegalArgumentException("Size is negative: " + size); // } // // // Allocating zero bytes, results in a pointer to null // if (size == 0) { // return NULL_POINTER; // } // // long address = unsafe.allocateMemory(size); // UnsafeAllocation memory = new UnsafeAllocation(address, size); // // new UnsafeMemoryPhantomReference(memory, referenceQueue); todo // return memory; // } // // private static class UnsafeMemoryFinalizer implements Runnable // { // private final ReferenceQueue<UnsafeAllocation> referenceQueue; // // private UnsafeMemoryFinalizer(ReferenceQueue<UnsafeAllocation> referenceQueue) // { // this.referenceQueue = referenceQueue; // } // // @SuppressWarnings({"InfiniteLoopStatement"}) // public void run() // { // while (true) { // try { // Reference<? extends UnsafeAllocation> reference = referenceQueue.remove(); // if (reference instanceof UnsafeMemoryPhantomReference) { // UnsafeMemoryPhantomReference phantomReference = (UnsafeMemoryPhantomReference) reference; // phantomReference.free(); // } // } // catch (InterruptedException ignored) { // // this is a daemon thread that can't die // Thread.interrupted(); // } // } // } // } // // private static class UnsafeMemoryPhantomReference extends PhantomReference<UnsafeAllocation> // { // private final long address; // // public UnsafeMemoryPhantomReference(UnsafeAllocation referent, ReferenceQueue<UnsafeAllocation> q) // { // super(referent, q); // if (referent == null) { // throw new NullPointerException("referent is null"); // } // address = referent.address; // if (address <= 0) { // throw new IllegalArgumentException("Invalid address " + address); // } // } // // public void free() // { // unsafe.freeMemory(address); // } // } // } // Path: src/main/java/org/iq80/memory/UnsafeAllocation.java import java.nio.ByteBuffer; import static org.iq80.memory.Allocator.CHAR_SIZE; import static org.iq80.memory.Allocator.DOUBLE_SIZE; import static org.iq80.memory.Allocator.FLOAT_SIZE; import static org.iq80.memory.Allocator.INT_SIZE; import static org.iq80.memory.Allocator.LONG_SIZE; import static org.iq80.memory.Allocator.NULL_POINTER; import static org.iq80.memory.Allocator.SHORT_SIZE; import static org.iq80.memory.UnsafeAllocator.*; /* * Copyright 2010 Proofpoint, Inc. * Copyright (C) 2012, FuseSource Corp. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.iq80.memory; public class UnsafeAllocation implements Allocation { public final long address; public final long size; private boolean released; static { if( unsafe == null || blockCopy ==null ) { throw new RuntimeException("Unsafe access not available"); } } UnsafeAllocation(long address, long size) { if (address <= 0) { throw new IllegalArgumentException("Invalid address: " + address); } if (size <= 0) { throw new IllegalArgumentException("Invalid size: " + size); } if (address + size < size) { throw new IllegalArgumentException("Address + size is greater than 64 bits"); } this.address = address; this.size = size; } public Allocator getAllocator() {
return UnsafeAllocator.INSTANCE;